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
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="10.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="10.0.0" />
<PackageVersion Include="WPF-UI" Version="4.2.0" />
<PackageVersion Include="H.NotifyIcon.Wpf" Version="2.4.1" />
<PackageVersion Include="Microsoft.WindowsAppSDK.Foundation" Version="2.6.5" />

<!-- src/Bermuda.Api -->
Expand Down
2 changes: 2 additions & 0 deletions src/Bermuda.AppHost/AppHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
var host = builder.AddProject<Projects.Bermuda>("host")
.WithEnvironment("WEB_URL", web.GetEndpoint("http"))
.WithEnvironment("CDP_PORT", cdpPort)
// Keep this run from handing over to (or being taken over by) an installed Bermuda.
.WithEnvironment("SINGLE_INSTANCE_KEY", "Bermuda.AppHost")
.WaitFor(web)
.WaitFor(api);
if (!string.IsNullOrWhiteSpace(pipeName)) host.WithEnvironment("FDC3_GRPC_PIPE", pipeName);
Expand Down
38 changes: 38 additions & 0 deletions src/Bermuda.Web/e2e/hostProcess.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { spawn } from 'node:child_process'
import { existsSync, statSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

// The key the Aspire host gives the app under test (AppHost.cs: SINGLE_INSTANCE_KEY). A second process must use
// the same one to find it.
const SINGLE_INSTANCE_KEY = 'Bermuda.AppHost'

/** The Bermuda.exe Aspire started: BERMUDA_EXE, else the newest build of the host project. */
function findHostExe(): string {
if (process.env.BERMUDA_EXE) return process.env.BERMUDA_EXE
const candidates = ['Debug', 'Release']
.map((config) => resolve(dirname(fileURLToPath(import.meta.url)), `../../Bermuda/bin/${config}/net10.0-windows10.0.19041.0/Bermuda.exe`))
.filter(existsSync)
.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)
if (candidates.length === 0) throw new Error('Bermuda.exe not found; build src/Bermuda or set BERMUDA_EXE.')
return candidates[0]
}

/** Starts a second Bermuda process and resolves with its exit code (it must exit by itself). */
export function launchSecondInstance(args: string[]): Promise<number | null> {
return new Promise((resolveExit, reject) => {
const child = spawn(findHostExe(), args, {
env: { ...process.env, SINGLE_INSTANCE_KEY, FDC3_GRPC_ENABLED: 'false', NATIVE_APP_AUTOSTART: 'false' },
stdio: 'ignore',
})
const timer = setTimeout(() => {
child.kill()
reject(new Error('The second Bermuda did not exit: it did not hand over to the running instance.'))
}, 20_000)
child.once('error', reject)
child.once('exit', (code) => {
clearTimeout(timer)
resolveExit(code)
})
})
}
41 changes: 41 additions & 0 deletions src/Bermuda.Web/e2e/single-instance.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { test, expect } from './fixtures'
import { launchSecondInstance } from './hostProcess'

// Bermuda is one process per user: a second launch (jump list task, startup relaunch) hands its activation to
// the running one and exits. These specs launch that second process for real and check what the running
// instance did with it.

test.describe('Single instance', () => {
test('a second launch with --open opens that app in the running instance', async ({ page }) => {
const context = page.context()
const probeOpened = context.waitForEvent('page')

await launchSecondInstance(['--open', 'fdc3-probe'])

const probe = await probeOpened
try {
await expect(probe).toHaveURL(/fdc3-probe\.html$/)
await expect(probe.locator('#status')).toHaveText('fdc3 ready')
} finally {
// The shared fixture drives pages()[0], so the extra window must really be gone.
const closed = probe.waitForEvent('close')
await probe.evaluate(() => window.chrome.webview.hostObjects.windowController.Close()).catch(() => {})
await closed
}

// Closing a window that is not the last must not end the app.
await expect(page.locator('tbody tr').first()).toBeVisible()
})

test('a plain second launch opens no new window and leaves the first one running', async ({ page }) => {
const context = page.context()
const pagesBefore = context.pages().length

await launchSecondInstance([])
// Give a wrongly started second window time to appear.
await page.waitForTimeout(1500)

expect(context.pages()).toHaveLength(pagesBefore)
await expect(page.locator('tbody tr').first()).toBeVisible()
})
})
26 changes: 26 additions & 0 deletions src/Bermuda.Web/e2e/tray.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type { Page } from '@playwright/test'
import { test, expect } from './fixtures'
import { launchSecondInstance } from './hostProcess'

// With the tray icon on (the default), closing the main window only hides it: Bermuda keeps running and its
// page stays alive. A second launch (or the tray's Show) brings the window back.

const isVisible = (page: Page) => page.evaluate(async () => await window.chrome.webview.hostObjects.windowController.IsVisible)

