feat(app): keep sharing from the tray when the window closes

The owner wants the shared library to keep running while Chronos runs.
While sharing is on (or on its way), closing the main window now hides it
behind a tray icon (Open Chronos, Exit) instead of ending Chronos. Exit asks
first when clients used the library in the last minutes, then closes the
window for real, so the editor still stores its last edit and the exit path
stops sharing before the other services. A start at sign-in (--minimized)
with sharing on waits in the tray. With sharing off nothing changes.

The decisions live in ShareLifetime (unit-tested); ShellTray wires them to
the window, LibraryShare and OsNotifications, whose balloons reuse the icon.

Server > This library also warns when the 1.0 Windows Server's service
(ChronosServer) is installed, through a read-only SCM P/Invoke probe.

Refs #67

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 16:37:00 +01:00
1 parent f30eb2904a
commit 192265f1b7
18 files changed
+502 -6

No files matched your search

+6
View File
@@ -58,6 +58,12 @@ separate Uploader and later updates come through the Uploader's own check.
certificate fingerprint with Copy, the first admin's temporary password (Show, Copy), clients of the last 5
minutes and render nodes online, and Admin panel.
- The admin panel marks the settings Chronos Desktop owns as "Set in Chronos Desktop".
- While sharing, Chronos keeps running in the notification area: closing the window hides it (one notification
says so the first time), the tray icon offers Open Chronos and Exit, and Exit asks first when clients used the
library in the last minutes. Started with Windows while sharing, Chronos waits in the tray instead of on the
taskbar. With sharing off, closing the window exits as before.
- Server › This library warns when the 1.0 Windows Server's service is still installed (it may hold the same
ports; the setup can remove it).
- The owner review 5 request file (`docs/requests/2026-11-15-owner-review-5.md`).
### Changed
+5
View File
@@ -892,3 +892,8 @@ One line per decision: date · decision · alternative · reason.
| 2026-11-15 | While sharing, the job events and the job API expose only kinds clients may see whose first target is the shared archive or one of its sequences; sequence and project events skip sequences of other archives; render nodes never take a render without `CreatedBy` (the desktop's own) or of a sequence the share does not own | Expose every job of the engine | The desktop's engine also runs its workspace and private jobs; clients must not see or take them |
| 2026-11-15 | The desktop counts its share as its own from the moment the hosted server is built, not only once it has started | Only after start | A LAN beacon or a sign-in during the start would otherwise reach itself |
| 2026-11-15 | The Server section reads a job it does not list once, on its first progress event, and lists it if running or paused | Reload the list on unknown progress | A job that started between the list and the event socket stayed hidden until the next reload; one read per job is cheap |
| 2026-11-15 | While sharing, the desktop cancels the main window's close and hides it (tray icon: Open Chronos, Exit); `ShutdownMode` stays `OnMainWindowClose` and Exit closes the window for real, so the editor's save-before-closing handler and the existing exit path (sharing stops first in `AppServices.DisposeAsync`) run unchanged | Switch to `OnExplicitShutdown` while sharing (design §2.5) | A cancelled close never ends the app, so the explicit mode buys nothing; one exit path is simpler to keep right |
| 2026-11-15 | "Sharing" for the tray means served or starting, or on in the settings and not started yet (index opening, archive drive unplugged); a share that failed to start keeps nothing running, and an icon that goes while the window is hidden brings the window back minimised on the taskbar | Tray only while served | A start at sign-in must wait in the tray before the share is up; Chronos must never run out of sight |
| 2026-11-15 | Exit asks first only when the share is on and the programs of the last minutes plus the render nodes online (`LibraryShare.ActiveClientsAsync`, read again at the click) are not 0; Keep sharing is the default | Ask at every Exit while sharing | The question matters only when someone loses the library; the Server section counts clients the same way |
| 2026-11-15 | The "keeps sharing" notification shows once per run, at the first hide; the balloons of unseen toasts go through the same tray icon (`OsNotifications.SharedIcon`) | Once ever (a setting); a second icon for toasts | No new setting for a one-line hint; one icon in the notification area |
| 2026-11-15 | The 1.0 service probe (`ServiceProbe`: `OpenSCManager` connect + `OpenService` query-status P/Invoke) runs when Server › This library opens and at each change of sharing state, shows a warning row whatever the state, and reads access denied as installed | `System.ServiceProcess` (not in the shared framework, a package); probe only after a port failure | Read-only and unelevated; the row is advice before sharing is turned on as much as after a failure |
+1
View File
@@ -208,6 +208,7 @@
<data name="Server.Share.Copy" xml:space="preserve"><value>Copy</value></data>
<data name="Server.Share.Fingerprint" xml:space="preserve"><value>Fingerprint</value></data>
<data name="Server.Share.Hide" xml:space="preserve"><value>Hide</value></data>
<data name="Server.Share.LegacyService" xml:space="preserve"><value>1.0 server installed</value></data>
<data name="Server.Share.NoClients" xml:space="preserve"><value>None</value></data>
<data name="Server.Share.Ports" xml:space="preserve"><value>Ports</value></data>
<data name="Server.Share.PortsValue" xml:space="preserve"><value>HTTPS {0} · HTTP {1}</value></data>
+9
View File
@@ -5,6 +5,10 @@
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Shell.AppName" xml:space="preserve"><value>Chronos</value><comment>invariant</comment></data>
<data name="Shell.Exit.Heading" xml:space="preserve"><value>Stop sharing?</value></data>
<data name="Shell.Exit.Keep" xml:space="preserve"><value>Keep sharing</value></data>
<data name="Shell.Exit.Message.one" xml:space="preserve"><value>{0} client used this library in the last minutes. Exiting Chronos stops sharing it.</value><comment>long; {0} count; confirmation under Stop sharing?</comment></data>
<data name="Shell.Exit.Message.other" xml:space="preserve"><value>{0} clients used this library in the last minutes. Exiting Chronos stops sharing it.</value><comment>long; {0} count; confirmation under Stop sharing?</comment></data>
<data name="Shell.Homes.Clash" xml:space="preserve"><value>Server ID clash</value></data>
<data name="Shell.Homes.Moved.one" xml:space="preserve"><value>{0} project moved</value><comment>{0} count</comment></data>
<data name="Shell.Homes.Moved.other" xml:space="preserve"><value>{0} projects moved</value><comment>{0} count</comment></data>
@@ -40,6 +44,11 @@
<data name="Shell.Status.Photos.other" xml:space="preserve"><value>{0:N0} photos</value></data>
<data name="Shell.Status.Sequences.one" xml:space="preserve"><value>{0:N0} sequence</value></data>
<data name="Shell.Status.Sequences.other" xml:space="preserve"><value>{0:N0} sequences</value></data>
<data name="Shell.Tray.Exit" xml:space="preserve"><value>Exit</value></data>
<data name="Shell.Tray.KeepsSharing" xml:space="preserve"><value>Still sharing</value></data>
<data name="Shell.Tray.KeepsSharingText" xml:space="preserve"><value>Chronos keeps sharing this library from the notification area. Exit there stops it.</value><comment>long; Windows notification under Still sharing</comment></data>
<data name="Shell.Tray.Open" xml:space="preserve"><value>Open Chronos</value></data>
<data name="Shell.Tray.Sharing" xml:space="preserve"><value>Chronos · sharing {0}</value><comment>tray tooltip; {0} the library's name</comment></data>
<data name="Shell.Tray.Show" xml:space="preserve"><value>Show Chronos</value></data>
<data name="Shell.Welcome.Adopt" xml:space="preserve"><value>Adopt an existing folder</value></data>
<data name="Shell.Welcome.Change" xml:space="preserve"><value>Change…</value></data>
+3
View File
@@ -715,6 +715,7 @@
<data name="Tooltips.Server.Share.CopyFingerprint" xml:space="preserve"><value>Copy the fingerprint</value></data>
<data name="Tooltips.Server.Share.CopyPassword" xml:space="preserve"><value>Copy the temporary password</value></data>
<data name="Tooltips.Server.Share.Fingerprint" xml:space="preserve"><value>Clients see this fingerprint the first time they connect; it must match</value></data>
<data name="Tooltips.Server.Share.LegacyService" xml:space="preserve"><value>The Windows service of Chronos Server 1.0 is installed on this PC: it may hold the same ports. The Chronos setup can remove it</value></data>
<data name="Tooltips.Server.Share.Ports" xml:space="preserve"><value>The ports the shared library listens on</value></data>
<data name="Tooltips.Server.Share.Restart" xml:space="preserve"><value>Try to start sharing again</value></data>
<data name="Tooltips.Server.Share.Settings" xml:space="preserve"><value>Open Settings › Server to share this library</value></data>
@@ -930,6 +931,8 @@
<data name="Tooltips.Setup.UninstallAll" xml:space="preserve"><value>No program is selected: remove the whole installation · the next step shows what goes</value></data>
<data name="Tooltips.Setup.Update" xml:space="preserve"><value>Update the installed programs in place and apply the changes listed · your data is kept</value></data>
<data name="Tooltips.Shell.CollapseRail" xml:space="preserve"><value>Collapse navigation to icons · Ctrl+B</value></data>
<data name="Tooltips.Shell.Exit.Exit" xml:space="preserve"><value>Stop sharing and close Chronos; the clients lose this library until Chronos runs again</value></data>
<data name="Tooltips.Shell.Exit.Keep" xml:space="preserve"><value>Keep Chronos running in the notification area, sharing this library</value></data>
<data name="Tooltips.Shell.ExpandRail" xml:space="preserve"><value>Show navigation names · Ctrl+B</value></data>
<data name="Tooltips.Shell.Homes.Logs" xml:space="preserve"><value>Show the logs folder in Explorer: the log says which folder could not be sorted</value></data>
<data name="Tooltips.Shell.PauseJob" xml:space="preserve"><value>Pause the job shown; it continues from its checkpoint when resumed</value></data>
+1
View File
@@ -206,6 +206,7 @@
<data name="Server.Share.Copy" xml:space="preserve"><value>Copia</value></data>
<data name="Server.Share.Fingerprint" xml:space="preserve"><value>Impronta</value></data>
<data name="Server.Share.Hide" xml:space="preserve"><value>Nascondi</value></data>
<data name="Server.Share.LegacyService" xml:space="preserve"><value>Server 1.0 installato</value></data>
<data name="Server.Share.NoClients" xml:space="preserve"><value>Nessuno</value></data>
<data name="Server.Share.Ports" xml:space="preserve"><value>Porte</value></data>
<data name="Server.Share.PortsValue" xml:space="preserve"><value>HTTPS {0} · HTTP {1}</value></data>
+9
View File
@@ -4,6 +4,10 @@
<resheader name="version"><value>2.0</value></resheader>
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
<data name="Shell.Exit.Heading" xml:space="preserve"><value>Interrompere la condivisione?</value></data>
<data name="Shell.Exit.Keep" xml:space="preserve"><value>Continua a condividere</value></data>
<data name="Shell.Exit.Message.one" xml:space="preserve"><value>{0} client ha usato questa libreria negli ultimi minuti. Uscendo da Chronos la condivisione si interrompe.</value></data>
<data name="Shell.Exit.Message.other" xml:space="preserve"><value>{0} client hanno usato questa libreria negli ultimi minuti. Uscendo da Chronos la condivisione si interrompe.</value></data>
<data name="Shell.Homes.Clash" xml:space="preserve"><value>ID server in conflitto</value></data>
<data name="Shell.Homes.Moved.one" xml:space="preserve"><value>{0} progetto spostato</value></data>
<data name="Shell.Homes.Moved.other" xml:space="preserve"><value>{0} progetti spostati</value></data>
@@ -39,6 +43,11 @@
<data name="Shell.Status.Photos.other" xml:space="preserve"><value>{0:N0} foto</value></data>
<data name="Shell.Status.Sequences.one" xml:space="preserve"><value>{0:N0} sequenza</value></data>
<data name="Shell.Status.Sequences.other" xml:space="preserve"><value>{0:N0} sequenze</value></data>
<data name="Shell.Tray.Exit" xml:space="preserve"><value>Esci</value></data>
<data name="Shell.Tray.KeepsSharing" xml:space="preserve"><value>Condivisione attiva</value></data>
<data name="Shell.Tray.KeepsSharingText" xml:space="preserve"><value>Chronos continua a condividere questa libreria dall'area di notifica. Esci, lì, la interrompe.</value></data>
<data name="Shell.Tray.Open" xml:space="preserve"><value>Apri Chronos</value></data>
<data name="Shell.Tray.Sharing" xml:space="preserve"><value>Chronos · condivide {0}</value></data>
<data name="Shell.Tray.Show" xml:space="preserve"><value>Mostra Chronos</value></data>
<data name="Shell.Welcome.Adopt" xml:space="preserve"><value>Adotta una cartella esistente</value></data>
<data name="Shell.Welcome.Change" xml:space="preserve"><value>Cambia…</value></data>
+3
View File
@@ -786,6 +786,7 @@
<data name="Tooltips.Server.Share.CopyFingerprint" xml:space="preserve"><value>Copia l'impronta</value></data>
<data name="Tooltips.Server.Share.CopyPassword" xml:space="preserve"><value>Copia la password temporanea</value></data>
<data name="Tooltips.Server.Share.Fingerprint" xml:space="preserve"><value>I client vedono questa impronta la prima volta che si connettono; deve coincidere</value></data>
<data name="Tooltips.Server.Share.LegacyService" xml:space="preserve"><value>Su questo PC è installato il servizio Windows di Chronos Server 1.0: potrebbe occupare le stesse porte. Il setup di Chronos può rimuoverlo</value></data>
<data name="Tooltips.Server.Share.Ports" xml:space="preserve"><value>Le porte su cui ascolta la libreria condivisa</value></data>
<data name="Tooltips.Server.Share.Restart" xml:space="preserve"><value>Riprova ad avviare la condivisione</value></data>
<data name="Tooltips.Server.Share.Settings" xml:space="preserve"><value>Apri Impostazioni › Server per condividere questa libreria</value></data>
@@ -1031,6 +1032,8 @@
<data name="Tooltips.Setup.UninstallAll" xml:space="preserve"><value>Nessun programma selezionato: rimuovi l'intera installazione · il passo successivo mostra cosa viene rimosso</value></data>
<data name="Tooltips.Setup.Update" xml:space="preserve"><value>Aggiorna sul posto i programmi installati e applica le modifiche elencate · i tuoi dati restano</value></data>
<data name="Tooltips.Shell.CollapseRail" xml:space="preserve"><value>Riduci la navigazione alle icone · Ctrl+B</value></data>
<data name="Tooltips.Shell.Exit.Exit" xml:space="preserve"><value>Interrompi la condivisione e chiudi Chronos; i client perdono questa libreria finché Chronos non si riavvia</value></data>
<data name="Tooltips.Shell.Exit.Keep" xml:space="preserve"><value>Lascia Chronos attivo nell'area di notifica, a condividere questa libreria</value></data>
<data name="Tooltips.Shell.ExpandRail" xml:space="preserve"><value>Mostra i nomi della navigazione · Ctrl+B</value></data>
<data name="Tooltips.Shell.Homes.Logs" xml:space="preserve"><value>Mostra la cartella dei log in Esplora file: il log dice quale cartella non è stata riordinata</value></data>
<data name="Tooltips.Shell.PauseJob" xml:space="preserve"><value>Mette in pausa l'attività mostrata; quando la riprendi continua dal punto di ripresa</value></data>
+8 -1
View File
@@ -26,6 +26,7 @@ public partial class App : Application
private readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously);
private FileLogSink? _log;
private SingleInstance? _instance;
private ShellTray? _tray;
private bool _windowClosed;
public AppEnvironment Environment { get; private set; } = null!;
@@ -113,7 +114,10 @@ public partial class App : Application
_windowClosed = true;
_instance?.StopListening();
};
window.Show();
// While sharing: closing hides the window to the tray, and a start at sign-in waits there (owner review 5, #67).
_tray = new ShellTray(window, shell);
_tray.Update();
if (ShareLifetime.Start(Shell.MainWindow.StartsMinimized(e.Args), Settings.Share.Enabled) != StartWindow.Tray) window.Show();
_instance?.Receive(args => Dispatcher.BeginInvoke(() => OnHandOver(shell, args)));
_ = StartAsync(shell, projectFile);
}
@@ -197,6 +201,8 @@ public partial class App : Application
}
// Every settings change passes here, Settings › Advanced › Logs, its Reset and an imported file included.
ApplyLogSettings();
// Sharing turned on or off, or a new name: the tray icon follows.
_tray?.Update();
}
/// <summary>Settings › Advanced › Logs to the log files, from the next line on (owner review 2, R11).</summary>
@@ -209,6 +215,7 @@ public partial class App : Application
{
// The mutex stays until the services have stopped, so a launch now waits for this one to exit.
_instance?.StopListening();
_tray?.Dispose();
SaveSettings();
if (MainWindow?.DataContext is ShellViewModel shell) shell.Dispose();
try
+2
View File
@@ -72,6 +72,8 @@
</DockPanel>
<ui:StatusGlyph Kind="Error" Text="{Binding Reason}" FontSize="12" Margin="0,8,0,0" HorizontalAlignment="Left"
Visibility="{Binding Reason, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<ui:StatusGlyph Kind="Warning" Text="{l:Loc Server.Share.LegacyService}" FontSize="12" Margin="0,8,0,0" HorizontalAlignment="Left"
ToolTip="{l:Loc Tooltips.Server.Share.LegacyService}" Visibility="{Binding HasLegacyService, Converter={StaticResource BoolToVisibility}}" />
<Grid Margin="0,10,0,0" Visibility="{Binding IsOn, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
@@ -8,6 +8,7 @@ using Chronos.App.Server;
using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Core.Windows.Services;
using Chronos.Core.Localization;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
@@ -21,7 +22,8 @@ public sealed record ShareAddressRow(string Address, ICommand CopyCommand);
/// Server › This library (owner review 5, #67): whether this PC shares its library, why not when it could not start
/// (with Restart), the addresses with Copy, the ports, the certificate's fingerprint with Copy, the first administrator's
/// temporary password while it exists (Show, Copy), the clients of the last minutes and the admin panel. Off, one row and
/// Sharing settings. Follows <see cref="LibraryShare"/> on the UI thread; the clients are read again every few seconds.
/// Sharing settings. Follows <see cref="LibraryShare"/> on the UI thread; the clients are read again every few seconds. A
/// warning row shows while the 1.0 Windows Server's service is installed, read at the start and at each change of state.
/// </summary>
public sealed class SharePanelViewModel : LocalizedViewModel
{
@@ -30,12 +32,18 @@ public sealed class SharePanelViewModel : LocalizedViewModel
private readonly ShellViewModel _shell;
private readonly LibraryShare _share;
private readonly DispatcherTimer? _timer;
private readonly Func<bool> _legacyService;
private bool _showPassword;
private bool _hasLegacyService;
public SharePanelViewModel(ShellViewModel shell)
/// <param name="shell">The shell whose shared library the panel shows.</param>
/// <param name="legacyService">Whether the 1.0 Windows Server is installed; the Service Control Manager by default (never during screenshots).</param>
public SharePanelViewModel(ShellViewModel shell, Func<bool>? legacyService = null)
{
_shell = shell;
_share = shell.Services.Share;
_legacyService = legacyService ?? (shell.Services.Environment.IsCapture ? () => false : () => ServiceProbe.IsInstalled(ServiceProbe.LegacyServer));
_hasLegacyService = _legacyService();
_share.PropertyChanged += OnShareChanged;
CopyCommand = new RelayCommand(p => Copy(p as string));
CopyFingerprintCommand = new RelayCommand(() => Copy(_share.Fingerprint), () => _share.Fingerprint is not null);
@@ -111,6 +119,9 @@ public sealed class SharePanelViewModel : LocalizedViewModel
public bool HasClients => _share.Clients.Count > 0;
/// <summary>The 1.0 Windows Server's service is installed: it may hold the same ports, and the setup can remove it.</summary>
public bool HasLegacyService => _hasLegacyService;
public string ClientsText => HasClients ? Loc.Plural("Server.Share.ClientCount", _share.Clients.Count) : Loc.L("Server.Share.NoClients");
public override void Dispose()
@@ -165,6 +176,7 @@ public sealed class SharePanelViewModel : LocalizedViewModel
private void Changed()
{
if (!_share.IsOn) _showPassword = false;
_hasLegacyService = _legacyService();
OnAllPropertiesChanged();
CommandManager.InvalidateRequerySuggested();
}
+18
View File
@@ -250,6 +250,24 @@ public sealed class LibraryShare : ObservableObject, IAsyncDisposable
AdminPassword = server.AdminPassword();
}
/// <summary>
/// How many programs used the library in the last minutes plus the render nodes online, read again now; 0 while it is not
/// served. Exit asks first when this is not 0. Never throws: a failed read counts the clients read last.
/// </summary>
public async Task<int> ActiveClientsAsync(CancellationToken cancellationToken = default)
{
if (!IsOn) return 0;
try
{
await RefreshAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException or OperationCanceledException)
{
Log.Warning("share", "The clients of the shared library could not be read", ex);
}
return Clients.Count;
}
/// <summary>The <c>uploads</c> clean-up step while sharing (<see cref="ShareUploadsStep"/>): the server's sweep, or nothing.</summary>
public Task<string> SweepUploadsAsync(CleanupContext context, CleanupParameters parameters) =>
_server is { } server ? server.SweepUploadsAsync(context, parameters) : Task.FromResult(Loc.L("Server.Log.SharingOff"));
+13
View File
@@ -39,6 +39,9 @@ public partial class MainWindow : ChronosWindow
Closed += (_, _) => _notifications.Dispose();
}
/// <summary>The Windows notifications of the toasts nobody sees (the shared library's tray icon carries them while sharing).</summary>
internal OsNotifications Notifications => _notifications;
/// <summary>Started at sign-in (Settings › General › Startup): the window waits minimised on the taskbar.</summary>
internal static bool StartsMinimized(IReadOnlyList<string> arguments) =>
arguments.Any(a => a.Equals(RunKeyStartWithWindows.MinimizedOption, StringComparison.OrdinalIgnoreCase));
@@ -50,6 +53,16 @@ public partial class MainWindow : ChronosWindow
_restoreTo = maximized ? WindowState.Maximized : WindowState.Normal;
}
/// <summary>
/// A hidden window comes back minimised on the taskbar (the tray icon went while it was hidden); its first restore
/// brings back the state it had, maximised or not.
/// </summary>
internal void ShowMinimized()
{
if (WindowState != WindowState.Minimized) WaitMinimized(WindowState == WindowState.Maximized);
Show();
}
/// <summary>The maximised flag to save: a window started minimised and never opened keeps the state it would come back to.</summary>
internal static bool SavesMaximized(WindowState state, WindowState? restoreTo) =>
state == WindowState.Maximized || (state == WindowState.Minimized && restoreTo == WindowState.Maximized);
+9 -3
View File
@@ -40,15 +40,21 @@ public sealed class OsNotifications : IDisposable
/// <summary>The tray icon is in the notification area (tests).</summary>
internal bool HasTrayIcon => _tray is not null;
/// <summary>
/// The persistent tray icon while the library is shared (<see cref="ShellTray"/>): the balloons go there instead of a
/// second icon of their own, and its balloon clicks come back to <see cref="OnBalloonClicked"/>. Null otherwise.
/// </summary>
internal TrayIcon? SharedIcon { get; set; }
/// <summary>Mirrors <paramref name="toast"/> as a Windows notification when nobody sees the window; true when it did.</summary>
public bool Show(Toast toast)
{
// A toast raised while the app closes (the window is hidden by then) needs no icon that would outlive it.
if (_disposed || !_enabled() || !IsUnseen(_window.WindowState, _window.IsVisible, AnyWindowActive())) return false;
_tray ??= new TrayIcon(Loc.L("Shell.AppName"), Menu, OnMenu, Restore, OnBalloonClicked);
var icon = SharedIcon ?? (_tray ??= new TrayIcon(Loc.L("Shell.AppName"), Menu, OnMenu, Restore, OnBalloonClicked));
_latest = toast;
_shown++;
_tray.ShowBalloon(toast.Title, BalloonText(toast), toast.IsError);
icon.ShowBalloon(toast.Title, BalloonText(toast), toast.IsError);
return true;
}
@@ -112,7 +118,7 @@ public sealed class OsNotifications : IDisposable
/// </summary>
private void OnActivated(object? sender, EventArgs e)
{
if (_tray is null) return;
if (_tray is null && _shown == 0) return;
_window.Dispatcher.BeginInvoke(() =>
{
if (!IsUnseen(_window.WindowState, _window.IsVisible, AnyWindowActive())) RemoveIcon();
+61
View File
@@ -0,0 +1,61 @@
using Chronos.App.Server;
using Chronos.Core.Localization;
namespace Chronos.App.Shell;
/// <summary>How the main window appears when Chronos starts.</summary>
public enum StartWindow
{
/// <summary>On screen, as the user left it.</summary>
Shown,
/// <summary>Started at sign-in: minimised on the taskbar.</summary>
Minimized,
/// <summary>Started at sign-in while sharing: hidden, only the tray icon shows.</summary>
Tray,
}
/// <summary>What closing the main window does.</summary>
public enum CloseAction
{
/// <summary>Chronos ends (sharing, if any, stops first).</summary>
Exit,
/// <summary>The window hides; Chronos keeps sharing from the tray icon.</summary>
HideToTray,
}
/// <summary>
/// The desktop's lifetime while it shares its library (owner review 5, #67, design §2.5): while sharing is on, or on its
/// way, Chronos keeps running with a tray icon, closing the window hides it, Exit asks first when clients are active, and
/// a start at sign-in waits in the tray. With sharing off nothing changes. Pure decisions, for <see cref="ShellTray"/>.
/// </summary>
public static class ShareLifetime
{
/// <summary>
/// True while Chronos must outlive its window: the library is served or starting, or sharing is on in the settings and
/// has not started yet (the index is opening, the archive's drive is unplugged). A share that failed to start, or one
/// turned off and stopped, keeps nothing running.
/// </summary>
public static bool KeepsRunning(bool shareEnabled, ShareState state) => state switch
{
ShareState.On or ShareState.Starting => true,
ShareState.Off => shareEnabled,
_ => false,
};
/// <summary>Closing the window hides it while sharing, unless the user chose Exit (or Windows is ending the session).</summary>
public static CloseAction OnClose(bool exiting, bool keepsRunning) => !exiting && keepsRunning ? CloseAction.HideToTray : CloseAction.Exit;
/// <summary>Exit asks first when programs used the shared library in the last minutes or render nodes are online.</summary>
public static bool AsksBeforeExit(ShareState state, int activeClients) => state == ShareState.On && activeClients > 0;
/// <summary>A start at sign-in (<c>--minimized</c>) waits in the tray while sharing is on, else minimised on the taskbar.</summary>
public static StartWindow Start(bool minimized, bool shareEnabled) =>
!minimized ? StartWindow.Shown : shareEnabled ? StartWindow.Tray : StartWindow.Minimized;
/// <summary>The tray icon's hover text: "Chronos · sharing studio-pc" (the name clients see; empty: this PC's name).</summary>
public static string ToolTip(string? name, string machineName) =>
Loc.L("Shell.Tray.Sharing", string.IsNullOrWhiteSpace(name) ? machineName : name.Trim());
}
+198
View File
@@ -0,0 +1,198 @@
using System.ComponentModel;
using System.Windows;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Ui.Interop;
namespace Chronos.App.Shell;
/// <summary>
/// The desktop's tray while it shares its library (owner review 5, #67, design §2.5): while <see cref="ShareLifetime.KeepsRunning"/>
/// a tray icon shows (Open Chronos, Exit; tooltip "Chronos · sharing name"), closing the main window hides it instead of
/// ending Chronos (one balloon says so, the first time), and Exit asks first when clients are active, then closes the window
/// for real: the editor stores its last edit, and the app's exit stops sharing before the other services. Without sharing
/// nothing changes: no icon, closing ends Chronos. Create, use and dispose it on the UI thread.
/// </summary>
public sealed class ShellTray : IDisposable
{
private const int MenuOpen = 1;
private const int MenuExit = 2;
private readonly MainWindow _window;
private readonly ShellViewModel _shell;
private readonly LibraryShare _share;
private TrayIcon? _icon;
private string? _toolTip;
private bool _exiting;
private bool _asking;
private bool _told;
private bool _closed;
private bool _disposed;
public ShellTray(MainWindow window, ShellViewModel shell)
{
_window = window;
_shell = shell;
_share = shell.Services.Share;
_window.Closing += OnClosing;
_window.Closed += OnClosed;
_share.Changed += OnShareChanged;
if (Application.Current is { } app) app.SessionEnding += OnSessionEnding;
}
/// <summary>Chronos outlives its window now: sharing is on or on its way.</summary>
public bool KeepsRunning => ShareLifetime.KeepsRunning(_shell.Services.Settings.Share.Enabled, _share.State);
/// <summary>
/// Shows or removes the icon as sharing goes on or off, and follows a new name. An icon that goes while the window is
/// hidden brings the window back, minimised on the taskbar, so Chronos never runs out of sight. Any thread.
/// </summary>
public void Update()
{
if (!_window.Dispatcher.CheckAccess())
{
_window.Dispatcher.BeginInvoke(Update);
return;
}
if (_disposed) return;
if (KeepsRunning)
{
var text = ShareLifetime.ToolTip(_shell.Services.Settings.Share.Name, System.Environment.MachineName);
if (_icon is null)
{
_icon = new TrayIcon(text, Menu, OnMenu, Open, _window.Notifications.OnBalloonClicked);
_window.Notifications.SharedIcon = _icon;
}
else if (text != _toolTip)
{
_icon.SetToolTip(text);
}
_toolTip = text;
return;
}
if (_icon is null) return;
RemoveIcon();
if (!_exiting && !_closed && !_window.IsVisible) _window.ShowMinimized();
}
/// <summary>The window in front, as it was before it was hidden or minimised.</summary>
public void Open()
{
if (_disposed) return;
_window.Show();
if (_window.WindowState == WindowState.Minimized) _window.WindowState = WindowState.Normal;
_window.Activate();
}
/// <summary>
/// Tray › Exit: asks first when clients are active, then ends Chronos. A window with an edit still to store comes back
/// first, since storing it may ask; a window never shown (started in the tray) has no editor and the app shuts down.
/// </summary>
public async Task ExitAsync()
{
if (_disposed || _exiting || _asking) return;
_asking = true;
try
{
var clients = await _share.ActiveClientsAsync();
if (ShareLifetime.AsksBeforeExit(_share.State, clients) && !_shell.Services.Dialogs.Confirm(ExitRequest(clients))) return;
}
finally
{
_asking = false;
}
_exiting = true;
if (!_window.IsLoaded)
{
Application.Current?.Shutdown();
return;
}
if (_shell.Sequence.HasPendingSave) Open();
_window.Close();
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_window.Closing -= OnClosing;
_window.Closed -= OnClosed;
_share.Changed -= OnShareChanged;
if (Application.Current is { } app) app.SessionEnding -= OnSessionEnding;
RemoveIcon();
}
/// <summary>The confirmation of Exit while clients use the library: Keep sharing is the safe, default choice.</summary>
internal static ConfirmRequest ExitRequest(int clients) => new()
{
Heading = Loc.L("Shell.Exit.Heading"),
Message = Loc.Plural("Shell.Exit.Message", clients),
SafeText = Loc.L("Shell.Exit.Keep"),
SafeToolTip = Loc.L("Tooltips.Shell.Exit.Keep"),
ActionText = Loc.L("Shell.Tray.Exit"),
ActionToolTip = Loc.L("Tooltips.Shell.Exit.Exit"),
};
private IReadOnlyList<TrayMenuItem> Menu() =>
[
new(MenuOpen, Loc.L("Shell.Tray.Open")),
new(0, null),
new(MenuExit, Loc.L("Shell.Tray.Exit")),
];
private void OnMenu(int id)
{
switch (id)
{
case MenuOpen:
Open();
break;
case MenuExit:
_ = RunExitAsync();
break;
}
}
private async Task RunExitAsync()
{
try
{
await ExitAsync();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Error("app", "Chronos could not exit from the tray", ex);
}
}
/// <summary>Closing hides the window while sharing; the first time, a balloon says Chronos goes on sharing.</summary>
private void OnClosing(object? sender, CancelEventArgs e)
{
if (e.Cancel || ShareLifetime.OnClose(_exiting, KeepsRunning) == CloseAction.Exit) return;
e.Cancel = true;
// The icon exists before the window goes, whatever the last state change was.
Update();
_window.Hide();
if (_told || _icon is null) return;
_told = true;
_icon.ShowBalloon(Loc.L("Shell.Tray.KeepsSharing"), Loc.L("Shell.Tray.KeepsSharingText"));
}
private void OnShareChanged() => Update();
private void OnClosed(object? sender, EventArgs e) => _closed = true;
/// <summary>Windows is signing out or shutting down: the window closes for real (WPF closes it without waiting anyway).</summary>
private void OnSessionEnding(object? sender, SessionEndingCancelEventArgs e) => _exiting = true;
private void RemoveIcon()
{
if (_icon is null) return;
if (ReferenceEquals(_window.Notifications.SharedIcon, _icon)) _window.Notifications.SharedIcon = null;
_icon.Dispose();
_icon = null;
_toolTip = null;
}
}
@@ -0,0 +1,51 @@
using System.Runtime.InteropServices;
namespace Chronos.Core.Windows.Services;
/// <summary>
/// Read-only look at the Service Control Manager (owner review 5, #67): whether a Windows service is installed, so the
/// desktop can warn that the 1.0 Windows Server (<see cref="LegacyServer"/>) may hold the ports its shared library wants.
/// Connect and query-status rights only, which any user has; the service is never opened for anything else.
/// </summary>
public static partial class ServiceProbe
{
/// <summary>The service name Chronos Server 1.0 installed itself under.</summary>
public const string LegacyServer = "ChronosServer";
private const uint ScManagerConnect = 0x0001;
private const uint ServiceQueryStatus = 0x0004;
private const int ErrorAccessDenied = 5;
/// <summary>True when the service <paramref name="name"/> exists on this PC; false when it does not or the manager cannot be read.</summary>
public static bool IsInstalled(string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
var manager = OpenSCManagerW(null, null, ScManagerConnect);
if (manager == IntPtr.Zero) return false;
try
{
var service = OpenServiceW(manager, name, ServiceQueryStatus);
if (service != IntPtr.Zero)
{
CloseServiceHandle(service);
return true;
}
// A service the user may not even query still exists; any other error (1060, no such service) means it does not.
return Marshal.GetLastPInvokeError() == ErrorAccessDenied;
}
finally
{
CloseServiceHandle(manager);
}
}
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
private static partial IntPtr OpenSCManagerW(string? machine, string? database, uint access);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
private static partial IntPtr OpenServiceW(IntPtr manager, string name, uint access);
[LibraryImport("advapi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool CloseServiceHandle(IntPtr handle);
}
@@ -0,0 +1,91 @@
using System.Globalization;
using Chronos.App.Server;
using Chronos.App.Shell;
using Chronos.Core.Localization;
using Chronos.Core.Windows.Services;
using Chronos.Testing;
namespace Chronos.App.Tests.Server;
/// <summary>
/// The desktop's lifetime while it shares its library (owner review 5, #67): closing hides to the tray while sharing, Exit
/// asks first when clients are active, a start at sign-in waits in the tray; with sharing off nothing changes.
/// </summary>
public sealed class ShareTrayTests
{
public ShareTrayTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public void ChronosOutlivesItsWindowOnlyWhileSharingIsOnOrOnItsWay()
{
Assert.True(ShareLifetime.KeepsRunning(shareEnabled: true, ShareState.On));
Assert.True(ShareLifetime.KeepsRunning(shareEnabled: true, ShareState.Starting));
// On in the settings, not started yet: the index is opening, or the archive's drive is unplugged.
Assert.True(ShareLifetime.KeepsRunning(shareEnabled: true, ShareState.Off));
Assert.False(ShareLifetime.KeepsRunning(shareEnabled: true, ShareState.Failed));
// Turned off and still stopping: the icon stays until it has stopped.
Assert.True(ShareLifetime.KeepsRunning(shareEnabled: false, ShareState.On));
Assert.False(ShareLifetime.KeepsRunning(shareEnabled: false, ShareState.Off));
Assert.False(ShareLifetime.KeepsRunning(shareEnabled: false, ShareState.Failed));
}
[Test]
public void ClosingHidesToTheTrayWhileSharingAndExitsOtherwise()
{
Assert.Equal(CloseAction.HideToTray, ShareLifetime.OnClose(exiting: false, keepsRunning: true));
Assert.Equal(CloseAction.Exit, ShareLifetime.OnClose(exiting: false, keepsRunning: false));
// Tray › Exit, or Windows ending the session: the window closes for real.
Assert.Equal(CloseAction.Exit, ShareLifetime.OnClose(exiting: true, keepsRunning: true));
Assert.Equal(CloseAction.Exit, ShareLifetime.OnClose(exiting: true, keepsRunning: false));
}
[Test]
public void ExitAsksFirstOnlyWhenClientsUseTheSharedLibrary()
{
Assert.True(ShareLifetime.AsksBeforeExit(ShareState.On, 1));
Assert.True(ShareLifetime.AsksBeforeExit(ShareState.On, 3));
Assert.False(ShareLifetime.AsksBeforeExit(ShareState.On, 0));
Assert.False(ShareLifetime.AsksBeforeExit(ShareState.Starting, 2));
Assert.False(ShareLifetime.AsksBeforeExit(ShareState.Failed, 2));
Assert.False(ShareLifetime.AsksBeforeExit(ShareState.Off, 2));
}
[Test]
public void TheExitQuestionKeepsSharingByDefaultAndCountsTheClients()
{
var one = ShellTray.ExitRequest(1);
Assert.Equal("Stop sharing?", one.Heading);
Assert.Equal("1 client used this library in the last minutes. Exiting Chronos stops sharing it.", one.Message);
Assert.Equal(("Keep sharing", "Exit"), (one.SafeText, one.ActionText));
Assert.False(one.IsDestructive);
Assert.Null(one.TypedConfirmation);
Assert.Contains("4 clients used", ShellTray.ExitRequest(4).Message);
}
[Test]
public void AStartAtSignInWaitsInTheTrayWhileSharingIsOn()
{
Assert.Equal(StartWindow.Tray, ShareLifetime.Start(minimized: true, shareEnabled: true));
Assert.Equal(StartWindow.Minimized, ShareLifetime.Start(minimized: true, shareEnabled: false));
Assert.Equal(StartWindow.Shown, ShareLifetime.Start(minimized: false, shareEnabled: true));
Assert.Equal(StartWindow.Shown, ShareLifetime.Start(minimized: false, shareEnabled: false));
}
[Test]
public void TheTrayToolTipNamesTheLibraryOrThisPc()
{
Assert.Equal("Chronos · sharing Studio", ShareLifetime.ToolTip(" Studio ", "STUDIO-PC"));
Assert.Equal("Chronos · sharing STUDIO-PC", ShareLifetime.ToolTip(null, "STUDIO-PC"));
Assert.Equal("Chronos · sharing STUDIO-PC", ShareLifetime.ToolTip(" ", "STUDIO-PC"));
}
[Test]
[WindowsOnly]
public void TheServiceProbeFindsInstalledServicesOnly()
{
// The event log service runs on every Windows; the probe asks connect and query-status rights only.
Assert.True(ServiceProbe.IsInstalled("EventLog"));
Assert.False(ServiceProbe.IsInstalled("ChronosNoSuchService" + Guid.NewGuid().ToString("N")));
Assert.Equal("ChronosServer", ServiceProbe.LegacyServer);
}
}