using System.Diagnostics; using System.IO; using System.Windows; using Microsoft.Extensions.DependencyInjection; using Moli.Desktop.Api; using Moli.Desktop.Diagnostics; using Moli.Desktop.Host; using Moli.Desktop.Management; using Moli.Desktop.Runtime; using Forms = System.Windows.Forms; using Drawing = System.Drawing; using Application = System.Windows.Application; namespace Moli.Desktop.Tray; public sealed class TrayShell : ITrayShell, IDisposable { private readonly IServiceProvider _services; private readonly IDesktopRuntime _runtime; private readonly IDiagnosticsService _diagnostics; private readonly ILocalApiStatus _apiStatus; private readonly IStartupService _startup; private readonly DesktopPaths _paths; private Forms.NotifyIcon? _notifyIcon; private ManagementWindow? _managementWindow; public TrayShell( IServiceProvider services, IDesktopRuntime runtime, IDiagnosticsService diagnostics, ILocalApiStatus apiStatus, IStartupService startup, DesktopPaths paths) { _services = services; _runtime = runtime; _diagnostics = diagnostics; _apiStatus = apiStatus; _startup = startup; _paths = paths; } public Task StartAsync(CancellationToken cancellationToken = default) { _notifyIcon = new Forms.NotifyIcon { Icon = LoadTrayIcon(), Text = "Moli Desktop", Visible = true, ContextMenuStrip = BuildMenu() }; _notifyIcon.DoubleClick += (_, _) => OpenManagementWindow(); _diagnostics.Record(DiagnosticSeverity.Info, "TrayShellStarted", "Tray shell started."); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken = default) { Dispose(); return Task.CompletedTask; } public void Dispose() { if (_notifyIcon is not null) { _notifyIcon.Visible = false; _notifyIcon.Dispose(); _notifyIcon = null; } } private Forms.ContextMenuStrip BuildMenu() { var menu = new Forms.ContextMenuStrip(); menu.Opening += async (_, _) => await RefreshMenuAsync(menu).ConfigureAwait(true); menu.Items.Add(Command("打开管理窗口", (_, _) => OpenManagementWindow())); menu.Items.Add(new Forms.ToolStripSeparator()); menu.Items.Add(Command("启用壁纸", async (_, _) => await _runtime.EnableWallpaperAsync().ConfigureAwait(true), "wallpaper.enable")); menu.Items.Add(Command("禁用壁纸", async (_, _) => await _runtime.DisableWallpaperAsync().ConfigureAwait(true), "wallpaper.disable")); menu.Items.Add(CheckCommand("进入编辑模式", async item => await _runtime.SetEditModeAsync(item.Checked).ConfigureAwait(true), "edit")); menu.Items.Add(CheckCommand("锁定全部", async item => await _runtime.SetGlobalLockedAsync(item.Checked).ConfigureAwait(true), "lock")); menu.Items.Add(CheckCommand("安全输入模式", async item => await _runtime.SetSafeInputModeAsync(item.Checked).ConfigureAwait(true), "safe")); menu.Items.Add(new Forms.ToolStripSeparator()); menu.Items.Add(Command("重载插件", async (_, _) => await _runtime.ReloadPluginsAsync().ConfigureAwait(true))); menu.Items.Add(Command("打开日志目录", (_, _) => OpenDirectory(_paths.LogDirectory))); menu.Items.Add(CheckCommand("设置开机启动", async item => await _startup.SetEnabledAsync(item.Checked).ConfigureAwait(true), "startup")); menu.Items.Add(new Forms.ToolStripSeparator()); menu.Items.Add(Command("退出应用", async (_, _) => await ShutdownApplicationAsync().ConfigureAwait(true))); return menu; } private async Task RefreshMenuAsync(Forms.ContextMenuStrip menu) { var state = await _runtime.GetStateAsync().ConfigureAwait(true); SetChecked(menu, "edit", state.IsEditMode); SetChecked(menu, "lock", state.IsGlobalLocked); SetChecked(menu, "safe", state.IsSafeInputMode); SetChecked(menu, "startup", _startup.IsEnabled()); var worst = state.Diagnostics.OrderByDescending(entry => entry.Severity).FirstOrDefault(); var api = _apiStatus.GetStatus(); var statusText = api.IsListening ? $"API 127.0.0.1:{api.Port}" : $"API 未监听: {api.ErrorCode ?? "Stopped"}"; _notifyIcon!.Text = TrimForTray(worst is null ? $"Moli Desktop - {statusText}" : $"Moli Desktop - {worst.Code}"); } private void OpenManagementWindow() { Application.Current.Dispatcher.Invoke(() => { if (_managementWindow is { IsVisible: true }) { _managementWindow.Activate(); return; } _managementWindow = _services.GetRequiredService(); _managementWindow.Closed += (_, _) => _managementWindow = null; _managementWindow.Show(); _managementWindow.Activate(); }); } private async Task ShutdownApplicationAsync() { await _runtime.ShutdownAsync().ConfigureAwait(true); Application.Current.Dispatcher.Invoke(Application.Current.Shutdown); } private static Forms.ToolStripMenuItem Command(string text, EventHandler onClick, string? name = null) { var item = new Forms.ToolStripMenuItem(text) { Name = name ?? text }; item.Click += onClick; return item; } private static Forms.ToolStripMenuItem CheckCommand(string text, Func onClick, string name) { var item = new Forms.ToolStripMenuItem(text) { Name = name, CheckOnClick = true }; item.Click += async (_, _) => await onClick(item).ConfigureAwait(true); return item; } private static void SetChecked(Forms.ContextMenuStrip menu, string name, bool value) { if (menu.Items[name] is Forms.ToolStripMenuItem item) { item.Checked = value; } } private static void OpenDirectory(string path) { Directory.CreateDirectory(path); Process.Start(new ProcessStartInfo(path) { UseShellExecute = true }); } private static string TrimForTray(string text) => text.Length <= 63 ? text : text[..63]; private static Drawing.Icon LoadTrayIcon() { try { var iconPath = Path.Combine(AppContext.BaseDirectory, "Assets", "Moli.Desktop.ico"); if (File.Exists(iconPath)) { return new Drawing.Icon(iconPath); } } catch (Exception) { // Fall back to the embedded executable icon below. } try { var executablePath = Environment.ProcessPath; if (!string.IsNullOrWhiteSpace(executablePath) && File.Exists(executablePath)) { return Drawing.Icon.ExtractAssociatedIcon(executablePath) ?? Drawing.SystemIcons.Application; } } catch (Exception) { // Last resort keeps the tray available even if icon loading fails. } return Drawing.SystemIcons.Application; } }