基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-03 c3a5f58e60f85400edfb5f5379145390316394c5
暂存
8个文件已添加
22个文件已修改
1479 ■■■■■ 已修改文件
docs/README.md 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/architecture/detailed-design.md 33 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/architecture/runtime-architecture.md 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/data/configuration-and-storage.md 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/development/mvp-dev-task-breakdown.md 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/product/desktop-enhancement-prd.md 23 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/product/user-manual.md 328 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/qa/mvp-integration-handoff.md 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.audio-visualizer/index.html 194 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.audio-visualizer/plugin.json 30 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Audio/AudioSpectrumAnalyzerTests.cs 36 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Host/DefaultContentInstallerTests.cs 39 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Layout/LayoutManagerTests.cs 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Assets/Moli.Desktop.ico 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Audio/AudioSpectrumAnalyzer.cs 124 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Audio/AudioSpectrumFrame.cs 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Audio/WasapiLoopbackAudioSpectrumService.cs 160 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Configuration/ConfigurationDocuments.cs 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Diagnostics/DiagnosticsService.cs 15 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Host/DefaultContentInstaller.cs 66 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Host/DesktopHostBuilder.cs 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Layout/Geometry.cs 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Layout/LayoutManager.cs 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Management/ManagementWindow.xaml 27 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Management/ManagementWindow.xaml.cs 276 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Moli.Desktop.csproj 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Plugins/PluginManifest.cs 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/WebView/WebViewHost.cs 64 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Windows/WidgetWindow.cs 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/README.md
@@ -15,6 +15,7 @@
## 当前产品文档
- [Windows 11 桌面增强应用 PRD](product/desktop-enhancement-prd.md)
- [Moli.Desktop 用户操作手册](product/user-manual.md)
## 当前架构文档
docs/architecture/detailed-design.md
@@ -517,6 +517,7 @@
| `height` | `40` | 当前显示器高度 |
| `scale` | `0.5` | `3.0` |
| `opacity` | `0.1` | `1.0` |
| `displayPriority` | `desktopLayer` | `appLayer` |
位置约束:
@@ -582,7 +583,7 @@
| `SetGlobalLocked(true)` | 所有组件拒绝拖拽缩放 |
| `ReloadPlugins` | 重新扫描插件目录,保留同 id 组件布局 |
| `DisableWallpaper` | 关闭壁纸窗口,保留壁纸配置 |
| `UpdateWidgetLayout` | 校验、应用窗口、保存布局、广播事件 |
| `UpdateWidgetLayout` | 校验、应用窗口、保存布局、广播事件,包含 `displayPriority` 更新 |
所有命令都通过 `DesktopRuntimeCoordinator` 进入,托盘、管理窗口、HTTP API 不直接调用底层服务。
@@ -700,12 +701,33 @@
| Tab | 内容 |
| --- | --- |
| 状态 | 当前运行状态、WebView2 Runtime、API 监听、显示器信息 |
| 壁纸 | 当前壁纸插件、启停、重载、静音、点击穿透、显示器选择 |
| 组件 | 组件列表、显示隐藏、锁定、透明度、点击穿透、重载 |
| 插件 | 插件扫描结果、manifest 错误、启用禁用 |
| 诊断 | 日志摘要、错误列表、打开日志目录、重置布局 |
| 壁纸 | 当前壁纸插件、启停、重载、静音、点击穿透、显示器选择、本地文件选择 |
| 组件 | 组件列表、显示隐藏、锁定、透明度、点击穿透、显示优先级、右键编辑位置/大小、打开 `layout.json` |
| 插件 | 插件扫描结果、manifest 错误、启用禁用、右键打开 `plugin.json` / `plugins.json` |
| 诊断 | 日志摘要、错误列表、打开日志目录、二次确认恢复默认 |
管理窗口不得作为桌面覆盖层,必须是普通 WPF 工具窗口。
### Built-in Audio Visualizer
默认样例插件:
```text
samples/plugins/sample.audio-visualizer/
  plugin.json
  index.html
```
默认布局由 `DefaultContentInstaller` 特判:
- `x = 0`
- `width = SystemParameters.PrimaryScreenWidth`
- `y = SystemParameters.PrimaryScreenHeight * 2 / 3`
- `height = min(SystemParameters.PrimaryScreenHeight * 0.25, manifest.defaultLayout.height)`
- `locked = true`
- `clickThrough = true`
MVP 插件端通过 Web Audio API 尝试捕获带音频的屏幕流。若系统或用户授权不允许,则使用占位律动,避免桌面视觉出现空白。真实无授权声卡输出采集作为后续 `IAudioLoopbackService` 扩展。
## Diagnostics Detailed Design
@@ -907,4 +929,3 @@
| 日志库 | `Microsoft.Extensions.Logging` + 文件 provider 或 Serilog | 如果需要结构化日志和滚动文件,优先 Serilog |
| WebView2 用户数据目录 | `%LocalAppData%\DesktopEnhancer\WebView2` | 多 profile 需求出现后再拆 |
| 默认 API 端口 | `8765` | 端口冲突时允许用户在配置中修改 |
docs/architecture/runtime-architecture.md
@@ -118,6 +118,7 @@
- 每个组件实例对应一个独立组件窗口和一个 WebView2 表面。
- 组件窗口保存独立布局:`x`、`y`、`width`、`height`、`zIndex`、`scale`、`locked`、`visible`、`opacity`、`clickThrough`。
- 组件窗口保存 `displayPriority`,用于表达桌面上层、图标上层、应用上层三档显示意图;具体 Win32 层级由窗口控制器降级处理。
- 编辑模式下宿主层接管拖拽和缩放输入,并暂时关闭组件点击穿透。
- 非编辑模式下按组件配置恢复点击穿透和 Web 内容交互。
- 单个组件加载失败时,组件进入 `error` 状态,宿主继续运行。
@@ -406,6 +407,14 @@
- `locked = true` 时拒绝拖拽和缩放。
- `visible = false` 时窗口隐藏但布局保留。
- `clickThrough = true` 时由 Win32 扩展样式透传鼠标输入。
- `displayPriority` 支持 `desktopLayer`、`iconLayer`、`appLayer`,MVP 先以窗口 Topmost 与桌面层策略组合实现,后续再细化 WorkerW/Explorer 图标层之间的精确排序。
### Audio Visualizer Plugin
- 默认样例插件新增 `sample.audio-visualizer`,类型为 `widget`。
- 默认内容安装器按主屏尺寸计算布局:`x=0`,`width=screenWidth`,`y=screenHeight*2/3`,`height<=screenHeight*0.25`。
- 插件页面使用 Web Audio API 驱动细密霓虹竖线律动,并保留透明背景、中心亮线和低透明反射;当用户未授权音频捕获时使用低强度占位动效,保证视觉层仍可验收。
- 宿主后续可新增 `IAudioLoopbackService`,通过 WASAPI loopback 采集声卡输出后向 WebView 派发音频频谱事件。
### Configuration
@@ -530,4 +539,3 @@
- 修改布局后退出并重启,布局恢复。
- 手工破坏 `layout.json` 后启动,原文件被备份,默认布局加载,诊断记录错误。
- 插件入口缺失时插件进入 `error` 状态,其他插件继续运行。
docs/data/configuration-and-storage.md
@@ -123,7 +123,8 @@
      "isLocked": false,
      "opacity": 1,
      "clickThrough": true,
      "scale": 1
      "scale": 1,
      "displayPriority": "iconLayer"
    }
  ]
}
@@ -160,7 +161,8 @@
    "locked": false,
    "clickThrough": true,
    "opacity": 1,
    "scale": 1
    "scale": 1,
    "displayPriority": "iconLayer"
  },
  "config": {}
}
@@ -179,6 +181,7 @@
| `defaultLayout.height` | `40..2160` |
| `defaultLayout.opacity` | `0.1..1.0` |
| `defaultLayout.scale` | `0.5..3.0` |
| `defaultLayout.displayPriority` | `desktopLayer` / `iconLayer` / `appLayer` |
本地入口必须留在插件目录内,不能通过相对路径逃逸到插件根目录外。
@@ -189,6 +192,7 @@
- `sample.wallpaper`
- `sample.clock`
- `sample.system-info`
- `sample.audio-visualizer`
安装行为:
@@ -196,6 +200,7 @@
- 只补缺失文件,不覆盖用户已存在文件。
- 若 `plugins.json` 中没有对应记录,则写入 `enabled`。
- 对 widget 插件,如果 `layout.json` 中没有对应布局实例,则根据 manifest `defaultLayout` 创建 `<pluginId>.default` 实例。
- `sample.audio-visualizer` 会按主屏尺寸生成全宽布局,默认高度不超过屏幕高度 `25%`,纵向位置约为屏幕高度 `2/3`。
`sample.webview-test` 保留为开发/手工验证 fixture,不属于默认启用样例。
@@ -218,4 +223,3 @@
- `schemaVersion` 作为升级入口。
- 插件 manifest 与用户布局分离,避免插件升级覆盖用户布局。
- API 和 UI 通过 `IDesktopRuntime` 修改状态,不直接写配置文件。
docs/development/mvp-dev-task-breakdown.md
@@ -682,6 +682,7 @@
  - `sample.wallpaper`
  - `sample.clock`
  - `sample.system-info` 或占位 widget
  - `sample.audio-visualizer` 音乐律动 widget
