diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3fd72db4..8607ec06 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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 diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index a390f98b..f02f2b34 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -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 | diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index 54bb31c8..6712d588 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -208,6 +208,7 @@ Copy Fingerprint Hide + 1.0 server installed None Ports HTTPS {0} · HTTP {1} diff --git a/i18n/en/Shell.resx b/i18n/en/Shell.resx index e8b4e776..533c0004 100644 --- a/i18n/en/Shell.resx +++ b/i18n/en/Shell.resx @@ -5,6 +5,10 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Chronosinvariant + Stop sharing? + Keep sharing + {0} client used this library in the last minutes. Exiting Chronos stops sharing it.long; {0} count; confirmation under Stop sharing? + {0} clients used this library in the last minutes. Exiting Chronos stops sharing it.long; {0} count; confirmation under Stop sharing? Server ID clash {0} project moved{0} count {0} projects moved{0} count @@ -40,6 +44,11 @@ {0:N0} photos {0:N0} sequence {0:N0} sequences + Exit + Still sharing + Chronos keeps sharing this library from the notification area. Exit there stops it.long; Windows notification under Still sharing + Open Chronos + Chronos · sharing {0}tray tooltip; {0} the library's name Show Chronos Adopt an existing folder Change… diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index d900793e..f9273fbe 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -715,6 +715,7 @@ Copy the fingerprint Copy the temporary password Clients see this fingerprint the first time they connect; it must match + 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 The ports the shared library listens on Try to start sharing again Open Settings › Server to share this library @@ -930,6 +931,8 @@ No program is selected: remove the whole installation · the next step shows what goes Update the installed programs in place and apply the changes listed · your data is kept Collapse navigation to icons · Ctrl+B + Stop sharing and close Chronos; the clients lose this library until Chronos runs again + Keep Chronos running in the notification area, sharing this library Show navigation names · Ctrl+B Show the logs folder in Explorer: the log says which folder could not be sorted Pause the job shown; it continues from its checkpoint when resumed diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index 95fc5649..29604c34 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -206,6 +206,7 @@ Copia Impronta Nascondi + Server 1.0 installato Nessuno Porte HTTPS {0} · HTTP {1} diff --git a/i18n/it/Shell.it.resx b/i18n/it/Shell.it.resx index 13b193e9..d121feb6 100644 --- a/i18n/it/Shell.it.resx +++ b/i18n/it/Shell.it.resx @@ -4,6 +4,10 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Interrompere la condivisione? + Continua a condividere + {0} client ha usato questa libreria negli ultimi minuti. Uscendo da Chronos la condivisione si interrompe. + {0} client hanno usato questa libreria negli ultimi minuti. Uscendo da Chronos la condivisione si interrompe. ID server in conflitto {0} progetto spostato {0} progetti spostati @@ -39,6 +43,11 @@ {0:N0} foto {0:N0} sequenza {0:N0} sequenze + Esci + Condivisione attiva + Chronos continua a condividere questa libreria dall'area di notifica. Esci, lì, la interrompe. + Apri Chronos + Chronos · condivide {0} Mostra Chronos Adotta una cartella esistente Cambia… diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index bf528ceb..9d180c50 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -786,6 +786,7 @@ Copia l'impronta Copia la password temporanea I client vedono questa impronta la prima volta che si connettono; deve coincidere + Su questo PC è installato il servizio Windows di Chronos Server 1.0: potrebbe occupare le stesse porte. Il setup di Chronos può rimuoverlo Le porte su cui ascolta la libreria condivisa Riprova ad avviare la condivisione Apri Impostazioni › Server per condividere questa libreria @@ -1031,6 +1032,8 @@ Nessun programma selezionato: rimuovi l'intera installazione · il passo successivo mostra cosa viene rimosso Aggiorna sul posto i programmi installati e applica le modifiche elencate · i tuoi dati restano Riduci la navigazione alle icone · Ctrl+B + Interrompi la condivisione e chiudi Chronos; i client perdono questa libreria finché Chronos non si riavvia + Lascia Chronos attivo nell'area di notifica, a condividere questa libreria Mostra i nomi della navigazione · Ctrl+B Mostra la cartella dei log in Esplora file: il log dice quale cartella non è stata riordinata Mette in pausa l'attività mostrata; quando la riprendi continua dal punto di ripresa diff --git a/src/Chronos.App/App.xaml.cs b/src/Chronos.App/App.xaml.cs index 9accf2d9..cccc84ae 100644 --- a/src/Chronos.App/App.xaml.cs +++ b/src/Chronos.App/App.xaml.cs @@ -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(); } /// Settings › Advanced › Logs to the log files, from the next line on (owner review 2, R11). @@ -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 diff --git a/src/Chronos.App/Sections/ServerView.xaml b/src/Chronos.App/Sections/ServerView.xaml index dc43e909..9993b55a 100644 --- a/src/Chronos.App/Sections/ServerView.xaml +++ b/src/Chronos.App/Sections/ServerView.xaml @@ -72,6 +72,8 @@ + diff --git a/src/Chronos.App/Sections/SharePanelViewModel.cs b/src/Chronos.App/Sections/SharePanelViewModel.cs index 387b2300..fe22e423 100644 --- a/src/Chronos.App/Sections/SharePanelViewModel.cs +++ b/src/Chronos.App/Sections/SharePanelViewModel.cs @@ -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 on the UI thread; the clients are read again every few seconds. +/// Sharing settings. Follows 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. /// 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 _legacyService; private bool _showPassword; + private bool _hasLegacyService; - public SharePanelViewModel(ShellViewModel shell) + /// The shell whose shared library the panel shows. + /// Whether the 1.0 Windows Server is installed; the Service Control Manager by default (never during screenshots). + public SharePanelViewModel(ShellViewModel shell, Func? 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; + /// The 1.0 Windows Server's service is installed: it may hold the same ports, and the setup can remove it. + 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(); } diff --git a/src/Chronos.App/Server/LibraryShare.cs b/src/Chronos.App/Server/LibraryShare.cs index 7c9adfc4..fbb1f426 100644 --- a/src/Chronos.App/Server/LibraryShare.cs +++ b/src/Chronos.App/Server/LibraryShare.cs @@ -250,6 +250,24 @@ public sealed class LibraryShare : ObservableObject, IAsyncDisposable AdminPassword = server.AdminPassword(); } + /// + /// 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. + /// + public async Task 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; + } + /// The uploads clean-up step while sharing (): the server's sweep, or nothing. public Task SweepUploadsAsync(CleanupContext context, CleanupParameters parameters) => _server is { } server ? server.SweepUploadsAsync(context, parameters) : Task.FromResult(Loc.L("Server.Log.SharingOff")); diff --git a/src/Chronos.App/Shell/MainWindow.xaml.cs b/src/Chronos.App/Shell/MainWindow.xaml.cs index fc05b0b1..70e59e35 100644 --- a/src/Chronos.App/Shell/MainWindow.xaml.cs +++ b/src/Chronos.App/Shell/MainWindow.xaml.cs @@ -39,6 +39,9 @@ public partial class MainWindow : ChronosWindow Closed += (_, _) => _notifications.Dispose(); } + /// The Windows notifications of the toasts nobody sees (the shared library's tray icon carries them while sharing). + internal OsNotifications Notifications => _notifications; + /// Started at sign-in (Settings › General › Startup): the window waits minimised on the taskbar. internal static bool StartsMinimized(IReadOnlyList 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; } + /// + /// 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. + /// + internal void ShowMinimized() + { + if (WindowState != WindowState.Minimized) WaitMinimized(WindowState == WindowState.Maximized); + Show(); + } + /// The maximised flag to save: a window started minimised and never opened keeps the state it would come back to. internal static bool SavesMaximized(WindowState state, WindowState? restoreTo) => state == WindowState.Maximized || (state == WindowState.Minimized && restoreTo == WindowState.Maximized); diff --git a/src/Chronos.App/Shell/OsNotifications.cs b/src/Chronos.App/Shell/OsNotifications.cs index 53fd31e8..231449cc 100644 --- a/src/Chronos.App/Shell/OsNotifications.cs +++ b/src/Chronos.App/Shell/OsNotifications.cs @@ -40,15 +40,21 @@ public sealed class OsNotifications : IDisposable /// The tray icon is in the notification area (tests). internal bool HasTrayIcon => _tray is not null; + /// + /// The persistent tray icon while the library is shared (): the balloons go there instead of a + /// second icon of their own, and its balloon clicks come back to . Null otherwise. + /// + internal TrayIcon? SharedIcon { get; set; } + /// Mirrors as a Windows notification when nobody sees the window; true when it did. 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 /// 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(); diff --git a/src/Chronos.App/Shell/ShareLifetime.cs b/src/Chronos.App/Shell/ShareLifetime.cs new file mode 100644 index 00000000..5149ca02 --- /dev/null +++ b/src/Chronos.App/Shell/ShareLifetime.cs @@ -0,0 +1,61 @@ +using Chronos.App.Server; +using Chronos.Core.Localization; + +namespace Chronos.App.Shell; + +/// How the main window appears when Chronos starts. +public enum StartWindow +{ + /// On screen, as the user left it. + Shown, + + /// Started at sign-in: minimised on the taskbar. + Minimized, + + /// Started at sign-in while sharing: hidden, only the tray icon shows. + Tray, +} + +/// What closing the main window does. +public enum CloseAction +{ + /// Chronos ends (sharing, if any, stops first). + Exit, + + /// The window hides; Chronos keeps sharing from the tray icon. + HideToTray, +} + +/// +/// 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 . +/// +public static class ShareLifetime +{ + /// + /// 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. + /// + public static bool KeepsRunning(bool shareEnabled, ShareState state) => state switch + { + ShareState.On or ShareState.Starting => true, + ShareState.Off => shareEnabled, + _ => false, + }; + + /// Closing the window hides it while sharing, unless the user chose Exit (or Windows is ending the session). + public static CloseAction OnClose(bool exiting, bool keepsRunning) => !exiting && keepsRunning ? CloseAction.HideToTray : CloseAction.Exit; + + /// Exit asks first when programs used the shared library in the last minutes or render nodes are online. + public static bool AsksBeforeExit(ShareState state, int activeClients) => state == ShareState.On && activeClients > 0; + + /// A start at sign-in (--minimized) waits in the tray while sharing is on, else minimised on the taskbar. + public static StartWindow Start(bool minimized, bool shareEnabled) => + !minimized ? StartWindow.Shown : shareEnabled ? StartWindow.Tray : StartWindow.Minimized; + + /// The tray icon's hover text: "Chronos · sharing studio-pc" (the name clients see; empty: this PC's name). + public static string ToolTip(string? name, string machineName) => + Loc.L("Shell.Tray.Sharing", string.IsNullOrWhiteSpace(name) ? machineName : name.Trim()); +} diff --git a/src/Chronos.App/Shell/ShellTray.cs b/src/Chronos.App/Shell/ShellTray.cs new file mode 100644 index 00000000..14f8f205 --- /dev/null +++ b/src/Chronos.App/Shell/ShellTray.cs @@ -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; + +/// +/// The desktop's tray while it shares its library (owner review 5, #67, design §2.5): while +/// 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. +/// +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; + } + + /// Chronos outlives its window now: sharing is on or on its way. + public bool KeepsRunning => ShareLifetime.KeepsRunning(_shell.Services.Settings.Share.Enabled, _share.State); + + /// + /// 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. + /// + 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(); + } + + /// The window in front, as it was before it was hidden or minimised. + public void Open() + { + if (_disposed) return; + _window.Show(); + if (_window.WindowState == WindowState.Minimized) _window.WindowState = WindowState.Normal; + _window.Activate(); + } + + /// + /// 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. + /// + 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(); + } + + /// The confirmation of Exit while clients use the library: Keep sharing is the safe, default choice. + 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 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); + } + } + + /// Closing hides the window while sharing; the first time, a balloon says Chronos goes on sharing. + 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; + + /// Windows is signing out or shutting down: the window closes for real (WPF closes it without waiting anyway). + 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; + } +} diff --git a/src/Chronos.Core.Windows/Services/ServiceProbe.cs b/src/Chronos.Core.Windows/Services/ServiceProbe.cs new file mode 100644 index 00000000..cc3f93ce --- /dev/null +++ b/src/Chronos.Core.Windows/Services/ServiceProbe.cs @@ -0,0 +1,51 @@ +using System.Runtime.InteropServices; + +namespace Chronos.Core.Windows.Services; + +/// +/// 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 () 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. +/// +public static partial class ServiceProbe +{ + /// The service name Chronos Server 1.0 installed itself under. + public const string LegacyServer = "ChronosServer"; + + private const uint ScManagerConnect = 0x0001; + private const uint ServiceQueryStatus = 0x0004; + private const int ErrorAccessDenied = 5; + + /// True when the service exists on this PC; false when it does not or the manager cannot be read. + 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); +} diff --git a/tests/Chronos.App.Tests/Server/ShareTrayTests.cs b/tests/Chronos.App.Tests/Server/ShareTrayTests.cs new file mode 100644 index 00000000..eb20530e --- /dev/null +++ b/tests/Chronos.App.Tests/Server/ShareTrayTests.cs @@ -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; + +/// +/// 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. +/// +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); + } +}