Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions src/Bermuda.Web/e2e/host-api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,3 +296,94 @@ test.describe('taskbar overlay badge', () => {
expect(clearAfterSet.ok).toBe(true)
})
})

test.describe('taskbar flash', () => {
let original: Snapshot

test.beforeEach(async ({ page }) => {
await inPage(page, 'await chrome.webview.hostObjects.windowController.StopFlash()')
original = await getState(page)
})

// Flash tests minimize the window so it is not the foreground window. Put it back afterwards.
test.afterEach(async ({ page }) => {
await inPage(
page,
`const c = chrome.webview.hostObjects.windowController
await c.StopFlash()
await c.Restore()
await c.Resize(${original.bounds.width}, ${original.bounds.height})
await c.Move(${original.bounds.left}, ${original.bounds.top})
${original.isMaximized ? 'await c.Maximize()' : ''}`,
)
})

const isFlashing = (page: Page) =>
inPage<boolean>(page, 'return await chrome.webview.hostObjects.windowController.IsFlashing')

test('window.stopFlash is safe when the taskbar is not flashing', async ({ page }) => {
await inPage(page, 'await chrome.webview.hostObjects.windowController.StopFlash()')
expect(await isFlashing(page)).toBe(false)
})

test('window.flash starts flashing in the background and window.stopFlash stops it', async ({ page }) => {
await inPage(page, 'await chrome.webview.hostObjects.windowController.Minimize()')
expect(await inPage<boolean>(page, 'return await chrome.webview.hostObjects.windowController.IsFocused')).toBe(false)

await inPage(page, 'await chrome.webview.hostObjects.windowController.Flash()')
expect(await isFlashing(page)).toBe(true)

await inPage(page, 'await chrome.webview.hostObjects.windowController.StopFlash()')
expect(await isFlashing(page)).toBe(false)
})

test('window.flash does not leave a focused window flashing', async ({ page }) => {
await inPage(page, 'await chrome.webview.hostObjects.windowController.Restore()')
const focused = await inPage<boolean>(page, 'return await chrome.webview.hostObjects.windowController.IsFocused')
test.skip(!focused, 'This session did not leave the Bermuda window in the foreground.')

await inPage(page, 'await chrome.webview.hostObjects.windowController.Flash()')
expect(await isFlashing(page)).toBe(false)
})

test('bermudaHost.window.flash and stopFlash call the host object', async ({ page }) => {
await inPage(page, 'await chrome.webview.hostObjects.windowController.Minimize()')
await inPage(page, 'await bermudaHost.window.flash()')
expect(await inPage<boolean>(page, 'return await bermudaHost.window.isFlashing()')).toBe(true)

await inPage(page, 'await bermudaHost.window.stopFlash()')
expect(await inPage<boolean>(page, 'return await bermudaHost.window.isFlashing()')).toBe(false)
})

test('a background toast starts flashing and activation stops it', async ({ page }) => {
await inPage(page, 'await chrome.webview.hostObjects.windowController.Minimize()')
expect(await inPage<boolean>(page, 'return await chrome.webview.hostObjects.windowController.IsFocused')).toBe(false)

const shown = await inPage<{ shown: boolean; message: string }>(
page,
`return await bermudaHost.notifications.show({ id: 'e2e-flash', title: 'Bermuda e2e', body: 'Flash the taskbar', expiresInSeconds: 4 })`,
)
expect(shown).toEqual({ shown: true, message: '' })
expect(await isFlashing(page)).toBe(true)

const delivered = await inPage<{ delivered: boolean; message: string }>(
page,
`return await bermudaHost.notifications.simulateActivation({ notificationId: 'e2e-flash' })`,
)
expect(delivered).toEqual({ delivered: true, message: '' })
expect(await isFlashing(page)).toBe(false)
})

test('a toast does not flash the taskbar when the window is focused', async ({ page }) => {
await inPage(page, 'await chrome.webview.hostObjects.windowController.Restore()')
const focused = await inPage<boolean>(page, 'return await chrome.webview.hostObjects.windowController.IsFocused')
test.skip(!focused, 'This session did not leave the Bermuda window in the foreground.')

const shown = await inPage<{ shown: boolean }>(
page,
`return await bermudaHost.notifications.show({ id: 'e2e-flash-focused', title: 'Bermuda e2e', body: 'Already here', expiresInSeconds: 4 })`,
)
expect(shown.shown).toBe(true)
expect(await isFlashing(page)).toBe(false)
})
})
9 changes: 9 additions & 0 deletions src/Bermuda.Web/src/bridge/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,15 @@ const windowApi = {
setOverlay: (iconPng: string, description = '') => windowController().SetOverlayIcon(iconPng, description),
/** Sets the taskbar progress bar's state ('none' hides it). */
setProgressState: (state: TaskbarProgressState) => windowController().SetProgressState(state),
/**
* Flashes the taskbar button until the window is in the foreground or stopFlash() runs.
* A window that is already in front is left not flashing.
*/
flash: () => windowController().Flash(),
/** Stops taskbar flashing started by flash(). */
stopFlash: () => windowController().StopFlash(),
/** True while the taskbar button is flashing. */
isFlashing: () => windowController().IsFlashing,
} as const