- 提供默认配置引用样例插件。
- 提供本地运行说明。
@@ -802,4 +803,3 @@
- 样例插件可用于手工验证。
- 配置路径、日志路径和 API 监听地址已在交付说明中明确。
- 对任何未完成项标注任务编号和影响范围。
docs/product/desktop-enhancement-prd.md
@@ -245,6 +245,21 @@
- 应用应提供一个 WPF 管理窗口,用于壁纸选择、插件列表、组件布局、配置、日志和诊断。
- 管理窗口不应被实现为桌面覆盖层本身。
- 管理窗口应包含插件加载失败、缺失 WebView2 运行时、manifest 无效和配置解析错误等明确错误状态。
- 管理窗口应支持对组件/插件右键操作,包括编辑简单配置、查看或打开对应 JSON 配置文件。
- 管理窗口应支持选择本地壁纸文件并切换当前壁纸,文件格式至少覆盖 `html`、`png`、`jpeg`、`gif` 和 `svg`。
- 管理窗口应在刷新按钮附近提供“恢复默认”入口,并在执行前进行二次确认。
- 管理窗口应支持设置组件显示优先级:桌面上层、图标上层、应用上层。
优先级:P1
### FR-15 音乐律动插件
- 应用应内置一个动感音乐插件,默认作为桌面组件加载。
- 插件视觉由一组细密竖线组成,横向贯穿整个屏幕宽度,背景必须保持透明。
- 插件最大高度不得超过屏幕高度的 `25%`。
- 插件默认位于屏幕顶部向下约 `66%` 的区域,即 `screenHeight * 2 / 3`。
- 插件应随音频节奏律动;MVP 可使用 Web 音频授权采集路径,后续可升级为宿主级 WASAPI loopback 采集。
- 插件默认点击穿透且锁定,避免干扰桌面图标和应用交互。
优先级:P1
@@ -412,6 +427,14 @@
- 当本地 API 启用后,回环客户端请求当前组件状态时,API 应返回当前状态。
- 当非回环客户端默认尝试访问 API 时,请求应被拒绝,或服务对外不可达。
### 音乐律动与管理窗口增量
- 当首次启动并安装默认样例插件时,应包含 `sample.audio-visualizer`,其布局宽度覆盖主屏宽度,高度不超过主屏高度 `25%`,位置接近主屏高度 `2/3`。
- 当用户在组件列表右键操作时,应能编辑位置/大小或打开 `layout.json`。
- 当用户在插件列表右键操作时,应能打开插件自身 `plugin.json` 或全局 `plugins.json`。
- 当用户选择本地壁纸文件后,应生成可加载的用户壁纸插件并启用该壁纸。
- 当用户点击“恢复默认”时,应用必须先弹出二次确认。
## 已确认决策
| 问题 | 决策 |
docs/product/user-manual.md
New file
@@ -0,0 +1,328 @@
# Moli.Desktop 用户操作手册
日期:2026-05-02
## 适用范围
本文档面向 Moli.Desktop 的最终用户、试用用户和现场验证人员,说明如何安装、启动、管理动态壁纸、管理桌面小组件、查看诊断信息以及处理常见问题。
Moli.Desktop 是一款 Windows 11 桌面增强应用。它不会替代 Windows 桌面、Explorer、任务栏或开始菜单,而是在原生桌面之上增加 WebView2 驱动的 H5 动态壁纸和 HTML 小组件能力。
## 使用前准备
使用前请确认:
- 操作系统为 Windows 11。
- 已安装 Microsoft Edge WebView2 Runtime。
- 如从源码运行,需要安装 .NET SDK 10。
- 当前用户有权限读写自己的 `%AppData%` 和 `%LocalAppData%` 目录。
Moli.Desktop 的用户数据默认写入:
| 类型 | 默认位置 |
| --- | --- |
| 配置文件 | `%AppData%\DesktopEnhancer\config` |
| 插件目录 | `%AppData%\DesktopEnhancer\plugins` |
| 日志目录 | `%LocalAppData%\DesktopEnhancer\logs` |
| WebView2 数据 | `%LocalAppData%\DesktopEnhancer\WebView2` |
## 安装与启动
### 使用便携包
如果你拿到的是 `Moli.Desktop-win-x64.zip`:
1. 将 zip 解压到一个固定目录,例如 `D:\Apps\Moli.Desktop`。
2. 进入解压后的目录。
3. 双击 `Moli.Desktop.exe` 启动。
4. 首次启动后,在 Windows 系统托盘区域找到 `Moli Desktop` 图标。
便携包会携带内置样例插件。首次启动时,应用会把默认样例复制到用户插件目录,并生成基础配置文件和布局文件。
### 从源码运行
适合开发、测试或现场验证:
```powershell
dotnet restore Moli.Desktop.slnx
dotnet build Moli.Desktop.slnx
dotnet run --project src/Moli.Desktop/Moli.Desktop.csproj
```
首次启动会自动准备以下样例内容:
- `sample.wallpaper`:本地 H5 动态壁纸。
- `sample.clock`:桌面时钟小组件。
- `sample.system-info`:系统信息占位小组件。
## 托盘菜单
应用启动后主要通过系统托盘操作。你可以右键托盘图标打开菜单,或双击托盘图标打开管理窗口。
托盘菜单包含:
| 菜单项 | 用途 |
| --- | --- |
| 打开管理窗口 | 打开 Moli.Desktop 管理界面 |
| 启用壁纸 | 显示当前壁纸插件 |
| 禁用壁纸 | 关闭当前壁纸显示 |
| 进入编辑模式 | 允许调整小组件位置和尺寸 |
| 锁定全部 | 禁止全部小组件被移动或调整 |
| 安全输入模式 | 临时恢复输入控制,便于处理点击穿透场景 |
| 重载插件 | 重新扫描并加载插件 |
| 打开日志目录 | 打开本机日志文件夹 |
| 设置开机启动 | 切换是否随 Windows 登录启动 |
| 退出应用 | 关闭 Moli.Desktop |
托盘提示文本会显示 API 状态或最近的诊断代码。如果本地 API 启动失败,也可以先从托盘提示和日志目录排查。
## 管理窗口
通过托盘菜单的“打开管理窗口”或双击托盘图标进入管理窗口。
管理窗口顶部显示当前概览,包括插件数量、组件数量和诊断数量。底部提供常用操作按钮:
| 按钮 | 用途 |
| --- | --- |
| 启用壁纸 | 打开当前壁纸 |
| 禁用壁纸 | 关闭当前壁纸 |
| 进入编辑 / 退出编辑 | 切换小组件编辑模式 |
| 安全输入 / 退出安全 | 切换安全输入模式 |
| 锁定全部 / 解锁全部 | 切换全局锁定 |
| 重载插件 | 重新加载插件清单和运行状态 |
| 重置布局 | 将组件恢复为可见、解锁、透明度 1、点击穿透开启 |
管理窗口包含以下页面:
| 页面 | 内容 |
| --- | --- |
| 状态 | 运行模式、API 状态、壁纸状态、WebView2 初始化状态和最近诊断 |
| 壁纸 | 当前壁纸启用状态、暂停状态、透明度、点击穿透状态 |
| 组件 | 小组件实例列表,可选择组件并显示/隐藏或锁定/解锁 |
| 插件 | 已扫描插件的名称、类型、状态、入口和错误码 |
| 诊断 | 诊断记录和插件 manifest 错误摘要 |
## 动态壁纸
Moli.Desktop 使用 WebView2 加载 H5 壁纸。默认样例为 `sample.wallpaper`。
常用操作:
1. 打开托盘菜单或管理窗口。
2. 点击“启用壁纸”显示壁纸。
3. 点击“禁用壁纸”关闭壁纸。
4. 如果桌面鼠标操作受影响,打开“安全输入模式”恢复可操作状态。
壁纸层设计目标是位于桌面图标之后,与原生桌面融合。不同 Windows 桌面状态、显卡驱动和 WebView2 Runtime 状态可能影响实际表现;如显示异常,请先查看诊断页和日志目录。
## 桌面小组件
小组件来自本地 HTML 插件。默认样例包含:
| 插件 | 用途 |
| --- | --- |
| `sample.clock` | 时钟小组件 |
| `sample.system-info` | 系统信息占位小组件 |
### 显示或隐藏组件
1. 打开管理窗口。
2. 进入“组件”页面。
3. 在下拉框选择目标组件。
4. 点击“显示/隐藏”。
### 锁定或解锁组件
1. 打开管理窗口。
2. 进入“组件”页面。
3. 选择目标组件。
4. 点击“锁定/解锁”。
锁定后的组件会拒绝移动和缩放。也可以使用底部的“锁定全部 / 解锁全部”一次控制全部组件。
### 调整组件布局
1. 通过托盘菜单或管理窗口进入编辑模式。
2. 在桌面上调整小组件位置和尺寸。
3. 调整完成后退出编辑模式。
布局会保存到 `%AppData%\DesktopEnhancer\config\layout.json`。重启应用后会尝试恢复上一次布局。
## 插件管理
Moli.Desktop MVP 支持从本地目录安装插件。每个插件目录至少需要包含:
- `plugin.json`
- `plugin.json` 中声明的入口文件,例如 `index.html`
插件默认放在:
```text
%AppData%\DesktopEnhancer\plugins\<pluginId>
```
添加本地插件的一般流程:
1. 在插件目录下创建或复制一个插件文件夹。
2. 确认插件文件夹内存在有效的 `plugin.json`。
3. 打开托盘菜单或管理窗口。
4. 点击“重载插件”。
5. 在管理窗口“插件”页面查看插件状态。
6. 如果插件失败,进入“诊断”页面查看错误码。
`plugin.json` 的常见字段包括:
```json
{
  "id": "sample.clock",
  "name": "Sample Clock",
  "version": "1.0.0",
  "type": "widget",
  "entry": "index.html",
  "description": "Local clock widget.",
  "author": "Moli.Desktop",
  "permissions": [],
  "defaultLayout": {
    "x": 80,
    "y": 80,
    "width": 320,
    "height": 160,
    "locked": false,
    "clickThrough": true,
    "opacity": 1,
    "scale": 1
  },
  "config": {}
}
```
常见校验要求:
| 字段 | 要求 |
| --- | --- |
| `id` | 3 到 64 个字符,以字母或数字开头,可包含字母、数字、点、下划线、短横线 |
| `name` | 1 到 80 个字符 |
| `version` | 类 SemVer 格式,例如 `1.0.0` |
| `type` | `wallpaper` 或 `widget` |
| `entry` | 插件目录内入口文件,或 `http` / `https` URL |
| `opacity` | `0.1` 到 `1.0` |
| `scale` | `0.5` 到 `3.0` |
MVP 阶段没有插件沙箱隔离,也没有插件市场。请只安装可信来源的插件。
## 开机启动
在托盘菜单中勾选“设置开机启动”后,应用会写入当前用户的启动项:
```text
HKCU\Software\Microsoft\Windows\CurrentVersion\Run\Moli.Desktop
```
同时,该状态会同步到:
```text
%AppData%\DesktopEnhancer\config\appsettings.json
```
如果移动了便携包目录,请重新启动应用并重新切换一次“设置开机启动”,确保注册表中的路径指向新的 `Moli.Desktop.exe`。
## 本地 API
Moli.Desktop 默认提供本地回环 API,供自动化、调试工具或后续管理端使用:
```text
http://127.0.0.1:8765
```
常用状态查询:
```powershell
Invoke-RestMethod -Method Get -Uri http://127.0.0.1:8765/api/status
```
常用接口:
| 方法 | 路径 | 用途 |
| --- | --- | --- |
| `GET` | `/api/status` | 查询运行状态 |
| `GET` | `/api/plugins` | 查询插件列表 |
| `POST` | `/api/plugins/{id}/reload` | 重载指定插件 |
| `POST` | `/api/wallpaper/enable` | 启用壁纸 |
| `POST` | `/api/wallpaper/disable` | 禁用壁纸 |
| `POST` | `/api/edit-mode` | 切换编辑模式 |
| `POST` | `/api/safe-input-mode` | 切换安全输入模式 |
| `POST` | `/api/widgets/{instanceId}/layout` | 更新组件布局 |
| `GET` | `/ws/events` | 订阅 WebSocket 事件 |
API 只绑定 `127.0.0.1`。如果端口被占用,桌面应用仍会继续启动,但 API 状态会显示未监听,并写入诊断。
## 备份与恢复
建议备份以下目录:
```text
%AppData%\DesktopEnhancer\config
%AppData%\DesktopEnhancer\plugins
```
恢复时:
1. 退出 Moli.Desktop。
2. 复制备份的 `config` 和 `plugins` 到原位置。
3. 重新启动 Moli.Desktop。
4. 在管理窗口检查插件、组件和诊断状态。
如果 JSON 配置文件损坏,应用会尝试将损坏文件备份为 `.invalid.<timestamp>.json`,然后生成默认配置继续启动。
## 常见问题
### 启动后没有看到托盘图标
- 检查 Windows 托盘隐藏区域。
- 确认 `Moli.Desktop.exe` 进程是否仍在运行。
- 查看 `%LocalAppData%\DesktopEnhancer\logs`。
- 如果从源码运行,先确认 `dotnet build Moli.Desktop.slnx` 成功。
### 壁纸或组件没有显示
- 打开管理窗口,检查“状态”“插件”“诊断”页面。
- 确认 WebView2 Runtime 已安装。
- 点击“重载插件”。
- 检查插件目录中是否存在有效的 `plugin.json` 和入口文件。
- 如果是首次运行,确认 `%AppData%\DesktopEnhancer\plugins` 下是否已生成样例插件。
### 鼠标无法点击桌面内容
- 从托盘菜单开启“安全输入模式”。
- 或进入管理窗口,退出编辑模式、解锁全部组件。
- 对单个组件可在“组件”页面切换显示、锁定或点击穿透相关布局状态。
### 插件显示错误码
- 打开管理窗口的“诊断”页面。
- 检查 manifest 错误摘要。
- 确认插件 `id`、`version`、`type`、`entry` 和 `defaultLayout` 满足校验要求。
- 修正插件后点击“重载插件”。
### API 无法访问
- 在管理窗口“状态”页面查看 API 是否监听。
- 确认访问地址为 `http://127.0.0.1:8765`。
- 检查 `%AppData%\DesktopEnhancer\config\appsettings.json` 中的 `runtime.apiPort`。
- 如果端口被其他程序占用,修改端口后重启应用。
### 开机启动失效
- 确认托盘菜单“设置开机启动”已勾选。
- 如果移动过应用目录,重新勾选一次开机启动。
- 检查注册表项 `HKCU\Software\Microsoft\Windows\CurrentVersion\Run\Moli.Desktop` 是否指向当前 exe。
## 当前 MVP 限制
- 当前没有完整安装器,推荐使用便携 zip 或源码运行。
- 插件只支持本地目录安装;不提供插件市场。
- 首版插件无沙箱隔离,请只使用可信插件。
- 开机启动通过当前用户 HKCU Run 注册表实现。
- 管理窗口的“重置布局”是软重置,不会重新创建组件实例。
- WebView2 Runtime 缺失、桌面层级和点击穿透行为需要在真实 Windows 桌面环境中验证。
docs/qa/mvp-integration-handoff.md
@@ -25,6 +25,12 @@
- 托盘可切换编辑模式、安全输入模式、锁定全部,并可正常退出应用。
- 管理窗口不是桌面覆盖层,tabs 可查看状态、插件、组件和诊断。
- 管理窗口可执行壁纸启停、组件显示隐藏、组件锁定、重载插件、重置布局。
- 管理窗口顶部“恢复默认”执行前需要二次确认。
- 组件列表右键可编辑位置/大小,并可打开 `layout.json`。
- 插件列表右键可打开插件 `plugin.json` 或全局 `plugins.json`。
- 壁纸 tab 可选择 `html/png/jpeg/gif/svg` 文件并切换为用户壁纸。
- 默认插件包含 `sample.audio-visualizer`,视觉为透明背景、全屏宽度细密霓虹竖线,默认高度不超过屏幕高度 `25%`,默认位置接近 `screenHeight * 2 / 3`。
- 组件显示优先级可在管理窗口切换为桌面上层、图标上层、应用上层。
- `GET /api/status` 返回运行时状态和 API 监听状态。
- `POST /api/edit-mode` 可通过 JSON body 或无 body 切换编辑模式。
- `GET /ws/events` 可接收 `widget.layoutChanged`、`app.statusChanged` 等运行时事件。
samples/plugins/sample.audio-visualizer/index.html
New file
@@ -0,0 +1,194 @@
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Music Visualizer</title>
  <style>
    html,
    body {
      width: 100%;
      height: 100%;
      margin: 0;
      overflow: hidden;
      background: transparent;
      user-select: none;
    }
    #stage {
      width: 100vw;
      height: 100vh;
      position: relative;
      box-sizing: border-box;
      background: transparent;
      --base-y: 58%;
      --glow: rgba(255, 47, 179, 0.42);
      --cool: #29d8ff;
      --hot: #ff2fb3;
      --accent: #f8fbff;
    }
    #stage::before {
      content: "";
      position: absolute;
      left: 0;
      right: 0;
      top: var(--base-y);
      height: 1px;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.72), transparent);
      box-shadow:
        0 0 8px rgba(255, 255, 255, 0.7),
        0 0 22px var(--glow);
      opacity: 0.86;
    }
    .bars {
      position: absolute;
      inset: 0 10px;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      gap: 2px;
    }
    .bar {
      --level: 0.16;
      --bar-height: 7%;
      --bar-top: 51%;
      --bar-opacity: 0.43;
      --reflection-height: 4vh;
      --reflection-opacity: 0.06;
      position: relative;
      flex: 1 1 auto;
      min-width: 1px;
      max-width: 4px;
      height: var(--bar-height);
      margin-top: var(--bar-top);
      border-radius: 999px;
      transform-origin: bottom center;
      background:
        linear-gradient(180deg, var(--accent), var(--hot) 36%, var(--cool));
      box-shadow:
        0 0 5px rgba(255, 255, 255, 0.72),
        0 0 12px var(--glow);
      opacity: var(--bar-opacity);
      transition:
        height 64ms linear,
        margin-top 64ms linear,
        opacity 64ms linear;
    }
    .bar::after {
      content: "";
      position: absolute;
      width: inherit;
      min-width: inherit;
      max-width: inherit;
      height: var(--reflection-height);
      transform: translateY(100%) scaleY(0.72);
      transform-origin: top center;
      border-radius: inherit;
      background: linear-gradient(180deg, rgba(255, 47, 179, 0.26), rgba(41, 216, 255, 0.02));
      filter: blur(1px);
      opacity: var(--reflection-opacity);
    }
  </style>
