基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-04 ddd6889459bccf5015cd0c9629cdf4f4ce8fb8e1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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>();
            _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<Forms.ToolStripMenuItem, Task> 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;
    }
}