diff --git a/App.axaml.cs b/App.axaml.cs index 857e08e..c97d40a 100644 --- a/App.axaml.cs +++ b/App.axaml.cs @@ -21,6 +21,10 @@ namespace CxShell; public partial class App : Application { private TrayIcon? _windowsTrayIcon; + private NativeMenuItem? _trayShowWindowItem; + private NativeMenuItem? _trayExitItem; + + public bool HasActiveTrayIcon => _windowsTrayIcon is { IsVisible: true }; public override void Initialize() { @@ -71,6 +75,7 @@ public override void OnFrameworkInitializationCompleted() RegisterAtomUiWindowDecorationsTheme(); desktop.MainWindow = new MainWindow(desktop.Args ?? Array.Empty()); InitializeWindowsTrayIcon(desktop); + desktop.ShutdownRequested += (_, _) => PrepareMainWindowForExit(desktop); desktop.Exit += (_, _) => DisposeWindowsTrayIcon(); } @@ -104,16 +109,20 @@ private void InitializeWindowsTrayIcon(IClassicDesktopStyleApplicationLifetime d if (!OperatingSystem.IsWindows() || desktop.MainWindow is not { } mainWindow) return; - var showWindowItem = new NativeMenuItem("显示 CxShell"); - showWindowItem.Click += (_, _) => ShowMainWindow(desktop); + _trayShowWindowItem = new NativeMenuItem(LocalizationService.Shared.Text("Tray.ShowWindow")); + _trayShowWindowItem.Click += (_, _) => ShowMainWindow(desktop); - var exitItem = new NativeMenuItem("退出"); - exitItem.Click += (_, _) => desktop.Shutdown(); + _trayExitItem = new NativeMenuItem(LocalizationService.Shared.Text("Tray.Exit")); + _trayExitItem.Click += (_, _) => + { + PrepareMainWindowForExit(desktop); + desktop.Shutdown(); + }; var menu = new NativeMenu(); - menu.Items.Add(showWindowItem); + menu.Items.Add(_trayShowWindowItem); menu.Items.Add(new NativeMenuItemSeparator()); - menu.Items.Add(exitItem); + menu.Items.Add(_trayExitItem); _windowsTrayIcon = new TrayIcon { @@ -127,6 +136,21 @@ private void InitializeWindowsTrayIcon(IClassicDesktopStyleApplicationLifetime d var trayIcons = new TrayIcons(); trayIcons.Add(_windowsTrayIcon); TrayIcon.SetIcons(this, trayIcons); + LocalizationService.Shared.LanguageChanged += OnTrayLanguageChanged; + } + + private void OnTrayLanguageChanged(object? sender, EventArgs e) + { + if (_trayShowWindowItem != null) + _trayShowWindowItem.Header = LocalizationService.Shared.Text("Tray.ShowWindow"); + if (_trayExitItem != null) + _trayExitItem.Header = LocalizationService.Shared.Text("Tray.Exit"); + } + + private static void PrepareMainWindowForExit(IClassicDesktopStyleApplicationLifetime desktop) + { + if (desktop.MainWindow is MainWindow mainWindow) + mainWindow.PrepareForExit(); } private static void ShowMainWindow(IClassicDesktopStyleApplicationLifetime desktop) @@ -134,15 +158,20 @@ private static void ShowMainWindow(IClassicDesktopStyleApplicationLifetime deskt if (desktop.MainWindow is not { } mainWindow) return; + if (!mainWindow.IsVisible) + mainWindow.Show(); + if (mainWindow.WindowState == WindowState.Minimized) mainWindow.WindowState = WindowState.Normal; - mainWindow.Show(); mainWindow.Activate(); } private void DisposeWindowsTrayIcon() { + LocalizationService.Shared.LanguageChanged -= OnTrayLanguageChanged; + _trayShowWindowItem = null; + _trayExitItem = null; _windowsTrayIcon?.Dispose(); _windowsTrayIcon = null; TrayIcon.SetIcons(this, new TrayIcons()); diff --git a/CxShell.Tests/ApplicationSettingsStoreTests.cs b/CxShell.Tests/ApplicationSettingsStoreTests.cs index 6d7dbda..c1174e9 100644 --- a/CxShell.Tests/ApplicationSettingsStoreTests.cs +++ b/CxShell.Tests/ApplicationSettingsStoreTests.cs @@ -1,6 +1,8 @@ using System.Text.Json; +using Avalonia.Controls; using CxShell.Models; using CxShell.Services; +using CxShell.Views; namespace CxShell.Tests; @@ -71,6 +73,47 @@ public void SaveAndLoad_PreservesGlobalPanelVisibility() Assert.True(loaded.ShowAgentPanel); } + [Fact] + public void MinimizeToTrayOnClose_DefaultsToTrueAndPersistsChanges() + { + using var directory = new TemporaryDirectory(); + var store = new ApplicationSettingsStore(directory.Path); + + var defaults = new ApplicationSettings(); + Assert.True(defaults.MinimizeToTrayOnClose); + + store.Save(new ApplicationSettings { MinimizeToTrayOnClose = false }); + var loadedDisabled = store.Load(); + Assert.False(loadedDisabled.MinimizeToTrayOnClose); + + store.Save(new ApplicationSettings { MinimizeToTrayOnClose = true }); + var loadedEnabled = store.Load(); + Assert.True(loadedEnabled.MinimizeToTrayOnClose); + } + + [Theory] + [InlineData(false, true, true, WindowCloseReason.WindowClosing, true)] + [InlineData(false, true, false, WindowCloseReason.WindowClosing, false)] + [InlineData(false, false, true, WindowCloseReason.WindowClosing, false)] + [InlineData(true, true, true, WindowCloseReason.WindowClosing, false)] + [InlineData(false, true, true, WindowCloseReason.ApplicationShutdown, false)] + [InlineData(false, true, true, WindowCloseReason.OSShutdown, false)] + public void ShouldMinimizeToTrayOnClose_HandlesCloseReasonsAndGuards( + bool allowClose, + bool hasActiveTrayIcon, + bool minimizeToTrayOnClose, + WindowCloseReason closeReason, + bool expected) + { + var result = MainWindow.ShouldMinimizeToTrayOnClose( + allowClose, + hasActiveTrayIcon, + minimizeToTrayOnClose, + closeReason); + + Assert.Equal(expected, result); + } + [Fact] public void SaveAndLoad_PreservesExternalLaunchSecuritySettings() { diff --git a/Models/SessionInfo.cs b/Models/SessionInfo.cs index eab8df4..611346e 100644 --- a/Models/SessionInfo.cs +++ b/Models/SessionInfo.cs @@ -318,6 +318,7 @@ public class ApplicationSettings public string UiLanguage { get; set; } = "zh-CN"; public string ThemeMode { get; set; } = DarkThemeMode; public bool ShowSessionManagerOnStartup { get; set; } = true; + public bool MinimizeToTrayOnClose { get; set; } = true; public bool AutoCheckForUpdates { get; set; } = true; public bool IncludePrereleaseUpdates { get; set; } public AgentProviderSettings AgentProvider { get; set; } = new(); diff --git a/Services/LocalizationService.cs b/Services/LocalizationService.cs index e93dd5a..bbf514b 100644 --- a/Services/LocalizationService.cs +++ b/Services/LocalizationService.cs @@ -1018,6 +1018,10 @@ static LocalizationService() EnglishTexts["ApplicationSettings.Title"] = "Application Settings"; EnglishTexts["ApplicationSettings.General"] = "Settings that apply to CxShell rather than an individual connection"; EnglishTexts["ApplicationSettings.Startup"] = "Startup"; + EnglishTexts["ApplicationSettings.Window"] = "Window"; + EnglishTexts["ApplicationSettings.MinimizeToTrayOnClose"] = "Minimize to notification area when closing the main window"; + EnglishTexts["Tray.ShowWindow"] = "Show CxShell"; + EnglishTexts["Tray.Exit"] = "Exit"; EnglishTexts["ApplicationSettings.Appearance"] = "Appearance"; EnglishTexts["ApplicationSettings.BackgroundImage"] = "Background Image"; EnglishTexts["ApplicationSettings.BackgroundImageDescription"] = "Used by terminals when the session does not configure its own background image."; @@ -1583,6 +1587,10 @@ static LocalizationService() ChineseTexts["ApplicationSettings.Title"] = "\u5e94\u7528\u8bbe\u7f6e"; ChineseTexts["ApplicationSettings.General"] = "\u8fd9\u4e9b\u8bbe\u7f6e\u9002\u7528\u4e8e CxShell \u6574\u4f53\uff0c\u4e0d\u9488\u5bf9\u5355\u4e2a\u8fde\u63a5"; ChineseTexts["ApplicationSettings.Startup"] = "\u542f\u52a8"; + ChineseTexts["ApplicationSettings.Window"] = "\u7a97\u53e3"; + ChineseTexts["ApplicationSettings.MinimizeToTrayOnClose"] = "\u5173\u95ed\u4e3b\u7a97\u53e3\u65f6\u6700\u5c0f\u5316\u5230\u901a\u77e5\u680f"; + ChineseTexts["Tray.ShowWindow"] = "\u663e\u793a CxShell"; + ChineseTexts["Tray.Exit"] = "\u9000\u51fa"; ChineseTexts["ApplicationSettings.Appearance"] = "\u5916\u89c2"; ChineseTexts["ApplicationSettings.BackgroundImage"] = "\u80cc\u666f\u56fe"; ChineseTexts["ApplicationSettings.BackgroundImageDescription"] = "\u4f1a\u8bdd\u672a\u5355\u72ec\u914d\u7f6e\u80cc\u666f\u56fe\u65f6\uff0c\u7ec8\u7aef\u4f7f\u7528\u6b64\u5168\u5c40\u80cc\u666f\u3002"; diff --git a/ViewModels/ApplicationSettingsViewModel.cs b/ViewModels/ApplicationSettingsViewModel.cs index b898f42..0b8e1d1 100644 --- a/ViewModels/ApplicationSettingsViewModel.cs +++ b/ViewModels/ApplicationSettingsViewModel.cs @@ -55,6 +55,7 @@ public partial class ApplicationSettingsViewModel : ObservableObject public Func>? ConfirmRemoveKnownHostAsync { get; set; } [ObservableProperty] private bool _showSessionManagerOnStartup; + [ObservableProperty] private bool _minimizeToTrayOnClose; [ObservableProperty] private bool _showTabBar; [ObservableProperty] private bool _showSftpPanel; [ObservableProperty] private bool _showMonitorPanel; @@ -118,6 +119,9 @@ public partial class ApplicationSettingsViewModel : ObservableObject public string TitleText => Text("ApplicationSettings.Title"); public string GeneralText => Text("ApplicationSettings.General"); public string StartupText => Text("ApplicationSettings.Startup"); + public string WindowText => Text("ApplicationSettings.Window"); + public string MinimizeToTrayOnCloseText => Text("ApplicationSettings.MinimizeToTrayOnClose"); + public bool IsMinimizeToTraySupported => OperatingSystem.IsWindows(); public string AppearanceText => Text("ApplicationSettings.Appearance"); public string ThemeText => Text("ApplicationSettings.Theme"); public string DarkThemeText => Text("ApplicationSettings.DarkTheme"); @@ -271,6 +275,7 @@ public ApplicationSettingsViewModel( globalProxyProvider: () => GetGlobalProxyIfEnabled()); _showSessionManagerOnStartup = settings.ShowSessionManagerOnStartup; + _minimizeToTrayOnClose = settings.MinimizeToTrayOnClose; _showTabBar = settings.ShowTabBar; _showSftpPanel = settings.ShowSftpPanel; _showMonitorPanel = settings.ShowMonitorPanel; @@ -346,6 +351,12 @@ partial void OnShowSessionManagerOnStartupChanged(bool value) Persist(); } + partial void OnMinimizeToTrayOnCloseChanged(bool value) + { + _settings.MinimizeToTrayOnClose = value; + Persist(); + } + partial void OnShowTabBarChanged(bool value) { _settings.ShowTabBar = value; @@ -936,6 +947,8 @@ private void OnLanguageChanged(object? sender, EventArgs e) OnPropertyChanged(nameof(TitleText)); OnPropertyChanged(nameof(GeneralText)); OnPropertyChanged(nameof(StartupText)); + OnPropertyChanged(nameof(WindowText)); + OnPropertyChanged(nameof(MinimizeToTrayOnCloseText)); OnPropertyChanged(nameof(AppearanceText)); OnPropertyChanged(nameof(ThemeText)); OnPropertyChanged(nameof(DarkThemeText)); diff --git a/Views/ApplicationSettingsPage.axaml b/Views/ApplicationSettingsPage.axaml index c9ab66e..ebb776d 100644 --- a/Views/ApplicationSettingsPage.axaml +++ b/Views/ApplicationSettingsPage.axaml @@ -20,6 +20,20 @@ + + + + + + + + + + + + + + ()) @@ -139,6 +141,8 @@ public MainWindow(string[] startupArgs) WriteToolbarDiagnostics("MainWindow initialized; toolbar menus use AtomUI ContextMenu."); Closed += (_, _) => { + _commandLineHandoffServer?.Dispose(); + _commandLineHandoffServer = null; CloseTabDragGhost(); DetachedTabWindow.CloseAll(); vm.Dispose(); @@ -163,6 +167,39 @@ public MainWindow(string[] startupArgs) QueueApplySftpPanelWidth(vm); } + public void PrepareForExit() + { + _allowClose = true; + } + + internal static bool ShouldMinimizeToTrayOnClose( + bool allowClose, + bool hasActiveTrayIcon, + bool minimizeToTrayOnClose, + Avalonia.Controls.WindowCloseReason closeReason) + { + if (allowClose || !hasActiveTrayIcon || !minimizeToTrayOnClose) + return false; + + return closeReason is not ( + Avalonia.Controls.WindowCloseReason.ApplicationShutdown or + Avalonia.Controls.WindowCloseReason.OSShutdown); + } + + protected override void OnClosing(Avalonia.Controls.WindowClosingEventArgs e) + { + var hasActiveTrayIcon = Avalonia.Application.Current is App { HasActiveTrayIcon: true }; + var minimizeToTray = SessionTreeViewModel.SharedSettings?.MinimizeToTrayOnClose ?? true; + if (ShouldMinimizeToTrayOnClose(_allowClose, hasActiveTrayIcon, minimizeToTray, e.CloseReason)) + { + e.Cancel = true; + Hide(); + return; + } + + base.OnClosing(e); + } + protected override void OnLoaded(RoutedEventArgs e) { base.OnLoaded(e); @@ -172,9 +209,14 @@ protected override void OnLoaded(RoutedEventArgs e) $"leftVisible={LeftToolbarAddOn.IsVisible}; rightVisible={RightToolbarAddOn.IsVisible}."), DispatcherPriority.ApplicationIdle); StartCommandLineHandoffServer(); - StartRdpSmokeIfRequested(); - HandleCommandLineLaunchIfRequested(); - ShowSessionManagerOnStartupIfNeeded(); + var isInitialLoad = !_hasCompletedInitialLoad; + _hasCompletedInitialLoad = true; + if (isInitialLoad) + { + StartRdpSmokeIfRequested(); + HandleCommandLineLaunchIfRequested(); + ShowSessionManagerOnStartupIfNeeded(); + } if (DataContext is MainWindowViewModel vm) { AttachTabReorderHandlers(); @@ -189,7 +231,8 @@ protected override void OnLoaded(RoutedEventArgs e) _isQuickSessionActivationReady = true; }, DispatcherPriority.ApplicationIdle); UpdateApplicationSuspension(vm); - vm.StartAutomaticUpdateCheck(_startupArgs); + if (isInitialLoad) + vm.StartAutomaticUpdateCheck(_startupArgs); } } @@ -201,8 +244,6 @@ protected override void OnUnloaded(RoutedEventArgs e) DetachTabReorderHandlers(); if (DataContext is MainWindowViewModel vm) vm.SetApplicationSuspended(true); - _commandLineHandoffServer?.Dispose(); - _commandLineHandoffServer = null; base.OnUnloaded(e); } @@ -1615,6 +1656,9 @@ private Task HandleCommandLineHandoffAsync(string[] args) { try { + if (!IsVisible) + Show(); + if (WindowState == Avalonia.Controls.WindowState.Minimized) WindowState = Avalonia.Controls.WindowState.Normal;