</head>
<body>
  <main id="stage" aria-hidden="true">
    <div id="bars" class="bars"></div>
  </main>
  <script>
    const stage = document.getElementById("stage");
    const barRoot = document.getElementById("bars");
    const settings = {
      barCount: 192,
      primaryColor: "#ff2fb3",
      secondaryColor: "#29d8ff",
      accentColor: "#f8fbff",
      sensitivity: 1.42
    };
    let hostLevels = null;
    let lastHostSampleAt = 0;
    let fallbackPhase = 0;
    let bars = [];
    function applyConfig(config) {
      Object.assign(settings, config || {});
      stage.style.setProperty("--hot", settings.primaryColor);
      stage.style.setProperty("--cool", settings.secondaryColor);
      stage.style.setProperty("--accent", settings.accentColor);
      stage.style.setProperty("--glow", `${hexToRgb(settings.primaryColor, "255, 47, 179")}, 0.42)`.replace(/^/, "rgba("));
      const count = Math.max(96, Math.min(320, Number(settings.barCount) || 192));
      if (bars.length === count) {
        return;
      }
      barRoot.textContent = "";
      bars = Array.from({ length: count }, () => {
        const node = document.createElement("i");
        node.className = "bar";
        barRoot.appendChild(node);
        return node;
      });
    }
    function sample(index) {
      if (hostLevels && performance.now() - lastHostSampleAt < 420) {
        const bin = Math.min(hostLevels.length - 1, Math.floor(index / Math.max(1, bars.length) * hostLevels.length));
        const value = Number(hostLevels[bin]) || 0;
        const neighbor = (Number(hostLevels[Math.max(0, bin - 1)]) || 0) * 0.16
          + (Number(hostLevels[Math.min(hostLevels.length - 1, bin + 1)]) || 0) * 0.16;
        return Math.min(1, Math.pow(value, 0.72) * settings.sensitivity + neighbor);
      }
      fallbackPhase += 0.0025;
      const main = Math.sin(index * 0.18 + fallbackPhase * 54) * 0.5 + 0.5;
      const ripple = Math.sin(index * 0.047 - fallbackPhase * 22) * 0.5 + 0.5;
      const burst = Math.pow(Math.sin(index * 0.022 + fallbackPhase * 13) * 0.5 + 0.5, 7);
      return 0.08 + main * 0.18 + ripple * 0.12 + burst * 0.58;
    }
    function draw() {
      bars.forEach((bar, index) => {
        const centerBias = Math.sin((index / Math.max(1, bars.length - 1)) * Math.PI);
        const value = Math.min(1, sample(index) * (0.72 + centerBias * 0.36));
        const height = value * 44;
        const top = Math.max(0, 58 - height);
        bar.style.setProperty("--level", value.toFixed(3));
        bar.style.setProperty("--bar-height", `${height.toFixed(2)}%`);
        bar.style.setProperty("--bar-top", `${top.toFixed(2)}%`);
        bar.style.setProperty("--bar-opacity", (0.32 + value * 0.68).toFixed(3));
        bar.style.setProperty("--reflection-height", `${(value * 26).toFixed(2)}vh`);
        bar.style.setProperty("--reflection-opacity", (value * 0.36).toFixed(3));
      });
      requestAnimationFrame(draw);
    }
    function hexToRgb(hex, fallback) {
      const match = String(hex || "").trim().match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
      if (!match) {
        return fallback;
      }
      return `${parseInt(match[1], 16)}, ${parseInt(match[2], 16)}, ${parseInt(match[3], 16)}`;
    }
    window.addEventListener("moli:widget-loaded", async () => {
      if (window.moliDesktop?.getConfig) {
        applyConfig(await window.moliDesktop.getConfig());
      }
    });
    window.addEventListener("moli:audio-spectrum", event => {
      const levels = event.detail?.levels;
      if (Array.isArray(levels) && levels.length > 0) {
        hostLevels = levels;
        lastHostSampleAt = performance.now();
      }
    });
    window.addEventListener("moli:config-changed", event => applyConfig(event.detail));
    applyConfig();
    draw();
  </script>