test.describe('Tray icon', () => {
test('closing the main window hides it to the tray instead of ending the app', async ({ page }) => {
expect(await isVisible(page)).toBe(true)

try {
await page.evaluate(() => window.chrome.webview.hostObjects.windowController.Close())
await expect.poll(() => isVisible(page)).toBe(false)

// Still running: the page answers and has not been disposed.
await expect(page.locator('tbody tr').first()).toBeAttached()
} finally {
// A second launch asks the running instance to bring its window forward.
await launchSecondInstance([])
await expect.poll(() => isVisible(page)).toBe(true)
}
})
})
1 change: 1 addition & 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.

143 changes: 140 additions & 3 deletions src/Bermuda/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
using Bermuda.Fdc3;
using Bermuda.Fdc3.Grpc;
using Microsoft.Extensions.Configuration;
using Microsoft.Windows.AppLifecycle;
using Microsoft.Windows.AppNotifications;
using Windows.ApplicationModel.Activation;

namespace Bermuda;

Expand All @@ -11,18 +14,32 @@ public partial class App : Application
/// <summary>The App Directory appId the main window's page runs as (see fdc3-appd.json).</summary>
public const string MainAppId = "bermuda-incidents";

private AppDirectory _directory = AppDirectory.Empty;
private WindowAppLauncher? _launcher;

// False for a second launch that handed over to the running Bermuda: it must not tear down that one's toasts.
private bool _isPrimary;

protected override void OnStartup(StartupEventArgs e)
{
// Closing the last window no longer ends the app by itself: WindowRegistry decides (and the tray
// icon will keep the app alive with no window).
ShutdownMode = ShutdownMode.OnExplicitShutdown;
base.OnStartup(e);

var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true)
.AddEnvironmentVariables()
.Build();

// One Bermuda per user: a second launch (jump list task, startup relaunch, toast click) hands its
// activation to the running one and exits before it opens anything.
if (!BecomeSingleInstance(config)) return;
_isPrimary = true;

NotificationService.Initialize();
var directory = AppDirectory.Load(Path.Combine(AppContext.BaseDirectory, "fdc3-appd.json"));
var launcher = new WindowAppLauncher(config);
var directory = _directory = AppDirectory.Load(Path.Combine(AppContext.BaseDirectory, "fdc3-appd.json"));
var launcher = _launcher = new WindowAppLauncher(config);
var fdc3 = new DesktopAgent(directory, launcher);
launcher.Agent = fdc3;

Expand All @@ -34,8 +51,127 @@ protected override void OnStartup(StartupEventArgs e)
StartNativeApps(config, directory);
}

// Tray icon (TRAY_ENABLED, default true): the app then lives on with no window, so it also keeps
// running when the last window is hidden.
WindowRegistry.TrayEnabled = !(bool.TryParse(config["TRAY_ENABLED"], out var trayEnabled) && !trayEnabled);
if (WindowRegistry.TrayEnabled)
{
try
{
_tray = new TrayService(() => { if (directory.Find(MainAppId) is { } main) launcher.Open(main); });
// Logging off or shutting down must not be stopped by the main window hiding itself.
SessionEnding += (_, _) => WindowRegistry.MarkQuitting();
}
catch (Exception ex)
{
// No tray means no way to bring a hidden window back, so fall back to closing normally.
System.Diagnostics.Debug.WriteLine($"Tray icon failed to start: {ex}");
WindowRegistry.TrayEnabled = false;
}
}

var window = new MainWindow(config, fdc3, MainAppId);
window.ShowActivated = !StartsInBackground();
window.Show();
// Started at sign-in (or with --background): sit in the tray, no window until the user asks for it.
if (!window.ShowActivated) window.HideWindow();

// The launch itself may ask for an app on top of the main window (e.g. a jump list task).
HandleLaunchArguments(Environment.GetCommandLineArgs().Skip(1).ToArray(), activateMainOtherwise: false);
}

private TrayService? _tray;

/// <summary>
/// True when this launch should start hidden in the tray: the MSIX startup task (sign-in) or --background.
/// Never without the tray, since there would be no way to bring the window back.
/// </summary>
private static bool StartsInBackground()
{
if (!WindowRegistry.TrayEnabled) return false;
if (Environment.GetCommandLineArgs().Any(a => string.Equals(a, "--background", StringComparison.OrdinalIgnoreCase)))
return true;
try
{
return AppInstance.GetCurrent().GetActivatedEventArgs().Kind == ExtendedActivationKind.StartupTask;
}
catch
{
return false;
}
}

/// <summary>
/// Registers this process as the user's Bermuda, or — when one is already running — forwards this launch's
/// activation to it, shuts this process down and returns false. SINGLE_INSTANCE=false turns it off;
/// SINGLE_INSTANCE_KEY isolates a dev/test run (the Aspire host sets one) from an installed Bermuda.
/// </summary>
private bool BecomeSingleInstance(IConfiguration config)
{
if (bool.TryParse(config["SINGLE_INSTANCE"], out var enabled) && !enabled) return true;

var key = config["SINGLE_INSTANCE_KEY"] is { Length: > 0 } custom ? custom : "Bermuda";
var instance = AppInstance.FindOrRegisterForKey(key);
if (instance.IsCurrent)
{
instance.Activated += OnActivatedByAnotherLaunch;
return true;
}

try
{
// Off the UI thread: redirecting waits on the other process, and an STA that blocks can deadlock.
var activation = AppInstance.GetCurrent().GetActivatedEventArgs();
Task.Run(() => instance.RedirectActivationToAsync(activation).AsTask()).Wait(TimeSpan.FromSeconds(10));
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Could not hand this launch to the running Bermuda: {ex}");
}

Shutdown();
return false;
}