export type WindowApi = typeof windowApi
Expand Down
3 changes: 3 additions & 0 deletions src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions src/Bermuda/IWindowController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,16 @@ public interface IWindowController

/// <summary>Sets the taskbar progress value. Clamped to 0.0–1.0; ignored while the state is "none" or "indeterminate".</summary>
void SetProgressValue(double value);

/// <summary>
/// Flashes the taskbar button until the window comes to the foreground or <see cref="StopFlash"/> is called.
/// A window that is already in the foreground is left not flashing.
/// </summary>
void Flash();

/// <summary>Stops taskbar flashing started by <see cref="Flash"/>.</summary>
void StopFlash();

/// <summary>True while the taskbar button is flashing.</summary>
bool IsFlashing { get; }
}
76 changes: 75 additions & 1 deletion src/Bermuda/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ public partial class MainWindow : Window, IWindowController, IFdc3AppSink
// is disposed, so every continuation checks this before touching it.
private bool _closed;

// True after Flash() until StopFlash(), or until the window comes to the foreground
// (FLASHW_TIMERNOFG). Read from the WebView thread; written on the UI thread.
private volatile bool _flashing;

/// <param name="fdc3AppId">The App Directory appId this window's page runs as.</param>
/// <param name="fdc3InstanceId">Set when FDC3 launched this window; the agent is waiting on this id.</param>
/// <param name="url">Overrides WEB_URL (FDC3-launched windows load their App Directory URL).</param>
Expand All @@ -82,8 +86,11 @@ public MainWindow(IConfiguration configuration, DesktopAgent fdc3, string fdc3Ap

Loaded += OnLoaded;
StateChanged += OnStateChanged;
// FLASHW_TIMERNOFG stops on its own once this window is in front; keep our flag in step.
Activated += OnWindowActivated;

// A toast (or one of its buttons) was clicked: surface the window and tell the web app.
NotificationService.ToastShown += OnNotificationShown;
NotificationService.Activated += OnNotificationActivated;
WindowRegistry.Add(this);
// With the tray icon on, closing the main window only hides it; the tray's Quit is the way out.
Expand All @@ -96,6 +103,8 @@ public MainWindow(IConfiguration configuration, DesktopAgent fdc3, string fdc3Ap
Closed += (_, _) =>
{
_closed = true;
StopFlash();
NotificationService.ToastShown -= OnNotificationShown;
NotificationService.Activated -= OnNotificationActivated;
_fdc3Connection?.Dispose();
_fdc3Connection = null;
Expand All @@ -108,17 +117,31 @@ public MainWindow(IConfiguration configuration, DesktopAgent fdc3, string fdc3Ap
};
}

// Only the app's main window reacts to toast clicks (every window is subscribed to the static event).
// Only the app's main window reacts to toasts (every window is subscribed to the static events).
private void OnNotificationShown() => Dispatcher.Invoke(() =>
{
if (_closed || WindowRegistry.Main != this) return;
if (!((IWindowController)this).IsFocused)
Flash();
});

private void OnNotificationActivated(NotificationActivation activation) => Dispatcher.Invoke(() =>
{
if (_closed || WindowRegistry.Main != this) return;

StopFlash();
ShowWindow();
Activate();
if (_webView.CoreWebView2 is not null)
PushEvent(activation);
});

private void OnWindowActivated(object? sender, EventArgs e)
{
if (_closed || !_flashing) return;
StopFlash();
}

private Task<CoreWebView2Environment> GetEnvironmentAsync()
{
if (_environment is not null) return _environment;
Expand Down Expand Up @@ -430,6 +453,57 @@ public void SetProgressValue(double value)
});
}