</body>
</html>
samples/plugins/sample.audio-visualizer/plugin.json
New file
@@ -0,0 +1,30 @@
{
  "id": "sample.audio-visualizer",
  "name": "Music Visualizer",
  "version": "1.0.0",
  "type": "widget",
  "entry": "index.html",
  "description": "Full-width music rhythm bars for the lower desktop area.",
  "author": "Moli.Desktop",
  "permissions": [
    "audio-capture"
  ],
  "defaultLayout": {
    "x": 0,
    "y": 720,
    "width": 1920,
    "height": 240,
    "locked": false,
    "clickThrough": true,
    "opacity": 0.92,
    "scale": 1,
    "displayPriority": "iconLayer"
  },
  "config": {
    "barCount": 192,
    "primaryColor": "#ff2fb3",
    "secondaryColor": "#29d8ff",
    "accentColor": "#f8fbff",
    "sensitivity": 1.42
  }
}
src/Moli.Desktop.Tests/Audio/AudioSpectrumAnalyzerTests.cs
New file
@@ -0,0 +1,36 @@
using Moli.Desktop.Audio;
namespace Moli.Desktop.Tests.Audio;
public class AudioSpectrumAnalyzerTests
{
    [Fact]
    public void TryCreateFrame_ReturnsSpectrumForSineWave()
    {
        var analyzer = new AudioSpectrumAnalyzer(48000);
        var samples = new float[AudioSpectrumAnalyzer.DefaultFftSize];
        for (var index = 0; index < samples.Length; index++)
        {
            samples[index] = MathF.Sin(2 * MathF.PI * 440 * index / 48000);
        }
        analyzer.AddSamples(samples);
        var created = analyzer.TryCreateFrame(out var frame);
        Assert.True(created);
        Assert.Equal(AudioSpectrumAnalyzer.DefaultLevelCount, frame.Levels.Length);
        Assert.Contains(frame.Levels, level => level > 0.05f);
        Assert.True(frame.Rms > 0);
    }
    [Fact]
    public void TryCreateFrame_WaitsForEnoughSamples()
    {
        var analyzer = new AudioSpectrumAnalyzer(48000);
        analyzer.AddSamples([0.1f, 0.2f, 0.3f]);
        Assert.False(analyzer.TryCreateFrame(out _));
    }
}
src/Moli.Desktop.Tests/Host/DefaultContentInstallerTests.cs
@@ -2,6 +2,7 @@
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
namespace Moli.Desktop.Tests.Host;
@@ -22,15 +23,53 @@
        Assert.True(File.Exists(Path.Combine(paths.PluginDirectory, "sample.wallpaper", "plugin.json")));
        Assert.True(File.Exists(Path.Combine(paths.PluginDirectory, "sample.clock", "index.html")));
        Assert.True(File.Exists(Path.Combine(paths.PluginDirectory, "sample.system-info", "index.html")));
        Assert.True(File.Exists(Path.Combine(paths.PluginDirectory, "sample.audio-visualizer", "index.html")));
        var registry = await configuration.LoadPluginRegistryAsync();
        Assert.Contains(registry.Plugins, item => item.Id == new PluginId("sample.wallpaper") && item.State == PluginState.Enabled);
        Assert.Contains(registry.Plugins, item => item.Id == new PluginId("sample.clock") && item.State == PluginState.Enabled);
        Assert.Contains(registry.Plugins, item => item.Id == new PluginId("sample.system-info") && item.State == PluginState.Enabled);
        Assert.Contains(registry.Plugins, item => item.Id == new PluginId("sample.audio-visualizer") && item.State == PluginState.Enabled);
        var layout = await configuration.LoadLayoutAsync();
        Assert.Contains(layout.Instances, item => item.PluginId == new PluginId("sample.clock"));
        Assert.Contains(layout.Instances, item => item.PluginId == new PluginId("sample.system-info"));
        Assert.Contains(layout.Instances, item =>
            item.PluginId == new PluginId("sample.audio-visualizer")
            && item.Bounds.X == 0
            && !item.IsLocked
            && item.Bounds.Height <= System.Windows.SystemParameters.PrimaryScreenHeight * 0.25);
        Assert.DoesNotContain(layout.Instances, item => item.PluginId == new PluginId("sample.wallpaper"));
    }
    [Fact]
    public async Task InstallAsync_RepairsLockedAudioVisualizerLayout()
    {
        var root = Path.Combine(Path.GetTempPath(), "Moli.Desktop.Tests", Guid.NewGuid().ToString("N"));
        var paths = new DesktopPaths(Path.Combine(root, "app"), Path.Combine(root, "local"));
        var diagnostics = new DiagnosticsService(paths, NullLogger<DiagnosticsService>.Instance);
        var configuration = new JsonConfigurationService(paths, diagnostics);
        await configuration.SaveLayoutAsync(new LayoutDocument
        {
            Instances =
            [
                new WidgetLayout
                {
                    InstanceId = new WidgetInstanceId("sample.audio-visualizer.default"),
                    PluginId = new PluginId("sample.audio-visualizer"),
                    MonitorId = new MonitorId("primary"),
                    Bounds = new RectD(0, 720, 1920, 240),
                    IsLocked = true
                }
            ]
        });
        var installer = new DefaultContentInstaller(paths, configuration, diagnostics);
        await installer.InstallAsync();
        var layout = await configuration.LoadLayoutAsync();
        var visualizer = Assert.Single(layout.Instances, item => item.PluginId == new PluginId("sample.audio-visualizer"));
        Assert.False(visualizer.IsLocked);
    }
}
src/Moli.Desktop.Tests/Layout/LayoutManagerTests.cs
@@ -28,6 +28,7 @@
        Assert.Equal(LayoutManager.MinHeight, result.Value.Bounds.Height);
        Assert.Equal(LayoutManager.MaxScale, result.Value.Scale);
        Assert.Equal(LayoutManager.MinOpacity, result.Value.Opacity);
        Assert.Equal(DisplayPriority.AppLayer, manager.Update(layout.InstanceId, new WidgetLayoutPatch { DisplayPriority = DisplayPriority.AppLayer }).Value?.DisplayPriority);
        Assert.True(result.Value.Bounds.Right >= monitor.WorkArea.X + LayoutManager.MinVisibleDip);
        Assert.True(result.Value.Bounds.Bottom >= monitor.WorkArea.Y + LayoutManager.MinVisibleDip);
    }
