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/AppDataPathsTests.cs b/CxShell.Tests/AppDataPathsTests.cs new file mode 100644 index 0000000..4e3c3bc --- /dev/null +++ b/CxShell.Tests/AppDataPathsTests.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; +using CxShell.Services; + +namespace CxShell.Tests; + +public sealed class AppDataPathsTests +{ + [Fact] + public void Resolve_EntersPortableModeWhenDataFolderExistsNextToExecutable() + { + using var root = new TemporaryDirectory(); + var exeDir = Path.Combine(root.Path, "portable-app"); + var dataDir = Path.Combine(exeDir, "data"); + Directory.CreateDirectory(dataDir); + + var resolved = AppDataPaths.Resolve( + exeDir, + Directory.Exists, + () => Path.Combine(root.Path, "roaming"), + () => Path.Combine(root.Path, "local"), + exeDir); + + Assert.True(resolved.IsPortableMode); + Assert.Equal(Path.GetFullPath(dataDir), resolved.StorageDirectory); + Assert.Equal(Path.GetFullPath(dataDir), resolved.LocalCacheDirectory); + Assert.Equal(Path.Combine(Path.GetFullPath(dataDir), "Logs"), resolved.LogsDirectory); + } + + [Fact] + public void Resolve_UsesInstalledDirectoriesWhenDataFolderIsMissing() + { + using var root = new TemporaryDirectory(); + var exeDir = Path.Combine(root.Path, "installed-app"); + var roamingRoot = Path.Combine(root.Path, "roaming"); + var localRoot = Path.Combine(root.Path, "local"); + Directory.CreateDirectory(exeDir); + + var resolved = AppDataPaths.Resolve( + exeDir, + Directory.Exists, + () => roamingRoot, + () => localRoot, + exeDir); + + Assert.False(resolved.IsPortableMode); + Assert.Equal(Path.Combine(Path.GetFullPath(roamingRoot), "CxShell"), resolved.StorageDirectory); + Assert.Equal(Path.Combine(Path.GetFullPath(localRoot), "CxShell"), resolved.LocalCacheDirectory); + Assert.Equal(Path.Combine(Path.GetFullPath(localRoot), "CxShell", "Logs"), resolved.LogsDirectory); + } + + private sealed class TemporaryDirectory : IDisposable + { + public TemporaryDirectory() + { + Path = System.IO.Path.Combine( + System.IO.Path.GetTempPath(), + $"cxshell-portable-tests-{Guid.NewGuid():N}"); + Directory.CreateDirectory(Path); + } + + public string Path { get; } + + public void Dispose() + { + try + { + Directory.Delete(Path, recursive: true); + } + catch + { + // Best-effort cleanup for test artifacts. + } + } + } +} 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/CxShell.Tests/SingleInstanceChannelTests.cs b/CxShell.Tests/SingleInstanceChannelTests.cs new file mode 100644 index 0000000..956f431 --- /dev/null +++ b/CxShell.Tests/SingleInstanceChannelTests.cs @@ -0,0 +1,121 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using CxShell.Services; + +namespace CxShell.Tests; + +public sealed class SingleInstanceChannelTests +{ + [Fact] + public async Task SingleInstanceChannel_BlocksSecondInstanceInSameDataDirAndForwardsArguments() + { + using var dataDir = new TemporaryDirectory(); + var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + using var first = new SingleInstanceChannel(dataDir.Path, isPortableMode: true); + Assert.True(first.IsFirstInstance); + + using var second = new SingleInstanceChannel(dataDir.Path, isPortableMode: true); + Assert.False(second.IsFirstInstance); + Assert.Equal(first.PipeName, second.PipeName); + + // Send before handler is attached to verify pending messages are buffered and flushed on AttachHandler. + var sent = second.SendToFirstInstance(["-url", "ssh://ops@example.test:22"]); + Assert.True(sent); + + first.AttachHandler(args => + { + received.TrySetResult(args); + return Task.CompletedTask; + }); + + var delivered = await received.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal(["-url", "ssh://ops@example.test:22"], delivered); + } + + [Fact] + public async Task SingleInstanceChannel_ForwardsEmptyActivationPing() + { + using var dataDir = new TemporaryDirectory(); + var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + using var first = new SingleInstanceChannel(dataDir.Path, isPortableMode: true); + first.AttachHandler(args => + { + received.TrySetResult(args); + return Task.CompletedTask; + }); + + using var second = new SingleInstanceChannel(dataDir.Path, isPortableMode: true); + Assert.False(second.IsFirstInstance); + Assert.True(second.SendToFirstInstance([])); + + var delivered = await received.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Empty(delivered); + } + + [Fact] + public void SingleInstanceChannel_AllowsInstalledAndPortableInstancesSimultaneously() + { + using var installedDir = new TemporaryDirectory(); + using var portableDir = new TemporaryDirectory(); + + using var installedInstance = new SingleInstanceChannel(installedDir.Path, isPortableMode: false); + using var portableInstance = new SingleInstanceChannel(portableDir.Path, isPortableMode: true); + + Assert.True(installedInstance.IsFirstInstance); + Assert.True(portableInstance.IsFirstInstance); + Assert.NotEqual(installedInstance.PipeName, portableInstance.PipeName); + Assert.NotEqual(installedInstance.LockFilePath, portableInstance.LockFilePath); + } + + [Fact] + public void SingleInstanceChannel_ReleasesLockOnDispose() + { + using var dataDir = new TemporaryDirectory(); + + var first = new SingleInstanceChannel(dataDir.Path, isPortableMode: true); + Assert.True(first.IsFirstInstance); + first.Dispose(); + + using var restarted = new SingleInstanceChannel(dataDir.Path, isPortableMode: true); + Assert.True(restarted.IsFirstInstance); + } + + [Theory] + [InlineData(new string[0], false)] + [InlineData(new[] { "-url", "ssh://ops@example.test:22" }, false)] + [InlineData(new[] { "-newwin" }, true)] + [InlineData(new[] { "--newwin", "-url", "ssh://ops@example.test:22" }, true)] + [InlineData(new[] { "--rdp-smoke" }, true)] + public void ShouldBypassSingleInstance_RespectsExplicitNewWindowAndSmokeArgs(string[] args, bool expected) + { + Assert.Equal(expected, CommandLineHandoffService.ShouldBypassSingleInstance(args)); + } + + private sealed class TemporaryDirectory : IDisposable + { + public TemporaryDirectory() + { + Path = System.IO.Path.Combine( + System.IO.Path.GetTempPath(), + $"cxshell-single-instance-tests-{Guid.NewGuid():N}"); + Directory.CreateDirectory(Path); + } + + public string Path { get; } + + public void Dispose() + { + try + { + Directory.Delete(Path, recursive: true); + } + catch + { + // Best-effort cleanup for test artifacts. + } + } + } +} 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/Program.cs b/Program.cs index 0df4e18..272479e 100644 --- a/Program.cs +++ b/Program.cs @@ -16,11 +16,14 @@ public static void Main(string[] args) .SetArgs(args) .Run(); - if (CommandLineHandoffService.TrySendToExistingInstance(args)) + if (!CommandLineHandoffService.TryAcquireSingleInstanceOrForward(args, out var singleInstance)) return; - BuildAvaloniaApp() - .StartWithClassicDesktopLifetime(args); + using (singleInstance) + { + BuildAvaloniaApp() + .StartWithClassicDesktopLifetime(args); + } } public static AppBuilder BuildAvaloniaApp() diff --git a/Services/Agent/AgentRunHistoryStore.cs b/Services/Agent/AgentRunHistoryStore.cs index 2e58f69..e670d5e 100644 --- a/Services/Agent/AgentRunHistoryStore.cs +++ b/Services/Agent/AgentRunHistoryStore.cs @@ -32,8 +32,7 @@ public SqliteAgentRunHistoryStore(string? legacyHistoryPath = null) var isDefaultPath = string.IsNullOrWhiteSpace(legacyHistoryPath); _legacyHistoryPath = isDefaultPath ? Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), - "CxShell", + AppDataPaths.GetLocalCacheDirectory(), "agent-runs.json") : Path.GetFullPath(legacyHistoryPath!); _legacyRecoveryPath = _legacyHistoryPath + ".recovery"; diff --git a/Services/Agent/SqliteAgentConversationHistoryStore.cs b/Services/Agent/SqliteAgentConversationHistoryStore.cs index caf6f75..0c8dc35 100644 --- a/Services/Agent/SqliteAgentConversationHistoryStore.cs +++ b/Services/Agent/SqliteAgentConversationHistoryStore.cs @@ -40,14 +40,12 @@ public SqliteAgentConversationHistoryStore(string? filePath = null, string? lega : Path.GetFullPath(filePath!); _legacyFilePath = string.IsNullOrWhiteSpace(legacyFilePath) ? Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), - "CxShell", + AppDataPaths.GetLocalCacheDirectory(), "agent-history.json") : Path.GetFullPath(legacyFilePath); _legacyDatabasePath = isDefaultPath ? Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), - "CxShell", + AppDataPaths.GetLocalCacheDirectory(), "agent-history.db") : string.Empty; diff --git a/Services/AppDataPaths.cs b/Services/AppDataPaths.cs new file mode 100644 index 0000000..fc273a0 --- /dev/null +++ b/Services/AppDataPaths.cs @@ -0,0 +1,161 @@ +using System; +using System.IO; + +namespace CxShell.Services; + +/// +/// Resolves CxShell's storage, cache, and log directories. When a data +/// directory exists next to the running executable (or AppImage on Linux), +/// CxShell enters portable mode and keeps all runtime data inside that folder. +/// +public static class AppDataPaths +{ + private const string CurrentAppDirectoryName = "CxShell"; + private const string PortableDirectoryName = "data"; + + private static readonly Lazy Cached = new(ResolveCurrentProcessPaths); + + public static bool IsPortableMode => Cached.Value.IsPortableMode; + + public static string GetStorageDirectory() => Cached.Value.StorageDirectory; + + public static string GetLocalCacheDirectory() => Cached.Value.LocalCacheDirectory; + + public static string GetLogsDirectory() => Cached.Value.LogsDirectory; + + internal static ResolvedPaths Resolve( + string? executableDirectory, + Func directoryExists, + Func resolveInstalledStorageRoot, + Func resolveInstalledLocalRoot, + string? fallbackBaseDirectory = null) + { + if (!string.IsNullOrWhiteSpace(executableDirectory)) + { + var portableDir = TryGetFullPath(Path.Combine(executableDirectory, PortableDirectoryName)); + if (!string.IsNullOrWhiteSpace(portableDir) && directoryExists(portableDir)) + { + return new ResolvedPaths( + IsPortableMode: true, + StorageDirectory: portableDir, + LocalCacheDirectory: portableDir, + LogsDirectory: Path.Combine(portableDir, "Logs")); + } + } + + var installedRoot = TryGetFullPath(resolveInstalledStorageRoot()); + var storageDir = !string.IsNullOrWhiteSpace(installedRoot) + ? Path.Combine(installedRoot, CurrentAppDirectoryName) + : Path.Combine(fallbackBaseDirectory ?? AppContext.BaseDirectory, ".cxshell-data"); + + var localRoot = TryGetFullPath(resolveInstalledLocalRoot()); + var localCacheDir = !string.IsNullOrWhiteSpace(localRoot) + ? Path.Combine(localRoot, CurrentAppDirectoryName) + : storageDir; + + return new ResolvedPaths( + IsPortableMode: false, + StorageDirectory: storageDir, + LocalCacheDirectory: localCacheDir, + LogsDirectory: Path.Combine(localCacheDir, "Logs")); + } + + internal static string? GetExecutableDirectory() + { + if (OperatingSystem.IsLinux()) + { + var appImage = Environment.GetEnvironmentVariable("APPIMAGE"); + if (!string.IsNullOrWhiteSpace(appImage) && File.Exists(appImage)) + { + var appImageDir = Path.GetDirectoryName(appImage); + if (!string.IsNullOrWhiteSpace(appImageDir)) + return appImageDir; + } + } + + var processPath = Environment.ProcessPath; + if (!string.IsNullOrWhiteSpace(processPath)) + { + var processDir = Path.GetDirectoryName(processPath); + if (!string.IsNullOrWhiteSpace(processDir)) + return processDir; + } + + return AppContext.BaseDirectory; + } + + private static ResolvedPaths ResolveCurrentProcessPaths() + { + return Resolve( + GetExecutableDirectory(), + Directory.Exists, + ResolveInstalledStorageRoot, + ResolveInstalledLocalRoot, + AppContext.BaseDirectory); + } + + private static string? ResolveInstalledStorageRoot() + { + var appData = TryGetFullPath(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); + if (!string.IsNullOrWhiteSpace(appData)) + return appData; + + if (OperatingSystem.IsWindows()) + return null; + + var xdgConfigHome = TryGetFullPath(Environment.GetEnvironmentVariable("XDG_CONFIG_HOME")); + if (!string.IsNullOrWhiteSpace(xdgConfigHome)) + return xdgConfigHome; + + var userProfile = TryGetFullPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); + if (!string.IsNullOrWhiteSpace(userProfile)) + { + return OperatingSystem.IsMacOS() + ? Path.Combine(userProfile, "Library", "Application Support") + : Path.Combine(userProfile, ".config"); + } + + return null; + } + + private static string? ResolveInstalledLocalRoot() + { + var localAppData = TryGetFullPath(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); + if (!string.IsNullOrWhiteSpace(localAppData)) + return localAppData; + + if (OperatingSystem.IsWindows()) + return null; + + var xdgCacheHome = TryGetFullPath(Environment.GetEnvironmentVariable("XDG_CACHE_HOME")); + if (!string.IsNullOrWhiteSpace(xdgCacheHome)) + return xdgCacheHome; + + return ResolveInstalledStorageRoot(); + } + + private static string? TryGetFullPath(string? path) + { + if (string.IsNullOrWhiteSpace(path)) + return null; + + try + { + var expanded = Environment.ExpandEnvironmentVariables(path); + if (!Path.IsPathFullyQualified(expanded)) + return null; + + return Path.GetFullPath(expanded); + } + catch + { + return null; + } + } + + internal sealed record ResolvedPaths( + bool IsPortableMode, + string StorageDirectory, + string LocalCacheDirectory, + string LogsDirectory); +} diff --git a/Services/CommandLineHandoffService.cs b/Services/CommandLineHandoffService.cs index 1a50217..64460cd 100644 --- a/Services/CommandLineHandoffService.cs +++ b/Services/CommandLineHandoffService.cs @@ -1,133 +1,59 @@ using System; -using System.IO; -using System.IO.Pipes; -using System.Security.Cryptography; -using System.Text; -using System.Text.Json; -using System.Threading; using System.Threading.Tasks; namespace CxShell.Services; public static class CommandLineHandoffService { - private const int ConnectTimeoutMilliseconds = 350; - private const int MaximumPayloadBytes = 64 * 1024; - private static readonly string UserScope = BuildUserScope(); - private static readonly string PipeName = $"CxShell.CommandLineLaunch.v1.{UserScope}"; - private static readonly string MutexName = $"CxShell.CommandLineLaunch.Mutex.v1.{UserScope}"; - - public static bool TrySendToExistingInstance(string[] args) + private static readonly object ChannelGate = new(); + private static SingleInstanceChannel? _activeChannel; + + /// + /// Attempts to claim single-instance ownership for the current data + /// directory. When another instance already owns the same data directory, + /// forwards the launch arguments (or an activation ping when empty) to that + /// instance and returns so this process can exit. + /// + public static bool TryAcquireSingleInstanceOrForward(string[] args, out IDisposable? instanceLifetime) { - if (!ShouldForwardToExistingInstance(args)) - return false; + instanceLifetime = null; + if (ShouldBypassSingleInstance(args)) + return true; - try - { - using var client = new NamedPipeClientStream( - ".", - PipeName, - PipeDirection.InOut, - PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); - client.Connect(ConnectTimeoutMilliseconds); - - using var writer = new StreamWriter(client, new UTF8Encoding(false), leaveOpen: true) - { - AutoFlush = true - }; - writer.WriteLine(EncodePayload(args)); - - using var acknowledgementTimeout = new CancellationTokenSource(ConnectTimeoutMilliseconds); - var acknowledgement = new byte[1]; - var read = client.ReadAsync( - acknowledgement.AsMemory(0, 1), - acknowledgementTimeout.Token) - .GetAwaiter() - .GetResult(); - return read == 1 && acknowledgement[0] == 1; - } - catch + var channel = new SingleInstanceChannel(); + if (channel.IsFirstInstance) { - return false; - } - } - - public static IDisposable StartServer(Func handler) - { - var mutex = TryAcquireServerMutex(); - if (mutex == null) - return NoopDisposable.Instance; - - var cts = new CancellationTokenSource(); - var task = Task.Run(() => RunServerAsync(handler, cts.Token)); - return new ServerLifetime(cts, mutex, task); - } + lock (ChannelGate) + _activeChannel = channel; - private static bool ShouldForwardToExistingInstance(string[] args) - { - if (args.Length == 0 || ContainsArgument(args, "--rdp-smoke")) - return false; + instanceLifetime = new ChannelRegistration(channel); + return true; + } - var options = CommandLineLaunchOptions.Parse(args); - return options.HasCommand && !options.NewWindow; + channel.SendToFirstInstance(args); + channel.Dispose(); + return false; } - private static async Task RunServerAsync(Func handler, CancellationToken cancellationToken) + public static void AttachHandler(Func handler) { - while (!cancellationToken.IsCancellationRequested) - { - try - { - await using var server = CreateServerStream(); - await server.WaitForConnectionAsync(cancellationToken); - - using var reader = new StreamReader(server, Encoding.UTF8, leaveOpen: true); - var line = await reader.ReadLineAsync(cancellationToken); - var accepted = TryDecodePayload(line, out var args); - await server.WriteAsync( - new[] { accepted ? (byte)1 : (byte)0 }, - cancellationToken); - await server.FlushAsync(cancellationToken); - if (accepted) - await handler(args); - } - catch (OperationCanceledException) - { - break; - } - catch - { - await Task.Delay(200, cancellationToken).ContinueWith(_ => { }, TaskScheduler.Default); - } - } - } + SingleInstanceChannel? channel; + lock (ChannelGate) + channel = _activeChannel; - private static NamedPipeServerStream CreateServerStream() - { - return new NamedPipeServerStream( - PipeName, - PipeDirection.In, - 1, - PipeTransmissionMode.Byte, - PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + channel?.AttachHandler(handler); } - private static Mutex? TryAcquireServerMutex() + internal static bool ShouldBypassSingleInstance(string[] args) { - try - { - var mutex = new Mutex(true, MutexName, out var createdNew); - if (createdNew) - return mutex; + if (args.Length == 0) + return false; - mutex.Dispose(); - } - catch - { - // If mutex creation fails, avoid starting a second command receiver. - } + if (ContainsArgument(args, "--rdp-smoke")) + return true; - return null; + var options = CommandLineLaunchOptions.Parse(args); + return options.NewWindow; } private static bool ContainsArgument(string[] args, string expected) @@ -141,72 +67,19 @@ private static bool ContainsArgument(string[] args, string expected) return false; } - private static string EncodePayload(string[] args) - { - var json = JsonSerializer.SerializeToUtf8Bytes(new HandoffPayload(args), AppJsonOptions.Default); - return Convert.ToBase64String(json); - } - - private static bool TryDecodePayload(string? payload, out string[] args) - { - args = []; - if (string.IsNullOrWhiteSpace(payload) || payload.Length > MaximumPayloadBytes) - return false; - - try - { - var json = Convert.FromBase64String(payload.Trim()); - var decoded = JsonSerializer.Deserialize(json, AppJsonOptions.Default); - if (decoded?.Args is not { Length: > 0 } decodedArgs) - return false; - - args = decodedArgs; - return true; - } - catch - { - return false; - } - } - - private static string BuildUserScope() - { - var identity = $"{Environment.UserDomainName}\\{Environment.UserName}"; - var hash = SHA256.HashData(Encoding.UTF8.GetBytes(identity)); - return Convert.ToHexString(hash)[..16].ToLowerInvariant(); - } - internal sealed record HandoffPayload(string[] Args); - private sealed class ServerLifetime( - CancellationTokenSource cancellationTokenSource, - Mutex mutex, - Task serverTask) : IDisposable + private sealed class ChannelRegistration(SingleInstanceChannel channel) : IDisposable { public void Dispose() { - cancellationTokenSource.Cancel(); - cancellationTokenSource.Dispose(); - - try + lock (ChannelGate) { - mutex.ReleaseMutex(); + if (ReferenceEquals(_activeChannel, channel)) + _activeChannel = null; } - catch - { - // Ignore shutdown races. - } - - mutex.Dispose(); - _ = serverTask; - } - } - private sealed class NoopDisposable : IDisposable - { - public static readonly NoopDisposable Instance = new(); - public void Dispose() - { + channel.Dispose(); } } } diff --git a/Services/ConnectionAuditService.cs b/Services/ConnectionAuditService.cs index c955592..157ec42 100644 --- a/Services/ConnectionAuditService.cs +++ b/Services/ConnectionAuditService.cs @@ -223,10 +223,6 @@ private static string TrimDetail(string? detail) private static string ResolveStorageDirectory() { - var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); - if (!string.IsNullOrWhiteSpace(appData) && Path.IsPathFullyQualified(appData)) - return Path.Combine(appData, "CxShell"); - - return Path.Combine(AppContext.BaseDirectory, ".cxshell-data"); + return AppDataPaths.GetStorageDirectory(); } } 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/Services/RdpBridgeClient.cs b/Services/RdpBridgeClient.cs index 1f332ff..0042d90 100644 --- a/Services/RdpBridgeClient.cs +++ b/Services/RdpBridgeClient.cs @@ -1433,11 +1433,7 @@ private void OnClipboardFiles(IntPtr userData, IntPtr filePaths) private static string GetDebugLogDirectory() { - var root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - if (string.IsNullOrWhiteSpace(root)) - root = AppContext.BaseDirectory; - - return Path.Combine(root, "CxShell", "Logs"); + return AppDataPaths.GetLogsDirectory(); } private static void DebugLog(string message) diff --git a/Services/RdpSecurityProfileCache.cs b/Services/RdpSecurityProfileCache.cs index 077cea7..c600f4a 100644 --- a/Services/RdpSecurityProfileCache.cs +++ b/Services/RdpSecurityProfileCache.cs @@ -21,8 +21,7 @@ internal static class RdpSecurityProfileCache }; private static readonly string CachePath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), - "CxShell", + AppDataPaths.GetLocalCacheDirectory(), "rdp-security-profiles.json"); private static Dictionary? _profiles; diff --git a/Services/ServerMonitorService.cs b/Services/ServerMonitorService.cs index f43b9ca..b7d5395 100644 --- a/Services/ServerMonitorService.cs +++ b/Services/ServerMonitorService.cs @@ -711,17 +711,7 @@ private void DebugLog(string message) private static string GetDebugLogDirectory() { - try - { - var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - if (!string.IsNullOrWhiteSpace(localAppData)) - return Path.Combine(localAppData, "CxShell", "Logs"); - } - catch - { - } - - return AppContext.BaseDirectory; + return AppDataPaths.GetLogsDirectory(); } private static bool IsPowerShellClixml(string? text) diff --git a/Services/SessionLogWriter.cs b/Services/SessionLogWriter.cs index 60f7eb1..7a2e207 100644 --- a/Services/SessionLogWriter.cs +++ b/Services/SessionLogWriter.cs @@ -158,10 +158,12 @@ public static string ResolveLogPath(SessionInfo session, string? chosenPath = nu expanded = SanitizePath(expanded); if (!Path.IsPathRooted(expanded)) { - var baseDir = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), - "CxShell", - "Logs"); + var baseDir = AppDataPaths.IsPortableMode + ? AppDataPaths.GetLogsDirectory() + : Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), + "CxShell", + "Logs"); expanded = Path.Combine(baseDir, expanded); } diff --git a/Services/SessionStorageService.cs b/Services/SessionStorageService.cs index a986e24..f667500 100644 --- a/Services/SessionStorageService.cs +++ b/Services/SessionStorageService.cs @@ -20,8 +20,6 @@ public class SessionData public class SessionStorageService { - private const string CurrentAppDirectoryName = "CxShell"; - private readonly string _storageDir; private readonly string _storagePath; private readonly SqliteAppDataStore _store; @@ -37,7 +35,7 @@ public SessionStorageService(string? directory = null) public static string GetStorageDirectory() { - return ResolveStorageDirectory(); + return AppDataPaths.GetStorageDirectory(); } public SessionData Load() @@ -87,56 +85,4 @@ public void Save(SessionData data) return null; } } - - private static string ResolveStorageDirectory() - { - var root = ResolveStorageRoot(); - if (!string.IsNullOrWhiteSpace(root)) - return Path.Combine(root, CurrentAppDirectoryName); - - return Path.Combine(AppContext.BaseDirectory, ".cxshell-data"); - } - - private static string? ResolveStorageRoot() - { - var appData = TryGetFullRoot(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); - if (!string.IsNullOrWhiteSpace(appData)) - return appData; - - if (OperatingSystem.IsWindows()) - return null; - - var xdgConfigHome = TryGetFullRoot(Environment.GetEnvironmentVariable("XDG_CONFIG_HOME")); - if (!string.IsNullOrWhiteSpace(xdgConfigHome)) - return xdgConfigHome; - - var userProfile = TryGetFullRoot(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); - if (!string.IsNullOrWhiteSpace(userProfile)) - { - return OperatingSystem.IsMacOS() - ? Path.Combine(userProfile, "Library", "Application Support") - : Path.Combine(userProfile, ".config"); - } - - return null; - } - - private static string? TryGetFullRoot(string? root) - { - if (string.IsNullOrWhiteSpace(root)) - return null; - - try - { - var expanded = Environment.ExpandEnvironmentVariables(root); - if (!Path.IsPathFullyQualified(expanded)) - return null; - - return Path.GetFullPath(expanded); - } - catch - { - return null; - } - } } diff --git a/Services/SftpTransferQueueStore.cs b/Services/SftpTransferQueueStore.cs index b6910f9..f668e23 100644 --- a/Services/SftpTransferQueueStore.cs +++ b/Services/SftpTransferQueueStore.cs @@ -140,10 +140,6 @@ private static bool IsValidLegacyQueue(string json) private static string ResolveStorageDirectory() { - var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); - if (!string.IsNullOrWhiteSpace(appData) && Path.IsPathFullyQualified(appData)) - return Path.Combine(appData, "CxShell"); - - return Path.Combine(AppContext.BaseDirectory, ".cxshell-data"); + return AppDataPaths.GetStorageDirectory(); } } diff --git a/Services/SingleInstanceChannel.cs b/Services/SingleInstanceChannel.cs new file mode 100644 index 0000000..3bded6e --- /dev/null +++ b/Services/SingleInstanceChannel.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Pipes; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace CxShell.Services; + +/// +/// Coordinates single-instance locking and IPC forwarding scoped to a specific +/// data directory, following SourceGit's lock-file + named-pipe pattern so an +/// installed instance and one or more portable instances can run side by side. +/// +public sealed class SingleInstanceChannel : IDisposable +{ + private const int ConnectTimeoutMilliseconds = 1000; + private const int MaximumPayloadBytes = 64 * 1024; + + private readonly string _lockFilePath; + private readonly string _pipeName; + private readonly FileStream? _singletonLock; + private readonly Thread? _serverThread; + private readonly object _handlerGate = new(); + private readonly Queue _pendingMessages = new(); + private Func? _handler; + private volatile bool _stopping; + private bool _disposed; + + public bool IsFirstInstance { get; } + + public string PipeName => _pipeName; + + public string LockFilePath => _lockFilePath; + + public SingleInstanceChannel(string? storageDirectory = null, bool? isPortableMode = null) + { + var effectiveStorageDir = string.IsNullOrWhiteSpace(storageDirectory) + ? AppDataPaths.GetStorageDirectory() + : Path.GetFullPath(storageDirectory); + var effectivePortable = isPortableMode ?? AppDataPaths.IsPortableMode; + + _pipeName = BuildPipeName(effectiveStorageDir); + var lockFile = ResolveLockFile(effectiveStorageDir, effectivePortable); + _lockFilePath = lockFile.Path; + + var lockDir = Path.GetDirectoryName(_lockFilePath); + if (!string.IsNullOrWhiteSpace(lockDir)) + Directory.CreateDirectory(lockDir); + + _singletonLock = TryAcquireLock(lockFile); + IsFirstInstance = _singletonLock != null; + + if (IsFirstInstance) + { + _serverThread = new Thread(RunServerLoop) + { + Name = "CxShell.SingleInstanceServer", + IsBackground = true + }; + _serverThread.Start(); + } + } + + public void AttachHandler(Func handler) + { + ArgumentNullException.ThrowIfNull(handler); + + List? queued = null; + lock (_handlerGate) + { + _handler = handler; + if (_pendingMessages.Count > 0) + { + queued = new List(_pendingMessages.Count); + while (_pendingMessages.Count > 0) + queued.Add(_pendingMessages.Dequeue()); + } + } + + if (queued == null) + return; + + foreach (var args in queued) + _ = DispatchToHandlerAsync(handler, args); + } + + public bool SendToFirstInstance(string[]? args) + { + var payload = EncodePayload(args ?? []); + for (var attempt = 0; attempt < 3; attempt++) + { + try + { + using var client = new NamedPipeClientStream( + ".", + _pipeName, + PipeDirection.InOut, + PipeOptions.CurrentUserOnly); + client.Connect(ConnectTimeoutMilliseconds); + + using var writer = new StreamWriter(client, new UTF8Encoding(false), leaveOpen: true) + { + AutoFlush = true + }; + writer.WriteLine(payload); + + var acknowledgement = client.ReadByte(); + return acknowledgement == 1; + } + catch + { + if (attempt < 2) + Thread.Sleep(100); + } + } + + return false; + } + + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + _stopping = true; + + if (IsFirstInstance) + { + WakeServerLoop(); + try + { + _serverThread?.Join(TimeSpan.FromSeconds(2)); + } + catch + { + // Ignore shutdown races. + } + } + + _singletonLock?.Dispose(); + + if (IsFirstInstance && File.Exists(_lockFilePath)) + { + try + { + File.Delete(_lockFilePath); + } + catch + { + // Ignore best-effort lock file cleanup failures on shutdown. + } + } + } + + internal static string BuildPipeName(string storageDirectory) + { + var scope = BuildInstanceScope(storageDirectory); + return $"CxShell.Instance.v2.{scope}"; + } + + internal static string BuildInstanceScope(string storageDirectory) + { + var normalizedDir = NormalizeDirectoryForScope(storageDirectory); + var identity = $"{Environment.UserDomainName}\\{Environment.UserName}|{normalizedDir}"; + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(identity)); + return Convert.ToHexString(hash)[..16].ToLowerInvariant(); + } + + private static string NormalizeDirectoryForScope(string storageDirectory) + { + var fullPath = Path.GetFullPath(storageDirectory) + .Replace('\\', '/') + .TrimEnd('/'); + return OperatingSystem.IsWindows() + ? fullPath.ToLowerInvariant() + : fullPath; + } + + private static LockFileInfo ResolveLockFile(string storageDirectory, bool isPortableMode) + { + if (!OperatingSystem.IsLinux() || isPortableMode) + return new LockFileInfo(Path.Combine(storageDirectory, "process.lock"), false); + + var runtimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR"); + if (string.IsNullOrWhiteSpace(runtimeDir) || !Directory.Exists(runtimeDir)) + return new LockFileInfo(Path.Combine(storageDirectory, "process.lock"), false); + + var scope = BuildInstanceScope(storageDirectory); + return new LockFileInfo(Path.Combine(runtimeDir, $"cxshell.{scope}.lock"), true); + } + + private static FileStream? TryAcquireLock(LockFileInfo lockFile) + { + if (OperatingSystem.IsLinux() && lockFile.NeedChangePermissions) + { + try + { + var created = new FileStream( + lockFile.Path, + FileMode.CreateNew, + FileAccess.ReadWrite, + FileShare.None); + File.SetUnixFileMode( + lockFile.Path, + File.GetUnixFileMode(lockFile.Path) | UnixFileMode.StickyBit); + return created; + } + catch + { + try + { + return new FileStream( + lockFile.Path, + FileMode.Open, + FileAccess.ReadWrite, + FileShare.None); + } + catch + { + return null; + } + } + } + + try + { + return new FileStream( + lockFile.Path, + FileMode.OpenOrCreate, + FileAccess.ReadWrite, + FileShare.None); + } + catch + { + return null; + } + } + + private void RunServerLoop() + { + while (!_stopping) + { + try + { + using var server = new NamedPipeServerStream( + _pipeName, + PipeDirection.InOut, + NamedPipeServerStream.MaxAllowedServerInstances, + PipeTransmissionMode.Byte, + PipeOptions.CurrentUserOnly); + server.WaitForConnection(); + + if (_stopping) + break; + + using var reader = new StreamReader(server, Encoding.UTF8, leaveOpen: true); + var line = reader.ReadLine(); + if (_stopping) + break; + + var accepted = TryDecodePayload(line, out var args); + server.WriteByte(accepted ? (byte)1 : (byte)0); + server.Flush(); + + if (accepted) + EnqueueOrDispatch(args); + } + catch + { + if (_stopping) + break; + + Thread.Sleep(200); + } + } + } + + private void WakeServerLoop() + { + try + { + using var client = new NamedPipeClientStream( + ".", + _pipeName, + PipeDirection.InOut, + PipeOptions.CurrentUserOnly); + client.Connect(150); + } + catch + { + // Server loop may not have entered WaitForConnection yet or has already exited. + } + } + + private void EnqueueOrDispatch(string[] args) + { + Func? handler; + lock (_handlerGate) + { + handler = _handler; + if (handler == null) + { + _pendingMessages.Enqueue(args); + return; + } + } + + _ = DispatchToHandlerAsync(handler, args); + } + + private static async Task DispatchToHandlerAsync(Func handler, string[] args) + { + try + { + await handler(args); + } + catch + { + // Keep the IPC server alive even if a dispatched message fails. + } + } + + private static string EncodePayload(string[] args) + { + var json = JsonSerializer.SerializeToUtf8Bytes( + new CommandLineHandoffService.HandoffPayload(args), + AppJsonOptions.Default); + return Convert.ToBase64String(json); + } + + private static bool TryDecodePayload(string? payload, out string[] args) + { + args = []; + if (string.IsNullOrWhiteSpace(payload) || payload.Length > MaximumPayloadBytes) + return false; + + try + { + var json = Convert.FromBase64String(payload.Trim()); + var decoded = JsonSerializer.Deserialize( + json, + AppJsonOptions.Default); + if (decoded == null) + return false; + + args = decoded.Args ?? []; + return true; + } + catch + { + return false; + } + } + + private sealed record LockFileInfo(string Path, bool NeedChangePermissions); +} 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/ViewModels/VncViewModel.cs b/ViewModels/VncViewModel.cs index 94f51ff..4253a3a 100644 --- a/ViewModels/VncViewModel.cs +++ b/ViewModels/VncViewModel.cs @@ -844,13 +844,7 @@ public void Dispose() private static string GetLogDirectory() { - var root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - if (string.IsNullOrWhiteSpace(root)) - root = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); - if (string.IsNullOrWhiteSpace(root)) - root = AppContext.BaseDirectory; - - var directory = Path.Combine(root, "CxShell", "Logs"); + var directory = AppDataPaths.GetLogsDirectory(); Directory.CreateDirectory(directory); return directory; } 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 @@ + + + + + + + + + + + + + + _quickSessionActivationsPending = []; @@ -67,6 +66,8 @@ public partial class MainWindow : AtomWindow private readonly KeepTaskbarFullScreen _keepTaskbarFullScreen; private Avalonia.Controls.WindowState _windowStateBeforeFullScreen = Avalonia.Controls.WindowState.Normal; private bool _restoreFullScreenAfterMinimize; + private bool _allowClose; + private bool _hasCompletedInitialLoad; public MainWindow() : this(Array.Empty()) @@ -163,6 +164,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 +206,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 +228,8 @@ protected override void OnLoaded(RoutedEventArgs e) _isQuickSessionActivationReady = true; }, DispatcherPriority.ApplicationIdle); UpdateApplicationSuspension(vm); - vm.StartAutomaticUpdateCheck(_startupArgs); + if (isInitialLoad) + vm.StartAutomaticUpdateCheck(_startupArgs); } } @@ -201,8 +241,6 @@ protected override void OnUnloaded(RoutedEventArgs e) DetachTabReorderHandlers(); if (DataContext is MainWindowViewModel vm) vm.SetApplicationSuspended(true); - _commandLineHandoffServer?.Dispose(); - _commandLineHandoffServer = null; base.OnUnloaded(e); } @@ -733,10 +771,7 @@ private static void WriteToolbarDiagnostics(string message) { try { - var logDirectory = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), - "CxShell", - "Logs"); + var logDirectory = AppDataPaths.GetLogsDirectory(); Directory.CreateDirectory(logDirectory); var path = Path.Combine(logDirectory, "toolbar-menu.log"); var line = $"{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fff zzz} {message}{Environment.NewLine}"; @@ -1603,10 +1638,7 @@ private void HandleCommandLineLaunchIfRequested() private void StartCommandLineHandoffServer() { - if (_commandLineHandoffServer != null) - return; - - _commandLineHandoffServer = CommandLineHandoffService.StartServer(HandleCommandLineHandoffAsync); + CommandLineHandoffService.AttachHandler(HandleCommandLineHandoffAsync); } private Task HandleCommandLineHandoffAsync(string[] args) @@ -1615,12 +1647,21 @@ private Task HandleCommandLineHandoffAsync(string[] args) { try { + if (!IsVisible) + Show(); + if (WindowState == Avalonia.Controls.WindowState.Minimized) WindowState = Avalonia.Controls.WindowState.Normal; + if (!Topmost) + { + Topmost = true; + Topmost = false; + } + Activate(); - if (DataContext is MainWindowViewModel vm) + if (args.Length > 0 && DataContext is MainWindowViewModel vm) await vm.ExecuteCommandLineLaunchAsync(CommandLineLaunchOptions.Parse(args)); } catch