public void Flash() => ApplyWindowAction(() =>
{
// TIMERNOFG does not keep flashing a window that is already in front.
var foreground = IsWindowForeground();
FlashWindow(foreground ? FLASHW_STOP : (FLASHW_TRAY | FLASHW_TIMERNOFG));
_flashing = NativeWindowHandle != IntPtr.Zero && !foreground;
});

public void StopFlash() => ApplyWindowAction(() =>
{
FlashWindow(FLASHW_STOP);
_flashing = false;
});

public bool IsFlashing => _flashing;

// FLASHW_TRAY | FLASHW_TIMERNOFG flashes the taskbar button until this window is in
// the foreground or FLASHW_STOP. dwTimeout 0 uses the caret blink rate.
private const uint FLASHW_STOP = 0;
private const uint FLASHW_TRAY = 0x00000002;
private const uint FLASHW_TIMERNOFG = 0x0000000C;

[StructLayout(LayoutKind.Sequential)]
private struct FLASHWINFO
{
public uint cbSize;
public IntPtr hwnd;
public uint dwFlags;
public uint uCount;
public uint dwTimeout;
}

[DllImport("user32.dll")]
private static extern bool FlashWindowEx(ref FLASHWINFO pwfi);

private void FlashWindow(uint flags)
{
var hwnd = NativeWindowHandle;
if (hwnd == IntPtr.Zero) return;

var info = new FLASHWINFO
{
cbSize = (uint)Marshal.SizeOf<FLASHWINFO>(),
hwnd = hwnd,
dwFlags = flags,
uCount = flags == FLASHW_STOP ? 0u : uint.MaxValue,
dwTimeout = 0,
};
FlashWindowEx(ref info);
}

[DllImport("user32.dll", EntryPoint = "GetForegroundWindow")]
private static extern IntPtr NativeGetForegroundWindow();

Expand Down
4 changes: 4 additions & 0 deletions src/Bermuda/NotificationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ internal static class NotificationService
/// <summary>Raised (on a background thread) when a toast or one of its buttons is clicked.</summary>
public static event Action<NotificationActivation>? Activated;

/// <summary>Raised (possibly off the UI thread) after a toast has been shown.</summary>
public static event Action? ToastShown;

public static void Initialize()
{
var manager = AppNotificationManager.Default;
Expand Down Expand Up @@ -181,6 +184,7 @@ public static async Task<ShowNotificationResult> ShowAsync(ShowNotificationReque

AppNotificationManager.Default.Show(notification);
Shown[id] = new ShownToast(bodyArguments, buttonArguments, hasReply);
ToastShown?.Invoke();
return new(true, "");
}
catch (Exception ex)
Expand Down
4 changes: 4 additions & 0 deletions src/Bermuda/WindowScriptHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,8 @@ public void ToggleMaximize()

public void SetProgressState(string state) => _window.SetProgressState(state);
public void SetProgressValue(double value) => _window.SetProgressValue(value);

public void Flash() => _window.Flash();
public void StopFlash() => _window.StopFlash();
public bool IsFlashing => _window.IsFlashing;
}
Loading