src/Moli.Desktop/Assets/Moli.Desktop.ico
src/Moli.Desktop/Audio/AudioSpectrumAnalyzer.cs
New file
@@ -0,0 +1,124 @@
using NAudio.Dsp;
namespace Moli.Desktop.Audio;
public sealed class AudioSpectrumAnalyzer
{
    public const int DefaultFftSize = 1024;
    public const int DefaultLevelCount = 64;
    private readonly object _gate = new();
    private readonly int _fftSize;
    private readonly int _levelCount;
    private readonly float[] _ring;
    private int _writeIndex;
    private int _sampleCount;
    private bool _hasNewSamples;
    public AudioSpectrumAnalyzer(int sampleRate, int fftSize = DefaultFftSize, int levelCount = DefaultLevelCount)
    {
        if (!IsPowerOfTwo(fftSize))
        {
            throw new ArgumentException("FFT size must be a power of two.", nameof(fftSize));
        }
        SampleRate = sampleRate > 0 ? sampleRate : 48000;
        _fftSize = fftSize;
        _levelCount = levelCount > 0 ? levelCount : DefaultLevelCount;
        _ring = new float[fftSize * 2];
    }
    public int SampleRate { get; }
    public void AddSamples(ReadOnlySpan<float> samples)
    {
        lock (_gate)
        {
            foreach (var sample in samples)
            {
                _ring[_writeIndex] = Math.Clamp(sample, -1f, 1f);
                _writeIndex = (_writeIndex + 1) % _ring.Length;
                _sampleCount = Math.Min(_sampleCount + 1, _ring.Length);
            }
            if (samples.Length > 0)
            {
                _hasNewSamples = true;
            }
        }
    }
    public bool TryCreateFrame(out AudioSpectrumFrame frame)
    {
        var samples = new float[_fftSize];
        lock (_gate)
        {
            if (!_hasNewSamples || _sampleCount < _fftSize)
            {
                frame = default!;
                return false;
            }
            var start = (_writeIndex - _fftSize + _ring.Length) % _ring.Length;
            for (var index = 0; index < _fftSize; index++)
            {
                samples[index] = _ring[(start + index) % _ring.Length];
            }
            _hasNewSamples = false;
        }
        frame = BuildFrame(samples);
        return true;
    }
    private AudioSpectrumFrame BuildFrame(float[] samples)
    {
        var fft = new Complex[_fftSize];
        var rms = 0f;
        for (var index = 0; index < _fftSize; index++)
        {
            var window = (float)FastFourierTransform.HammingWindow(index, _fftSize);
            var sample = samples[index];
            rms += sample * sample;
            fft[index].X = sample * window;
            fft[index].Y = 0;
        }
        FastFourierTransform.FFT(true, (int)Math.Log2(_fftSize), fft);
        var levels = new float[_levelCount];
        var maxBin = _fftSize / 2 - 1;
        var minFrequency = 40d;
        var maxFrequency = Math.Min(16000d, SampleRate / 2d);
        for (var levelIndex = 0; levelIndex < levels.Length; levelIndex++)
        {
            var startRatio = (double)levelIndex / levels.Length;
            var endRatio = (double)(levelIndex + 1) / levels.Length;
            var startFrequency = minFrequency * Math.Pow(maxFrequency / minFrequency, startRatio);
            var endFrequency = minFrequency * Math.Pow(maxFrequency / minFrequency, endRatio);
            var startBin = Math.Clamp((int)Math.Floor(startFrequency * _fftSize / SampleRate), 1, maxBin);
            var endBin = Math.Clamp((int)Math.Ceiling(endFrequency * _fftSize / SampleRate), startBin, maxBin);
            var sum = 0d;
            var count = 0;
            for (var bin = startBin; bin <= endBin; bin++)
            {
                var magnitude = Math.Sqrt(fft[bin].X * fft[bin].X + fft[bin].Y * fft[bin].Y);
                sum += magnitude;
                count++;
            }
            var average = count == 0 ? 0 : sum / count;
            levels[levelIndex] = Math.Clamp((float)Math.Log10(1 + average * 32), 0f, 1f);
        }
        return new AudioSpectrumFrame
        {
            Levels = levels,
            Rms = Math.Clamp(MathF.Sqrt(rms / _fftSize), 0f, 1f),
            SampleRate = SampleRate
        };
    }
    private static bool IsPowerOfTwo(int value) => value > 0 && (value & (value - 1)) == 0;
}
src/Moli.Desktop/Audio/AudioSpectrumFrame.cs
New file
@@ -0,0 +1,9 @@
namespace Moli.Desktop.Audio;
public sealed record AudioSpectrumFrame
{
    public required float[] Levels { get; init; }
    public float Rms { get; init; }
    public int SampleRate { get; init; }
    public DateTimeOffset CapturedAt { get; init; } = DateTimeOffset.UtcNow;
}
src/Moli.Desktop/Audio/WasapiLoopbackAudioSpectrumService.cs
New file
@@ -0,0 +1,160 @@
using Microsoft.Extensions.Hosting;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Runtime;
using NAudio.Wave;
namespace Moli.Desktop.Audio;
public sealed class WasapiLoopbackAudioSpectrumService : BackgroundService
{
    private static readonly TimeSpan PublishInterval = TimeSpan.FromMilliseconds(33);
    private readonly IDiagnosticsService _diagnostics;
    private readonly IRuntimeEventBus _events;
    private WasapiLoopbackCapture? _capture;
    private AudioSpectrumAnalyzer? _analyzer;
    public WasapiLoopbackAudioSpectrumService(IDiagnosticsService diagnostics, IRuntimeEventBus events)
    {
        _diagnostics = diagnostics;
        _events = events;
    }
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            _capture = new WasapiLoopbackCapture();
            _analyzer = new AudioSpectrumAnalyzer(_capture.WaveFormat.SampleRate);
            _capture.DataAvailable += OnDataAvailable;
            _capture.RecordingStopped += OnRecordingStopped;
            _capture.StartRecording();
            _diagnostics.Record(
                DiagnosticSeverity.Info,
                "AudioLoopbackStarted",
                "WASAPI loopback audio capture started.",
                new Dictionary<string, string>
                {
                    ["sampleRate"] = _capture.WaveFormat.SampleRate.ToString(),
                    ["channels"] = _capture.WaveFormat.Channels.ToString()
                });
            using var timer = new PeriodicTimer(PublishInterval);
            while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false))
            {
                if (_analyzer.TryCreateFrame(out var frame))
                {
                    await _events.PublishAsync(new RuntimeEvent
                    {
                        Name = "audio.spectrum",
                        Payload = frame
                    }, stoppingToken).ConfigureAwait(false);
                }
            }
        }
        catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
        {
        }
        catch (Exception ex)
        {
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                "AudioLoopbackFailed",
                "WASAPI loopback audio capture failed.",
                new Dictionary<string, string> { ["exception"] = ex.GetType().Name, ["message"] = ex.Message });
        }
    }
    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        if (_capture is not null)
        {
            _capture.DataAvailable -= OnDataAvailable;
            _capture.RecordingStopped -= OnRecordingStopped;
            _capture.StopRecording();
            _capture.Dispose();
            _capture = null;
        }
        await base.StopAsync(cancellationToken).ConfigureAwait(false);
    }
    private void OnDataAvailable(object? sender, WaveInEventArgs e)
    {
        if (_capture is null || _analyzer is null)
        {
            return;
        }
        var samples = DecodeToMonoSamples(e.Buffer.AsSpan(0, e.BytesRecorded), _capture.WaveFormat);
        _analyzer.AddSamples(samples);
    }
    private void OnRecordingStopped(object? sender, StoppedEventArgs e)
    {
        if (e.Exception is null)
        {
            return;
        }
        _diagnostics.Record(
            DiagnosticSeverity.Warning,
            "AudioLoopbackStopped",
            "WASAPI loopback audio capture stopped unexpectedly.",
            new Dictionary<string, string> { ["exception"] = e.Exception.GetType().Name, ["message"] = e.Exception.Message });
    }
    private static float[] DecodeToMonoSamples(ReadOnlySpan<byte> buffer, WaveFormat format)
    {
        var bytesPerSample = format.BitsPerSample / 8;
        if (bytesPerSample <= 0 || format.Channels <= 0)
        {
            return [];
        }
        var frameSize = bytesPerSample * format.Channels;
        var frameCount = buffer.Length / frameSize;
        var samples = new float[frameCount];
        for (var frame = 0; frame < frameCount; frame++)
        {
            var frameOffset = frame * frameSize;
            var sum = 0f;
            for (var channel = 0; channel < format.Channels; channel++)
            {
                var offset = frameOffset + channel * bytesPerSample;
                sum += DecodeSample(buffer[offset..], format);
            }
            samples[frame] = sum / format.Channels;
        }
        return samples;
    }
    private static float DecodeSample(ReadOnlySpan<byte> sample, WaveFormat format)
    {
        if (format.Encoding == WaveFormatEncoding.IeeeFloat && format.BitsPerSample == 32)
        {
            return BitConverter.ToSingle(sample[..4]);
        }
        return format.BitsPerSample switch
        {
            16 => BitConverter.ToInt16(sample[..2]) / 32768f,
            24 => Decode24BitSample(sample[..3]) / 8388608f,
            32 => BitConverter.ToInt32(sample[..4]) / 2147483648f,
            _ => 0f
        };
    }
    private static int Decode24BitSample(ReadOnlySpan<byte> sample)
    {
        var value = sample[0] | (sample[1] << 8) | (sample[2] << 16);
        if ((value & 0x800000) != 0)
        {
            value |= unchecked((int)0xFF000000);
        }
        return value;
    }
}
src/Moli.Desktop/Configuration/ConfigurationDocuments.cs
@@ -62,6 +62,7 @@
    public double Opacity { get; init; } = 1;
    public bool ClickThrough { get; init; } = true;
    public double Scale { get; init; } = 1;
    public DisplayPriority DisplayPriority { get; init; } = DisplayPriority.IconLayer;
}
public sealed record LayoutDocument
src/Moli.Desktop/Diagnostics/DiagnosticsService.cs
@@ -33,13 +33,13 @@
            Properties = properties ?? new Dictionary<string, string>()
        };
        _logger.Log(MapLevel(severity), "{Code}: {Message}", code, message);
        lock (_gate)
        {
            _entries.Add(entry);
            AppendLog(entry);
        }
        _logger.Log(MapLevel(severity), "{Code}: {Message}", code, message);
        AppendLog(entry);
        return entry;
    }