// Another Bermuda process was launched and handed its activation here (on a background thread).
private void OnActivatedByAnotherLaunch(object? sender, AppActivationArguments args) => Dispatcher.BeginInvoke(() =>
{
switch (args.Data)
{
case AppNotificationActivatedEventArgs toast:
NotificationService.HandleForwarded(toast);
break;
case ILaunchActivatedEventArgs launch:
HandleLaunchArguments(launch.Arguments.Split(' ', StringSplitOptions.RemoveEmptyEntries), activateMainOtherwise: true);
break;
default:
WindowRegistry.ActivateMain();
break;
}
});

/// <summary>
/// <c>--open &lt;appId&gt;</c> opens that App Directory app's window; anything else just brings the main window
/// forward. Used for the first launch and for activations forwarded from a second launch.
/// </summary>
private void HandleLaunchArguments(string[] args, bool activateMainOtherwise)
{
var index = Array.FindIndex(args, a => string.Equals(a, "--open", StringComparison.OrdinalIgnoreCase));
if (index < 0 || index + 1 >= args.Length || _directory.Find(args[index + 1]) is not { } app || _launcher is null)
{
if (activateMainOtherwise) WindowRegistry.ActivateMain();
return;
}

try
{
_launcher.Open(app);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Could not open {app.AppId}: {ex.Message}");
if (activateMainOtherwise) WindowRegistry.ActivateMain();
}
}

/// <summary>
Expand Down Expand Up @@ -83,13 +219,14 @@ private void StartNativeApps(IConfiguration config, AppDirectory directory)

protected override void OnExit(ExitEventArgs e)
{
_tray?.Dispose();
_nativeApps?.Dispose();

if (_grpcHost is { } grpcHost)
{
Task.Run(() => grpcHost.DisposeAsync().AsTask()).Wait(TimeSpan.FromSeconds(6));
}
NotificationService.Clear();
if (_isPrimary) NotificationService.Clear();
base.OnExit(e);
}
}
1 change: 1 addition & 0 deletions src/Bermuda/Bermuda.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Json" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" />
<PackageReference Include="WPF-UI" />
<PackageReference Include="H.NotifyIcon.Wpf" />
<PackageReference Include="Microsoft.WindowsAppSDK.Foundation" />
</ItemGroup>

Expand Down
3 changes: 3 additions & 0 deletions src/Bermuda/IWindowController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ public interface IWindowController
bool IsMinimized { get; }
bool IsFocused { get; }

/// <summary>False while the window is hidden (for example in the tray).</summary>
bool IsVisible { get; }

int Left { get; }
int Top { get; }
int Width { get; }
Expand Down
12 changes: 11 additions & 1 deletion src/Bermuda/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,14 @@ public MainWindow(IConfiguration configuration, DesktopAgent fdc3, string fdc3Ap

// A toast (or one of its buttons) was clicked: surface the window and tell the web app.
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.
Closing += (_, e) =>
{
if (!WindowRegistry.HidesToTray(this)) return;
e.Cancel = true;
HideWindow();
};
Closed += (_, _) =>
{
_closed = true;
Expand All @@ -95,13 +103,15 @@ public MainWindow(IConfiguration configuration, DesktopAgent fdc3, string fdc3Ap
// this one, so release its page explicitly — otherwise it lingers
// as an orphaned, never-rendering CDP target.
_webView.Dispose();
// Last: may end the app, which tears down everything above.
WindowRegistry.Remove(this);
};
}

// Only the app's main window reacts to toast clicks (every window is subscribed to the static event).
private void OnNotificationActivated(NotificationActivation activation) => Dispatcher.Invoke(() =>
{
if (_closed || Application.Current.MainWindow != this) return;
if (_closed || WindowRegistry.Main != this) return;

ShowWindow();
Activate();
Expand Down
6 changes: 6 additions & 0 deletions src/Bermuda/NotificationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ public static void Initialize()

private static string? _registrationError;

/// <summary>
/// A toast click that Windows delivered to a second Bermuda process, which forwarded it to this one
/// (see <see cref="App"/>'s single-instance handling), as if it had arrived through the manager here.
/// </summary>
public static void HandleForwarded(AppNotificationActivatedEventArgs args) => Dispatch(args.Arguments, args.UserInput);

/// <summary>
/// Turns what Windows hands back on a click (the clicked element's arguments plus any reply text)
/// into the event pushed to the web app. Shared by real clicks and <see cref="Simulate"/>.
Expand Down
Loading
Loading