| New file |
| | |
| | | # Moli.Desktop MVP 集成移交记录 |
| | | |
| | | 日期:2026-05-02 |
| | | |
| | | ## 范围 |
| | | |
| | | - T12 Tray Shell:托盘图标、菜单命令、日志目录、开机启动、退出流程。 |
| | | - T13 Management Window:状态、壁纸、组件、插件、诊断 tabs 和核心命令。 |
| | | - T14 Local API and WebSocket:`127.0.0.1:8765` Minimal API、事件 WebSocket、错误响应。 |
| | | - T16 Integration Hardening:构建测试、API smoke test 脚本、手工验收清单。 |
| | | |
| | | ## 自动化验证 |
| | | |
| | | ```powershell |
| | | dotnet build .\Moli.Desktop.slnx |
| | | dotnet test .\Moli.Desktop.slnx |
| | | .\scripts\api-smoke-test.ps1 |
| | | ``` |
| | | |
| | | `api-smoke-test.ps1` 需要先启动 `Moli.Desktop`,默认访问 `http://127.0.0.1:8765`。 |
| | | |
| | | ## 手工验收清单 |
| | | |
| | | - 托盘菜单可打开,双击托盘图标可打开管理窗口。 |
| | | - 托盘可切换编辑模式、安全输入模式、锁定全部,并可正常退出应用。 |
| | | - 管理窗口不是桌面覆盖层,tabs 可查看状态、插件、组件和诊断。 |
| | | - 管理窗口可执行壁纸启停、组件显示隐藏、组件锁定、重载插件、重置布局。 |
| | | - `GET /api/status` 返回运行时状态和 API 监听状态。 |
| | | - `POST /api/edit-mode` 可通过 JSON body 或无 body 切换编辑模式。 |
| | | - `GET /ws/events` 可接收 `widget.layoutChanged`、`app.statusChanged` 等运行时事件。 |
| | | - API 只绑定 `127.0.0.1`;端口占用时应用继续启动并记录 `LocalApiStartFailed`。 |
| | | - 配置损坏恢复、WebView2 Runtime 缺失提示、拖拽缩放保存需在真实桌面环境复验。 |
| | | |
| | | ## 已知限制 |
| | | |
| | | - 开机启动当前使用 HKCU Run 注册表项,未实现安装器级启动项管理。 |
| | | - 管理窗口的重置布局是 MVP 级软重置:恢复可见、解锁、透明度和点击穿透,不重建组件实例。 |
| | | - WebView2 Runtime 缺失只能在缺失运行时的机器上完整验证。 |
| New file |
| | |
| | | param( |
| | | [string]$BaseUrl = "http://127.0.0.1:8765" |
| | | ) |
| | | |
| | | $ErrorActionPreference = "Stop" |
| | | |
| | | function Invoke-MoliApi { |
| | | param( |
| | | [string]$Method, |
| | | [string]$Path, |
| | | [object]$Body = $null |
| | | ) |
| | | |
| | | $uri = "$BaseUrl$Path" |
| | | if ($null -eq $Body) { |
| | | Invoke-RestMethod -Method $Method -Uri $uri |
| | | } |
| | | else { |
| | | Invoke-RestMethod -Method $Method -Uri $uri -ContentType "application/json" -Body ($Body | ConvertTo-Json -Depth 8) |
| | | } |
| | | } |
| | | |
| | | $status = Invoke-MoliApi -Method Get -Path "/api/status" |
| | | Write-Host "status: editMode=$($status.isEditMode), safeInput=$($status.isSafeInputMode), plugins=$($status.plugins.Count), widgets=$($status.widgets.Count)" |
| | | |
| | | try { |
| | | $edit = Invoke-MoliApi -Method Post -Path "/api/edit-mode" -Body @{ enabled = -not $status.isEditMode } |
| | | Write-Host "edit-mode toggled: $($edit.isEditMode)" |
| | | |
| | | $safe = Invoke-MoliApi -Method Post -Path "/api/safe-input-mode" -Body @{ enabled = $status.isSafeInputMode } |
| | | Write-Host "safe-input confirmed: $($safe.isSafeInputMode)" |
| | | |
| | | $plugins = Invoke-MoliApi -Method Get -Path "/api/plugins" |
| | | Write-Host "plugins endpoint returned $($plugins.Count) item(s)" |
| | | |
| | | if ($status.widgets.Count -gt 0) { |
| | | $widget = $status.widgets[0] |
| | | $updated = Invoke-MoliApi -Method Post -Path "/api/widgets/$($widget.instanceId)/layout" -Body @{ |
| | | isVisible = $widget.isVisible |
| | | isLocked = $widget.isLocked |
| | | opacity = $widget.opacity |
| | | } |
| | | Write-Host "widget layout accepted: $($updated.instanceId)" |
| | | } |
| | | } |
| | | finally { |
| | | Invoke-MoliApi -Method Post -Path "/api/edit-mode" -Body @{ enabled = $status.isEditMode } | Out-Null |
| | | Invoke-MoliApi -Method Post -Path "/api/safe-input-mode" -Body @{ enabled = $status.isSafeInputMode } | Out-Null |
| | | } |
| | | |
| | | Write-Host "API smoke test completed." |
| New file |
| | |
| | | using System.Text.Json.Serialization; |
| | | using Moli.Desktop.Diagnostics; |
| | | using Moli.Desktop.Layout; |
| | | using Moli.Desktop.Plugins; |
| | | using Moli.Desktop.Runtime; |
| | | |
| | | namespace Moli.Desktop.Api; |
| | | |
| | | public sealed record LocalApiStatusSnapshot |
| | | { |
| | | public bool IsListening { get; init; } |
| | | public string Host { get; init; } = "127.0.0.1"; |
| | | public int Port { get; init; } = 8765; |
| | | public string? ErrorCode { get; init; } |
| | | public string? Message { get; init; } |
| | | } |
| | | |
| | | public interface ILocalApiStatus |
| | | { |
| | | LocalApiStatusSnapshot GetStatus(); |
| | | } |
| | | |
| | | public sealed record ApiErrorResponse(string ErrorCode, string Message); |
| | | |
| | | public sealed record ModeRequest(bool? Enabled); |
| | | |
| | | public sealed record RectDto(double X, double Y, double Width, double Height) |
| | | { |
| | | public RectD ToRect() => new(X, Y, Width, Height); |
| | | public static RectDto From(RectD rect) => new(rect.X, rect.Y, rect.Width, rect.Height); |
| | | } |
| | | |
| | | public sealed record WidgetLayoutPatchRequest |
| | | { |
| | | public RectDto? Bounds { get; init; } |
| | | public string? MonitorId { get; init; } |
| | | public bool? IsVisible { get; init; } |
| | | public bool? IsLocked { get; init; } |
| | | public double? Opacity { get; init; } |
| | | public bool? ClickThrough { get; init; } |
| | | public double? Scale { get; init; } |
| | | |
| | | public WidgetLayoutPatch ToPatch() => new() |
| | | { |
| | | Bounds = Bounds?.ToRect(), |
| | | MonitorId = string.IsNullOrWhiteSpace(MonitorId) ? null : new MonitorId(MonitorId), |
| | | IsVisible = IsVisible, |
| | | IsLocked = IsLocked, |
| | | Opacity = Opacity, |
| | | ClickThrough = ClickThrough, |
| | | Scale = Scale |
| | | }; |
| | | } |
| | | |
| | | public sealed record ApiStatusResponse |
| | | { |
| | | public bool IsEditMode { get; init; } |
| | | public bool IsGlobalLocked { get; init; } |
| | | public bool IsSafeInputMode { get; init; } |
| | | public LocalApiStatusSnapshot Api { get; init; } = new(); |
| | | public WallpaperResponse Wallpaper { get; init; } = new(); |
| | | public IReadOnlyList<PluginResponse> Plugins { get; init; } = []; |
| | | public IReadOnlyList<WidgetResponse> Widgets { get; init; } = []; |
| | | public IReadOnlyList<DiagnosticEntry> Diagnostics { get; init; } = []; |
| | | |
| | | public static ApiStatusResponse From(AppRuntimeState state, LocalApiStatusSnapshot api) => new() |
| | | { |
| | | IsEditMode = state.IsEditMode, |
| | | IsGlobalLocked = state.IsGlobalLocked, |
| | | IsSafeInputMode = state.IsSafeInputMode, |
| | | Api = api, |
| | | Wallpaper = WallpaperResponse.From(state.Wallpaper), |
| | | Plugins = [.. state.Plugins.Select(PluginResponse.From)], |
| | | Widgets = [.. state.Widgets.Select(WidgetResponse.From)], |
| | | Diagnostics = state.Diagnostics |
| | | }; |
| | | } |
| | | |
| | | public sealed record WallpaperResponse |
| | | { |
| | | public bool IsEnabled { get; init; } |
| | | public bool IsPaused { get; init; } |
| | | public bool IsMuted { get; init; } |
| | | public double Opacity { get; init; } |
| | | public bool ClickThrough { get; init; } |
| | | public string? PluginId { get; init; } |
| | | |
| | | public static WallpaperResponse From(WallpaperRuntimeState state) => new() |
| | | { |
| | | IsEnabled = state.IsEnabled, |
| | | IsPaused = state.IsPaused, |
| | | IsMuted = state.IsMuted, |
| | | Opacity = state.Opacity, |
| | | ClickThrough = state.ClickThrough, |
| | | PluginId = state.PluginId?.Value |
| | | }; |
| | | } |
| | | |
| | | public sealed record PluginResponse |
| | | { |
| | | public required string Id { get; init; } |
| | | public required string Name { get; init; } |
| | | [JsonConverter(typeof(JsonStringEnumConverter<PluginType>))] |
| | | public PluginType Type { get; init; } |
| | | [JsonConverter(typeof(JsonStringEnumConverter<PluginState>))] |
| | | public PluginState State { get; init; } |
| | | public string? ErrorCode { get; init; } |
| | | public string Entry { get; init; } = ""; |
| | | |
| | | public static PluginResponse From(PluginRuntimeState state) => new() |
| | | { |
| | | Id = state.Id.Value, |
| | | Name = state.Name, |
| | | Type = state.Type, |
| | | State = state.State, |
| | | ErrorCode = state.ErrorCode, |
| | | Entry = state.Entry ?? "" |
| | | }; |
| | | } |
| | | |
| | | public sealed record WidgetResponse |
| | | { |
| | | public required string InstanceId { get; init; } |
| | | public required string PluginId { get; init; } |
| | | public required RectDto Bounds { get; init; } |
| | | public required string MonitorId { get; init; } |
| | | public bool IsVisible { get; init; } |
| | | public bool IsLocked { get; init; } |
| | | public double Opacity { get; init; } |
| | | public bool ClickThrough { get; init; } |
| | | |
| | | public static WidgetResponse From(WidgetRuntimeState state) => new() |
| | | { |
| | | InstanceId = state.InstanceId.Value, |
| | | PluginId = state.PluginId.Value, |
| | | Bounds = RectDto.From(state.Bounds), |
| | | MonitorId = state.MonitorId.Value, |
| | | IsVisible = state.IsVisible, |
| | | IsLocked = state.IsLocked, |
| | | Opacity = state.Opacity, |
| | | ClickThrough = state.ClickThrough |
| | | }; |
| | | } |
| | | |
| | | public sealed record RuntimeEventResponse(string Name, DateTimeOffset Timestamp, object? Payload) |
| | | { |
| | | public static RuntimeEventResponse From(RuntimeEvent runtimeEvent) |
| | | => new(runtimeEvent.Name, runtimeEvent.Timestamp, runtimeEvent.Payload); |
| | | } |
| New file |
| | |
| | | using System.Collections.Concurrent; |
| | | using System.IO; |
| | | using System.Net; |
| | | using System.Net.WebSockets; |
| | | using System.Text; |
| | | using System.Text.Json; |
| | | using System.Text.Json.Serialization; |
| | | using Microsoft.AspNetCore.Builder; |
| | | using Microsoft.AspNetCore.Http; |
| | | using Microsoft.AspNetCore.Http.Json; |
| | | using Microsoft.AspNetCore.Hosting; |
| | | using Microsoft.Extensions.DependencyInjection; |
| | | using Microsoft.Extensions.Hosting; |
| | | using Moli.Desktop.Configuration; |
| | | using Moli.Desktop.Diagnostics; |
| | | using Moli.Desktop.Layout; |
| | | using Moli.Desktop.Plugins; |
| | | using Moli.Desktop.Runtime; |
| | | |
| | | namespace Moli.Desktop.Api; |
| | | |
| | | public sealed class LocalApiService : BackgroundService, ILocalApiStatus |
| | | { |
| | | private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) |
| | | { |
| | | Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } |
| | | }; |
| | | |
| | | private readonly IDesktopRuntime _runtime; |
| | | private readonly IConfigurationService _configuration; |
| | | private readonly IPluginManager _plugins; |
| | | private readonly IDiagnosticsService _diagnostics; |
| | | private readonly IRuntimeEventBus _events; |
| | | private readonly ConcurrentDictionary<WebSocket, byte> _sockets = new(); |
| | | private readonly object _statusGate = new(); |
| | | private IDisposable? _eventSubscription; |
| | | private WebApplication? _app; |
| | | private LocalApiStatusSnapshot _status = new(); |
| | | |
| | | public LocalApiService( |
| | | IDesktopRuntime runtime, |
| | | IConfigurationService configuration, |
| | | IPluginManager plugins, |
| | | IDiagnosticsService diagnostics, |
| | | IRuntimeEventBus events) |
| | | { |
| | | _runtime = runtime; |
| | | _configuration = configuration; |
| | | _plugins = plugins; |
| | | _diagnostics = diagnostics; |
| | | _events = events; |
| | | } |
| | | |
| | | public LocalApiStatusSnapshot GetStatus() |
| | | { |
| | | lock (_statusGate) |
| | | { |
| | | return _status; |
| | | } |
| | | } |
| | | |
| | | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| | | { |
| | | var settings = await _configuration.LoadAppSettingsAsync(stoppingToken).ConfigureAwait(false); |
| | | SetStatus(new LocalApiStatusSnapshot { Port = settings.Runtime.ApiPort }); |
| | | _eventSubscription = _events.Subscribe(BroadcastAsync); |
| | | |
| | | try |
| | | { |
| | | var builder = WebApplication.CreateBuilder(new WebApplicationOptions |
| | | { |
| | | ApplicationName = typeof(LocalApiService).Assembly.GetName().Name, |
| | | Args = [] |
| | | }); |
| | | builder.WebHost.UseUrls($"http://127.0.0.1:{settings.Runtime.ApiPort}"); |
| | | builder.Services.Configure<JsonOptions>(options => |
| | | { |
| | | options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; |
| | | options.SerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); |
| | | }); |
| | | |
| | | _app = builder.Build(); |
| | | _app.UseWebSockets(); |
| | | MapEndpoints(_app); |
| | | |
| | | SetStatus(new LocalApiStatusSnapshot |
| | | { |
| | | IsListening = true, |
| | | Port = settings.Runtime.ApiPort, |
| | | Message = $"Listening on http://127.0.0.1:{settings.Runtime.ApiPort}" |
| | | }); |
| | | _diagnostics.Record( |
| | | DiagnosticSeverity.Info, |
| | | "LocalApiStarted", |
| | | "Local API started.", |
| | | new Dictionary<string, string> { ["url"] = $"http://127.0.0.1:{settings.Runtime.ApiPort}" }); |
| | | |
| | | await _app.RunAsync(stoppingToken).ConfigureAwait(false); |
| | | } |
| | | catch (Exception ex) when (ex is IOException or InvalidOperationException or HttpListenerException) |
| | | { |
| | | SetStatus(new LocalApiStatusSnapshot |
| | | { |
| | | Port = settings.Runtime.ApiPort, |
| | | ErrorCode = "LocalApiStartFailed", |
| | | Message = ex.Message |
| | | }); |
| | | _diagnostics.Record( |
| | | DiagnosticSeverity.Error, |
| | | "LocalApiStartFailed", |
| | | "Local API failed to start; desktop runtime will continue.", |
| | | new Dictionary<string, string> |
| | | { |
| | | ["host"] = "127.0.0.1", |
| | | ["port"] = settings.Runtime.ApiPort.ToString(), |
| | | ["exception"] = ex.GetType().Name, |
| | | ["message"] = ex.Message |
| | | }); |
| | | } |
| | | } |
| | | |
| | | public override async Task StopAsync(CancellationToken cancellationToken) |
| | | { |
| | | _eventSubscription?.Dispose(); |
| | | foreach (var socket in _sockets.Keys) |
| | | { |
| | | if (socket.State == WebSocketState.Open) |
| | | { |
| | | await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Application stopping.", cancellationToken).ConfigureAwait(false); |
| | | } |
| | | |
| | | socket.Dispose(); |
| | | } |
| | | |
| | | _sockets.Clear(); |
| | | if (_app is not null) |
| | | { |
| | | await _app.StopAsync(cancellationToken).ConfigureAwait(false); |
| | | await _app.DisposeAsync().ConfigureAwait(false); |
| | | } |
| | | |
| | | SetStatus(GetStatus() with { IsListening = false, Message = "Stopped." }); |
| | | await base.StopAsync(cancellationToken).ConfigureAwait(false); |
| | | } |
| | | |
| | | private void MapEndpoints(WebApplication app) |
| | | { |
| | | app.MapGet("/api/status", async () => |
| | | { |
| | | var state = await _runtime.GetStateAsync().ConfigureAwait(false); |
| | | return Results.Json(ApiStatusResponse.From(state, GetStatus()), JsonOptions); |
| | | }); |
| | | |
| | | app.MapGet("/api/plugins", async () => |
| | | { |
| | | var state = await _runtime.GetStateAsync().ConfigureAwait(false); |
| | | return Results.Json(state.Plugins.Select(PluginResponse.From), JsonOptions); |
| | | }); |
| | | |
| | | app.MapPost("/api/plugins/{id}/reload", async (string id) => |
| | | { |
| | | var reload = await _plugins.ReloadAsync(new PluginId(id)).ConfigureAwait(false); |
| | | if (!reload.Succeeded) |
| | | { |
| | | return Error(reload.ErrorCode ?? "PluginReloadFailed", reload.Message ?? "Plugin reload failed.", StatusCodes.Status404NotFound); |
| | | } |
| | | |
| | | var state = await _runtime.ReloadPluginsAsync().ConfigureAwait(false); |
| | | return ToResult(state); |
| | | }); |
| | | |
| | | app.MapPost("/api/wallpaper/enable", async () => ToResult(await _runtime.EnableWallpaperAsync().ConfigureAwait(false))); |
| | | app.MapPost("/api/wallpaper/disable", async () => ToResult(await _runtime.DisableWallpaperAsync().ConfigureAwait(false))); |
| | | app.MapPost("/api/edit-mode", async (HttpContext context) => |
| | | { |
| | | var enabled = await ReadModeAsync(context).ConfigureAwait(false) |
| | | ?? !(await _runtime.GetStateAsync().ConfigureAwait(false)).IsEditMode; |
| | | return ToResult(await _runtime.SetEditModeAsync(enabled).ConfigureAwait(false)); |
| | | }); |
| | | app.MapPost("/api/safe-input-mode", async (HttpContext context) => |
| | | { |
| | | var enabled = await ReadModeAsync(context).ConfigureAwait(false) |
| | | ?? !(await _runtime.GetStateAsync().ConfigureAwait(false)).IsSafeInputMode; |
| | | return ToResult(await _runtime.SetSafeInputModeAsync(enabled).ConfigureAwait(false)); |
| | | }); |
| | | app.MapPost("/api/widgets/{instanceId}/layout", async (string instanceId, WidgetLayoutPatchRequest request) => |
| | | { |
| | | var result = await _runtime.UpdateWidgetLayoutAsync(new WidgetInstanceId(instanceId), request.ToPatch()).ConfigureAwait(false); |
| | | if (!result.Succeeded) |
| | | { |
| | | return Error(result.ErrorCode ?? "WidgetLayoutUpdateFailed", result.Message ?? "Widget layout update failed.", StatusCodes.Status400BadRequest); |
| | | } |
| | | |
| | | return Results.Json(WidgetResponse.From(result.Value!), JsonOptions); |
| | | }); |
| | | app.MapGet("/ws/events", AcceptWebSocketAsync); |
| | | } |
| | | |
| | | private async Task AcceptWebSocketAsync(HttpContext context) |
| | | { |
| | | if (!context.WebSockets.IsWebSocketRequest) |
| | | { |
| | | context.Response.StatusCode = StatusCodes.Status400BadRequest; |
| | | await context.Response.WriteAsJsonAsync(new ApiErrorResponse("WebSocketRequired", "Use a WebSocket request."), JsonOptions).ConfigureAwait(false); |
| | | return; |
| | | } |
| | | |
| | | using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false); |
| | | _sockets.TryAdd(socket, 0); |
| | | await SendAsync(socket, new RuntimeEventResponse("api.connected", DateTimeOffset.UtcNow, GetStatus()), context.RequestAborted).ConfigureAwait(false); |
| | | |
| | | var buffer = new byte[1024]; |
| | | try |
| | | { |
| | | while (!context.RequestAborted.IsCancellationRequested && socket.State == WebSocketState.Open) |
| | | { |
| | | var message = await socket.ReceiveAsync(buffer, context.RequestAborted).ConfigureAwait(false); |
| | | if (message.MessageType == WebSocketMessageType.Close) |
| | | { |
| | | break; |
| | | } |
| | | } |
| | | } |
| | | finally |
| | | { |
| | | _sockets.TryRemove(socket, out _); |
| | | } |
| | | } |
| | | |
| | | private async Task BroadcastAsync(RuntimeEvent runtimeEvent) |
| | | { |
| | | var payload = RuntimeEventResponse.From(runtimeEvent); |
| | | foreach (var socket in _sockets.Keys) |
| | | { |
| | | if (socket.State != WebSocketState.Open) |
| | | { |
| | | _sockets.TryRemove(socket, out _); |
| | | continue; |
| | | } |
| | | |
| | | try |
| | | { |
| | | await SendAsync(socket, payload, CancellationToken.None).ConfigureAwait(false); |
| | | } |
| | | catch (WebSocketException) |
| | | { |
| | | _sockets.TryRemove(socket, out _); |
| | | } |
| | | } |
| | | } |
| | | |
| | | private static async Task<bool?> ReadModeAsync(HttpContext context) |
| | | { |
| | | if (context.Request.Query.TryGetValue("enabled", out var values) |
| | | && bool.TryParse(values.FirstOrDefault(), out var queryValue)) |
| | | { |
| | | return queryValue; |
| | | } |
| | | |
| | | if (context.Request.ContentLength is null or 0) |
| | | { |
| | | return null; |
| | | } |
| | | |
| | | var request = await context.Request.ReadFromJsonAsync<ModeRequest>(JsonOptions).ConfigureAwait(false); |
| | | return request?.Enabled; |
| | | } |
| | | |
| | | private IResult ToResult(OperationResult<AppRuntimeState> result) |
| | | { |
| | | if (!result.Succeeded) |
| | | { |
| | | return Error(result.ErrorCode ?? "RuntimeCommandFailed", result.Message ?? "Runtime command failed.", StatusCodes.Status400BadRequest); |
| | | } |
| | | |
| | | return Results.Json(ApiStatusResponse.From(result.Value!, GetStatus()), JsonOptions); |
| | | } |
| | | |
| | | private static IResult Error(string code, string message, int statusCode) |
| | | => Results.Json(new ApiErrorResponse(code, message), JsonOptions, statusCode: statusCode); |
| | | |
| | | private static Task SendAsync(WebSocket socket, object payload, CancellationToken cancellationToken) |
| | | { |
| | | var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(payload, JsonOptions)); |
| | | return socket.SendAsync(bytes, WebSocketMessageType.Text, true, cancellationToken); |
| | | } |
| | | |
| | | private void SetStatus(LocalApiStatusSnapshot status) |
| | | { |
| | | lock (_statusGate) |
| | | { |
| | | _status = status; |
| | | } |
| | | } |
| | | } |
| | |
| | | using System.Windows; |
| | | using Microsoft.Extensions.DependencyInjection; |
| | | using Microsoft.Extensions.Hosting; |
| | | using Moli.Desktop.Configuration; |
| | | using Moli.Desktop.Host; |
| | | using Moli.Desktop.Management; |
| | | using Moli.Desktop.Runtime; |
| | | using Moli.Desktop.Tray; |
| | | |
| | | namespace Moli.Desktop; |
| | | |
| | | /// <summary>Application entry point and composition root.</summary> |
| | | public partial class App : Application |
| | | public partial class App : System.Windows.Application |
| | | { |
| | | private IHost? _host; |
| | | |
| | |
| | | _host = DesktopHostBuilder.Create(e.Args).Build(); |
| | | await _host.StartAsync(); |
| | | await _host.Services.GetRequiredService<IDesktopRuntime>().StartAsync(); |
| | | await _host.Services.GetRequiredService<ITrayShell>().StartAsync(); |
| | | |
| | | var mainWindow = _host.Services.GetRequiredService<MainWindow>(); |
| | | mainWindow.Show(); |
| | | var settings = await _host.Services.GetRequiredService<IConfigurationService>().LoadAppSettingsAsync(); |
| | | if (!settings.Startup.StartMinimized) |
| | | { |
| | | _host.Services.GetRequiredService<ManagementWindow>().Show(); |
| | | } |
| | | } |
| | | |
| | | protected override async void OnExit(ExitEventArgs e) |
| | | { |
| | | if (_host is not null) |
| | | { |
| | | await _host.Services.GetRequiredService<ITrayShell>().StopAsync(); |
| | | await _host.Services.GetRequiredService<IDesktopRuntime>().ShutdownAsync(); |
| | | await _host.StopAsync(TimeSpan.FromSeconds(5)); |
| | | _host.Dispose(); |
| | |
| | | using Moli.Desktop.Diagnostics; |
| | | using Moli.Desktop.Interop; |
| | | using Moli.Desktop.Layout; |
| | | using Moli.Desktop.Api; |
| | | using Moli.Desktop.Management; |
| | | using Moli.Desktop.Plugins; |
| | | using Moli.Desktop.Runtime; |
| | | using Moli.Desktop.Tray; |
| | | using Moli.Desktop.WebView; |
| | | using Moli.Desktop.Windows; |
| | | |
| | |
| | | services.AddSingleton<IWin32InteropService, Win32InteropService>(); |
| | | services.AddSingleton<PluginBridgeDispatcher>(); |
| | | services.AddSingleton<IWebViewHostFactory, WebViewHostFactory>(); |
| | | services.AddSingleton<MainWindow>(); |
| | | services.AddSingleton<LocalApiService>(); |
| | | services.AddSingleton<ILocalApiStatus>(sp => sp.GetRequiredService<LocalApiService>()); |
| | | services.AddHostedService(sp => sp.GetRequiredService<LocalApiService>()); |
| | | services.AddSingleton<IStartupService, RegistryStartupService>(); |
| | | services.AddSingleton<ITrayShell, TrayShell>(); |
| | | services.AddTransient<ManagementWindow>(); |
| | | }); |
| | | } |
| | | } |
| New file |
| | |
| | | <Window x:Class="Moli.Desktop.Management.ManagementWindow" |
| | | xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" |
| | | xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" |
| | | Title="Moli Desktop 管理" |
| | | Height="620" |
| | | Width="920" |
| | | MinHeight="520" |
| | | MinWidth="760" |
| | | WindowStartupLocation="CenterScreen"> |
| | | <DockPanel> |
| | | <Border DockPanel.Dock="Top" Background="#20242C" Padding="16,12"> |
| | | <DockPanel> |
| | | <StackPanel> |
| | | <TextBlock Text="Moli Desktop" Foreground="White" FontSize="20" FontWeight="SemiBold" /> |
| | | <TextBlock x:Name="StatusSummaryText" Foreground="#BFC7D5" Margin="0,4,0,0" /> |
| | | </StackPanel> |
| | | <Button Content="刷新" DockPanel.Dock="Right" Width="88" Height="32" Click="RefreshButton_Click" /> |
| | | </DockPanel> |
| | | </Border> |
| | | |
| | | <Grid DockPanel.Dock="Bottom" Background="#F4F6F8" MinHeight="56"> |
| | | <WrapPanel Margin="12" VerticalAlignment="Center"> |
| | | <Button Content="启用壁纸" Width="92" Margin="0,0,8,0" Click="EnableWallpaper_Click" /> |
| | | <Button Content="禁用壁纸" Width="92" Margin="0,0,8,0" Click="DisableWallpaper_Click" /> |
| | | <Button x:Name="EditModeButton" Content="切换编辑" Width="92" Margin="0,0,8,0" Click="ToggleEditMode_Click" /> |
| | | <Button x:Name="SafeInputButton" Content="安全输入" Width="92" Margin="0,0,8,0" Click="ToggleSafeInput_Click" /> |
| | | <Button x:Name="GlobalLockButton" Content="锁定全部" Width="92" Margin="0,0,8,0" Click="ToggleGlobalLock_Click" /> |
| | | <Button Content="重载插件" Width="92" Margin="0,0,8,0" Click="ReloadPlugins_Click" /> |
| | | <Button Content="重置布局" Width="92" Margin="0,0,8,0" Click="ResetLayout_Click" /> |
| | | </WrapPanel> |
| | | </Grid> |
| | | |
| | | <TabControl Margin="12"> |
| | | <TabItem Header="状态"> |
| | | <Grid Margin="8"> |
| | | <Grid.RowDefinitions> |
| | | <RowDefinition Height="Auto" /> |
| | | <RowDefinition Height="Auto" /> |
| | | <RowDefinition Height="*" /> |
| | | </Grid.RowDefinitions> |
| | | <UniformGrid Columns="2"> |
| | | <TextBlock x:Name="RuntimeText" Margin="0,0,12,8" /> |
| | | <TextBlock x:Name="ApiText" Margin="0,0,12,8" /> |
| | | <TextBlock x:Name="WallpaperText" Margin="0,0,12,8" /> |
| | | <TextBlock x:Name="WebViewText" Margin="0,0,12,8" /> |
| | | </UniformGrid> |
| | | <TextBlock Grid.Row="1" Text="最近诊断" FontWeight="SemiBold" Margin="0,12,0,6" /> |
| | | <DataGrid Grid.Row="2" x:Name="RecentDiagnosticsGrid" AutoGenerateColumns="True" IsReadOnly="True" /> |
| | | </Grid> |
| | | </TabItem> |
| | | <TabItem Header="壁纸"> |
| | | <StackPanel Margin="8"> |
| | | <TextBlock x:Name="WallpaperDetailText" Margin="0,0,0,12" /> |
| | | <TextBlock Text="壁纸控制通过底部命令栏执行。" Foreground="#526070" /> |
| | | </StackPanel> |
| | | </TabItem> |
| | | <TabItem Header="组件"> |
| | | <DockPanel Margin="8"> |
| | | <WrapPanel DockPanel.Dock="Top" Margin="0,0,0,8"> |
| | | <ComboBox x:Name="WidgetSelector" Width="260" DisplayMemberPath="InstanceId" Margin="0,0,8,0" /> |
| | | <Button Content="显示/隐藏" Width="96" Margin="0,0,8,0" Click="ToggleWidgetVisible_Click" /> |
| | | <Button Content="锁定/解锁" Width="96" Margin="0,0,8,0" Click="ToggleWidgetLocked_Click" /> |
| | | </WrapPanel> |
| | | <DataGrid x:Name="WidgetsGrid" AutoGenerateColumns="True" IsReadOnly="True" /> |
| | | </DockPanel> |
| | | </TabItem> |
| | | <TabItem Header="插件"> |
| | | <DataGrid x:Name="PluginsGrid" Margin="8" AutoGenerateColumns="True" IsReadOnly="True" /> |
| | | </TabItem> |
| | | <TabItem Header="诊断"> |
| | | <DockPanel Margin="8"> |
| | | <TextBlock x:Name="ManifestErrorsText" DockPanel.Dock="Top" TextWrapping="Wrap" Margin="0,0,0,8" /> |
| | | <DataGrid x:Name="DiagnosticsGrid" AutoGenerateColumns="True" IsReadOnly="True" /> |
| | | </DockPanel> |
| | | </TabItem> |
| | | </TabControl> |
| | | </DockPanel> |
| | | </Window> |
| New file |
| | |
| | | using System.Windows; |
| | | using System.Windows.Threading; |
| | | using Moli.Desktop.Api; |
| | | using Moli.Desktop.Diagnostics; |
| | | using Moli.Desktop.Layout; |
| | | using Moli.Desktop.Plugins; |
| | | using Moli.Desktop.Runtime; |
| | | using MessageBox = System.Windows.MessageBox; |
| | | |
| | | namespace Moli.Desktop.Management; |
| | | |
| | | public partial class ManagementWindow : Window |
| | | { |
| | | private readonly IDesktopRuntime _runtime; |
| | | private readonly IDiagnosticsService _diagnostics; |
| | | private readonly ILocalApiStatus _apiStatus; |
| | | private readonly DispatcherTimer _timer; |
| | | private AppRuntimeState? _state; |
| | | |
| | | public ManagementWindow( |
| | | IDesktopRuntime runtime, |
| | | IDiagnosticsService diagnostics, |
| | | ILocalApiStatus apiStatus) |
| | | { |
| | | _runtime = runtime; |
| | | _diagnostics = diagnostics; |
| | | _apiStatus = apiStatus; |
| | | InitializeComponent(); |
| | | _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) }; |
| | | _timer.Tick += async (_, _) => await RefreshAsync(); |
| | | Loaded += async (_, _) => |
| | | { |
| | | _timer.Start(); |
| | | await RefreshAsync(); |
| | | }; |
| | | Closed += (_, _) => _timer.Stop(); |
| | | } |
| | | |
| | | private async Task RefreshAsync() |
| | | { |
| | | _state = await _runtime.GetStateAsync(); |
| | | var api = _apiStatus.GetStatus(); |
| | | var diagnostics = _diagnostics.Snapshot().OrderByDescending(entry => entry.Timestamp).ToArray(); |
| | | var webViewStatus = diagnostics.FirstOrDefault(entry => entry.Code == DiagnosticCodes.WebViewHostInitialized) is null |
| | | ? "未检测到初始化记录" |
| | | : "已初始化"; |
| | | |
| | | StatusSummaryText.Text = $"插件 {_state.Plugins.Count} 个,组件 {_state.Widgets.Count} 个,诊断 {diagnostics.Length} 条"; |
| | | RuntimeText.Text = $"运行时:编辑={_state.IsEditMode},安全输入={_state.IsSafeInputMode},全局锁定={_state.IsGlobalLocked}"; |
| | | ApiText.Text = api.IsListening ? $"API:127.0.0.1:{api.Port}" : $"API:未监听 {api.ErrorCode ?? ""}"; |
| | | WallpaperText.Text = $"壁纸:启用={_state.Wallpaper.IsEnabled},插件={_state.Wallpaper.PluginId?.Value ?? "无"}"; |
| | | WebViewText.Text = $"WebView2:{webViewStatus}"; |
| | | WallpaperDetailText.Text = $"启用:{_state.Wallpaper.IsEnabled}\n暂停:{_state.Wallpaper.IsPaused}\n静音:{_state.Wallpaper.IsMuted}\n透明度:{_state.Wallpaper.Opacity}\n点击穿透:{_state.Wallpaper.ClickThrough}"; |
| | | EditModeButton.Content = _state.IsEditMode ? "退出编辑" : "进入编辑"; |
| | | SafeInputButton.Content = _state.IsSafeInputMode ? "退出安全" : "安全输入"; |
| | | GlobalLockButton.Content = _state.IsGlobalLocked ? "解锁全部" : "锁定全部"; |
| | | |
| | | var widgets = _state.Widgets.Select(WidgetRow.From).ToArray(); |
| | | var selected = (WidgetSelector.SelectedItem as WidgetRow)?.InstanceId; |
| | | WidgetSelector.ItemsSource = widgets; |
| | | WidgetSelector.SelectedItem = widgets.FirstOrDefault(widget => widget.InstanceId == selected) ?? widgets.FirstOrDefault(); |
| | | WidgetsGrid.ItemsSource = widgets; |
| | | PluginsGrid.ItemsSource = _state.Plugins.Select(PluginRow.From).ToArray(); |
| | | DiagnosticsGrid.ItemsSource = diagnostics.Select(DiagnosticRow.From).ToArray(); |
| | | RecentDiagnosticsGrid.ItemsSource = diagnostics.Take(8).Select(DiagnosticRow.From).ToArray(); |
| | | ManifestErrorsText.Text = BuildManifestErrorText(_state); |
| | | } |
| | | |
| | | private async void RefreshButton_Click(object sender, RoutedEventArgs e) => await RefreshAsync(); |
| | | private async void EnableWallpaper_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.EnableWallpaperAsync()); |
| | | private async void DisableWallpaper_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.DisableWallpaperAsync()); |
| | | private async void ToggleEditMode_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.SetEditModeAsync(!(_state?.IsEditMode ?? false))); |
| | | private async void ToggleSafeInput_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.SetSafeInputModeAsync(!(_state?.IsSafeInputMode ?? false))); |
| | | private async void ToggleGlobalLock_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.SetGlobalLockedAsync(!(_state?.IsGlobalLocked ?? false))); |
| | | private async void ReloadPlugins_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.ReloadPluginsAsync()); |
| | | |
| | | private async void ToggleWidgetVisible_Click(object sender, RoutedEventArgs e) |
| | | { |
| | | if (SelectedWidget() is not { } widget) |
| | | { |
| | | return; |
| | | } |
| | | |
| | | await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { IsVisible = !widget.IsVisible }); |
| | | } |
| | | |
| | | private async void ToggleWidgetLocked_Click(object sender, RoutedEventArgs e) |
| | | { |
| | | if (SelectedWidget() is not { } widget) |
| | | { |
| | | return; |
| | | } |
| | | |
| | | await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { IsLocked = !widget.IsLocked }); |
| | | } |
| | | |
| | | private async void ResetLayout_Click(object sender, RoutedEventArgs e) |
| | | { |
| | | if (_state is null) |
| | | { |
| | | return; |
| | | } |
| | | |
| | | foreach (var widget in _state.Widgets) |
| | | { |
| | | await _runtime.UpdateWidgetLayoutAsync( |
| | | widget.InstanceId, |
| | | new WidgetLayoutPatch |
| | | { |
| | | IsVisible = true, |
| | | IsLocked = false, |
| | | Opacity = 1, |
| | | ClickThrough = true |
| | | }); |
| | | } |
| | | |
| | | await RefreshAsync(); |
| | | } |
| | | |
| | | private WidgetRow? SelectedWidget() => WidgetSelector.SelectedItem as WidgetRow; |
| | | |
| | | private async Task ExecuteAsync(Func<Task<OperationResult<AppRuntimeState>>> command) |
| | | { |
| | | var result = await command(); |
| | | if (!result.Succeeded) |
| | | { |
| | | MessageBox.Show(this, result.Message ?? "命令执行失败。", result.ErrorCode ?? "RuntimeCommandFailed", MessageBoxButton.OK, MessageBoxImage.Warning); |
| | | } |
| | | |
| | | await RefreshAsync(); |
| | | } |
| | | |
| | | private async Task ExecuteWidgetAsync(string instanceId, WidgetLayoutPatch patch) |
| | | { |
| | | var result = await _runtime.UpdateWidgetLayoutAsync(new WidgetInstanceId(instanceId), patch); |
| | | if (!result.Succeeded) |
| | | { |
| | | MessageBox.Show(this, result.Message ?? "组件命令执行失败。", result.ErrorCode ?? "WidgetCommandFailed", MessageBoxButton.OK, MessageBoxImage.Warning); |
| | | } |
| | | |
| | | await RefreshAsync(); |
| | | } |
| | | |
| | | private static string BuildManifestErrorText(AppRuntimeState state) |
| | | { |
| | | var errors = state.Plugins |
| | | .Where(plugin => !string.IsNullOrWhiteSpace(plugin.ErrorCode)) |
| | | .Select(plugin => $"{plugin.Id.Value}: {plugin.ErrorCode}") |
| | | .ToArray(); |
| | | return errors.Length == 0 ? "未发现插件 manifest 错误。" : string.Join(Environment.NewLine, errors); |
| | | } |
| | | |
| | | private sealed record WidgetRow(string InstanceId, string PluginId, string Bounds, string MonitorId, bool IsVisible, bool IsLocked, double Opacity, bool ClickThrough) |
| | | { |
| | | public static WidgetRow From(WidgetRuntimeState state) |
| | | => new( |
| | | state.InstanceId.Value, |
| | | state.PluginId.Value, |
| | | $"{state.Bounds.X:0},{state.Bounds.Y:0} {state.Bounds.Width:0}x{state.Bounds.Height:0}", |
| | | state.MonitorId.Value, |
| | | state.IsVisible, |
| | | state.IsLocked, |
| | | state.Opacity, |
| | | state.ClickThrough); |
| | | } |
| | | |
| | | private sealed record PluginRow(string Id, string Name, string Type, string State, string? ErrorCode, string Entry) |
| | | { |
| | | public static PluginRow From(PluginRuntimeState state) |
| | | => new(state.Id.Value, state.Name, state.Type.ToString(), state.State.ToString(), state.ErrorCode, state.Entry ?? ""); |
| | | } |
| | | |
| | | private sealed record DiagnosticRow(DateTimeOffset Timestamp, string Severity, string Code, string Message) |
| | | { |
| | | public static DiagnosticRow From(DiagnosticEntry entry) |
| | | => new(entry.Timestamp, entry.Severity.ToString(), entry.Code, entry.Message); |
| | | } |
| | | } |
| | |
| | | <Nullable>enable</Nullable> |
| | | <ImplicitUsings>enable</ImplicitUsings> |
| | | <UseWPF>true</UseWPF> |
| | | <UseWindowsForms>true</UseWindowsForms> |
| | | </PropertyGroup> |
| | | |
| | | <ItemGroup> |
| | | <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.7" /> |
| | | <PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.7" /> |
| | | <PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.7" /> |
| | | <FrameworkReference Include="Microsoft.AspNetCore.App" /> |
| | | <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.3912.50" /> |
| | | </ItemGroup> |
| | | |
| New file |
| | |
| | | namespace Moli.Desktop.Tray; |
| | | |
| | | public interface IStartupService |
| | | { |
| | | bool IsEnabled(); |
| | | Task SetEnabledAsync(bool enabled, CancellationToken cancellationToken = default); |
| | | } |
| New file |
| | |
| | | namespace Moli.Desktop.Tray; |
| | | |
| | | public interface ITrayShell |
| | | { |
| | | Task StartAsync(CancellationToken cancellationToken = default); |
| | | Task StopAsync(CancellationToken cancellationToken = default); |
| | | } |
| New file |
| | |
| | | using Microsoft.Win32; |
| | | using Moli.Desktop.Configuration; |
| | | |
| | | namespace Moli.Desktop.Tray; |
| | | |
| | | public sealed class RegistryStartupService : IStartupService |
| | | { |
| | | private const string RunKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Run"; |
| | | private const string ValueName = "Moli.Desktop"; |
| | | private readonly IConfigurationService _configuration; |
| | | |
| | | public RegistryStartupService(IConfigurationService configuration) |
| | | { |
| | | _configuration = configuration; |
| | | } |
| | | |
| | | public bool IsEnabled() |
| | | { |
| | | using var key = Registry.CurrentUser.OpenSubKey(RunKeyPath, writable: false); |
| | | return key?.GetValue(ValueName) is string value && !string.IsNullOrWhiteSpace(value); |
| | | } |
| | | |
| | | public async Task SetEnabledAsync(bool enabled, CancellationToken cancellationToken = default) |
| | | { |
| | | using var key = Registry.CurrentUser.CreateSubKey(RunKeyPath, writable: true); |
| | | if (enabled) |
| | | { |
| | | var executable = Environment.ProcessPath ?? AppContext.BaseDirectory; |
| | | key.SetValue(ValueName, $"\"{executable}\"", RegistryValueKind.String); |
| | | } |
| | | else |
| | | { |
| | | key.DeleteValue(ValueName, throwOnMissingValue: false); |
| | | } |
| | | |
| | | var settings = await _configuration.LoadAppSettingsAsync(cancellationToken).ConfigureAwait(false); |
| | | await _configuration.SaveAppSettingsAsync( |
| | | settings with { Startup = settings.Startup with { StartWithWindows = enabled } }, |
| | | cancellationToken).ConfigureAwait(false); |
| | | } |
| | | } |
| New file |
| | |
| | | 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 = Drawing.SystemIcons.Application, |
| | | 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]; |
| | | } |
| | |
| | | using Moli.Desktop.Plugins; |
| | | using Moli.Desktop.Runtime; |
| | | using Moli.Desktop.WebView; |
| | | using Application = System.Windows.Application; |
| | | |
| | | namespace Moli.Desktop.Windows; |
| | | |
| | |
| | | using Moli.Desktop.Plugins; |
| | | using Moli.Desktop.Runtime; |
| | | using Moli.Desktop.WebView; |
| | | using Brushes = System.Windows.Media.Brushes; |
| | | |
| | | namespace Moli.Desktop.Windows; |
| | | |
| | |
| | | using Moli.Desktop.Plugins; |
| | | using Moli.Desktop.Runtime; |
| | | using Moli.Desktop.WebView; |
| | | using Brushes = System.Windows.Media.Brushes; |
| | | using Cursors = System.Windows.Input.Cursors; |
| | | using HorizontalAlignment = System.Windows.HorizontalAlignment; |
| | | using MouseEventArgs = System.Windows.Input.MouseEventArgs; |
| | | using Point = System.Windows.Point; |
| | | |
| | | namespace Moli.Desktop.Windows; |
| | | |