@@ -59,8 +59,19 @@
            line += " " + string.Join(";", entry.Properties.Select(p => $"{p.Key}={p.Value}"));
        }
        try
        {
        File.AppendAllText(_logFile, line + Environment.NewLine, Encoding.UTF8);
    }
        catch (IOException)
        {
            _logger.LogWarning("Failed to append diagnostic log file because it is currently unavailable.");
        }
        catch (UnauthorizedAccessException)
        {
            _logger.LogWarning("Failed to append diagnostic log file because access was denied.");
        }
    }
    private static LogLevel MapLevel(DiagnosticSeverity severity) => severity switch
    {
src/Moli.Desktop/Host/DefaultContentInstaller.cs
@@ -1,6 +1,7 @@
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Layout;
@@ -15,7 +16,8 @@
    {
        "sample.wallpaper",
        "sample.clock",
        "sample.system-info"
        "sample.system-info",
        "sample.audio-visualizer"
    };
    private readonly DesktopPaths _paths;
@@ -71,7 +73,7 @@
            }
            var targetDirectory = Path.Combine(_paths.PluginDirectory, manifest.Id);
            CopyDirectoryMissingFiles(sourceDirectory, targetDirectory);
            CopyDirectoryReplacingFiles(sourceDirectory, targetDirectory);
            manifests.Add((manifest, manifest.Id));
        }
@@ -144,8 +146,14 @@
        foreach (var manifest in manifests.Where(manifest => manifest.Type == PluginType.Widget))
        {
            var pluginId = new PluginId(manifest.Id);
            if (layout.Instances.Any(instance => instance.PluginId == pluginId))
            var existingInstances = layout.Instances.Where(instance => instance.PluginId == pluginId).ToList();
            if (existingInstances.Count > 0)
            {
                if (RepairAudioVisualizerLayout(manifest, layout.Instances))
                {
                    changed = true;
                }
                continue;
            }
@@ -155,14 +163,15 @@
                PluginId = pluginId,
                MonitorId = new MonitorId("primary"),
                Bounds = new RectD(
                    manifest.DefaultLayout.X,
                    manifest.DefaultLayout.Y,
                    manifest.DefaultLayout.Width,
                    manifest.DefaultLayout.Height),
                    ResolveDefaultX(manifest),
                    ResolveDefaultY(manifest),
                    ResolveDefaultWidth(manifest),
                    ResolveDefaultHeight(manifest)),
                IsLocked = manifest.DefaultLayout.Locked,
                ClickThrough = manifest.DefaultLayout.ClickThrough,
                Opacity = manifest.DefaultLayout.Opacity,
                Scale = manifest.DefaultLayout.Scale
                Scale = manifest.DefaultLayout.Scale,
                DisplayPriority = manifest.DefaultLayout.DisplayPriority
            });
            changed = true;
        }
@@ -173,7 +182,7 @@
        }
    }
    private static void CopyDirectoryMissingFiles(string sourceDirectory, string targetDirectory)
    private static void CopyDirectoryReplacingFiles(string sourceDirectory, string targetDirectory)
    {
        Directory.CreateDirectory(targetDirectory);
@@ -182,13 +191,48 @@
            var relativePath = Path.GetRelativePath(sourceDirectory, sourceFile);
            var targetFile = Path.Combine(targetDirectory, relativePath);
            Directory.CreateDirectory(Path.GetDirectoryName(targetFile)!);
            if (!File.Exists(targetFile))
            File.Copy(sourceFile, targetFile, overwrite: true);
        }
    }
    private static bool RepairAudioVisualizerLayout(PluginManifest manifest, IList<WidgetLayout> layouts)
            {
                File.Copy(sourceFile, targetFile);
        if (!IsAudioVisualizer(manifest))
        {
            return false;
        }
        var changed = false;
        for (var index = 0; index < layouts.Count; index++)
        {
            var layout = layouts[index];
            if (layout.PluginId == new PluginId(manifest.Id) && layout.IsLocked)
            {
                layouts[index] = layout with { IsLocked = false };
                changed = true;
            }
        }
        return changed;
    }
    private static bool IsAudioVisualizer(PluginManifest manifest)
        => string.Equals(manifest.Id, "sample.audio-visualizer", StringComparison.OrdinalIgnoreCase);
    private static double ResolveDefaultX(PluginManifest manifest)
        => IsAudioVisualizer(manifest) ? 0 : manifest.DefaultLayout.X;
    private static double ResolveDefaultY(PluginManifest manifest)
        => IsAudioVisualizer(manifest) ? SystemParameters.PrimaryScreenHeight * 2 / 3 : manifest.DefaultLayout.Y;
    private static double ResolveDefaultWidth(PluginManifest manifest)
        => IsAudioVisualizer(manifest) ? SystemParameters.PrimaryScreenWidth : manifest.DefaultLayout.Width;
    private static double ResolveDefaultHeight(PluginManifest manifest)
        => IsAudioVisualizer(manifest)
            ? Math.Min(SystemParameters.PrimaryScreenHeight * 0.25, Math.Max(LayoutManager.MinHeight, manifest.DefaultLayout.Height))
            : manifest.DefaultLayout.Height;
    private static string? ResolveSamplePluginRoot()
    {
        var candidates = new[]
src/Moli.Desktop/Host/DesktopHostBuilder.cs
@@ -1,6 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Moli.Desktop.Audio;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Interop;
@@ -32,6 +33,7 @@
                services.AddSingleton<IDiagnosticsService, DiagnosticsService>();
                services.AddSingleton<IDefaultContentInstaller, DefaultContentInstaller>();
                services.AddSingleton<IRuntimeEventBus, RuntimeEventBus>();
                services.AddHostedService<WasapiLoopbackAudioSpectrumService>();
                services.AddSingleton<IRuntimeSurfaceController, RuntimeSurfaceController>();
                services.AddSingleton<IDesktopRuntime, DesktopRuntimeCoordinator>();
                services.AddSingleton<IConfigurationService, JsonConfigurationService>();
src/Moli.Desktop/Layout/Geometry.cs
@@ -23,6 +23,13 @@
    public override string ToString() => Value;
}
public enum DisplayPriority
{
    DesktopLayer,
    IconLayer,
    AppLayer
}
public sealed record WidgetRuntimeState
{
    public required WidgetInstanceId InstanceId { get; init; }
@@ -33,6 +40,7 @@
    public bool IsLocked { get; init; }
    public double Opacity { get; init; } = 1;
    public bool ClickThrough { get; init; } = true;
    public DisplayPriority DisplayPriority { get; init; } = DisplayPriority.IconLayer;
}
public sealed record WidgetLayoutPatch
@@ -44,4 +52,5 @@
    public double? Opacity { get; init; }
    public bool? ClickThrough { get; init; }
    public double? Scale { get; init; }
    public DisplayPriority? DisplayPriority { get; init; }
}
src/Moli.Desktop/Layout/LayoutManager.cs
@@ -82,7 +82,8 @@
            IsLocked = plugin.Manifest.DefaultLayout.Locked,
            ClickThrough = plugin.Manifest.DefaultLayout.ClickThrough,
            Opacity = Clamp(plugin.Manifest.DefaultLayout.Opacity, MinOpacity, MaxOpacity),
            Scale = Clamp(plugin.Manifest.DefaultLayout.Scale, MinScale, MaxScale)
            Scale = Clamp(plugin.Manifest.DefaultLayout.Scale, MinScale, MaxScale),
            DisplayPriority = plugin.Manifest.DefaultLayout.DisplayPriority
        };
        lock (_gate)
@@ -119,7 +120,8 @@
            IsLocked = patch.IsLocked ?? layout.IsLocked,
            Opacity = patch.Opacity ?? layout.Opacity,
            ClickThrough = patch.ClickThrough ?? layout.ClickThrough,
            Scale = patch.Scale ?? layout.Scale
            Scale = patch.Scale ?? layout.Scale,
            DisplayPriority = patch.DisplayPriority ?? layout.DisplayPriority
        });
    }
src/Moli.Desktop/Management/ManagementWindow.xaml
@@ -14,7 +14,10 @@
                    <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" />
                <StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
                    <Button Content="刷新" Width="88" Height="32" Margin="0,0,8,0" Click="RefreshButton_Click" />
                    <Button Content="恢复默认" Width="96" Height="32" Click="RestoreDefaults_Click" />
                </StackPanel>
            </DockPanel>
        </Border>
@@ -51,7 +54,7 @@
            <TabItem Header="壁纸">
                <StackPanel Margin="8">
                    <TextBlock x:Name="WallpaperDetailText" Margin="0,0,0,12" />
                    <TextBlock Text="壁纸控制通过底部命令栏执行。" Foreground="#526070" />
                    <Button Content="选择壁纸文件" Width="128" HorizontalAlignment="Left" Click="ChooseWallpaperFile_Click" />
                </StackPanel>
            </TabItem>
            <TabItem Header="组件">
@@ -60,12 +63,28 @@
                        <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" />
                        <ComboBox x:Name="DisplayPrioritySelector" Width="132" Margin="0,0,8,0" />
                        <Button Content="应用优先级" Width="104" Margin="0,0,8,0" Click="ApplyDisplayPriority_Click" />
                    </WrapPanel>
                    <DataGrid x:Name="WidgetsGrid" AutoGenerateColumns="True" IsReadOnly="True" />
                    <DataGrid x:Name="WidgetsGrid" AutoGenerateColumns="True" IsReadOnly="True">
                        <DataGrid.ContextMenu>
                            <ContextMenu>
                                <MenuItem Header="编辑位置/大小" Click="EditWidgetLayout_Click" />
                                <MenuItem Header="打开 layout.json" Click="OpenLayoutJson_Click" />
                            </ContextMenu>
                        </DataGrid.ContextMenu>
                    </DataGrid>
                </DockPanel>
            </TabItem>
            <TabItem Header="插件">
                <DataGrid x:Name="PluginsGrid" Margin="8" AutoGenerateColumns="True" IsReadOnly="True" />
                <DataGrid x:Name="PluginsGrid" Margin="8" AutoGenerateColumns="True" IsReadOnly="True">
                    <DataGrid.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="打开 plugin.json" Click="OpenPluginJson_Click" />
                            <MenuItem Header="打开 plugins.json" Click="OpenPluginsJson_Click" />
                        </ContextMenu>
                    </DataGrid.ContextMenu>
                </DataGrid>
            </TabItem>
            <TabItem Header="诊断">
                <DockPanel Margin="8">
src/Moli.Desktop/Management/ManagementWindow.xaml.cs
@@ -1,11 +1,24 @@
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Moli.Desktop.Api;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
using Microsoft.Win32;
using MessageBox = System.Windows.MessageBox;
using WpfButton = System.Windows.Controls.Button;
using WpfTextBox = System.Windows.Controls.TextBox;
namespace Moli.Desktop.Management;
@@ -14,18 +27,22 @@
    private readonly IDesktopRuntime _runtime;
    private readonly IDiagnosticsService _diagnostics;
    private readonly ILocalApiStatus _apiStatus;
    private readonly DesktopPaths _paths;
    private readonly DispatcherTimer _timer;
    private AppRuntimeState? _state;
    public ManagementWindow(
        IDesktopRuntime runtime,
        IDiagnosticsService diagnostics,
        ILocalApiStatus apiStatus)
        ILocalApiStatus apiStatus,
        DesktopPaths paths)
    {
        _runtime = runtime;
        _diagnostics = diagnostics;
        _apiStatus = apiStatus;
        _paths = paths;
        InitializeComponent();
        DisplayPrioritySelector.ItemsSource = Enum.GetValues<DisplayPriority>();
        _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
        _timer.Tick += async (_, _) => await RefreshAsync();
        Loaded += async (_, _) =>
@@ -60,6 +77,7 @@
        WidgetSelector.ItemsSource = widgets;
        WidgetSelector.SelectedItem = widgets.FirstOrDefault(widget => widget.InstanceId == selected) ?? widgets.FirstOrDefault();
        WidgetsGrid.ItemsSource = widgets;
        DisplayPrioritySelector.SelectedItem = (WidgetSelector.SelectedItem as WidgetRow)?.DisplayPriority ?? DisplayPriority.IconLayer;
        PluginsGrid.ItemsSource = _state.Plugins.Select(PluginRow.From).ToArray();
        DiagnosticsGrid.ItemsSource = diagnostics.Select(DiagnosticRow.From).ToArray();
        RecentDiagnosticsGrid.ItemsSource = diagnostics.Take(8).Select(DiagnosticRow.From).ToArray();
@@ -73,6 +91,15 @@
    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 ApplyDisplayPriority_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedWidget() is not { } widget || DisplayPrioritySelector.SelectedItem is not DisplayPriority priority)
        {
            return;
        }
        await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { DisplayPriority = priority });
    }
    private async void ToggleWidgetVisible_Click(object sender, RoutedEventArgs e)
    {
@@ -95,10 +122,30 @@
    }
    private async void ResetLayout_Click(object sender, RoutedEventArgs e)
        => await ResetRuntimeLayoutAsync(confirm: false);
    private async void RestoreDefaults_Click(object sender, RoutedEventArgs e)
        => await ResetRuntimeLayoutAsync(confirm: true);
    private async Task ResetRuntimeLayoutAsync(bool confirm)
    {
        if (_state is null)
        {
            return;
        }
        if (confirm)
        {
            var choice = MessageBox.Show(
                this,
                "确认恢复默认布局和交互配置?此操作会显示并解锁组件,恢复透明度、点击穿透和默认显示优先级。",
                "恢复默认",
                MessageBoxButton.YesNo,
                MessageBoxImage.Warning);
            if (choice != MessageBoxResult.Yes)
            {
                return;
            }
        }
        foreach (var widget in _state.Widgets)
@@ -110,14 +157,150 @@
                    IsVisible = true,
                    IsLocked = false,
                    Opacity = 1,
                    ClickThrough = true
                    ClickThrough = true,
                    DisplayPriority = DisplayPriority.IconLayer
                });
        }
        await RefreshAsync();
    }
    private async void EditWidgetLayout_Click(object sender, RoutedEventArgs e)
    {
        if (SelectedWidget() is not { } widget)
        {
            return;
        }
        var dialog = new WidgetLayoutDialog(widget) { Owner = this };
        if (dialog.ShowDialog() == true)
        {
            await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { Bounds = dialog.Bounds });
        }
    }
    private void OpenLayoutJson_Click(object sender, RoutedEventArgs e)
        => OpenJson(Path.Combine(_paths.ConfigDirectory, "layout.json"));
    private void OpenPluginsJson_Click(object sender, RoutedEventArgs e)
        => OpenJson(Path.Combine(_paths.ConfigDirectory, "plugins.json"));
    private void OpenPluginJson_Click(object sender, RoutedEventArgs e)
    {
        if ((PluginsGrid.SelectedItem as PluginRow) is not { } plugin)
        {
            return;
        }
        OpenJson(Path.Combine(_paths.PluginDirectory, plugin.Id, "plugin.json"));
    }
    private async void ChooseWallpaperFile_Click(object sender, RoutedEventArgs e)
    {
        var dialog = new Microsoft.Win32.OpenFileDialog
        {
            Title = "选择壁纸文件",
            Filter = "壁纸文件|*.html;*.htm;*.png;*.jpg;*.jpeg;*.gif;*.svg|HTML|*.html;*.htm|图片|*.png;*.jpg;*.jpeg;*.gif;*.svg|所有文件|*.*"
        };
        if (dialog.ShowDialog(this) != true)
        {
            return;
        }
        await InstallWallpaperFilePluginAsync(dialog.FileName);
        await ExecuteAsync(() => _runtime.ReloadPluginsAsync());
        await ExecuteAsync(() => _runtime.EnableWallpaperAsync());
    }
    private WidgetRow? SelectedWidget() => WidgetSelector.SelectedItem as WidgetRow;
    private async Task InstallWallpaperFilePluginAsync(string fileName)
    {
        Directory.CreateDirectory(_paths.PluginDirectory);
        var pluginDirectory = Path.Combine(_paths.PluginDirectory, "user.wallpaper-file");
        Directory.CreateDirectory(pluginDirectory);
        var extension = Path.GetExtension(fileName).ToLowerInvariant();
        var uri = new Uri(fileName).AbsoluteUri;
        var body = extension switch
        {
            ".html" or ".htm" => $"<iframe src=\"{Html(uri)}\"></iframe>",
            ".svg" => $"<object data=\"{Html(uri)}\" type=\"image/svg+xml\"></object>",
            _ => $"<img src=\"{Html(uri)}\" alt=\"wallpaper\" />"
        };
        var indexHtml = $$"""
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #05070a; }
    img, object, iframe { width: 100vw; height: 100vh; border: 0; object-fit: cover; display: block; }
  </style>
</head>
<body>
  {{body}}
</body>
</html>
""";
        await File.WriteAllTextAsync(Path.Combine(pluginDirectory, "index.html"), indexHtml, new UTF8Encoding(false));
        var manifest = new
        {
            id = "user.wallpaper-file",
            name = "用户选择壁纸",
            version = "1.0.0",
            type = "wallpaper",
            entry = "index.html",
            description = $"Loaded from {Path.GetFileName(fileName)}.",
            author = "Moli.Desktop",
            permissions = Array.Empty<string>(),
            defaultLayout = new { width = 1920, height = 1080, x = 0, y = 0, locked = true, clickThrough = true, opacity = 1, scale = 1 },
            config = new { sourceFile = fileName, sourceType = extension.TrimStart('.') }
        };
        await File.WriteAllTextAsync(
            Path.Combine(pluginDirectory, "plugin.json"),
            JsonSerializer.Serialize(manifest, new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }),
            new UTF8Encoding(false));
        await PreferWallpaperPluginAsync("user.wallpaper-file");
    }
    private async Task PreferWallpaperPluginAsync(string pluginId)
    {
        var path = Path.Combine(_paths.ConfigDirectory, "plugins.json");
        if (!File.Exists(path))
        {
            return;
        }
        var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
        {
            Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
        };
        using var stream = File.OpenRead(path);
        var registry = await JsonSerializer.DeserializeAsync<PluginRegistryDocument>(stream, options);
        if (registry is null)
        {
            return;
        }
        registry.Plugins.RemoveAll(item => item.Id.Value is "sample.wallpaper" or "user.wallpaper-file");
        registry.Plugins.Insert(0, new PluginRegistryItem { Id = new PluginId(pluginId), State = PluginState.Enabled, UpdatedAt = DateTimeOffset.UtcNow });
        registry.Plugins.Add(new PluginRegistryItem { Id = new PluginId("sample.wallpaper"), State = PluginState.Disabled, UpdatedAt = DateTimeOffset.UtcNow });
        await File.WriteAllTextAsync(path, JsonSerializer.Serialize(registry, new JsonSerializerOptions(options) { WriteIndented = true }), new UTF8Encoding(false));
    }
    private void OpenJson(string path)
    {
        if (!File.Exists(path))
        {
            MessageBox.Show(this, $"文件不存在:{path}", "打开配置", MessageBoxButton.OK, MessageBoxImage.Information);
            return;
        }
        Process.Start(new ProcessStartInfo("notepad.exe", $"\"{path}\"") { UseShellExecute = true });
    }
    private async Task ExecuteAsync(Func<Task<OperationResult<AppRuntimeState>>> command)
    {
@@ -150,7 +333,9 @@
        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)
    private static string Html(string value) => System.Net.WebUtility.HtmlEncode(value);
    private sealed record WidgetRow(string InstanceId, string PluginId, string Bounds, string MonitorId, bool IsVisible, bool IsLocked, double Opacity, bool ClickThrough, DisplayPriority DisplayPriority)
    {
        public static WidgetRow From(WidgetRuntimeState state)
            => new(
@@ -161,7 +346,8 @@
                state.IsVisible,
                state.IsLocked,
                state.Opacity,
                state.ClickThrough);
                state.ClickThrough,
                state.DisplayPriority);
    }
    private sealed record PluginRow(string Id, string Name, string Type, string State, string? ErrorCode, string Entry)
@@ -175,4 +361,86 @@
        public static DiagnosticRow From(DiagnosticEntry entry)
            => new(entry.Timestamp, entry.Severity.ToString(), entry.Code, entry.Message);
    }
    private sealed class WidgetLayoutDialog : Window
    {
        private readonly WpfTextBox _x;
        private readonly WpfTextBox _y;
        private readonly WpfTextBox _width;
        private readonly WpfTextBox _height;
        public WidgetLayoutDialog(WidgetRow widget)
        {
            Title = "编辑位置/大小";
            Width = 320;
            Height = 230;
            WindowStartupLocation = WindowStartupLocation.CenterOwner;
            ResizeMode = ResizeMode.NoResize;
            var parts = widget.Bounds.Replace("x", " ").Replace(",", " ").Split(' ', StringSplitOptions.RemoveEmptyEntries);
            _x = Box(parts.ElementAtOrDefault(0) ?? "0");
            _y = Box(parts.ElementAtOrDefault(1) ?? "0");
            _width = Box(parts.ElementAtOrDefault(2) ?? "320");
            _height = Box(parts.ElementAtOrDefault(3) ?? "160");
            var grid = new Grid { Margin = new Thickness(16) };
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(72) });
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            for (var i = 0; i < 5; i++)
            {
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
            }
            AddRow(grid, 0, "X", _x);
            AddRow(grid, 1, "Y", _y);
            AddRow(grid, 2, "宽度", _width);
            AddRow(grid, 3, "高度", _height);
            var buttons = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, Margin = new Thickness(0, 12, 0, 0) };
            var ok = new WpfButton { Content = "确定", Width = 72, Margin = new Thickness(0, 0, 8, 0) };
            var cancel = new WpfButton { Content = "取消", Width = 72 };
            ok.Click += (_, _) =>
            {
                if (TryBuildBounds())
                {
                    DialogResult = true;
                }
            };
            cancel.Click += (_, _) => DialogResult = false;
            buttons.Children.Add(ok);
            buttons.Children.Add(cancel);
            Grid.SetRow(buttons, 4);
            Grid.SetColumnSpan(buttons, 2);
            grid.Children.Add(buttons);
            Content = grid;
        }
        public RectD Bounds { get; private set; }
        private bool TryBuildBounds()
        {
            if (double.TryParse(_x.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var x)
                && double.TryParse(_y.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var y)
                && double.TryParse(_width.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var width)
                && double.TryParse(_height.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var height))
            {
                Bounds = new RectD(x, y, width, height);
                return true;
            }
            MessageBox.Show(this, "请输入有效数字。", "编辑位置/大小", MessageBoxButton.OK, MessageBoxImage.Warning);
            return false;
        }
        private static WpfTextBox Box(string text) => new() { Text = text, Margin = new Thickness(0, 0, 0, 8) };
        private static void AddRow(Grid grid, int row, string label, WpfTextBox textBox)
        {
            var text = new TextBlock { Text = label, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 8, 8) };
            Grid.SetRow(text, row);
            Grid.SetColumn(text, 0);
            Grid.SetRow(textBox, row);
            Grid.SetColumn(textBox, 1);
            grid.Children.Add(text);
            grid.Children.Add(textBox);
        }
    }
}
src/Moli.Desktop/Moli.Desktop.csproj
@@ -7,11 +7,13 @@
    <ImplicitUsings>enable</ImplicitUsings>
    <UseWPF>true</UseWPF>
    <UseWindowsForms>true</UseWindowsForms>
    <ApplicationIcon>Assets\Moli.Desktop.ico</ApplicationIcon>
  </PropertyGroup>
  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.3912.50" />
    <PackageReference Include="NAudio" Version="2.3.0" />
  </ItemGroup>
  <ItemGroup>
src/Moli.Desktop/Plugins/PluginManifest.cs
@@ -13,6 +13,7 @@
    public bool ClickThrough { get; init; }
    public double Opacity { get; init; } = 1;
    public double Scale { get; init; } = 1;
    public DisplayPriority DisplayPriority { get; init; } = DisplayPriority.IconLayer;
}
public sealed record PluginManifest
src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
@@ -327,7 +327,8 @@
        IsVisible = layout.IsVisible,
        IsLocked = _isGlobalLocked || layout.IsLocked,
        Opacity = layout.Opacity,
        ClickThrough = _isEditMode || _isSafeInputMode ? false : layout.ClickThrough
        ClickThrough = _isEditMode || _isSafeInputMode ? false : layout.ClickThrough,
        DisplayPriority = layout.DisplayPriority
    };
    private WidgetLayout ToSurfaceLayout(WidgetLayout layout)
src/Moli.Desktop/WebView/WebViewHost.cs
@@ -2,6 +2,7 @@
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Windows;
using System.Drawing;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using Moli.Desktop.Diagnostics;
@@ -23,6 +24,7 @@
    };
    private PluginBridgeContext? _bridgeContext;
    private WebViewHostOptions? _options;
    private IDisposable? _audioSubscription;
    private bool _initialized;
    public WebViewHost(
@@ -51,10 +53,20 @@
        Directory.CreateDirectory(options.UserDataFolder);
        var environment = await CoreWebView2Environment.CreateAsync(null, options.UserDataFolder).ConfigureAwait(true);
        await Control.EnsureCoreWebView2Async(environment).ConfigureAwait(true);
        if (options.IsTransparent)
        {
            Control.DefaultBackgroundColor = Color.Transparent;
        }
        Control.CoreWebView2.Settings.AreDevToolsEnabled = options.AreDevToolsEnabled;
        Control.CoreWebView2.IsMuted = options.IsMuted;
        Control.CoreWebView2.WebMessageReceived += OnWebMessageReceived;
        Control.CoreWebView2.ScreenCaptureStarting += OnScreenCaptureStarting;
        Control.NavigationCompleted += OnNavigationCompleted;
        if (HasPermission("audio-capture"))
        {
            _audioSubscription = _events.Subscribe(DispatchAudioSpectrumAsync);
        }
        if (!string.IsNullOrWhiteSpace(options.InitialScript))
        {
@@ -113,14 +125,36 @@
    public async ValueTask DisposeAsync()
    {
        _audioSubscription?.Dispose();
        _audioSubscription = null;
        if (Control.CoreWebView2 is not null)
        {
            Control.CoreWebView2.WebMessageReceived -= OnWebMessageReceived;
            Control.CoreWebView2.ScreenCaptureStarting -= OnScreenCaptureStarting;
        }
        Control.NavigationCompleted -= OnNavigationCompleted;
        Control.Dispose();
        await Task.CompletedTask;
    }
    private Task DispatchAudioSpectrumAsync(RuntimeEvent runtimeEvent)
    {
        if (runtimeEvent.Name != "audio.spectrum" || runtimeEvent.Payload is null)
        {
            return Task.CompletedTask;
        }
        var detail = JsonSerializer.Serialize(runtimeEvent.Payload, _jsonOptions);
        var script = $"window.dispatchEvent(new CustomEvent(\"moli:audio-spectrum\", {{ detail: {detail} }}));";
        var dispatcher = Control.Dispatcher;
        if (dispatcher.CheckAccess())
        {
            return ExecuteScriptSafelyAsync(script);
        }
        return dispatcher.InvokeAsync(() => ExecuteScriptSafelyAsync(script)).Task.Unwrap();
    }
    private async void OnWebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
@@ -165,6 +199,36 @@
        }).ConfigureAwait(false);
    }
    private void OnScreenCaptureStarting(object? sender, CoreWebView2ScreenCaptureStartingEventArgs e)
    {
        e.Cancel = true;
        e.Handled = true;
        _diagnostics.Record(
            DiagnosticSeverity.Info,
            "WebViewScreenCaptureBlocked",
            "WebView screen capture request was blocked.",
            new Dictionary<string, string> { ["hostId"] = HostId, ["pluginId"] = PluginId.Value });
    }
    private async Task ExecuteScriptSafelyAsync(string script)
    {
        if (!_initialized || Control.CoreWebView2 is null)
        {
            return;
        }
        try
        {
            await Control.ExecuteScriptAsync(script).ConfigureAwait(true);
        }
        catch (InvalidOperationException)
        {
        }
    }
    private bool HasPermission(string permission)
        => _plugin.Manifest.Permissions.Any(item => string.Equals(item, permission, StringComparison.OrdinalIgnoreCase));
    private void EnsureInitialized()
    {
        if (!_initialized || Control.CoreWebView2 is null || _options is null)
src/Moli.Desktop/Windows/WidgetWindow.cs
@@ -126,6 +126,7 @@
        Height = layout.Bounds.Height;
        Opacity = Math.Clamp(layout.Opacity, 0.1, 1.0);
        Visibility = layout.IsVisible ? Visibility.Visible : Visibility.Hidden;
        Topmost = layout.DisplayPriority is DisplayPriority.IconLayer or DisplayPriority.AppLayer;
        _editBorder.Visibility = editMode ? Visibility.Visible : Visibility.Collapsed;
        _resizeGrip.Visibility = editMode && !layout.IsLocked ? Visibility.Visible : Visibility.Collapsed;
        ApplyWin32Styles();