Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fcbcf07b87 | ||
|
|
063718f86d | ||
|
|
6cfa74c901 | ||
|
|
c9e61f38c5 | ||
|
|
ad987111a3 |
No files matched your search
@@ -386,6 +386,7 @@ LibreHardwareMonitor 访问 CPU MSR(温度/时钟)、存储 SMART、SMBus、
|
||||
采用 **ShellExecuteW "runas"** 弹 UAC 提权启动 Kernel,架构上与普通模式分离:
|
||||
|
||||
- **启动**:[monitor_kernel.rs](file:///d:/Atie/Gitea/Thing/src-tauri/src/monitor_kernel.rs) `start_elevated` → 停止当前 Kernel → `ShellExecuteW "runas"` 启动管理员 Kernel(隐藏控制台窗口)→ 等待 ready → 重新订阅 SSE
|
||||
- **提权偏好(持久化)**:提权成功后会写入 `{app_data_dir}/monitor/settings.json` 的 `elevateOnStart=true`。此后 `start_with_subscription` 检测到该偏好且 Thing 非管理员时,改走 `start_elevated`,因此**应用重启后的自动启动路径也会提权**(仍会弹一次 UAC 确认)。前端「监控设置」提供同名开关可随时关闭(关闭后内核启动回到普通权限)。
|
||||
- **停止**:调用 Kernel 的 `POST /shutdown` 接口(普通权限无法 `TerminateProcess` 管理员进程)
|
||||
- **状态查询**:通过 HTTP `/status` 判断运行状态(pid 不可用,返回 None)
|
||||
|
||||
@@ -397,7 +398,7 @@ LibreHardwareMonitor 访问 CPU MSR(温度/时钟)、存储 SMART、SMBus、
|
||||
| 崩溃重启 | 3s 巡检 + 自动重启 | 不支持(需手动重新提权) |
|
||||
| 停止方式 | `ProcessManager.stop`(kill) | `POST /shutdown`(优雅退出) |
|
||||
| PID 查询 | 可用 | 不可用(返回 None) |
|
||||
| UAC 弹窗 | 无 | 每次启动需确认 |
|
||||
| UAC 弹窗 | 无 | 每次启动需确认(提权偏好开启时,应用重启后的自动启动同样弹一次) |
|
||||
|
||||
### 7.4 C# Kernel /shutdown 接口
|
||||
|
||||
|
||||
@@ -5,13 +5,43 @@
|
||||
"": {
|
||||
"name": "thing",
|
||||
"dependencies": {
|
||||
"@lucide/vue": "^1.28.0",
|
||||
"@codemirror/autocomplete": "^6.20.3",
|
||||
"@codemirror/commands": "^6.11.1",
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
"@codemirror/lang-go": "^6.0.1",
|
||||
"@codemirror/lang-html": "^6.4.12",
|
||||
"@codemirror/lang-java": "^6.0.2",
|
||||
"@codemirror/lang-javascript": "^6.2.5",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/lang-less": "^6.0.2",
|
||||
"@codemirror/lang-markdown": "^6.5.2",
|
||||
"@codemirror/lang-php": "^6.0.2",
|
||||
"@codemirror/lang-python": "^6.2.1",
|
||||
"@codemirror/lang-rust": "^6.0.2",
|
||||
"@codemirror/lang-sass": "^6.0.2",
|
||||
"@codemirror/lang-sql": "^6.10.0",
|
||||
"@codemirror/lang-vue": "^0.1.3",
|
||||
"@codemirror/lang-xml": "^6.1.0",
|
||||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/language": "^6.12.4",
|
||||
"@codemirror/language-data": "^6.5.2",
|
||||
"@codemirror/legacy-modes": "^6.5.4",
|
||||
"@codemirror/merge": "^6.12.2",
|
||||
"@codemirror/search": "^6.7.2",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@codemirror/view": "^6.43.13",
|
||||
"@lucide/vue": "^1.48.0",
|
||||
"@replit/codemirror-lang-csharp": "^6.2.0",
|
||||
"@replit/codemirror-lang-svelte": "^6.0.0",
|
||||
"@tailwindcss/vite": "^4.3.2",
|
||||
"@tauri-apps/api": "^2",
|
||||
"@tauri-apps/plugin-autostart": "~2",
|
||||
"@tauri-apps/plugin-dialog": "^2",
|
||||
"@tauri-apps/plugin-global-shortcut": "^2",
|
||||
"@tauri-apps/plugin-opener": "^2",
|
||||
"@tauri-apps/api": "^2.12.0",
|
||||
"@tauri-apps/plugin-autostart": "~2.6.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.0",
|
||||
"@tauri-apps/plugin-global-shortcut": "^2.4.0",
|
||||
"@tauri-apps/plugin-opener": "^2.7.0",
|
||||
"@uiw/codemirror-themes": "^4.25.12",
|
||||
"@vueuse/core": "^14.4.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-search": "^0.16.0",
|
||||
@@ -22,10 +52,15 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"codemirror-lang-elixir": "^4.0.1",
|
||||
"codemirror-lang-makefile": "^0.1.1",
|
||||
"dompurify": "^3.4.16",
|
||||
"highlight.js": "^11.12.0",
|
||||
"markdown-it": "^15.0.2",
|
||||
"pinia": "^3.0.4",
|
||||
"pinyin-pro": "^3.28.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"reka-ui": "^2.10.1",
|
||||
"reka-ui": "^2.10.5",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tailwindcss": "^4.3.2",
|
||||
"vue": "^3.5.13",
|
||||
@@ -33,7 +68,8 @@
|
||||
"vue-sonner": "^2.0.9",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2",
|
||||
"@tauri-apps/cli": "^2.12.0",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^26.1.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
@@ -60,6 +96,70 @@
|
||||
|
||||
"@cacheable/utils": ["@cacheable/utils@2.5.0", "https://registry.npmmirror.com/@cacheable/utils/-/utils-2.5.0.tgz", { "dependencies": { "hashery": "^1.5.1", "keyv": "^5.6.0" } }, "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA=="],
|
||||
|
||||
"@codemirror/autocomplete": ["@codemirror/autocomplete@6.20.3", "https://registry.npmmirror.com/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0" } }, "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g=="],
|
||||
|
||||
"@codemirror/commands": ["@codemirror/commands@6.11.1", "https://registry.npmmirror.com/@codemirror/commands/-/commands-6.11.1.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.7.0", "@codemirror/view": "^6.27.0", "@lezer/common": "^1.1.0" } }, "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg=="],
|
||||
|
||||
"@codemirror/lang-angular": ["@codemirror/lang-angular@0.1.4", "https://registry.npmmirror.com/@codemirror/lang-angular/-/lang-angular-0.1.4.tgz", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-javascript": "^6.1.2", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.3" } }, "sha512-oap+gsltb/fzdlTQWD6BFF4bSLKcDnlxDsLdePiJpCVNKWXSTAbiiQeYI3UmES+BLAdkmIC1WjyztC1pi/bX4g=="],
|
||||
|
||||
"@codemirror/lang-cpp": ["@codemirror/lang-cpp@6.0.3", "https://registry.npmmirror.com/@codemirror/lang-cpp/-/lang-cpp-6.0.3.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/cpp": "^1.0.0" } }, "sha512-URM26M3vunFFn9/sm6rzqrBzDgfWuDixp85uTY49wKudToc2jTHUrKIGGKs+QWND+YLofNNZpxcNGRynFJfvgA=="],
|
||||
|
||||
"@codemirror/lang-css": ["@codemirror/lang-css@6.3.1", "https://registry.npmmirror.com/@codemirror/lang-css/-/lang-css-6.3.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.2", "@lezer/css": "^1.1.7" } }, "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg=="],
|
||||
|
||||
"@codemirror/lang-go": ["@codemirror/lang-go@6.0.1", "https://registry.npmmirror.com/@codemirror/lang-go/-/lang-go-6.0.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.6.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/go": "^1.0.0" } }, "sha512-7fNvbyNylvqCphW9HD6WFnRpcDjr+KXX/FgqXy5H5ZS0eC5edDljukm/yNgYkwTsgp2busdod50AOTIy6Jikfg=="],
|
||||
|
||||
"@codemirror/lang-html": ["@codemirror/lang-html@6.4.12", "https://registry.npmmirror.com/@codemirror/lang-html/-/lang-html-6.4.12.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/css": "^1.1.0", "@lezer/html": "^1.3.12" } }, "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w=="],
|
||||
|
||||
"@codemirror/lang-java": ["@codemirror/lang-java@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-java/-/lang-java-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/java": "^1.0.0" } }, "sha512-m5Nt1mQ/cznJY7tMfQTJchmrjdjQ71IDs+55d1GAa8DGaB8JXWsVCkVT284C3RTASaY43YknrK2X3hPO/J3MOQ=="],
|
||||
|
||||
"@codemirror/lang-javascript": ["@codemirror/lang-javascript@6.2.5", "https://registry.npmmirror.com/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.6.0", "@codemirror/lint": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/javascript": "^1.0.0" } }, "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A=="],
|
||||
|
||||
"@codemirror/lang-jinja": ["@codemirror/lang-jinja@6.0.1", "https://registry.npmmirror.com/@codemirror/lang-jinja/-/lang-jinja-6.0.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.4.0" } }, "sha512-P5kyHLObzjtbGj16h+hyvZTxJhSjBEeSx4wMjbnAf3b0uwTy2+F0zGjMZL4PQOm/mh2eGZ5xUDVZXgwP783Nsw=="],
|
||||
|
||||
"@codemirror/lang-json": ["@codemirror/lang-json@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-json/-/lang-json-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/json": "^1.0.0" } }, "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ=="],
|
||||
|
||||
"@codemirror/lang-less": ["@codemirror/lang-less@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-less/-/lang-less-6.0.2.tgz", { "dependencies": { "@codemirror/lang-css": "^6.2.0", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-EYdQTG22V+KUUk8Qq582g7FMnCZeEHsyuOJisHRft/mQ+ZSZ2w51NupvDUHiqtsOy7It5cHLPGfHQLpMh9bqpQ=="],
|
||||
|
||||
"@codemirror/lang-liquid": ["@codemirror/lang-liquid@6.3.2", "https://registry.npmmirror.com/@codemirror/lang-liquid/-/lang-liquid-6.3.2.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.1" } }, "sha512-6PDVU3ZnfeYyz1at1E/ttorErZvZFXXt1OPhtfe1EZJ2V2iDFa0CwPqPgG5F7NXN0yONGoBogKmFAafKTqlwIw=="],
|
||||
|
||||
"@codemirror/lang-markdown": ["@codemirror/lang-markdown@6.5.2", "https://registry.npmmirror.com/@codemirror/lang-markdown/-/lang-markdown-6.5.2.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.7.1", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.3.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.2.1", "@lezer/markdown": "^1.0.0" } }, "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw=="],
|
||||
|
||||
"@codemirror/lang-php": ["@codemirror/lang-php@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-php/-/lang-php-6.0.2.tgz", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/php": "^1.0.0" } }, "sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA=="],
|
||||
|
||||
"@codemirror/lang-python": ["@codemirror/lang-python@6.2.1", "https://registry.npmmirror.com/@codemirror/lang-python/-/lang-python-6.2.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.3.2", "@codemirror/language": "^6.8.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.1", "@lezer/python": "^1.1.4" } }, "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw=="],
|
||||
|
||||
"@codemirror/lang-rust": ["@codemirror/lang-rust@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-rust/-/lang-rust-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/rust": "^1.0.0" } }, "sha512-EZaGjCUegtiU7kSMvOfEZpaCReowEf3yNidYu7+vfuGTm9ow4mthAparY5hisJqOHmJowVH3Upu+eJlUji6qqA=="],
|
||||
|
||||
"@codemirror/lang-sass": ["@codemirror/lang-sass@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-sass/-/lang-sass-6.0.2.tgz", { "dependencies": { "@codemirror/lang-css": "^6.2.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.2", "@lezer/sass": "^1.0.0" } }, "sha512-l/bdzIABvnTo1nzdY6U+kPAC51czYQcOErfzQ9zSm9D8GmNPD0WTW8st/CJwBTPLO8jlrbyvlSEcN20dc4iL0Q=="],
|
||||
|
||||
"@codemirror/lang-sql": ["@codemirror/lang-sql@6.10.0", "https://registry.npmmirror.com/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-6ayPkEd/yRw0XKBx5uAiToSgGECo/GY2NoJIHXIIQh1EVwLuKoU8BP/qK0qH5NLXAbtJRLuT73hx7P9X34iO4w=="],
|
||||
|
||||
"@codemirror/lang-vue": ["@codemirror/lang-vue@0.1.3", "https://registry.npmmirror.com/@codemirror/lang-vue/-/lang-vue-0.1.3.tgz", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-javascript": "^6.1.2", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.1" } }, "sha512-QSKdtYTDRhEHCfo5zOShzxCmqKJvgGrZwDQSdbvCRJ5pRLWBS7pD/8e/tH44aVQT6FKm0t6RVNoSUWHOI5vNug=="],
|
||||
|
||||
"@codemirror/lang-wast": ["@codemirror/lang-wast@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-wast/-/lang-wast-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-Imi2KTpVGm7TKuUkqyJ5NRmeFWF7aMpNiwHnLQe0x9kmrxElndyH0K6H/gXtWwY6UshMRAhpENsgfpSwsgmC6Q=="],
|
||||
|
||||
"@codemirror/lang-xml": ["@codemirror/lang-xml@6.1.0", "https://registry.npmmirror.com/@codemirror/lang-xml/-/lang-xml-6.1.0.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/xml": "^1.0.0" } }, "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg=="],
|
||||
|
||||
"@codemirror/lang-yaml": ["@codemirror/lang-yaml@6.1.3", "https://registry.npmmirror.com/@codemirror/lang-yaml/-/lang-yaml-6.1.3.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.0.0", "@lezer/yaml": "^1.0.0" } }, "sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ=="],
|
||||
|
||||
"@codemirror/language": ["@codemirror/language@6.12.4", "https://registry.npmmirror.com/@codemirror/language/-/language-6.12.4.tgz", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0", "style-mod": "^4.0.0" } }, "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A=="],
|
||||
|
||||
"@codemirror/language-data": ["@codemirror/language-data@6.5.2", "https://registry.npmmirror.com/@codemirror/language-data/-/language-data-6.5.2.tgz", { "dependencies": { "@codemirror/lang-angular": "^0.1.0", "@codemirror/lang-cpp": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-go": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-java": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/lang-jinja": "^6.0.0", "@codemirror/lang-json": "^6.0.0", "@codemirror/lang-less": "^6.0.0", "@codemirror/lang-liquid": "^6.0.0", "@codemirror/lang-markdown": "^6.0.0", "@codemirror/lang-php": "^6.0.0", "@codemirror/lang-python": "^6.0.0", "@codemirror/lang-rust": "^6.0.0", "@codemirror/lang-sass": "^6.0.0", "@codemirror/lang-sql": "^6.0.0", "@codemirror/lang-vue": "^0.1.1", "@codemirror/lang-wast": "^6.0.0", "@codemirror/lang-xml": "^6.0.0", "@codemirror/lang-yaml": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/legacy-modes": "^6.4.0" } }, "sha512-CPkWBKrNS8stYbEU5kwBwTf3JB1kghlbh4FSAwzGW2TEscdeHHH4FGysREW86Mqnj3Qn09s0/6Ea/TutmoTobg=="],
|
||||
|
||||
"@codemirror/legacy-modes": ["@codemirror/legacy-modes@6.5.4", "https://registry.npmmirror.com/@codemirror/legacy-modes/-/legacy-modes-6.5.4.tgz", { "dependencies": { "@codemirror/language": "^6.0.0" } }, "sha512-/cZr6qZyl08iYNLGsJ862CXXNI51LryRFRE40ejgoIjXZz0C1rGkD3/Ek5jM/8w1ceRjqtt4qx/KLMh4zBTgew=="],
|
||||
|
||||
"@codemirror/lint": ["@codemirror/lint@6.9.7", "https://registry.npmmirror.com/@codemirror/lint/-/lint-6.9.7.tgz", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.42.0", "crelt": "^1.0.5" } }, "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg=="],
|
||||
|
||||
"@codemirror/merge": ["@codemirror/merge@6.12.2", "https://registry.npmmirror.com/@codemirror/merge/-/merge-6.12.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/highlight": "^1.0.0", "style-mod": "^4.1.0" } }, "sha512-V8JvyAPjHbPupqP7BeMcsdsYCbyPij74jxIbaIJDORI+VZzW44zFmon8bF+oxGWvOKhcRmkiUMXd8MxHr3YA2w=="],
|
||||
|
||||
"@codemirror/search": ["@codemirror/search@6.7.2", "https://registry.npmmirror.com/@codemirror/search/-/search-6.7.2.tgz", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.37.0", "crelt": "^1.0.5" } }, "sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA=="],
|
||||
|
||||
"@codemirror/state": ["@codemirror/state@6.7.6", "https://registry.npmmirror.com/@codemirror/state/-/state-6.7.6.tgz", { "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } }, "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w=="],
|
||||
|
||||
"@codemirror/theme-one-dark": ["@codemirror/theme-one-dark@6.1.3", "https://registry.npmmirror.com/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/highlight": "^1.0.0" } }, "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA=="],
|
||||
|
||||
"@codemirror/view": ["@codemirror/view@6.43.13", "https://registry.npmmirror.com/@codemirror/view/-/view-6.43.13.tgz", { "dependencies": { "@codemirror/state": "^6.7.0", "crelt": "^1.0.6", "style-mod": "^4.1.0", "w3c-keyname": "^2.2.4" } }, "sha512-sihaFrUzAsYBQsL9J2t69y8nfMQGwcYmggAZsk+kjPbjYZMyuf2hU8tUNTZ+P+isb6XRr8JE22TZlJxBoVdH1A=="],
|
||||
|
||||
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="],
|
||||
|
||||
"@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.25.12.tgz", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="],
|
||||
@@ -162,7 +262,43 @@
|
||||
|
||||
"@keyv/serialize": ["@keyv/serialize@1.1.1", "https://registry.npmmirror.com/@keyv/serialize/-/serialize-1.1.1.tgz", {}, "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA=="],
|
||||
|
||||
"@lucide/vue": ["@lucide/vue@1.28.0", "https://registry.npmmirror.com/@lucide/vue/-/vue-1.28.0.tgz", { "peerDependencies": { "vue": ">=3.0.1" } }, "sha512-cO89UyNM/0i2Srdi04nFWeEOQkqzDZlM2ehtWyBhcMpRTJDKpMZPCGAVlmVBgBgr5HaeL5L6FsU8RHsOdwXtKw=="],
|
||||
"@lezer/common": ["@lezer/common@1.5.3", "https://registry.npmmirror.com/@lezer/common/-/common-1.5.3.tgz", {}, "sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q=="],
|
||||
|
||||
"@lezer/cpp": ["@lezer/cpp@1.1.6", "https://registry.npmmirror.com/@lezer/cpp/-/cpp-1.1.6.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA=="],
|
||||
|
||||
"@lezer/css": ["@lezer/css@1.3.8", "https://registry.npmmirror.com/@lezer/css/-/css-1.3.8.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-EJn1zcL9qoDptief6ipWKZKLiOpXkxSe0+t8CH9oiMVcZlq7NBWrjCqnc/41EIjeo/ITj1gFFiATdTkaJDL+Og=="],
|
||||
|
||||
"@lezer/go": ["@lezer/go@1.0.1", "https://registry.npmmirror.com/@lezer/go/-/go-1.0.1.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-xToRsYxwsgJNHTgNdStpcvmbVuKxTapV0dM0wey1geMMRc9aggoVyKgzYp41D2/vVOx+Ii4hmE206kvxIXBVXQ=="],
|
||||
|
||||
"@lezer/highlight": ["@lezer/highlight@1.2.5", "https://registry.npmmirror.com/@lezer/highlight/-/highlight-1.2.5.tgz", { "dependencies": { "@lezer/common": "^1.3.0" } }, "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w=="],
|
||||
|
||||
"@lezer/html": ["@lezer/html@1.3.13", "https://registry.npmmirror.com/@lezer/html/-/html-1.3.13.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg=="],
|
||||
|
||||
"@lezer/java": ["@lezer/java@1.1.4", "https://registry.npmmirror.com/@lezer/java/-/java-1.1.4.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-gQylJ2xHV2xXsVqtnAcJrcROvLZJaQiC0tR//+q0k961BxqvyYttusPkJ8d9T1fPDJKHJW2etUH8XbIn9jhVUg=="],
|
||||
|
||||
"@lezer/javascript": ["@lezer/javascript@1.5.5", "https://registry.npmmirror.com/@lezer/javascript/-/javascript-1.5.5.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.1.3", "@lezer/lr": "^1.3.0" } }, "sha512-sWg4yX1J6XW67AaAynVt0iwF0M5c+np36TEu+P2ifAJ8haRYvHnWDV28r1jdwnJehWCwXECutAUy56K4RBZIyg=="],
|
||||
|
||||
"@lezer/json": ["@lezer/json@1.0.3", "https://registry.npmmirror.com/@lezer/json/-/json-1.0.3.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ=="],
|
||||
|
||||
"@lezer/lr": ["@lezer/lr@1.4.10", "https://registry.npmmirror.com/@lezer/lr/-/lr-1.4.10.tgz", { "dependencies": { "@lezer/common": "^1.0.0" } }, "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A=="],
|
||||
|
||||
"@lezer/markdown": ["@lezer/markdown@1.7.2", "https://registry.npmmirror.com/@lezer/markdown/-/markdown-1.7.2.tgz", { "dependencies": { "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0" } }, "sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ=="],
|
||||
|
||||
"@lezer/php": ["@lezer/php@1.0.6", "https://registry.npmmirror.com/@lezer/php/-/php-1.0.6.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.1.0" } }, "sha512-QJ2xNXPmsm/Z3IpThq8fnJrEIVpxhsIoj6GZBW0JYEd/l9zxpJZW216X4fzqQY4vgpdGIumypvI4uQjd4tnYtw=="],
|
||||
|
||||
"@lezer/python": ["@lezer/python@1.1.19", "https://registry.npmmirror.com/@lezer/python/-/python-1.1.19.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ=="],
|
||||
|
||||
"@lezer/rust": ["@lezer/rust@1.0.3", "https://registry.npmmirror.com/@lezer/rust/-/rust-1.0.3.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-XxErOjZzQ7yJt1agUT4fu9qQvESZ3acgoxpPaPTPOiUx+duCjaVAtZGFIgphkHxlN05djdVAIOy/wItShMEjqQ=="],
|
||||
|
||||
"@lezer/sass": ["@lezer/sass@1.1.0", "https://registry.npmmirror.com/@lezer/sass/-/sass-1.1.0.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-3mMGdCTUZ/84ArHOuXWQr37pnf7f+Nw9ycPUeKX+wu19b7pSMcZGLbaXwvD2APMBDOGxPmpK/O6S1v1EvLoqgQ=="],
|
||||
|
||||
"@lezer/xml": ["@lezer/xml@1.0.6", "https://registry.npmmirror.com/@lezer/xml/-/xml-1.0.6.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww=="],
|
||||
|
||||
"@lezer/yaml": ["@lezer/yaml@1.0.4", "https://registry.npmmirror.com/@lezer/yaml/-/yaml-1.0.4.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.4.0" } }, "sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw=="],
|
||||
|
||||
"@lucide/vue": ["@lucide/vue@1.49.0", "https://registry.npmmirror.com/@lucide/vue/-/vue-1.49.0.tgz", { "peerDependencies": { "vue": ">=3.0.1" } }, "sha512-7xS5gYnLoIx0jlmlRE3Rb71fIHaNqhVBiKMpOlqrYt6nMPy3C/62HJHo5XNsV3HTK+9l3M0hXICrIA7S5v6y5Q=="],
|
||||
|
||||
"@marijn/find-cluster-break": ["@marijn/find-cluster-break@1.0.4", "https://registry.npmmirror.com/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", {}, "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ=="],
|
||||
|
||||
"@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "https://registry.npmmirror.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="],
|
||||
|
||||
@@ -170,6 +306,10 @@
|
||||
|
||||
"@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "https://registry.npmmirror.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="],
|
||||
|
||||
"@replit/codemirror-lang-csharp": ["@replit/codemirror-lang-csharp@6.2.0", "https://registry.npmmirror.com/@replit/codemirror-lang-csharp/-/codemirror-lang-csharp-6.2.0.tgz", { "peerDependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-6utbaWkoymhoAXj051mkRp+VIJlpwUgCX9Toevz3YatiZsz512fw3OVCedXQx+WcR0wb6zVHjChnuxqfCLtFVQ=="],
|
||||
|
||||
"@replit/codemirror-lang-svelte": ["@replit/codemirror-lang-svelte@6.0.0", "https://registry.npmmirror.com/@replit/codemirror-lang-svelte/-/codemirror-lang-svelte-6.0.0.tgz", { "peerDependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-css": "^6.0.1", "@codemirror/lang-html": "^6.2.0", "@codemirror/lang-javascript": "^6.1.1", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/highlight": "^1.0.0", "@lezer/javascript": "^1.2.0", "@lezer/lr": "^1.0.0" } }, "sha512-U2OqqgMM6jKelL0GNWbAmqlu1S078zZNoBqlJBW+retTc5M4Mha6/Y2cf4SVg6ddgloJvmcSpt4hHrVoM4ePRA=="],
|
||||
|
||||
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.62.2", "https://registry.npmmirror.com/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz", { "os": "android", "cpu": "arm" }, "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg=="],
|
||||
|
||||
"@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.62.2", "https://registry.npmmirror.com/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.2.tgz", { "os": "android", "cpu": "arm64" }, "sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw=="],
|
||||
@@ -256,39 +396,39 @@
|
||||
|
||||
"@tanstack/vue-virtual": ["@tanstack/vue-virtual@3.13.32", "https://registry.npmmirror.com/@tanstack/vue-virtual/-/vue-virtual-3.13.32.tgz", { "dependencies": { "@tanstack/virtual-core": "3.17.4" }, "peerDependencies": { "vue": "^2.7.0 || ^3.0.0" } }, "sha512-E8OCutx7QnwZdvpJijz0Q2PHsYDWBWjnGr3TvgWiqxTU35jB1kVhtkd93scRV7tTFuId2tg3x2iFiw+IE4evjQ=="],
|
||||
|
||||
"@tauri-apps/api": ["@tauri-apps/api@2.11.1", "https://registry.npmmirror.com/@tauri-apps/api/-/api-2.11.1.tgz", {}, "sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA=="],
|
||||
"@tauri-apps/api": ["@tauri-apps/api@2.12.0", "https://registry.npmmirror.com/@tauri-apps/api/-/api-2.12.0.tgz", {}, "sha512-fUSxFX8VABYe9W9K5ROdEaKVkNUFRcMSRofjruvaxztXA+I0XnQHcYHF8m/a6iExRUxsUf0HsFWhPBuH9IgzJw=="],
|
||||
|
||||
"@tauri-apps/cli": ["@tauri-apps/cli@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli/-/cli-2.11.4.tgz", { "optionalDependencies": { "@tauri-apps/cli-darwin-arm64": "2.11.4", "@tauri-apps/cli-darwin-x64": "2.11.4", "@tauri-apps/cli-linux-arm-gnueabihf": "2.11.4", "@tauri-apps/cli-linux-arm64-gnu": "2.11.4", "@tauri-apps/cli-linux-arm64-musl": "2.11.4", "@tauri-apps/cli-linux-riscv64-gnu": "2.11.4", "@tauri-apps/cli-linux-x64-gnu": "2.11.4", "@tauri-apps/cli-linux-x64-musl": "2.11.4", "@tauri-apps/cli-win32-arm64-msvc": "2.11.4", "@tauri-apps/cli-win32-ia32-msvc": "2.11.4", "@tauri-apps/cli-win32-x64-msvc": "2.11.4" }, "bin": { "tauri": "tauri.js" } }, "sha512-R8xGtMpwyetawSqm9kYOuMmEqkhUbvcUy8n0aNXIxollKBLESUu5f4Fx+64hgASYm1H+jSWq6jCW6zqTnH6hqQ=="],
|
||||
"@tauri-apps/cli": ["@tauri-apps/cli@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli/-/cli-2.12.0.tgz", { "optionalDependencies": { "@tauri-apps/cli-darwin-arm64": "2.12.0", "@tauri-apps/cli-darwin-x64": "2.12.0", "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.0", "@tauri-apps/cli-linux-arm64-gnu": "2.12.0", "@tauri-apps/cli-linux-arm64-musl": "2.12.0", "@tauri-apps/cli-linux-riscv64-gnu": "2.12.0", "@tauri-apps/cli-linux-x64-gnu": "2.12.0", "@tauri-apps/cli-linux-x64-musl": "2.12.0", "@tauri-apps/cli-win32-arm64-msvc": "2.12.0", "@tauri-apps/cli-win32-ia32-msvc": "2.12.0", "@tauri-apps/cli-win32-x64-msvc": "2.12.0" }, "bin": { "tauri": "tauri.js" } }, "sha512-GIShnAR4C16kSTA8NO02fo8fOw/I5z5sAUEB5S2HlPHFnBkbihL4c9a/MpkxOm1+q5S+tFd3X4QUjHWxfyGzpQ=="],
|
||||
|
||||
"@tauri-apps/cli-darwin-arm64": ["@tauri-apps/cli-darwin-arm64@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.11.4.tgz", { "os": "darwin", "cpu": "arm64" }, "sha512-1ryOF3ZhpZ/nemHV5zVwBQBz9jDGKmKPvWPADOhc83ig0P4bMc2iER4NbC6r9sjeIZ6RVQ4g3RZIYvezhcl4TQ=="],
|
||||
"@tauri-apps/cli-darwin-arm64": ["@tauri-apps/cli-darwin-arm64@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.0.tgz", { "os": "darwin", "cpu": "arm64" }, "sha512-v5J+jISihLGtih1+3yWagbsL+5dbLZORu4vaSI0vhY0Heb+MAW+T/1s1RyKxrQrwEPGBG5kqwfDDTnSbmVkuqA=="],
|
||||
|
||||
"@tauri-apps/cli-darwin-x64": ["@tauri-apps/cli-darwin-x64@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.11.4.tgz", { "os": "darwin", "cpu": "x64" }, "sha512-uFsGQAAfuyz1k/yGLmkWfkBlgKAqZfxqlHmLWx81QU27RJWfmbNHCIq8T8w1e+VClleIuZUjpHWfoE4E3DLo3A=="],
|
||||
"@tauri-apps/cli-darwin-x64": ["@tauri-apps/cli-darwin-x64@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.0.tgz", { "os": "darwin", "cpu": "x64" }, "sha512-g27I07pfW/dMS8vcNqB9lamgKF0TqLlcy8e7t9qDGsB1iaeyjJWb2TgBF4tM9ZwLqPAZUXbsz28oXljO12WC4g=="],
|
||||
|
||||
"@tauri-apps/cli-linux-arm-gnueabihf": ["@tauri-apps/cli-linux-arm-gnueabihf@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.11.4.tgz", { "os": "linux", "cpu": "arm" }, "sha512-IaHZn5CdBL21oUmjiVOS1ctw6Ip1O0pjp70FwOWmYz1myWe0SY96ZIj2FYf7pT0m8bI2h/hrs5ZbEXXh44/MkQ=="],
|
||||
"@tauri-apps/cli-linux-arm-gnueabihf": ["@tauri-apps/cli-linux-arm-gnueabihf@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.0.tgz", { "os": "linux", "cpu": "arm" }, "sha512-gXyQ710fNc99YuxFxNyeX9PLSrIpbtgBBj7GQo9tSeRT6fIK40q3/gm7X5jqZo7mWLR2m0R/2ALd3vAWo0Z32Q=="],
|
||||
|
||||
"@tauri-apps/cli-linux-arm64-gnu": ["@tauri-apps/cli-linux-arm64-gnu@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.11.4.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-N41/ukTRVe6XSuUTESuFdGeOW2i7k62tK+6gHK5Kd5/q5RPvvi19GaWAVPPb9u95HSGmTChSolBfzynUsssFaA=="],
|
||||
"@tauri-apps/cli-linux-arm64-gnu": ["@tauri-apps/cli-linux-arm64-gnu@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.0.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-H9cyXuq9WgxoHh2NZ+R+oN+W78x5UwaBDEp0/fmqUUkaBoioCuOZErM9xKiIV6bpNAhmw1RoWZ49u37q/vaiAg=="],
|
||||
|
||||
"@tauri-apps/cli-linux-arm64-musl": ["@tauri-apps/cli-linux-arm64-musl@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.11.4.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-v277UnT/fB64xAfSroL5N3Km3tLmvATWqJJw/wRI+g6o+HkeD0slyE7gOhNs1MbjE41R7bQOTxMVoL3aomUJmw=="],
|
||||
"@tauri-apps/cli-linux-arm64-musl": ["@tauri-apps/cli-linux-arm64-musl@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.0.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-5tFuk3JKMBa1M/iN4gN32OYlSfhY3aqb5PO3zCugxaT+sfecyMKpc3EM9VDbhmwWBE9QD4Tfj7wGhlqx2yy2pQ=="],
|
||||
|
||||
"@tauri-apps/cli-linux-riscv64-gnu": ["@tauri-apps/cli-linux-riscv64-gnu@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.11.4.tgz", { "os": "linux", "cpu": "none" }, "sha512-qqgNkQ2u1yZHxjhxsZaxUtRDW8dIqIYm33rx/mzwQv0SfY9x1B+iraj8vWeFiXjjSVVhEMepXSOts1TqPzvXNQ=="],
|
||||
"@tauri-apps/cli-linux-riscv64-gnu": ["@tauri-apps/cli-linux-riscv64-gnu@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.0.tgz", { "os": "linux", "cpu": "none" }, "sha512-LOrMyV+nb7pKq8P0BZtTBQuyzm1ORjn16R9MlupmxuT5LqxtuYJlw3VMwbaeXCToJ8jbP5u9JnkfmbqDlvETXw=="],
|
||||
|
||||
"@tauri-apps/cli-linux-x64-gnu": ["@tauri-apps/cli-linux-x64-gnu@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.11.4.tgz", { "os": "linux", "cpu": "x64" }, "sha512-2VRNWl84FOH0m2giiDkO2h0QXlcMJeX+zJDpI5kDIQAx6s+geF3v48F4DXfJez4GS/FdoDGnPnw1C2iYGbQ7bQ=="],
|
||||
"@tauri-apps/cli-linux-x64-gnu": ["@tauri-apps/cli-linux-x64-gnu@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.0.tgz", { "os": "linux", "cpu": "x64" }, "sha512-aMIkI+X9qvD2+k80QZB3tuOYT41/cEheikC510CwAIZ31KLXORsRASYYzM4mi1/58ICmtzSLFhCC08keir7COw=="],
|
||||
|
||||
"@tauri-apps/cli-linux-x64-musl": ["@tauri-apps/cli-linux-x64-musl@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.11.4.tgz", { "os": "linux", "cpu": "x64" }, "sha512-o9GyhYor/nc7xarmwDE3ka2szuW3uuZzXjHWh64Q8YX5AtSgxdQkFWzrY4O8KiGtVNvFBI14H3Q49Qj5TOIP/A=="],
|
||||
"@tauri-apps/cli-linux-x64-musl": ["@tauri-apps/cli-linux-x64-musl@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.0.tgz", { "os": "linux", "cpu": "x64" }, "sha512-9gl3NhUbfuGhSKjeGCypKSdtoezOQRcDUrkhTWtLQEjnajets6peO6NadgI2DF0OzbiiFOzrnnIGMwBS+Ap6Iw=="],
|
||||
|
||||
"@tauri-apps/cli-win32-arm64-msvc": ["@tauri-apps/cli-win32-arm64-msvc@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.11.4.tgz", { "os": "win32", "cpu": "arm64" }, "sha512-ld5Ehb598m0VkYyylRPNeCFsBe/km0jxis6KgMpl3IGY6I/i1RwQXO05I1AsXUXO2WC6AvB/Lw4qTf/asiuEiQ=="],
|
||||
"@tauri-apps/cli-win32-arm64-msvc": ["@tauri-apps/cli-win32-arm64-msvc@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.0.tgz", { "os": "win32", "cpu": "arm64" }, "sha512-1W+v86wsYLuyBDN0iDessD4CD9o+yNyO0m8Dp3+/vfjiZrJ/v7R7/aTRBeikaq2tLGgxeag0gxnFggBNBGw91A=="],
|
||||
|
||||
"@tauri-apps/cli-win32-ia32-msvc": ["@tauri-apps/cli-win32-ia32-msvc@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.11.4.tgz", { "os": "win32", "cpu": "ia32" }, "sha512-12Hxi0XX/H5VFxO/bGgHkFWhml9VMgEOu9CidjeCeTNQ1l6fpUlbiGgSP7CLI3PFtW9/FfbeHieZ+kyWK5H7CA=="],
|
||||
"@tauri-apps/cli-win32-ia32-msvc": ["@tauri-apps/cli-win32-ia32-msvc@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.0.tgz", { "os": "win32", "cpu": "ia32" }, "sha512-SsBjvq4f7YaBGqcWoE3cycoItPf0SrQeqFqWWgfxoeZWAIz01E31LDSeZ2p/etJiIY0R9oi045chkFfb0O7WGw=="],
|
||||
|
||||
"@tauri-apps/cli-win32-x64-msvc": ["@tauri-apps/cli-win32-x64-msvc@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.11.4.tgz", { "os": "win32", "cpu": "x64" }, "sha512-+vDiqBIU5dMISg/wNvX3sF+ZHfgJGJ5T0AcO+EHNXV9GGAG+P5fzodlDXD3QdKCRgZxMoCm5PPvj3BqLNjBthw=="],
|
||||
"@tauri-apps/cli-win32-x64-msvc": ["@tauri-apps/cli-win32-x64-msvc@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.0.tgz", { "os": "win32", "cpu": "x64" }, "sha512-9zzDKYUH4TKKBgRdDdVQX8fiRO5gJ8hD1nGsHU9DOHG5Jpm3arjbu9Xg1frR20EusG3Sl8X0dppoO/4EoUXUGg=="],
|
||||
|
||||
"@tauri-apps/plugin-autostart": ["@tauri-apps/plugin-autostart@2.5.1", "https://registry.npmmirror.com/@tauri-apps/plugin-autostart/-/plugin-autostart-2.5.1.tgz", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-zS/xx7yzveCcotkA+8TqkI2lysmG2wvQXv2HGAVExITmnFfHAdj1arGsbbfs3o6EktRHf6l34pJxc3YGG2mg7w=="],
|
||||
"@tauri-apps/plugin-autostart": ["@tauri-apps/plugin-autostart@2.6.0", "https://registry.npmmirror.com/@tauri-apps/plugin-autostart/-/plugin-autostart-2.6.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-myppl3C/dygGbn7Inmm3LqsAQ7SSsT3KtNpSt/e+fA5J7xeCIf8H+LMiE1tkS7mKzTfChCutfZCt0FQkrL/YdA=="],
|
||||
|
||||
"@tauri-apps/plugin-dialog": ["@tauri-apps/plugin-dialog@2.7.2", "https://registry.npmmirror.com/@tauri-apps/plugin-dialog/-/plugin-dialog-2.7.2.tgz", { "dependencies": { "@tauri-apps/api": "^2.11.0" } }, "sha512-pX0IGm1I3I6wc+zeKYcq1GSqogK6okCNX5fOdaNU5ab1AjGS6l1E5wFNjEb7meg7ZFSp0JUs+0jQGQNyOvLrsg=="],
|
||||
"@tauri-apps/plugin-dialog": ["@tauri-apps/plugin-dialog@2.8.0", "https://registry.npmmirror.com/@tauri-apps/plugin-dialog/-/plugin-dialog-2.8.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-HSSD5C8UFE9ijD1wue84F7jjaIReFmj8AAPtS+xyjYRltJafIc4BiWHY7SJ6vbbew6u+YljEJHfyNfy5VwywXg=="],
|
||||
|
||||
"@tauri-apps/plugin-global-shortcut": ["@tauri-apps/plugin-global-shortcut@2.3.2", "https://registry.npmmirror.com/@tauri-apps/plugin-global-shortcut/-/plugin-global-shortcut-2.3.2.tgz", { "dependencies": { "@tauri-apps/api": "^2.11.0" } }, "sha512-UReHNXrLvpEjylE4jb4oCYiy96uRykPUthoCQCmRXYrd5hs5X9DrW+qOn7GLW57EJN4tdK8bgK5twBTz2NOxzA=="],
|
||||
"@tauri-apps/plugin-global-shortcut": ["@tauri-apps/plugin-global-shortcut@2.4.0", "https://registry.npmmirror.com/@tauri-apps/plugin-global-shortcut/-/plugin-global-shortcut-2.4.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-XBA4PcRjRdJBp/jwFxc5YZ/yKhZuslpOG/pGaNfhnRDVGMQfoXEKMv/6A6vjzfKLUxr8ml3ay8o2W8Rk6mHICA=="],
|
||||
|
||||
"@tauri-apps/plugin-opener": ["@tauri-apps/plugin-opener@2.5.4", "https://registry.npmmirror.com/@tauri-apps/plugin-opener/-/plugin-opener-2.5.4.tgz", { "dependencies": { "@tauri-apps/api": "^2.11.0" } }, "sha512-1HnPkb+AmgO29HBazm4uPLKB+r7zzcTBW1d0fyYp1uP+jwtpoiNDGKMMzz58SFp49nOIrxdE3aUJtT57lfO9CQ=="],
|
||||
"@tauri-apps/plugin-opener": ["@tauri-apps/plugin-opener@2.7.0", "https://registry.npmmirror.com/@tauri-apps/plugin-opener/-/plugin-opener-2.7.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-mBorYfVKh9Lt7s4ZFtKbMUTxBw+Y/sVmSlKCtkkoBgMTC/DIbt/kaPm67L/2djAUqDI1wbixy5OHHVmipjuGMw=="],
|
||||
|
||||
"@types/esrecurse": ["@types/esrecurse@4.3.1", "https://registry.npmmirror.com/@types/esrecurse/-/esrecurse-4.3.1.tgz", {}, "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="],
|
||||
|
||||
@@ -296,12 +436,20 @@
|
||||
|
||||
"@types/json-schema": ["@types/json-schema@7.0.15", "https://registry.npmmirror.com/@types/json-schema/-/json-schema-7.0.15.tgz", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
|
||||
|
||||
"@types/linkify-it": ["@types/linkify-it@5.0.0", "https://registry.npmmirror.com/@types/linkify-it/-/linkify-it-5.0.0.tgz", {}, "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q=="],
|
||||
|
||||
"@types/markdown-it": ["@types/markdown-it@14.2.0", "https://registry.npmmirror.com/@types/markdown-it/-/markdown-it-14.2.0.tgz", { "dependencies": { "@types/linkify-it": "^5", "@types/mdurl": "^2" } }, "sha512-NoQ2yGlLWj4wpxMs+TYmRKk3thDrQ97agr7sFqfLsAlvoS8SNQuTrlObhFqG9iugdTtgOE9jpJ6FNM4ZGsa5xQ=="],
|
||||
|
||||
"@types/mdurl": ["@types/mdurl@2.0.0", "https://registry.npmmirror.com/@types/mdurl/-/mdurl-2.0.0.tgz", {}, "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg=="],
|
||||
|
||||
"@types/node": ["@types/node@26.1.1", "https://registry.npmmirror.com/@types/node/-/node-26.1.1.tgz", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="],
|
||||
|
||||
"@types/qrcode": ["@types/qrcode@1.5.6", "https://registry.npmmirror.com/@types/qrcode/-/qrcode-1.5.6.tgz", { "dependencies": { "@types/node": "*" } }, "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw=="],
|
||||
|
||||
"@types/sortablejs": ["@types/sortablejs@1.15.9", "https://registry.npmmirror.com/@types/sortablejs/-/sortablejs-1.15.9.tgz", {}, "sha512-7HP+rZGE2p886PKV9c9OJzLBI6BBJu1O7lJGYnPyG3fS4/duUCcngkNCjsLwIMV+WMqANe3tt4irrXHSIe68OQ=="],
|
||||
|
||||
"@types/trusted-types": ["@types/trusted-types@2.0.7", "https://registry.npmmirror.com/@types/trusted-types/-/trusted-types-2.0.7.tgz", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="],
|
||||
|
||||
"@types/web-bluetooth": ["@types/web-bluetooth@0.0.21", "https://registry.npmmirror.com/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", {}, "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA=="],
|
||||
|
||||
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.70.0.tgz", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.70.0", "@typescript-eslint/type-utils": "8.70.0", "@typescript-eslint/utils": "8.70.0", "@typescript-eslint/visitor-keys": "8.70.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.70.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-/v8HZt6RlyIZxB3ntehELOcUcfxKPVGWXnQdJuHRmzrqgF8nQypcC/oxGW+Ot4VGKDq81XugPKxx0n5PBtf9PA=="],
|
||||
@@ -324,6 +472,8 @@
|
||||
|
||||
"@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.70.0.tgz", { "dependencies": { "@typescript-eslint/types": "8.70.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-BoC8PiO4Hkdo0TVJh9Ntxr5MxPDI7/oFsrygN5ADelFSeXG/qgNuucIGA+L5Z6JpPTE/uRfcTWtscjbUaufepQ=="],
|
||||
|
||||
"@uiw/codemirror-themes": ["@uiw/codemirror-themes@4.25.12", "https://registry.npmmirror.com/@uiw/codemirror-themes/-/codemirror-themes-4.25.12.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0" } }, "sha512-3bLX6C+gstr82SmY2FAj2TfHXnl2SnC+whRZJmRsv82wMhG8RZlZVy+o0rLuGRIPD9acuY0gpouHVRNUnzBj3g=="],
|
||||
|
||||
"@vitejs/plugin-vue": ["@vitejs/plugin-vue@5.2.4", "https://registry.npmmirror.com/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz", { "peerDependencies": { "vite": "^5.0.0 || ^6.0.0", "vue": "^3.2.25" } }, "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA=="],
|
||||
|
||||
"@volar/language-core": ["@volar/language-core@2.4.15", "https://registry.npmmirror.com/@volar/language-core/-/language-core-2.4.15.tgz", { "dependencies": { "@volar/source-map": "2.4.15" } }, "sha512-3VHw+QZU0ZG9IuQmzT68IyN4hZNd9GchGPhbD9+pa8CVv7rnoOZwo7T8weIbrRmihqy3ATpdfXFnqRrfPVK6CA=="],
|
||||
@@ -394,6 +544,8 @@
|
||||
|
||||
"ansi-styles": ["ansi-styles@4.3.0", "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
|
||||
|
||||
"argparse": ["argparse@3.0.2", "https://registry.npmmirror.com/argparse/-/argparse-3.0.2.tgz", {}, "sha512-mFdDM6WqWKraGLsVb+C9CahPnzTXOefAOLq3jYcca2YZ8bEWpr++Tzj+zSaKW9+X9L5uSxcm1AZ3Y6aZJ09OhQ=="],
|
||||
|
||||
"aria-hidden": ["aria-hidden@1.2.6", "https://registry.npmmirror.com/aria-hidden/-/aria-hidden-1.2.6.tgz", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
|
||||
|
||||
"balanced-match": ["balanced-match@4.0.4", "https://registry.npmmirror.com/balanced-match/-/balanced-match-4.0.4.tgz", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
|
||||
@@ -416,12 +568,18 @@
|
||||
|
||||
"clsx": ["clsx@2.1.1", "https://registry.npmmirror.com/clsx/-/clsx-2.1.1.tgz", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
|
||||
|
||||
"codemirror-lang-elixir": ["codemirror-lang-elixir@4.0.1", "https://registry.npmmirror.com/codemirror-lang-elixir/-/codemirror-lang-elixir-4.0.1.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "lezer-elixir": "^1.0.0" } }, "sha512-z6W/XB4b7TZrp9EZYBGVq93vQfvKbff+1iM8YZaVErL0dguBAeLmVRlEv1NuDZHOP1qjJ3NwyibkUkNWn7q9VQ=="],
|
||||
|
||||
"codemirror-lang-makefile": ["codemirror-lang-makefile@0.1.1", "https://registry.npmmirror.com/codemirror-lang-makefile/-/codemirror-lang-makefile-0.1.1.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-aCmX0TIj88pQDFeBLmfhiE1ZYmLcWf2c9hk0pscbshCk1x1JO1314q67fbpSaPWm86fl8+wZ2gFuNPlVJ2iFzw=="],
|
||||
|
||||
"color-convert": ["color-convert@2.0.1", "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
|
||||
|
||||
"color-name": ["color-name@1.1.4", "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
|
||||
|
||||
"copy-anything": ["copy-anything@4.0.5", "https://registry.npmmirror.com/copy-anything/-/copy-anything-4.0.5.tgz", { "dependencies": { "is-what": "^5.2.0" } }, "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA=="],
|
||||
|
||||
"crelt": ["crelt@1.0.7", "https://registry.npmmirror.com/crelt/-/crelt-1.0.7.tgz", {}, "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA=="],
|
||||
|
||||
"cross-spawn": ["cross-spawn@7.0.6", "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.6.tgz", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
|
||||
|
||||
"cssesc": ["cssesc@3.0.0", "https://registry.npmmirror.com/cssesc/-/cssesc-3.0.0.tgz", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="],
|
||||
@@ -442,11 +600,13 @@
|
||||
|
||||
"dijkstrajs": ["dijkstrajs@1.0.3", "https://registry.npmmirror.com/dijkstrajs/-/dijkstrajs-1.0.3.tgz", {}, "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA=="],
|
||||
|
||||
"dompurify": ["dompurify@3.4.16", "https://registry.npmmirror.com/dompurify/-/dompurify-3.4.16.tgz", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ=="],
|
||||
|
||||
"emoji-regex": ["emoji-regex@8.0.0", "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-8.0.0.tgz", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
|
||||
|
||||
"enhanced-resolve": ["enhanced-resolve@5.21.6", "https://registry.npmmirror.com/enhanced-resolve/-/enhanced-resolve-5.21.6.tgz", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-aNnGCvbJ/RIyWo1IuhNdVjnNF+EjH9wpzpNHt+ci/m9He9LJvUN8wrCcXjp9cWsGNAuvSpVFTx/vraAFQ8qGjQ=="],
|
||||
|
||||
"entities": ["entities@7.0.1", "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
"entities": ["entities@8.1.0", "https://registry.npmmirror.com/entities/-/entities-8.1.0.tgz", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="],
|
||||
|
||||
"esbuild": ["esbuild@0.25.12", "https://registry.npmmirror.com/esbuild/-/esbuild-0.25.12.tgz", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="],
|
||||
|
||||
@@ -506,6 +666,8 @@
|
||||
|
||||
"he": ["he@1.2.0", "https://registry.npmmirror.com/he/-/he-1.2.0.tgz", { "bin": { "he": "bin/he" } }, "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw=="],
|
||||
|
||||
"highlight.js": ["highlight.js@11.12.0", "https://registry.npmmirror.com/highlight.js/-/highlight.js-11.12.0.tgz", {}, "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg=="],
|
||||
|
||||
"hookable": ["hookable@5.5.3", "https://registry.npmmirror.com/hookable/-/hookable-5.5.3.tgz", {}, "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ=="],
|
||||
|
||||
"hookified": ["hookified@1.15.1", "https://registry.npmmirror.com/hookified/-/hookified-1.15.1.tgz", {}, "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg=="],
|
||||
@@ -536,6 +698,8 @@
|
||||
|
||||
"levn": ["levn@0.4.1", "https://registry.npmmirror.com/levn/-/levn-0.4.1.tgz", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="],
|
||||
|
||||
"lezer-elixir": ["lezer-elixir@1.1.3", "https://registry.npmmirror.com/lezer-elixir/-/lezer-elixir-1.1.3.tgz", { "dependencies": { "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.3.0" } }, "sha512-Ymc58/WhxdZS9yEOlnKbF3rdeBdFcPm4OEm26KMqA1Za9vztXi7I5qwGw1KxYmm3Nv0iDHq//EQyBwSEzKG9Mg=="],
|
||||
|
||||
"lightningcss": ["lightningcss@1.32.0", "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.32.0.tgz", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
|
||||
|
||||
"lightningcss-android-arm64": ["lightningcss-android-arm64@1.32.0", "https://registry.npmmirror.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="],
|
||||
@@ -560,10 +724,16 @@
|
||||
|
||||
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "https://registry.npmmirror.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
|
||||
|
||||
"linkify-it": ["linkify-it@6.1.0", "https://registry.npmmirror.com/linkify-it/-/linkify-it-6.1.0.tgz", { "dependencies": { "uc.micro": "^3.0.0" } }, "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw=="],
|
||||
|
||||
"locate-path": ["locate-path@6.0.0", "https://registry.npmmirror.com/locate-path/-/locate-path-6.0.0.tgz", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="],
|
||||
|
||||
"magic-string": ["magic-string@0.30.21", "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
|
||||
"markdown-it": ["markdown-it@15.0.2", "https://registry.npmmirror.com/markdown-it/-/markdown-it-15.0.2.tgz", { "dependencies": { "argparse": "^3.0.0", "entities": "^8.0.0", "linkify-it": "^6.0.0", "mdurl": "^2.1.0", "punycode.js": "^2.3.1", "uc.micro": "^3.0.0" }, "bin": { "markdown-it": "bin/markdown-it.mjs" } }, "sha512-q4IGxMv56jCqT4OCRCADBoDP3LO4MhmTXjFbphHPXs4g3j9Xg5RDnxqN8IF/3vIWEU+VCnUq+7JUg/cfy2E6Qw=="],
|
||||
|
||||
"mdurl": ["mdurl@2.1.0", "https://registry.npmmirror.com/mdurl/-/mdurl-2.1.0.tgz", {}, "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg=="],
|
||||
|
||||
"merge2": ["merge2@1.4.1", "https://registry.npmmirror.com/merge2/-/merge2-1.4.1.tgz", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="],
|
||||
|
||||
"micromatch": ["micromatch@4.0.8", "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.8.tgz", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
|
||||
@@ -618,13 +788,15 @@
|
||||
|
||||
"punycode": ["punycode@2.3.1", "https://registry.npmmirror.com/punycode/-/punycode-2.3.1.tgz", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
|
||||
|
||||
"punycode.js": ["punycode.js@2.3.1", "https://registry.npmmirror.com/punycode.js/-/punycode.js-2.3.1.tgz", {}, "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA=="],
|
||||
|
||||
"qified": ["qified@0.10.1", "https://registry.npmmirror.com/qified/-/qified-0.10.1.tgz", { "dependencies": { "hookified": "^2.1.1" } }, "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA=="],
|
||||
|
||||
"qrcode": ["qrcode@1.5.4", "https://registry.npmmirror.com/qrcode/-/qrcode-1.5.4.tgz", { "dependencies": { "dijkstrajs": "^1.0.1", "pngjs": "^5.0.0", "yargs": "^15.3.1" }, "bin": { "qrcode": "bin/qrcode" } }, "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg=="],
|
||||
|
||||
"queue-microtask": ["queue-microtask@1.2.3", "https://registry.npmmirror.com/queue-microtask/-/queue-microtask-1.2.3.tgz", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
|
||||
|
||||
"reka-ui": ["reka-ui@2.10.1", "https://registry.npmmirror.com/reka-ui/-/reka-ui-2.10.1.tgz", { "dependencies": { "@floating-ui/dom": "^1.6.13", "@floating-ui/vue": "^1.1.6", "@internationalized/date": "^3.5.0", "@internationalized/number": "^3.5.0", "@tanstack/vue-virtual": "^3.12.0", "@vueuse/core": "^14.1.0", "@vueuse/shared": "^14.1.0", "aria-hidden": "^1.2.4", "defu": "^6.1.5", "ohash": "^2.0.11" }, "peerDependencies": { "vue": ">= 3.4.0" } }, "sha512-drcOQ4rQtDYAcGCsyQBqQg8QQ+H3B+zDaMJU0h8KPEPMa7g9BHu3zcOi4OB39XJSWizceFoNO0Z9tctSGLOXqg=="],
|
||||
"reka-ui": ["reka-ui@2.10.5", "https://registry.npmmirror.com/reka-ui/-/reka-ui-2.10.5.tgz", { "dependencies": { "@floating-ui/dom": "^1.6.13", "@floating-ui/vue": "^1.1.6", "@internationalized/date": "^3.5.0", "@internationalized/number": "^3.5.0", "@tanstack/vue-virtual": "^3.12.0", "@vueuse/core": "^14.1.0", "@vueuse/shared": "^14.1.0", "aria-hidden": "^1.2.4", "defu": "^6.1.5", "ohash": "^2.0.11" }, "peerDependencies": { "vue": ">= 3.4.0" } }, "sha512-/8o0y9BThE0hcHKFg+3770tWcJh3qKdOEFxLOPb9HIajXeFoH/J530cZH62jUJunbqwBgpSBL9v7nB8LJ5pDXA=="],
|
||||
|
||||
"require-directory": ["require-directory@2.1.1", "https://registry.npmmirror.com/require-directory/-/require-directory-2.1.1.tgz", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
|
||||
|
||||
@@ -654,6 +826,8 @@
|
||||
|
||||
"strip-ansi": ["strip-ansi@6.0.1", "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
|
||||
|
||||
"style-mod": ["style-mod@4.1.4", "https://registry.npmmirror.com/style-mod/-/style-mod-4.1.4.tgz", {}, "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw=="],
|
||||
|
||||
"superjson": ["superjson@2.2.6", "https://registry.npmmirror.com/superjson/-/superjson-2.2.6.tgz", { "dependencies": { "copy-anything": "^4" } }, "sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA=="],
|
||||
|
||||
"tailwind-merge": ["tailwind-merge@3.6.0", "https://registry.npmmirror.com/tailwind-merge/-/tailwind-merge-3.6.0.tgz", {}, "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w=="],
|
||||
@@ -678,6 +852,8 @@
|
||||
|
||||
"typescript-eslint": ["typescript-eslint@8.70.0", "https://registry.npmmirror.com/typescript-eslint/-/typescript-eslint-8.70.0.tgz", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.70.0", "@typescript-eslint/parser": "8.70.0", "@typescript-eslint/typescript-estree": "8.70.0", "@typescript-eslint/utils": "8.70.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-P/W5cz70/cQAuKfY3xwQMWWTV7BvJ0mAQmi+9mBcsVPaBUpd6Ohpa+fECv9rBFrQcig86jAiNBFNWUqnTjr4pw=="],
|
||||
|
||||
"uc.micro": ["uc.micro@3.0.0", "https://registry.npmmirror.com/uc.micro/-/uc.micro-3.0.0.tgz", {}, "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw=="],
|
||||
|
||||
"undici-types": ["undici-types@8.3.0", "https://registry.npmmirror.com/undici-types/-/undici-types-8.3.0.tgz", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
|
||||
|
||||
"uri-js": ["uri-js@4.4.1", "https://registry.npmmirror.com/uri-js/-/uri-js-4.4.1.tgz", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
|
||||
@@ -700,6 +876,8 @@
|
||||
|
||||
"vue-tsc": ["vue-tsc@2.2.12", "https://registry.npmmirror.com/vue-tsc/-/vue-tsc-2.2.12.tgz", { "dependencies": { "@volar/typescript": "2.4.15", "@vue/language-core": "2.2.12" }, "peerDependencies": { "typescript": ">=5.0.0" }, "bin": { "vue-tsc": "./bin/vue-tsc.js" } }, "sha512-P7OP77b2h/Pmk+lZdJ0YWs+5tJ6J2+uOQPo7tlBnY44QqQSPYvS0qVT4wqDJgwrZaLe47etJLLQRFia71GYITw=="],
|
||||
|
||||
"w3c-keyname": ["w3c-keyname@2.2.8", "https://registry.npmmirror.com/w3c-keyname/-/w3c-keyname-2.2.8.tgz", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="],
|
||||
|
||||
"which": ["which@2.0.2", "https://registry.npmmirror.com/which/-/which-2.0.2.tgz", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||
|
||||
"which-module": ["which-module@2.0.1", "https://registry.npmmirror.com/which-module/-/which-module-2.0.1.tgz", {}, "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ=="],
|
||||
@@ -734,6 +912,8 @@
|
||||
|
||||
"@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.9", "https://registry.npmmirror.com/ignore/-/ignore-7.0.9.tgz", {}, "sha512-brTTsvFRt5C1gGHtPst/281UjPD5t9fBqbgoMPlVWy11ZLTPfu7HxK4ZYqO9H7o/yC9rSTCI85EaQ4OoY12qYw=="],
|
||||
|
||||
"@vue/compiler-core/entities": ["entities@7.0.1", "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
|
||||
"@vue/language-core/minimatch": ["minimatch@9.0.9", "https://registry.npmmirror.com/minimatch/-/minimatch-9.0.9.tgz", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="],
|
||||
|
||||
"fast-glob/glob-parent": ["glob-parent@5.1.2", "https://registry.npmmirror.com/glob-parent/-/glob-parent-5.1.2.tgz", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
@@ -742,16 +922,10 @@
|
||||
|
||||
"qified/hookified": ["hookified@2.2.0", "https://registry.npmmirror.com/hookified/-/hookified-2.2.0.tgz", {}, "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA=="],
|
||||
|
||||
"reka-ui/@vueuse/core": ["@vueuse/core@14.3.0", "https://registry.npmmirror.com/@vueuse/core/-/core-14.3.0.tgz", { "dependencies": { "@types/web-bluetooth": "^0.0.21", "@vueuse/metadata": "14.3.0", "@vueuse/shared": "14.3.0" }, "peerDependencies": { "vue": "^3.5.0" } }, "sha512-aHfz47g0ZhMtTVHmIzMVpJy8ePhhOy68GY5bv110+5DVtZ+W7BsOx+m61UNQqfrWyPztIHIanWa3E2tib3NFIw=="],
|
||||
|
||||
"reka-ui/@vueuse/shared": ["@vueuse/shared@14.3.0", "https://registry.npmmirror.com/@vueuse/shared/-/shared-14.3.0.tgz", { "peerDependencies": { "vue": "^3.5.0" } }, "sha512-bZpge9eSXwa4ToSiqJ7j6KRwhAsneMFoSz3LMWKQDkqimm3D/tbFlrklrs/IOqC8tEcYmXQZJ6N0UrjhBirVCg=="],
|
||||
|
||||
"yargs/find-up": ["find-up@4.1.0", "https://registry.npmmirror.com/find-up/-/find-up-4.1.0.tgz", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="],
|
||||
|
||||
"@vue/language-core/minimatch/brace-expansion": ["brace-expansion@2.1.2", "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-2.1.2.tgz", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA=="],
|
||||
|
||||
"reka-ui/@vueuse/core/@vueuse/metadata": ["@vueuse/metadata@14.3.0", "https://registry.npmmirror.com/@vueuse/metadata/-/metadata-14.3.0.tgz", {}, "sha512-BwxmbAzwAVF50+MW57GXOUEV61nFBGnlBvrTqj49PqWJu3uw7hdu72ztXeZ33RdZtDY6kO+bfCAE1PCn88Tktw=="],
|
||||
|
||||
"yargs/find-up/locate-path": ["locate-path@5.0.0", "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],
|
||||
|
||||
"@vue/language-core/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,349 @@
|
||||
# 对比工具模块规划(Diff Module Plan)
|
||||
|
||||
> 状态:**P4 已落地**(选项卡 / 左右双树 / 下钻 / 快捷键 / 中间列快速替换)
|
||||
> 本轮决策(2026-10-13,用户已拍板):**移除 devtools 的文本对比工具**(并入本模块)· **目录对比暂不做写回**(只读浏览)· **需要拖入支持**
|
||||
> P4 决策(用户提出,2026-10-13):**选项卡式会话**(标题 `左 ↔ 右`)· **目录对比改为左右两棵结构树**(两侧路径可自由输入 + 图标按钮)· **点树里的文件新开文件选项卡** · **全局快捷键 Alt+C** · **中间列差异 + 快速替换**(参考 Beyond Compare)
|
||||
> 定位:Thing 工具集的第 14 个模块,`id = diff`,`category = 'tool'`
|
||||
> 作者:砚 | 日期:2026-10-13
|
||||
> 关联文档:`AI_DEV_GUIDE.md`(模块注册 / IPC / 独立窗口范式)、`UI_DESIGN_SYSTEM.md`(页面框架 / 组件规范)、`EDITOR_MODULE_PLAN.md`(CM6 装配 / 编码探测 / 独立窗口 / 任务栏身份范式)、`TERMINAL_MODULE_PLAN.md`(拖放补注入范式)
|
||||
|
||||
> 阅读顺序:§9 开工清单(执行入口)→ §0 结论 → §4 技术选型 → §6 文件清单 → §8 分期。
|
||||
|
||||
---
|
||||
|
||||
## 0. 结论先行
|
||||
|
||||
六个关键判断。
|
||||
|
||||
1. **可行,且仓库里已有大半基础设施。** 编辑器模块已经把「CM6 + 主题系统 + 多语言高亮」「带编码探测的文件读取」「递归遍历(`walkdir` 已在依赖树)」「独立窗口 + 任务栏身份 + 拖放补注入」四块能力做完了。本模块的主要工作是**组装**,而不是造轮子。
|
||||
|
||||
2. **做成独立模块 + 独立窗口,不塞进编辑器。** 编辑器模块的中心对象是「一篇文档的生命周期」(标签、自动保存、光标、会话恢复);对比工具是「两个只读视图 + 一棵目录树」,没有自动保存、没有文档标签。混进去会让本已很大的 `EditorWindow.vue`(1500 行)与 `editorStore.ts` 继续膨胀,也会让 `editor-window-*` 这个 capability 的语义变模糊。模块体系是现成的(`moduleConfig` + 一行注册 + 图标表 + 搜索索引 + 启用开关),独立成模块成本很低。
|
||||
|
||||
3. **渲染层用 `@codemirror/merge`(CM6 官方 MergeView),计算层留在 Rust。** MergeView 天然给出并排 / 统一视图、块级高亮、chunk 跳转、接受/拒绝,并且**直接吃项目现有的 CM6 主题**(编辑器那九套配色自动跟随,无需为对比工具再维护一套配色)。Rust 只负责目录级扫描与分类:`walkdir` 递归 + size/mtime 快速路径 + 按需内容比对。这样目录对比的每一项都能「点一下」下钻到 MergeView 的文件级对比 —— 正是 Beyond Compare 的交互主线。
|
||||
|
||||
4. **三层能力按「易 → 难」分期,P1 只做文本对比。** 文本对比(粘贴两段)→ 文件对比(两个路径,含编码探测)→ 文件夹对比(递归树 + 三态分类 + 下钻)。P1 的价值不只是功能,更是**验证 `@codemirror/merge` 与项目现有 CM6 版本的兼容性**(见 §10),风险最低、最快闭环。
|
||||
|
||||
5. **目录对比这一期只读,不做写回。** 「浏览差异」与「同步目录」是两个量级的工程:后者要处理冲突策略、部分失败回滚、覆盖确认、二进制文件、只读属性与长路径。这一期给出只读的三态树 + 下钻即可,写回(复制 / 镜像 / 双向同步)留待单独评估。
|
||||
|
||||
6. **拖入支持从 P2 起生效。** 文本对比没有文件路径,用不上拖放;P2 起需要把「拖文件进窗口」纳入。既有实现是编辑器专用的 `editor/drag_drop.rs`(不通用:它按 editor 窗口的 label 前缀做注入),因此本模块**另建一份同构实现**或把它**泛化成按 label 前缀参数化**(见 §7.1,倾向后者)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 定位与边界
|
||||
|
||||
| 维度 | 说明 |
|
||||
|---|---|
|
||||
| 一句话 | 一个 Beyond Compare 式的对比工具:文本 / 文件 / 文件夹三层,左右双栏 |
|
||||
| 中心对象 | **两个被比较的目标**(一段文本、一个文件、一棵目录树),而不是某篇文档 |
|
||||
| 首要入口 | 模块页「新建对比」+ 独立窗口(可拖入文件/文件夹) |
|
||||
| 与编辑器模块的关系 | 复用它的 CM6 装配、主题与语言包、Rust 文件读取;但**不共享窗口、不共享 store** |
|
||||
| 明确不做 | 不做三路合并(3-way merge)· 不做 Git 集成 · 本期不做目录写回/同步 · 不做二进制语义对比(只报「二进制不同」) |
|
||||
|
||||
---
|
||||
|
||||
## 2. 需求解构
|
||||
|
||||
| 用户原话 | 解构为 | 落点 |
|
||||
|---|---|---|
|
||||
| 「能够进行文本,文件,文件夹对比」 | 三种对比目标,同一条渲染管线 | §3.1 / §3.2 / §3.3 |
|
||||
| 「左右两个窗口对比,参考 beyond compare」 | 并排双栏 + 块级高亮 + 差异导航 + 三态目录树 | §3.1 / §3.3 |
|
||||
| 「调整…对比工具…做到编辑器里面还是单独做模块」 | 架构决策 → 独立模块 | §5 |
|
||||
| 「去除 devtools 里的 diff」 | 删除 `DiffTools.vue` 及其注册项,能力并入本模块 | §8 开工清单 |
|
||||
| 「目录对比暂时不用写回」 | P3 只读三态树,不做复制/同步 | §3.3 / §9 |
|
||||
| 「需要拖入支持」 | 拖文件/文件夹进窗口即作为某一侧目标 | §7.1 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 能力规格
|
||||
|
||||
### 3.1 文本对比(P1)
|
||||
|
||||
- 左右两个**可编辑**的 CM6 视图,构成一个 MergeView;任一侧输入即重算差异。
|
||||
- 差异呈现:行内块级高亮(左边「被删/被改」、右边「新增/被改」),行号槽标注变化。
|
||||
- 差异导航:上一个 / 下一个差异(工具栏按钮;到两端即停,不做循环跳转)。
|
||||
- 顶部工具栏:粘贴到某一侧(从剪贴板)、交换左右、差异导航、清空两侧。并排是**唯一**的视图形态(统一视图需要另一套渲染路径,留待后续评估)。
|
||||
- 状态栏:`差异 N 处 · +A 行 · -R 行 · 左侧 X 行 / 右侧 Y 行`。
|
||||
- 大文本保护:**不做「超过 N 行就不算」的硬阈值**,改用 MergeView 内置的 `diffConfig.scanLimit`(默认 500)—— 它在差异过大时放弃精确比对、退回快速(不精确)算法,从而避开二次方耗时,同时**仍然给出结果**(比「停算并提示」更可用)。已知代价:极端输入下差异块可能不够精确(`Chunk.precise` 为 false)。
|
||||
|
||||
### 3.2 文件对比(P2)
|
||||
|
||||
- 两个路径(任意磁盘文件,不限于笔记库),来源:文件对话框 / 拖入 / 命令行 / 编辑器「与…对比」。
|
||||
- **编码感知**:复用 `editor::files::read_file`(BOM → 严格 UTF-8 → chardetng 探测 → GB18030 兜底),状态栏显示两侧各自探测到的编码,不一致时给出提示(「左边 GBK / 右边 UTF-8」这类差异往往就是用户要找的问题)。
|
||||
- 二进制文件:不渲染 diff,只报「二进制文件,大小 X vs Y,内容不同/相同」。
|
||||
- 只读打开 + 可切换为可编辑;保存回写**仅作用于被显式编辑的一侧**(这一条属于 P2,不等同于 P3 的目录同步)。
|
||||
- 拖入:拖文件到左半区 = 设为左侧目标,右半区 = 右侧目标。
|
||||
|
||||
### 3.3 文件夹对比(P3,只读)
|
||||
|
||||
- 递归遍历两侧,按**相对路径**对齐(根目录不同名也要对齐)。
|
||||
- 每个条目三态 + 细分:
|
||||
| 状态 | 判据 |
|
||||
|---|---|
|
||||
| 仅左侧有 | 右侧无同相对路径 |
|
||||
| 仅右侧有 | 左侧无同相对路径 |
|
||||
| 两侧都有 · 相同 | size 相同 → mtime 相同 →(必要时)内容一致 |
|
||||
| 两侧都有 · 不同 | size 不同,或 size 相同但内容不同 |
|
||||
| 目标类型不同 | 一侧是文件、另一侧是同名目录 |
|
||||
- 树形展开 + 过滤(只看有差异 / 只看某一侧有)+ 「展开到下一个差异」。
|
||||
- 目录级汇总:`N 项不同 · M 项仅左 · K 项仅右`,可折叠跳过相同项。
|
||||
- 点击「不同」的文件行 → 在**同一个窗口**下钻到 §3.2 的文件对比视图(带返回上一级)。
|
||||
- 忽略规则(可选,P3 后期):`node_modules` / `.git` 等常见目录的默认忽略清单。
|
||||
|
||||
### 3.4 不做(本期明确划界)
|
||||
|
||||
- 目录写回 / 镜像 / 双向同步(用户已拍板暂不做)。
|
||||
- 三路合并与冲突解决。
|
||||
- 二进制内容级对比(只判「相同/不同」与大小)。
|
||||
- 大文件(> 阈值)的完整 diff —— 降级为只报状态,不做行级对齐。
|
||||
|
||||
---
|
||||
|
||||
## 4. 技术选型
|
||||
|
||||
### 4.1 渲染层:`@codemirror/merge`(已安装 6.12.2)
|
||||
|
||||
| 方案 | 结论 | 理由 |
|
||||
|---|---|---|
|
||||
| **`@codemirror/merge`** | **采用** | CM6 官方 MergeView:并排/统一、块级高亮、chunk 导航、接受/拒绝、行号 gutter 全部现成;与已装的 `@codemirror/state 6.7.6` / `view 6.43.x` 同源;主题直接复用 `editor/editor/themes.ts` 的九套配色 |
|
||||
| Rust `similar` crate | 暂不引入 | 计算快、可单测,但并排对齐 UI 要自己写;P1/P2 用不到,等 P3 目录级需要「批量算文件差异摘要」时再评估 |
|
||||
| 手写 LCS(原 devtools 实现) | 弃用 | O(n·m) DP 会卡死 UI,且没有对齐/高亮,已随 `DiffTools.vue` 一并移除 |
|
||||
|
||||
### 4.2 计算层:Rust 只做目录级
|
||||
|
||||
- `walkdir` 已在依赖树([Cargo.toml](../src-tauri/Cargo.toml)),递归扫描零新增成本。
|
||||
- 文件内容比对优先用 **size → mtime → 内容** 三级快速路径,避免几万文件目录下全量读盘。
|
||||
- 需要内容级判定时可选 `similar` 或 SHA-256(`sha2` 已在依赖树)。
|
||||
|
||||
### 4.3 主题:复用编辑器配色,不新建一套
|
||||
|
||||
对比窗口必须与编辑器窗口「同深同浅、同配色」,否则用户从编辑器跳到对比会感到割裂。做法:直接调用 `resolveEditorTheme` / `editorTypography` / `editorBackground`,并沿用编辑器窗口那套「跟随主应用主题 / 配色方案」的深浅推导(`EditorWindow.windowIsDark` 的逻辑)。**不需要在本模块重复维护配色表。**
|
||||
|
||||
---
|
||||
|
||||
## 5. 模块化决策(编辑器内 vs 独立模块)
|
||||
|
||||
| 维度 | 放进编辑器 | **独立 `diff` 模块(采纳)** |
|
||||
|---|---|---|
|
||||
| 中心对象 | 一篇文档的生命周期 | 两个被比较的目标 |
|
||||
| 窗口形态 | 编辑器标签栏 + 编辑区 | 双栏 + 目录树(布局不兼容) |
|
||||
| 状态 | 自动保存 / 脏标记 / 会话恢复 / 光标 | 无自动保存;目标是只读或被显式编辑 |
|
||||
| capability 语义 | 「编辑笔记」 | 「对比」(授权范围各自清晰) |
|
||||
| 代码影响面 | 继续膨胀 `EditorWindow.vue` / `editorStore.ts` | 新增独立目录,互不干扰 |
|
||||
| 复用方式 | —— | 复用 CM6 装配 / 主题 / 语言包 / Rust 文件读取,**不共享窗口与 store** |
|
||||
|
||||
补充两条:
|
||||
|
||||
- **不做成 devtools 里的小工具**:devtools 是「主窗口内的单页聚合」,双栏 + 目录树装不进那个壳,也没有空间与拖拽入口。
|
||||
- **交叉入口(可选,P2 之后再评估)**:编辑器窗口加「与…对比」,把当前文档发给 diff 窗口。它只是锦上添花,不影响主体结构。
|
||||
|
||||
---
|
||||
|
||||
## 6. 架构与文件清单
|
||||
|
||||
```
|
||||
主模块页(入口 / 进度) 独立窗口(双栏差异视图 / 目录三态树)
|
||||
↓ Tauri IPC ↓
|
||||
src-tauri/src/diff/ 命令层
|
||||
↓
|
||||
commands.rs 单文件读取 / 写回 / 路径类型探测 / 目录对比入口
|
||||
scan.rs 目录对比:递归遍历 + 三态分类(三层判据,见 §7.3)
|
||||
types.rs 回传前端的 DTO(与前端 types.ts 对齐)
|
||||
↓
|
||||
editor::files 文件读取与编码探测(**复用**,提升为 pub(crate))
|
||||
|
||||
src-tauri/src/drag_drop.rs 拖放补注入(**通用**,编辑器与对比窗口共用)
|
||||
|
||||
前端:
|
||||
src/modules/diff/
|
||||
index.ts moduleConfig(icon: 'diff',order 50)
|
||||
DiffModule.vue 主模块页:入口 + 三层能力进度
|
||||
DiffWindow.vue 独立窗口外壳:模式切换(文件 / 文本 ↔ 文件夹)+ 文件对比界面
|
||||
openWindow.ts diff-window 创建入口(单例,隐藏创建 + 拖放补注入)
|
||||
diffClient.ts 命令名唯一落点(照抄 editorClient.ts 范式)
|
||||
types.ts 与 Rust DTO 对齐的类型(DiffStats / DiffFileDoc / DirDiffEntry / DirDiffReport / DiffSide)
|
||||
components/
|
||||
TextMergeView.vue MergeView 封装(P1;P2 增补 setTexts / getText / doc-changed)
|
||||
DirDiffView.vue 目录对比视图(P3:工具行 / 根路径 / 过滤 / 三态树 / 汇总)
|
||||
|
||||
登记点:
|
||||
src/modules/index.ts 注册 moduleConfig
|
||||
src/modules/icons.ts 图标映射(diff → Diff)
|
||||
src/main.ts 独立窗口路由表加一行 '#diff-window'(按前缀匹配,支持 ?path=)
|
||||
src/lib/constants.ts WINDOWS.diffWindow
|
||||
src-tauri/src/taskbar_identity.rs 新增 'diff' 窗口类型(AUMID + 组合图标)
|
||||
src-tauri/capabilities/diff-window.json windows: ["diff-window"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 关键实现细节
|
||||
|
||||
### 7.1 拖入支持(用户点名需要)
|
||||
|
||||
既有实现原先在 `src-tauri/src/editor/drag_drop.rs`,**已泛化**为 `src-tauri/src/drag_drop.rs` 的 `window_attach_drag_drop`(按传入 label 生效,日志标记为 `drag-drop`),编辑器窗口与对比窗口共用同一份实现 —— 泛化而非复制,避免第二份同构实现各自腐坏。
|
||||
|
||||
要点(两条实现路径的取舍已定:**泛化**):
|
||||
|
||||
| 事项 | 结论 |
|
||||
|---|---|
|
||||
| 命令 | `window_attach_drag_drop(label)`,模块位于 crate 根部(不再属于 editor) |
|
||||
| 调用时机 | 窗口创建后**立即** fire-and-forget 调用(不能等 `tauri://created`:窗口创建过快时该事件可能早于监听注册而永远等不到)。Rust 侧自行重试等待子窗口就位 |
|
||||
| 窗口配置 | `dragDropEnabled: true` |
|
||||
| 落点分侧 | 前端按 drop 坐标分左右半边。坐标是**物理像素**,需除以 `devicePixelRatio` 再与 CSS 宽度比较 |
|
||||
| 目录 | `diff_read_file` 会拒绝目录并提示「目录对比尚未开放」——不让用户拖了没反应 |
|
||||
|
||||
### 7.2 编码与二进制(P2)
|
||||
|
||||
- 读取复用 `editor::files::read_file(path, max_mb)`:BOM → 严格 UTF-8 → chardetng 探测 → GB18030 兜底,并把「读到的编码 + 换行」成对记下来供写回原样还原。为此把 `editor::files` 提升为 `pub(crate)`(跨模块复用,范式同 `terminal::local_fs`)。
|
||||
- **二进制由对比模块自己判定**(`editor::files` 只负责解码,没有二进制概念):按**头部 8KB 含 NUL** 判定,与 `editor::grep` 的跳过判据完全一致 —— 否则会出现「搜索跳过了、对比工具却显示一堆乱码」这种自相矛盾的行为。判定为二进制后**不读内容**,只回元信息(避免把无意义字节解码成一大段乱码再走 IPC)。
|
||||
- 两侧编码分别在各自头部以 chip 显示;**编码不一致要在状态栏显式提示**(这是真实场景里最常见的「看起来全是乱码差异」根因)。
|
||||
- 尺寸两级:软阈值 5MB(置 `large`,供前端降级)、硬上限 16MB(直接拒绝)。硬上限比编辑器的每篇上限更严,因为对比窗口**同时**持有两侧内容。
|
||||
- 大文件降级:`large` 已回传,前端目前只在 `TextMergeView` 里靠 MergeView 的 `scanLimit` 兜底(见 §7.4),更细的降级(关折叠 / 不做行级对齐)留待后续。
|
||||
|
||||
### 7.3 目录扫描性能与判据(P3)
|
||||
|
||||
三层判据(代价递增,能不打盘就不打盘):
|
||||
|
||||
1. **size 不同** → 直接判「不同」(大小都不同,内容不可能相同);
|
||||
2. **size 相同且 mtime 相同** → 判「相同」;
|
||||
3. **size 相同但 mtime 不同** → 才读内容逐字节比对。
|
||||
|
||||
第 3 步有预算:[`MAX_CONTENT_COMPARES`] = 2000 条、单文件 ≤ 4MB。超出后不再读盘,按
|
||||
时间戳归入「不同」并把 `content_compared` 置 false —— 结论仍是「不同」,但界面会显式
|
||||
标注「未比对内容」,不与已确认的差异用同一种语气呈现(不能把「按元数据的推测」包装成
|
||||
「读过的结论」)。
|
||||
|
||||
其余边界:
|
||||
|
||||
- **条目上限** 8000(`truncated` 标记 + 界面提示):再大就让用户缩小范围,
|
||||
而不是把几十 MB 的 JSON 塞过 IPC。
|
||||
- **不跟随符号链接**(`walkdir` 默认):跟随会让「链接成的环」把遍历变成死循环。
|
||||
- **跳过清单由前端给出**(目录名、大小写不敏感、命中即整棵子树不遍历),默认清单与
|
||||
`editor` 模块的默认跳过清单一致,另有开关可关。后端只按清单执行 —— 同 `editor::grep`
|
||||
把默认清单留在前端的取舍。
|
||||
- 扫描是**同步命令 + 前端异步等待**(一次返回整棵树),不做进度事件:实测量级下
|
||||
(几万条目)耗时在百毫秒到数秒,做进度事件的复杂度不值当。若将来真的出现分钟级扫描,
|
||||
再改成分批回传。
|
||||
- 返回**扁平列表**(不是树):递归类型在 specta 下会生成无穷展开的 TS 类型(同
|
||||
`editor::types::LibraryEntry` 的坑);树的组装、剪枝、排序都在前端。
|
||||
|
||||
### 7.4 大文本保护(P1)
|
||||
|
||||
旧的 devtools 实现是 3000 行、LCS O(n·m)、超限直接停算。P1 **不设硬阈值**:MergeView 的 `diffConfig.scanLimit`(默认 500)会在差异过大时放弃精确比对、退回快速但不精确的算法,避开二次方耗时且仍然给出结果。真要做「超大文件不做行级对齐」的降级,留到 P2/P3 与文件读取的 `large` 标记一并处理 —— 那时才有「一个真实的大文件」这个输入,而不是用户粘贴的文本。
|
||||
|
||||
### 7.5 窗口与任务栏身份
|
||||
|
||||
沿用编辑器窗口的范式:**隐藏创建**(避免深色主题下闪白)→ 应用主题与窗口效果 → `window_set_taskbar_identity`(独立任务栏按钮 + 组合图标)→ `show()`。任务栏身份**必须在 show() 之前**设置。
|
||||
|
||||
---
|
||||
|
||||
## 8. 分期路线图
|
||||
|
||||
### P1 · 文本对比(**已落地**)
|
||||
|
||||
**目标**:双栏 MergeView 跑通,验证 `@codemirror/merge` 与项目 CM6 版本的兼容性。
|
||||
|
||||
已交付:
|
||||
|
||||
1. `src/modules/diff/`:`index.ts`(moduleConfig)+ `DiffModule.vue`(主模块页)+ `DiffWindow.vue`(独立窗口)+ `openWindow.ts` + `components/TextMergeView.vue` + `types.ts`。
|
||||
2. `src/modules/icons.ts` 加 `diff` 图标映射;`src/modules/index.ts` 注册模块;`src/main.ts` 加 `#diff-window` 路由。
|
||||
3. `src-tauri/capabilities/diff-window.json`(glob `diff-window-*` 同源权限集)。
|
||||
4. `src-tauri/src/taskbar_identity.rs` 新增 `diff` 类型(独立 AUMID + 双栏图形组合图标)。
|
||||
5. `src/lib/constants.ts` 加 `WINDOWS.diffWindow`。
|
||||
6. 删除 devtools 的文本对比工具:`DiffTools.vue` 已删,`tools/index.ts` 去掉元数据 / 图标 / 组件映射,`devtools/index.ts` 计数 20 → 19。
|
||||
7. 依赖:`@codemirror/merge ^6.12.2`(`@codemirror/state 6.7.6` 未变,`view 6.43.x` 补丁级同步)。
|
||||
8. 校验:`vue-tsc --noEmit`、`eslint`、`vite build`、`cargo check` 全部通过。
|
||||
|
||||
**尚未验证**:窗口在真实 Tauri 运行时的观感(滚动联动、mica 底色下的对比度、任务栏图标)需要跑一次 `tauri dev` 目视确认。
|
||||
|
||||
### P2 · 文件对比(**已落地**)
|
||||
|
||||
已交付:
|
||||
|
||||
1. Rust `src-tauri/src/diff/`:`mod.rs` / `types.rs`(`DiffFileDoc`)/ `commands.rs`(`diff_read_file`、`diff_write_file`)。读取复用 `editor::files::read_file`(编码探测 / 换行归一 / 只读探测),读取即登记授权(于是「打开过就能保存」成立)。为此把 `editor::files` 提升为 `pub(crate)`。
|
||||
2. 尺寸与二进制策略:软阈值 5MB(置 `large`)、硬上限 16MB(直接拒绝,对比窗口天生要同时持有两侧)、二进制按「头部 8KB 含 NUL」判定(与 `editor::grep` 同一判据),二进制**不读内容**只回元信息。
|
||||
3. 拖放泛化:`editor/drag_drop.rs` → `src-tauri/src/drag_drop.rs`,命令改名 `window_attach_drag_drop`,编辑器与对比窗口共用;`diff/openWindow.ts` 创建后立即补注入。
|
||||
4. `diffClient.ts`(命令名唯一落点)+ `types.ts` 扩展(`DiffFileDoc` / `DiffSide`)。
|
||||
5. `TextMergeView` 增补 `setTexts` / `getText` 与 `doc-changed` 事件(程序化装载期间抑制,避免把装载记成用户编辑)。
|
||||
6. `DiffWindow.vue`:两侧头部(打开文件 / 保存 / 编码 chip / 只读 chip / 脏标记)、拖入分侧高亮、编码不一致提示、二进制概览面板(只比大小,不断言「内容相同」)、`Ctrl+S` 单侧写回、关闭前三选一确认。
|
||||
7. `DiffModule.vue` 主模块页把「文件对比」标为可用。
|
||||
8. 校验:`cargo check`、`vue-tsc --noEmit`、`eslint`、`vite build` 全部通过。
|
||||
|
||||
**已知取舍**:
|
||||
|
||||
- `bindings.ts` 是 `run()` 里 `export_bindings()` 在 debug 构建时生成的,本次未跑 `tauri dev`,因此其中仍留着旧的 `editorAttachDragDrop` 声明(**无任何调用点**);下次 debug 运行会自动重建。
|
||||
- 脏标记是布尔(改过即脏),「改了又撤销回原样」仍显示为脏 —— 方向安全(至多多一次关闭确认),换来的是每次按键不必把整篇文档 `toString()` 出来比对。
|
||||
- 单侧写回**不检查另一侧是否也改了同一个文件**(两侧选中同一路径时后保存的覆盖先保存的)。仍是未解决的边界 —— P3 的目录模式是只读的,不会走到这条路径。
|
||||
|
||||
### P3 · 文件夹对比(**已落地**,只读)
|
||||
|
||||
已交付:
|
||||
|
||||
1. Rust `diff/scan.rs`:递归遍历(`walkdir`,不跟随符号链接)+ 三态分类 + 三层判据(见 §7.3)+ 跳过清单 + 条目上限。
|
||||
2. `diff/commands.rs` 增补 `diff_compare_dirs` 与 `diff_path_kind`(后者用于「拖入 / `?path=` 传进来的路径是文件还是目录」)。
|
||||
3. 前端 `diffClient.compareDirs` / `pathKind`,`types.ts` 增补 `DirDiffEntry` / `DirDiffReport` / `DirDiffStatus`。
|
||||
4. `components/DirDiffView.vue`:选两侧文件夹、跳过构建目录 / 比对内容两个开关、过滤(仅差异 / 全部 / 仅左侧 / 仅右侧)、树(目录在前、同名排序、可折叠、展开/折叠全部)、按子树剪枝、汇总栏(不同 / 仅左 / 仅右 / 相同 / 类型不一致 / 跳过目录数 / 耗时 / 截断提示)。
|
||||
5. `DiffWindow.vue` 增加模式切换(文件 / 文本 ↔ 文件夹,各自记住自己的目标)、拖入按模式分派(目录模式取该侧根;拖文件取父目录)、点差异行下钻到文件对比 + 「返回目录对比」。
|
||||
6. 校验:`cargo check`、`vue-tsc --noEmit`、`eslint`、`vite build` 全部通过(并核对 `h-6.5` 这类分数间距类确实被 Tailwind v4 生成)。
|
||||
|
||||
**关键取舍(都在实现里写了理由)**:
|
||||
|
||||
- **切模式不能丢改动**:目录模式下 `TextMergeView` 被卸载,用户刚敲的内容只存在于 CM6 实例里。离开文件模式前先 `snapshotEdits()` 把脏侧的内容取进 `contentA/B`,切回来时再灌回去(`setTexts` 抑制 `doc-changed`,脏标记原样保留)。
|
||||
- **保存必须先确保文件模式已挂载**:`saveSide` 在取不到内容时直接返回 false 而**不是**写空串;`Ctrl+S` / 「保存并关闭」走 `saveAllDirtyEnsuringFiles`,会先切回文件模式再保存 —— 否则目录模式下保存会把文件写空。
|
||||
- **目录的「相同 / 不同」由子树决定**:Rust 一律给目录标 `identical`,前端按子树是否含差异决定目录行的颜色与是否显示。
|
||||
- **只读**:本期不做任何写回 / 同步(用户已拍板)。
|
||||
|
||||
**尚未验证**:与 P1/P2 一样,真实 Tauri 运行时下的观感与拖放行为需要跑一次 `tauri dev` 目视确认。
|
||||
|
||||
### P4 · 交互层补全(**已落地**,参考 Beyond Compare)
|
||||
|
||||
用户提出的五项调整,逐项落地情况:
|
||||
|
||||
| # | 需求 | 实现 |
|
||||
|---|---|---|
|
||||
| 1 | 选项卡,标题 `xxx ↔ xxx` | `DiffWindow` 改为**会话(session)**架构:一个选项卡 = 一对目标。标题取两侧显示名(文件用文件名、目录用末段目录名)。窗口标题同步为 `对比 — 左 ↔ 右`,任务栏悬停可见 |
|
||||
| 2 | 目录对比改左右两个界面,都用结构树;两侧可自由输入与选择,选择改图标按钮 | `DirDiffView` 重写为**左右两棵结构树**:同一份并集行渲染两遍(行数/顺序一致、共用折叠状态),每侧只显示该侧真实存在的文件(缺失侧显示「—」并压暗名字);每侧顶部是**可编辑路径输入框 + 文件夹图标按钮**;列头对齐 Beyond Compare 的「名称 / 大小 / 已修改」 |
|
||||
| 3 | 点一侧文件 → 新开文件对比选项卡 | 行点击 → `open-file` → 新开文件选项卡(记录 `fromDirTabId`,工具栏出现「返回目录对比」)。**只在一侧存在的文件也能开**(另一侧留空,整篇为新增/删除) |
|
||||
| 4 | 快捷键唤出对比窗口,默认 Alt+C,参考编辑器机制 | Rust 侧新增 `DiffSettings` + `DiffManager`(`{app_data_dir}/diff/settings.json`),`init_on_launch` 用 `shortcut.rs` 注册(原子注册 + 应用内冲突检测),触发只发 `diff-open-window` 事件;`App.vue` **应用级**监听后调 `openDiffWindow()`。模块页可改快捷键(保存后就地重注册) |
|
||||
| 5 | 中间列显示差异、快速替换等 BC 细节 | 文件对比启用 MergeView 的 `revertControls`:**中间列**按差异块渲染 ⇜ / ⇝ 按钮,点一下即把该块替换到另一侧(替换后该侧变脏)。MergeView 一次只能渲染一个方向,因此工具栏给出「右 → 左 / 左 → 右」方向切换(`reconfigure` 热切换,不重建视图) |
|
||||
|
||||
**P4 关键取舍**:
|
||||
|
||||
- **切选项卡不能丢改动**:`TextMergeView` 只有一个实例,内容只在 CM6 里是最新的。切走前 `snapshotEdits()` 把脏侧内容取回会话,切回来再灌进去(`setTexts` 抑制 `doc-changed`,脏标记保留)。
|
||||
- **关闭选项卡的判据是「脏」而不是「编辑器是否挂载」**:非激活选项卡的编辑内容已快照在会话里,静默丢弃同样是丢改动 —— 因此脏就弹确认,确认后先激活它再保存(激活那一刻才能拿到最新内容)。
|
||||
- **会话状态里的大对象要 `markRaw`**:扫描报告可达数千条目,进响应式系统会逐条生成 Proxy。内容字符串是原始值,不进 Proxy,可以放心放会话里。
|
||||
- **`v-model:session` 而不是普通 prop**:`DirDiffView` 要直接改会话字段(8 个字段几乎都双向改),而 `vue/no-mutating-props` 禁止改 prop;`defineModel` 是 Vue 为这种场景给的正解。
|
||||
|
||||
---
|
||||
|
||||
## 9. 已拍板决策表
|
||||
|
||||
| # | 问题 | 决策 | 影响 |
|
||||
|---|---|---|---|
|
||||
| 1 | devtools 里的文本对比工具 | **移除**,能力并入本模块 | 避免仓库里存在两套 diff 引擎;顺带解决它的 3000 行上限 |
|
||||
| 2 | 目录对比是否写回 | **暂不做**(P3 只读) | P3 工程量显著下降;写回留待单独评估 |
|
||||
| 3 | 是否需要拖入 | **需要** | 已落地:P2 起拖入文件按落点装入左 / 右半区 |
|
||||
| 4 | 做进编辑器还是独立模块 | **独立模块 + 独立窗口** | 复用编辑器能力但不共享窗口/store |
|
||||
| 5 | 渲染层选型 | **`@codemirror/merge`** | 已有 6.12.2 安装;主题复用编辑器配色 |
|
||||
| 6 | 本期是否引入 Rust `similar` | **不引入**(P1/P2 不需要) | P3 目录级若需批量摘要再评估 |
|
||||
| 7 | 拖放补注入的实现路径 | **泛化既有实现**(不复制第二份) | `drag_drop.rs` 移到 crate 根部、命令改名 `window_attach_drag_drop`;编辑器调用点随之一并更新 |
|
||||
| 8 | 单文件读取的尺寸策略 | 软阈值 **5MB** / 硬上限 **16MB** | 硬上限比编辑器更严:对比窗口同时持有两侧内容 |
|
||||
| 9 | 目录对比的判据 | size → mtime → 内容(三层) | 内容比对有预算(2000 条 / 4MB):超出按时间戳判定,并在界面标注「未比对内容」 |
|
||||
| 10 | 目录树结构 | Rust 返回**扁平列表**,前端组装 | 避开 specta 递归类型的坑(同 `LibraryEntry`);剪枝 / 排序 / 过滤都在前端 |
|
||||
| 11 | 本期是否做目录写回 | **不做**(只读) | 用户已拍板;冲突策略等留待单独评估 |
|
||||
| 12 | 窗口内是否有选项卡 | **有**(P4):一选项卡 = 一对目标 | 状态按会话组织;目录下钻新开选项卡而不是替换 |
|
||||
| 13 | 目录对比的界面形态 | **左右两棵结构树**(P4,原为一棵并集树) | 同一份并集行渲染两遍,共用折叠状态保证不错行 |
|
||||
| 14 | 打开对比窗口的快捷键 | **Alt+C**(P4,可在模块页改) | 走 `shortcut.rs`;触发只发事件,窗口由前端创建 |
|
||||
| 15 | 中间列快速替换 | **启用**(P4):⇜/⇝ 单方向 + 工具栏切换 | MergeView 一次只能一个方向;双方向要自绘中间列,暂不做 |
|
||||
|
||||
---
|
||||
|
||||
## 10. 风险与待验证
|
||||
|
||||
| 风险 / 未知 | 说明 | 应对 |
|
||||
|---|---|---|
|
||||
| `@codemirror/merge` 与项目版本兼容 | 已确认安装 `6.12.2`,`@codemirror/state 6.7.6` 未变,`view` 由 `6.43.13` 升到 `6.43.14`(补丁级) | 已通过安装验证;P1 构建与运行再复核一次 |
|
||||
| MergeView 的块级高亮配色与自建主题的融合 | MergeView 提供的是结构类名/默认色,需按项目语义色覆盖(新增/删除/修改) | P1 里显式覆盖 `.cm-changedLine` 等规则,对齐 `--success-soft` / `--danger-soft` |
|
||||
| 目录扫描在大目录上的耗时 | 几十万文件递归 + 内容比对可能秒级到十几秒 | §7.3 快速路径 + 忽略清单 +(必要时)进度事件分批 |
|
||||
| 拖放注入射程 | 现实现是编辑器专用的,泛化会触及编辑器路径 | §7.1 二选一;若选泛化,回归编辑器窗口的拖入 |
|
||||
| 二进制与超长行文本在 MergeView 下的表现 | 极长单行(如压缩后的 JSON)会让对齐与渲染变慢 | 阈值降级 + 明确提示,不做静默失败 |
|
||||
@@ -0,0 +1,533 @@
|
||||
# 编辑器模块规划(Editor Module Plan)
|
||||
|
||||
> 状态:**方案已确认,待开工**(v1 已落地;v2 定位修订与本轮 10 项决策已定稿)
|
||||
> 本轮决策(2026-09-30,用户已拍板):**不引入工作区**(Q2=a)· **目录树不纳入索引**(Q3=a)· **标签页放 P4**(Q4=a)· **模块显示名 = 编辑器**(Q1=a)
|
||||
> v1 现状(原「笔记模块」,已全部落地):CM6 内核 + Live Preview + 本地笔记库 + 独立窗口 + 检索/索引 + WebDAV + 导入导出 + 模板 + 双链 + 图片预览 + 全局快捷键 + 文件关联
|
||||
> v2 修订方向:模块核心从「笔记」改为「**编辑器**」——一个 notepad++ 式的通用文本/代码编辑器;**笔记库与本地目录探查退化为它的两个并列导航能力**,不再是模块的中心
|
||||
> 已确认决策:所见即所得 = **Live Preview**(非块编辑);WebDAV = **备份 / 同步目标**(不做远端直连读写);编码 = **可探测、可切换、原样写回**
|
||||
> 定位:Thing 工具集的第 13 个模块,`id = editor`(原 `notes`),`category = 'tool'`
|
||||
> 作者:砚 | 日期:2026-09-30
|
||||
> 关联文档:`AI_DEV_GUIDE.md`(模块注册 / IPC / 进程管理范式)、`UI_DESIGN_SYSTEM.md`(页面框架 / 组件规范)、`TERMINAL_MODULE_PLAN.md`(独立窗口 / 跨窗口设置同步范式)
|
||||
>
|
||||
> 阅读顺序:**§11 开工清单(先读,它是执行入口)** → §0 结论 → §1 定位修订 → §3 功能规格 → §5 编码 → §7 缺口 → §8 路线图。
|
||||
> **§9 是 v1 的压缩实施记录**,只保留「为什么这么做」的结论与踩过的坑;**§10 是已拍板的决策表**(不再是待定项)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 结论先行
|
||||
|
||||
八个关键判断。
|
||||
|
||||
1. **模块改名 `notes` → `editor`,但一次到位、不留双命名。** `id` / 窗口 label / 事件名 / Rust 命令前缀 / 目录名 / 存储键全部统一。半改不改(模块叫 editor、命令还叫 `notes_*`)比不改更糟:读代码的人要同时维护两套心智。改名是机械工作(约 400 处标识符),风险集中在「漏改一处」,用脚本核对(§9.6)。
|
||||
|
||||
2. **「笔记」不是被删掉,而是被降级为一种能力。** 编辑器的最小模型是「路径 + 字节 + 编码」,笔记库是加在它之上的一层(库根沙箱 + front-matter + 索引 + 双链)。因此**文件是真相层,笔记库是视图层**——这条和 v1 的「文件即真相」并不冲突,只是把「库」从中心挪到了并列位置。
|
||||
|
||||
3. **左侧导航 = 两个并列的树 + 三块辅助能力。** 两个树:**笔记库**(沙箱、有索引、有双链)与**本地目录**(任意路径、无索引、无 front-matter 语义)。三块辅助:**文件名/内容搜索**、**最近打开(文件夹与文件分开记)**、**定位到资源管理器**。
|
||||
|
||||
4. **多编码是这一版的新增硬需求,且必须「可切换」。** 探测链:BOM → 严格 UTF-8 → GB18030(中文存量主力)→ 用户手动指定。写回**默认按读取时的编码**。切换编码的语义是「**换一种方式解释磁盘字节**」而不是「重新解释缓冲区文本」——因此切换动作会**从磁盘按新编码重新解码**(有未保存改动时先让用户三选一,见 §5.3)。
|
||||
|
||||
5. **系统集成走用户级注册表,不需要管理员权限。** 文件关联(双击打开)走 Tauri `fileAssociations`;**资源管理器右键菜单**(文件/文件夹)走 `HKCU\Software\Classes\*\shell\*` 与 `Directory\shell\*`,用**已在依赖树里的 `winreg`** 写(项目已有 `system_proxy.rs` / `glsmtc.rs` 两处先例)。**注册动作放在设置页按钮里、默认不自动写注册表**——开发模式下的 exe 路径是 `target\debug\thing.exe`,自动注册会留下指向临时产物的僵尸菜单项。
|
||||
|
||||
6. **默认全局快捷键 `Alt+E` 打开编辑器。** 走既有 `shortcut.rs`(原子注册 + 冲突检测),设置页可改。
|
||||
|
||||
7. **不引入「工作区」概念(已拍板)。** 用户要的是「右键文件夹 → 在这里打开」,用**当前目录根**这一个状态就够了(可切换 + 有历史)。引入 workspace 会连带出「多根 / 会话恢复 / 每根独立状态」三个复杂度,而收益(同时开两个目录树)在 notepad++ 式用法里很低。因此侧栏只有一个「目录」面板,根是单值。
|
||||
|
||||
8. **不做的事**(明确划界,避免无限扩张):不做 IDE 能力(调试器、终端内嵌、LSP 补全、Git 集成);不做块编辑器;不做远端工作区(WebDAV 只做备份/同步目标)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 定位修订(v1 → v2)
|
||||
|
||||
| 维度 | v1(笔记模块) | v2(编辑器模块) |
|
||||
|---|---|---|
|
||||
| 一句话 | 一个 Markdown 笔记库,带所见即所得编辑 | 一个通用文本/代码编辑器,**顺带**能管一个笔记库 |
|
||||
| 中心对象 | 笔记(库内 `.md`) | 文件(任意路径的任意文本) |
|
||||
| 首要入口 | 库树 → 选一篇笔记 | 打开文件 / 最近文件 / 目录树 → 选一个文件 |
|
||||
| 笔记库的角色 | 模块的**全部** | 两个导航根之一 + 一层语义(front-matter / 双链 / 索引) |
|
||||
| 编码 | 「尽量别写坏」(读时记、写回原样) | **一级功能**:探测 + 状态栏显示 + 可切换 |
|
||||
| 系统集成 | 无(P2 曾因依赖代价搁置) | 文件关联 + 资源管理器右键 + `Alt+E` |
|
||||
| 索引 | FTS5 全文检索(笔记的核心) | 保留,但只服务笔记库;目录树只做文件名匹配 |
|
||||
| markdown Live Preview | 默认视图 | **按文件类型自动选择**:`.md` 用 Live Preview,其余用纯高亮 |
|
||||
|
||||
> 一句话总结这次修订:**把「库」从产品中心降为两个导航能力之一,把「文件 + 编码 + 系统集成」提到中心。**
|
||||
|
||||
---
|
||||
|
||||
## 2. 需求解构
|
||||
|
||||
| 用户原话 | 解构为 | 落点 |
|
||||
|---|---|---|
|
||||
| 「核心改为 Editer,标题和其他都改」 | 模块改名 + 重定位 + 主页面/窗口标题/文案全面改口径 | §1 / §7 / §9.6 |
|
||||
| 「笔记作为编辑器模块的一个核心功能」 | 笔记库降为并列能力,但保留全部既有实现 | §1 / §3.3 |
|
||||
| 「左边导航栏有两个功能:笔记库 / 本地目录结构」 | 侧栏两个并列根:库根(沙箱 + 索引)与当前目录(任意) | §3.3 / §6 |
|
||||
| 「导航栏需要定位打开文件位置、搜索文件名(参考 idea)」 | 「在资源管理器中显示」+ 两级过滤(文件名 LIKE / 库内 FTS) | §3.4 |
|
||||
| 「核心只是普通编辑器,类似 notepad++」 | 不引入 IDE 能力;以「打开快、编码稳、快捷键全」为质量目标 | §0.8 / §3.1 |
|
||||
| 「快捷键直接打开编辑器,默认 alt+e」 | 全局快捷键,默认 `Alt+E`,设置页可改 | §3.7 |
|
||||
| 「文件管理器右键菜单,用 Thing Editer 打开」 | HKCU 注册 `*\shell\ThingEditor` 与 `Directory\shell\ThingEditor` | §3.6 |
|
||||
| 「历史打开的文件夹/文件记录」 | 最近文件 + 最近文件夹两份列表(分组显示、可清空) | §3.5 |
|
||||
| 「多编码,识别 + 支持切换编码」 | 探测链 + 状态栏编码菜单 + 重解码 + 按新编码重写 | §5 |
|
||||
| 「优化结构和功能完整性」 | 补齐:编码切换、目录树、最近记录、右键菜单、大文件策略、只读打开 | §3 / §4 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 功能规格
|
||||
|
||||
### 3.1 编辑器核心
|
||||
|
||||
- **打开方式**:最近文件 / 目录树 / 笔记库树 / 系统对话框 / 命令行 / 文件关联 / 资源管理器右键。
|
||||
- **视图按类型自动选**:`.md`/`.markdown`/`.mdx` 默认 Markdown(Live Preview,可在状态栏切到源码);其余按扩展名加载语言高亮(`@codemirror/lang-*` 按需 `import()`)。
|
||||
- **基础编辑**:行号、折叠、括号匹配、多光标、矩形选择、搜索替换(CM6 原生 `searchKeymap`)、转到行(`Alt+G`)、撤销栈、Tab 缩进。
|
||||
- **快捷键**(窗口内,CM6 `keymap` 优先于全局):`Ctrl+S` 保存、`Ctrl+Shift+S` 另存为、`Ctrl+O` 打开、`Ctrl+P` 快速打开、`Ctrl+W` 关闭当前文档、`Ctrl+Tab` 文档间切换、`Ctrl+E` 切换编码、`Ctrl+Shift+M` 切换 Live Preview/源码。
|
||||
- **多文档**:同一窗口内多标签(**新增**,见 §8-P1)。`Ctrl+W` 关闭标签,关闭前若有未保存改动则二次确认。
|
||||
- **大文件策略**:超过阈值(默认 5MB,可配)时关闭 Live Preview / 折叠 / 补全 / 装饰,只保留高亮 + 行号;并在状态栏给出可点击的降级说明。
|
||||
- **只读打开**:检测到文件不可写时以只读模式打开(替代「打开成功但保存失败」)。
|
||||
|
||||
### 3.2 笔记模式(`.md` 在库内)
|
||||
|
||||
保持 v1 全部能力:Live Preview(标题/强调/行内代码/列表/任务/引用/代码块/分隔线/表格/图片内联)、`[[wikilink]]` 点击跳转与一键新建、front-matter 属性面板、大纲、双链面板、字数/行数统计。
|
||||
|
||||
### 3.3 左侧导航(两个并列根)
|
||||
|
||||
| 面板 | 根 | 能力 | 数据来源 |
|
||||
|---|---|---|---|
|
||||
| **笔记库** | 库根(可切换,默认 `{appData}/editor/library`) | 树 / 新建 / 重命名 / 删除 / 标签 / 双链 / FTS 全文检索 | SQLite 索引(`notes.db` → `editor.db`) |
|
||||
| **本地目录** | 当前目录根(可切换,有历史) | 树 / 文件名过滤 / 打开文件 / 新建文件/文件夹 / 重命名 / 删除 / 在资源管理器中显示 / 复制路径 | 直接 `fs` 读目录(**不进索引**) |
|
||||
|
||||
两个面板都在**同一个侧栏**里用分段导航切换(v1 已有 4 段:文件/检索/大纲/双链;v2 扩为:**库 / 目录 / 检索 / 最近**,大纲与双链改为编辑区右侧的**抽屉**,因为它们跟「当前文档」绑定而不是跟「导航」绑定)。
|
||||
|
||||
> 为什么把大纲/双链挪到右侧抽屉:它们描述的是**当前文档**,而侧栏描述的是**去哪找文件**。混在一起会让侧栏在「导航」与「文档信息」两种语义之间摇摆(v1 已经能感到这个别扭)。
|
||||
|
||||
### 3.4 搜索与定位
|
||||
|
||||
- **文件名过滤**:侧栏顶部输入框,对当前树做不区分大小写的子串匹配,命中项的**祖先自动展开**(v1 已有)。
|
||||
- **快速打开 `Ctrl+P`**:跨「库 + 最近 + 当前目录」的文件名跳转,本地模糊排序(连续匹配 > 前缀 > 词首 > 位置),零网络、零后端。
|
||||
- **库内全文检索 `Ctrl+Shift+F`**:FTS5(trigram),标题权重高于正文,命中片段高亮(定界符方案,不注入 HTML)。目录树**不做**全文检索(不在索引里,也不该为此扫盘)。
|
||||
- **定位打开文件位置**:`revealItemInDir`(`opener` 插件,能力已授权)。三处入口:标签右键、侧栏行右键、状态栏路径点击。
|
||||
- **搜索文件名作用域切换**:输入框旁边一个「当前树 / 全库 / 当前目录」的小切换(idea 的 `Ctrl+Shift+N` 体验,但不引入独立对话框)。
|
||||
|
||||
### 3.5 历史记录
|
||||
|
||||
- **最近文件**:路径 + 显示名 + 时间 + 是否仍存在(失效项灰显、可一键清理)。
|
||||
- **最近文件夹**:同理,用于「右键文件夹 → 在这里打开」与侧栏目录面板的快速切换。
|
||||
- 存储:`editor/settings.json` 的 `recentFiles` / `recentFolders`(**与笔记库解耦** —— 库可以换/删,历史不该跟着丢)。各自上限 20 条,超出淘汰最旧。
|
||||
- 两份列表**分开存**:文件与文件夹的用途不同,混在一起会让「最近文件夹」被文件挤掉。
|
||||
|
||||
### 3.6 系统集成
|
||||
|
||||
| 集成 | 机制 | 权限 |
|
||||
|---|---|---|
|
||||
| 双击 `.md`/`.markdown`/`.mdx` 打开 | `bundle.fileAssociations`(安装器写 `OpenWithProgids`) | 安装器 |
|
||||
| 「用 Thing 编辑器打开」(文件) | `HKCU\Software\Classes\*\shell\ThingEditor` | 用户级,免管理员 |
|
||||
| 「用 Thing 编辑器打开」(文件夹) | `HKCU\Software\Classes\Directory\shell\ThingEditor` | 同上 |
|
||||
| 「用 Thing 编辑器打开」(目录背景) | `HKCU\Software\Classes\Directory\Background\shell\ThingEditor` | 同上 |
|
||||
| 菜单图标 | 菜单项 `Icon` 值指向 exe(用 exe 自带图标) | — |
|
||||
| 已运行时的二次启动 | `tauri-plugin-single-instance` 转交 argv 给已有实例 | 已落地 |
|
||||
| 免注册表运行 | 设置页提供「注册 / 卸载右键菜单」按钮,并显示当前 exe 路径 | — |
|
||||
|
||||
**关键约束**:注册表条目里写的是**绝对 exe 路径**。
|
||||
- 打包安装后:指向安装目录的 exe,稳定;
|
||||
- `tauri dev` 下:指向 `target\debug\thing.exe`,一旦清理 target 就变成死链。
|
||||
→ 因此**默认不注册**,且注册时校验 exe 存在;设置页在 dev 环境下给出明确提示。
|
||||
|
||||
### 3.7 全局快捷键
|
||||
|
||||
| 快捷键 | 动作 | 默认 |
|
||||
|---|---|---|
|
||||
| `Alt+E` | 打开编辑器窗口(无参数 = 上次的文档/最近文件) | **本版新增默认值** |
|
||||
| `Ctrl+Shift+N` | 新建笔记(直接落库根) | 空(v1 已有实现,改为可配) |
|
||||
|
||||
两者都走 `shortcut.rs`,触发时只发事件、窗口由前端创建(v1 已确立的姿态)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 存储、索引与目录树
|
||||
|
||||
```
|
||||
{appData}/editor/ # 模块自身(与库解耦)
|
||||
├── settings.json # 设置 + 最近文件/文件夹
|
||||
├── editor.db # 笔记库索引(可重建)
|
||||
└── library/ # 默认库根
|
||||
├── notes/ assets/ templates/
|
||||
└── .editor/ # 库内私有:同步基线 sync.json
|
||||
```
|
||||
|
||||
- **配置文件全量走 `settings.json`**(v1 已如此),新增 `recentFiles` / `recentFolders` / `defaultEncoding` / `largeFileMb` / `contextMenuEnabled`。
|
||||
- **索引服务架构不变**(单线程 worker 独占 `rusqlite` 连接 + 通道排队 + notify 监听),只改名。
|
||||
- **目录树不进索引**:它是「看盘」而不是「管库」。目录树节点按需 `read_dir`(带缓存与手动刷新),深度上限与库树一致(24)。
|
||||
- **配置改动只在用户显式操作下发生**:目录树上的新建/重命名/删除都是显式动作,且删除走系统回收站(复用 `quickpanel` 的回收站实现,`terminal/local_fs.rs` 已有先例)。**目录树自身不做任何隐式写入**(不生成索引、不生成元数据文件、不自动整理)。
|
||||
|
||||
---
|
||||
|
||||
## 5. 编码:探测、显示、切换
|
||||
|
||||
### 5.1 探测链(按优先级)
|
||||
|
||||
| 顺序 | 判据 | 结论 | 说明 |
|
||||
|---|---|---|---|
|
||||
| 1 | `EF BB BF` / `FF FE` / `FE FF` | `utf-8-bom` / `utf-16le` / `utf-16be` | BOM 是无歧义事实,直接采信 |
|
||||
| 2 | `std::str::from_utf8` 通过 | `utf-8` | 结构性校验,不是统计猜测 |
|
||||
| 3 | 以上失败 | `gb18030` | 中文存量主力(GBK 超集),比「猜 Big5/Shift_JIS」安全 |
|
||||
| 4 | 用户手动指定 | 用户值 | 前三级都可能错,必须留人工兜底 |
|
||||
|
||||
**刻意不做**:字符频率统计 + 多编码自信度比较(chardet 式)。理由是它在短文本上比规则更不可靠,而本项目的主要场景(代码/配置/中文笔记)恰好都是「UTF-8 或 GB18030」二选一。真错了有第 4 级兜底,代价可控。
|
||||
|
||||
### 5.2 读取与状态
|
||||
|
||||
读文件时一次性回传:`content`(已解码 UTF-8 字符串 + 换行归一为 `\n`)、`encoding`(探测结果)、`eol`(`lf`/`crlf`)、`size`、`large`、`readonly`。
|
||||
|
||||
- 状态栏显示:`UTF-8` / `GB18030` / `UTF-8 BOM` + `CRLF` / `LF` + 只读标记。
|
||||
- `readonly`:打开时用 `OpenOptions::new().write(true).open()` 探一次写权限(**不实际写入**),失败则置只读。这比「打开成功但保存时才报错」体验好得多。
|
||||
- 编码名一律用 `terminal/encoding.rs` 的 `normalize()` 规范形态(`utf-8` / `gbk` / `gb18030` / `big5` / `shift_jis` / `euc-kr` / `latin1`),双端取值同源,避免「状态栏写 GBK、设置里叫 cp936」这种不一致。
|
||||
|
||||
### 5.3 切换编码(关键设计)
|
||||
|
||||
**核心约束:切换编码不是「重新解释缓冲区文本」,而是「换一种方式去解释磁盘字节」。**
|
||||
|
||||
- **切换时**:以磁盘当前字节(而非缓冲区文本)按新编码重新解码 → 替换缓冲区内容。
|
||||
- 若此时有未保存改动:弹确认框给出三个选项——①**丢弃我的改动并按新编码重读**(默认,语义最清晰);②**先保存再重读**(用旧编码落盘,再按新编码读回——用户能立刻看出旧编码是否选错);③取消。
|
||||
- **保存时**:按当前 `encoding` 编码写回。若目标编码无法表示缓冲区里的某些字符(例如把含 emoji 的文本存成 GBK),**保存前报错并列出无法表示的字符位置**,而不是静默替换成 `?`(静默替换 = 不可逆数据损坏)。
|
||||
- **状态栏编码下拉**:`UTF-8` / `UTF-8 BOM` / `GB18030` / `GBK` / `Big5` / `Shift_JIS` / `EUC-KR` / `Latin-1` + 「重新载入为…」(不改变写回编码,仅重新解释)。
|
||||
- **换行切换**:`LF` / `CRLF` 独立于编码(v1 已按读取值写回),状态栏可切换。
|
||||
|
||||
### 5.4 与终端模块的编码复用
|
||||
|
||||
`terminal/encoding.rs` 提供 `decode` / `encode` / `normalize` / `SUPPORTED` / `is_supported`(v1 已直接复用,未提取为公共模块 —— 它们是纯函数,无业务耦合;若将来第三个模块要用再提取)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 界面结构
|
||||
|
||||
### 6.1 主模块页(设置与管理,不编辑)
|
||||
|
||||
Tab 收敛为 **概览 / 库 / 编辑器 / 集成**(把 v1 的「同步」并入「库」,因为同步是库的属性):
|
||||
|
||||
| Tab | 内容 |
|
||||
|---|---|
|
||||
| 概览 | 库状态横幅(路径/笔记数/索引)、最近文件与文件夹、快捷入口(打开编辑器 / 打开文件 / 打开文件夹 / 今日日记) |
|
||||
| 库 | 库根切换、重建索引、导入导出、WebDAV(连接/方向/冲突/快照) |
|
||||
| 编辑器 | 主题(含 JetBrains 三套)、字体字号行高连字、Live Preview 开关、默认编码、大文件阈值、自动保存、快捷键 |
|
||||
| 集成 | 文件关联状态、**右键菜单注册/卸载**、exe 路径、单实例说明 |
|
||||
|
||||
### 6.2 编辑器窗口
|
||||
|
||||
```
|
||||
┌─ 标题栏(自绘:文档名 + 未保存点 + 窗口按钮)────────────────────────┐
|
||||
├─ 工具栏:保存 另存 打开 快速打开 | 格式化(.md 时) | 编码 换行 主题 ─┤
|
||||
├────────────┬──────────────────────────────────────────┬─────────────┤
|
||||
│ 侧栏 │ 标签栏:doc1 × | doc2 × | … │ 抽屉(可选) │
|
||||
│ [库|目录| ├──────────────────────────────────────────┤ 大纲 / 双链 │
|
||||
│ 检索|最近] │ 编辑器(CM6) │ │
|
||||
│ │ │ │
|
||||
│ 树 / 结果 │ │ │
|
||||
├────────────┴──────────────────────────────────────────┴─────────────┤
|
||||
│ 状态栏:保存态 · 字数/行数 · 行列 · 语言 · 编码 · 换行 · 路径 │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**并排分屏**(标签右键 → 并排分屏)把编辑页平分为左右两列,各占一半宽:
|
||||
|
||||
```
|
||||
├─ 工具栏(整行,不参与分屏)──────────────────────────────────────────┤
|
||||
│ 标签栏:doc1 × | doc2 × │ 副文档名 × │
|
||||
├──────────────────────────────┼──────────────────────────────────────┤
|
||||
│ 编辑器(CM6)· 主文档 │ 编辑器(CM6)· 副文档 │
|
||||
└──────────────────────────────┴──────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 「标签栏 + 编辑栏」整体是**左半列**,副文档是**右半列**(自带 8px 标题行与关闭按钮),
|
||||
两列等宽、各自独立滚动 —— 副文档是并排的一列,**不是嵌在编辑栏内部的一块**。
|
||||
从前的做法把副面板塞在编辑栏(标签栏下方)内部,看起来像"同一栏里又开了个窗口"。
|
||||
- 不分屏时标签栏回到顶部、横跨整列宽度(即左半列占满),行为与基础形态一致。
|
||||
- 侧栏可整体折叠(腾出宽度给长行代码)。
|
||||
- 抽屉默认关闭,`Ctrl+Shift+O` 切大纲、`Ctrl+Shift+B` 切双链。**这两个键位在实现时由 `keymap.ts` 统一声明并做冲突检测**:若与 CM6 默认键位冲突,以 CM6 默认键位优先,本功能改用 `Alt+O` / `Alt+B`(冲突检测方式沿用 v1 的 `shortcut.rs` 思路,编辑器内用 CM6 的 keymap 优先级)。
|
||||
|
||||
### 6.3 目录面板的命令面(P3-5 实现依据)
|
||||
|
||||
| 命令 | 入参 | 说明 |
|
||||
|---|---|---|
|
||||
| `editor_read_dir` | `path: String`(空 = 用户主目录) | 返回 `cwd` / `parent` / `entries`(名字/路径/是否目录/大小/mtime) |
|
||||
| `editor_create_file` | `dir: String`, `name: String` | 重名报错(**不自动加序号**:目录树是用户的真实文件系统,静默改名会让人找不到刚建的文件) |
|
||||
| `editor_create_folder` | `dir: String`, `name: String` | 同上 |
|
||||
| `editor_rename_path` | `path: String`, `newName: String` | 同目录改名;目标存在则报错 |
|
||||
| `editor_delete_path` | `paths: Vec<String>` | **走系统回收站**(复用 `quickpanel::commands::delete_file_impl`),返回 `(成功数, 失败明细)`;拒绝盘符根 |
|
||||
| `editor_reveal_path` | `path: String` | 在资源管理器中选中(`opener` 的 `reveal_item_in_dir`) |
|
||||
|
||||
**安全边界**:目录树操作的是**用户真实文件系统**(不是沙箱),因此
|
||||
- 不设「必须在本目录根下」的限制(那是本地文件管理器,限制根目录只会挡住用户自己);
|
||||
- 但**拒绝删除盘符根**(`Path::new(p).parent().is_none()`)—— 这是唯一不可恢复的事故;
|
||||
- 删除一律走回收站,不用 `remove_file`;
|
||||
- 路径来自用户自己的浏览/输入,与 `terminal/local_fs.rs` 同一姿态(该模块已有 `list_dir` / `delete` 的成熟实现,**优先复用而不是重写**)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 缺口清单(v1 已有 → v2 要做)
|
||||
|
||||
| # | 缺口 | 严重度 | 落点 |
|
||||
|---|---|---|---|
|
||||
| G1 | 模块仍叫 notes(id / 命令 / 事件 / 目录 / 存储键) | 高(结构性) | §9.6 |
|
||||
| G2 | 没有「本地目录」导航根(只有笔记库) | 高 | §3.3 |
|
||||
| G3 | 编码只能探测不能切换;无状态栏显示 | 高 | §5 |
|
||||
| G4 | 没有最近文件夹记录(只有最近笔记,且存在 localStorage) | 中 | §3.5 |
|
||||
| G5 | 没有资源管理器右键菜单 | 中 | §3.6 |
|
||||
| G6 | 默认全局快捷键为空(`Alt+E` 未设) | 低 | §3.7 |
|
||||
| G7 | 单窗口单文档(无标签页) | 中 | §3.1 |
|
||||
| G8 | 大纲/双链挤在导航侧栏里,语义混杂 | 中 | §3.3 |
|
||||
| G9 | 大文件降级没有「只读打开」与显式提示 | 低 | §3.1 / §5.2 |
|
||||
| G10 | 主模块页 Tab 结构未随定位调整(同步应并入库) | 低 | §6.1 |
|
||||
| G11 | 语言包缺 `.sh`/`.ps1`/`.toml`/`.ini`/`.scss`(legacy-modes 未接) | 低 | §8-P5.1 |
|
||||
| G12 | Markdown 内嵌代码块高亮未做(`codeLanguages` 异步问题) | 低 | §8-P5.3 |
|
||||
| G13 | `FileDoc` 无 `readonly` 字段(只读文件要等保存时才报错) | 中 | §5.2 / P4-1 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 分期路线图
|
||||
|
||||
> v1 的 P0/P1/P2 已全部落地(见 §9)。以下是从 **P3 起**的新路线图。
|
||||
|
||||
### P3 — 编辑器化改造(结构)
|
||||
|
||||
1. **改名**:`notes` → `editor`(id / 窗口 label / 事件 / 命令前缀 / 目录 / 存储键 / Rust 模块名),脚本核对无残留(§9.6)。
|
||||
2. **库内目录改名**:`<库根>/.notes/` → `<库根>/.editor/`(含 `sync.json`),首次打开时惰性迁移;索引可重建,丢了无损。
|
||||
3. **侧栏重构**:`库 / 目录 / 检索 / 最近` 四段;大纲与双链移到编辑区右侧抽屉。
|
||||
4. **本地目录树**:打开文件夹(对话框 / 右键菜单 / 最近文件夹)、树浏览、文件名过滤、打开文件、在资源管理器中显示、复制路径、手动刷新。
|
||||
5. **最近记录**:最近文件 + 最近文件夹(落 `settings.json`,分组显示、可清空、失效项灰显)。
|
||||
6. **主模块页 Tab 调整**:概览 / 库 / 编辑器 / 集成。
|
||||
|
||||
### P4 — 编码与系统集成(这一版的核心价值)
|
||||
|
||||
1. **编码探测链**(§5.1)+ 状态栏显示编码/换行/只读。
|
||||
2. **切换编码**(§5.3):重解码对话框三选项、保存时不可表示字符报错、换行独立切换。
|
||||
3. **系统集成**:`Alt+E` 默认值;HKCU 右键菜单注册/卸载(文件 + 文件夹 + 目录背景),设置页按钮 + exe 路径显示 + dev 环境提示。
|
||||
4. **只读打开**与大文件降级提示。
|
||||
5. **标签页**(多文档):`Ctrl+W` / `Ctrl+Tab`、每标签独立编码与视图模式、关闭确认。
|
||||
|
||||
### P5 — 完善(本轮不做,按体感排后续优先级)
|
||||
|
||||
1. 语言包补齐:`.sh` / `.ps1` / `.toml` / `.ini` / `.dockerfile` 走 `legacy-modes`;`.scss` / `.less` 引入 `@codemirror/lang-sass`。
|
||||
2. 目录树上的文件操作完善:拖拽移动、在新窗口打开、批量重命名。
|
||||
3. Markdown 内嵌代码块高亮(`codeLanguages`,需解决 language-data 异步 vs `markdown()` 同步)。
|
||||
4. 双链图谱(数据已就绪:`editor_link_graph` 命令可用,仅缺可视化)。
|
||||
5. 会话恢复:关窗后重开恢复文档与光标位置。
|
||||
|
||||
---
|
||||
|
||||
## 9. v1 实施记录(压缩归档)
|
||||
|
||||
> 完整细节已在 v1 文档中,此处只留**结论**与**坑**——它们对 v2 仍然成立。
|
||||
|
||||
> **本节的文件名一律是 v2 目标名**。v1 代码里对应的真实路径是:
|
||||
> `src-tauri/src/notes/*.rs`、`src/modules/notes/**`、`src/stores/notesStore.ts`、
|
||||
> `src/types/notes.ts`,命令为 `notes_*`。
|
||||
|
||||
### 9.1 交付总览(v1,均已落地)
|
||||
|
||||
| 层 | 关键文件 |
|
||||
|---|---|
|
||||
| Rust 文件 IO | `editor/files.rs`(编码/换行探测、授权白名单、附件落盘) |
|
||||
| Rust 库 | `editor/library.rs`(`safe_join` 路径沙箱、扫描、增删改移) |
|
||||
| Rust 模板 | `editor/templates.rs`(4 个内置模板 + 库内覆盖 + `{{title}}`/`{{date}}`) |
|
||||
| Rust 导入导出 | `editor/import.rs`(文件/目录/zip,重名加序号、绝不覆盖)、`editor/export.rs`(整库/单目录 zip) |
|
||||
| Rust 索引 | `editor/index.rs`(SQLite + FTS5 trigram:front-matter、标签、双链、检索、片段)、`editor/index_service.rs`(单线程 worker + notify) |
|
||||
| Rust WebDAV | `editor/webdav/{client,sync}.rs`(PROPFIND/MKCOL/PUT/GET/DELETE/MOVE + 三方比对 + 冲突策略 + 改名识别)、`editor/backup.rs`(zip 快照 + 轮转 + 恢复) |
|
||||
| Rust 参数 | `editor/args.rs`(文件关联/命令行参数解析 + 待打开文件缓存) |
|
||||
| 前端内核 | `editor/core.ts`(Compartment 热重配置)、`markdownLivePreview.ts`、`languages.ts`、`themes.ts`、`keymap.ts`、`outline.ts`、`wikilink.ts`、`images.ts`、`markdownExport.ts` |
|
||||
| 前端组件 | `LibrarySidebar.vue`、`SearchPanel.vue`、`QuickOpen.vue`、`MarkdownOutline.vue`、`BacklinksPanel.vue`、`WebdavPanel.vue`、`ImportExportPanel.vue`、`NewNoteDialog.vue`、`EditorHost.vue`、`EditorToolbar.vue` |
|
||||
| 前端状态 | `stores/editorStore.ts`、`modules/editor/editorClient.ts`、`types/editor.ts` |
|
||||
| 命令 | 40 条(`notes_*` → 将统一改名为 `editor_*`) |
|
||||
|
||||
### 9.2 关键决策(v2 继续沿用)
|
||||
|
||||
- **真相是文件,索引可丢**:删掉 `editor.db` 的唯一后果是下次搜索前做一次全量扫描。
|
||||
- **索引由单线程 worker 独占**:`rusqlite::Connection` 非共享对象,而搜索命令(Tauri 线程池)、保存后的增量更新、notify 回调会并发进来;通道排队 + 专职线程换来「慢操作只排队不堵搜索」。
|
||||
- **FTS5 用 trigram**:默认 `unicode61` 把连续汉字切成一个词元,「会议」搜不到「周会议纪要」。代价是查询词 <3 字符静默返回空 → 回退 `LIKE` + Rust 侧自建片段。
|
||||
- **WebDAV 同步基线存两侧指纹**,不比 mtime(跨机时钟偏差会让「本地比远端新」两边都成立)。删除传播保守优先;同步有失败不推进基线。
|
||||
- **冲突「两侧都留」用远端 `MOVE`** 保留历史,而不是覆盖。
|
||||
- **同步/网络类命令一律 `async` + `spawn_blocking`**:`reqwest::blocking` 在 tokio 运行时线程上会 panic。
|
||||
- **HTML 导出零外链、失败关闭**:样式内联;DOMPurify 不可用时返回**空串**而不是原文。
|
||||
- **渲染链路按需 `import()`**:`markdownExport`(markdown-it + DOMPurify + highlight.js)约 1.1MB,静态引入会让模块 chunk 从 40kB 涨到 1.2MB。
|
||||
- **库外文件的路径授权白名单**:库内走 `safe_join`(根目录沙箱),库外走「用户显式打开过的绝对路径集合」。读宽松(读时登记),写严格。
|
||||
- **`from`(大纲)一律是行首偏移**:指向正文起点会让空标题没有合法取值。
|
||||
- **Live Preview 是装饰不是渲染**:只对 `view.visibleRanges` 计算(性能红线);光标行「显形」为可编辑源码。
|
||||
|
||||
### 9.3 验证状态(v1 收尾时)
|
||||
|
||||
```
|
||||
cargo check 0 warning
|
||||
cargo build 整包通过
|
||||
cargo test --lib 58 passed / 0 failed
|
||||
node --test 74 passed / 0 failed / 1 skipped(Node 无 DOM 的 XSS 断言)
|
||||
vue-tsc / eslint 通过
|
||||
vite build NotesModule 41kB(gzip 12.5) / NotesWindow 98kB(gzip 32.6)
|
||||
/ markdownExport 1.12MB(gzip 371) 按需加载
|
||||
接线核对 命令 定义=导出=注册 40/40/40,无差集
|
||||
事件 Rust 8 = TS 8,无差集
|
||||
类型 18 个结构字段名双端一一对应
|
||||
```
|
||||
|
||||
### 9.4 坑记录(跨版本有效)
|
||||
|
||||
1. **`<SelectItem>` 不能用空串 `value`**:reka-ui 把空串保留给 placeholder,会直接抛异常。用显式哨兵值(`'__all__'` / `'__current__'`)在调用点翻译。报错栈指向 `SelectItem.vue` 而不是调用方 —— 先搜 `value: ''`。
|
||||
2. **`cargo add <tauri 插件>` 会连带升级整个 tauri 依赖树**(wry / tray-icon / window-vibrancy),而 dev 启动会校验 JS 包与 crate 的 minor 是否一致。**改一边必须同时看另一边**。
|
||||
3. **不要把 `package.json` 交给 PowerShell 的 `Set-Content -Encoding UTF8`**(PS 5.1 写入 BOM),带 BOM 会让 Vite 读 PostCSS 配置直接失败。用 `node -e` 或 `UTF8Encoding($false)`。
|
||||
4. **CRLF 下反推行首偏移一律偏 1**:必须预先算 `lineStarts` 表,不要在循环里「减回去」。
|
||||
5. **front-matter 用状态机而不是布尔量**:首行 `---` 是*开头*,布尔量会在第 0 行就关掉状态,导致第 2 行的闭合 `---` 把上一行元数据提升成 Setext 标题。
|
||||
6. **`let plan = plan(...)` 会遮蔽函数名**,第二个测试起报 `E0618` 且位置离成因很远。函数名避开返回值名。
|
||||
7. **`enum` 不能出现在 `node --test` 直接跑的文件里**(Node 的 TS 支持是 strip-only)。用 `const X = {...} as const` + 类型别名。
|
||||
8. **quick-xml 0.42 的 `QName::as_ref()` 返回 `&str`**(旧版 `&[u8]`),`BytesText` 无 `decode()`;升级时只 `cargo update -p quick-xml`,避免动到 wry 链。
|
||||
9. **冷启动的文件关联事件会丢**:`setup` 里 `emit` 时 WebView 还没加载。改为存 `OnceLock<Mutex<Option<PathBuf>>>`,前端注册完监听后主动取走。
|
||||
10. **FTS5 的 `snippet()` 对「走 LIKE 回退的短词」什么都不产出**;列索引用 `-1`(让 FTS 挑最佳列)。
|
||||
|
||||
### 9.5 与 v1 规划不一致之处(保留结论)
|
||||
|
||||
| 规划 | 实际 | 原因 |
|
||||
|---|---|---|
|
||||
| 语言支持走 `language-data` 一处入口 | 手写扩展名映射表 + 逐语言 `import()` | `matchFilename` 覆盖不到 `.vue`/`.toml`/`.ps1`;手写表行为可预期 |
|
||||
| Markdown 内嵌代码块高亮 | 未做 | language-data 清单异步 vs `markdown()` 同步(见 G12) |
|
||||
| `.scss` / `.less` | 未做 | `@codemirror/lang-css` 只导出 `css()` |
|
||||
| 表格渲染 / 图片内联 | **已做**(图片走 data URL,非 asset 协议) | asset 协议要求把用户自选库根加进白名单,等于给 WebView 开任意读文件的口子 |
|
||||
| 提取 `terminal/encoding.rs` 为公共模块 | 未提取,直接复用 | 纯函数无耦合;第三个模块要用时再提取 |
|
||||
| 系统关联 | 已做文件关联;**右键菜单本轮补** | §3.6 |
|
||||
| 双链图谱 / 托盘入口 / Mermaid | 未做 | §8-P5 / §0.8 |
|
||||
|
||||
### 9.6 改名清单(P3 的执行依据)
|
||||
|
||||
| 面 | v1 | v2 | 规模 |
|
||||
|---|---|---|---|
|
||||
| 模块 id / 目录 | `notes` / `src/modules/notes/` | `editor` / `src/modules/editor/` | 10 处 |
|
||||
| 窗口 hash / label 前缀 | `#notes-window` / `notes-window-*` | `#editor-window` / `editor-window-*` | 16 处 + capability 文件名 |
|
||||
| 事件名 | `notes-settings` 等 8 个 | `editor-*` | 4 处(双端一致) |
|
||||
| Rust 命令前缀 | `notes_*`(40 条) | `editor_*` | 246 行 |
|
||||
| Rust 模块目录 | `src-tauri/src/notes/` | `src-tauri/src/editor/` | 18 处 |
|
||||
| store / client / types | `notesStore` / `notesClient` / `types/notes.ts` | `editorStore` / `editorClient` / `types/editor.ts` | 77 处 |
|
||||
| localStorage 键 | `thing_notes_recent` | 改为落 `settings.json`(不再用 localStorage) | 1 处 |
|
||||
| capability 文件 | `notes-window.json` | `editor-window.json` | 1 文件 |
|
||||
| 默认库目录 | `{appData}/notes/library` | `{appData}/editor/library` | 需迁移逻辑(见下) |
|
||||
|
||||
**迁移策略**:`{appData}/notes/` 若存在且 `{appData}/editor/` 不存在 → 启动时整目录重命名并记日志;否则各自独立。库内 `.notes/`(索引 + 同步基线)同理改 `.editor/`,并在首次打开时惰性迁移(索引可重建,丢了也无损)。
|
||||
|
||||
---
|
||||
|
||||
## 10. 决策表(已拍板,开工时按此执行)
|
||||
|
||||
> Q1–Q4 由用户于 2026-09-30 明确拍板;Q5–Q10 由本规划给出建议并**一并视为生效**(若要改,改这一行即可,不影响其它章节)。
|
||||
|
||||
| # | 决策点 | 结论 | 影响面 |
|
||||
|---|---|---|---|
|
||||
| Q1 | 模块显示名与英文 id | **`id = editor`,显示名「编辑器」**(一词式,与「终端」「下载」一致) | 模块注册、窗口标题、搜索项、改名清单 §9.6 |
|
||||
| Q2 | 是否引入「工作区」 | **不引入**。只有「笔记库根」与「当前目录根」两个单值 + 各自历史 | §3.3 侧栏只有一个目录面板;ST-4 无需 workspace 状态 |
|
||||
| Q3 | 目录树是否纳入索引 | **不纳入**。目录树只做文件名过滤;全文检索仅对笔记库可用(FTS5) | §3.4 / §4;`editor_index_*` 只处理库内 `.md` |
|
||||
| Q4 | 标签页放哪一期 | **P4**(与编码、系统集成同期) | §8-P4.5;`EditorHost` 需支持多 view 实例 |
|
||||
| Q5 | 右键菜单注册时机 | **设置页手动按钮**,默认不写注册表 | §3.6;dev 环境 exe 路径不稳定 |
|
||||
| Q6 | 目录树删除语义 | **走系统回收站**(复用 `quickpanel` 实现) | §4;与 `terminal/local_fs.rs` 同口径 |
|
||||
| Q7 | 默认编码兜底 | **`GB18030`**(探测链第 3 级) | §5.1;第 4 级人工指定兜底 |
|
||||
| Q8 | 「笔记库」这一叫法 | **保留**(库内文件仍是笔记,用户已理解该词) | §3.3 面板名「笔记库」 |
|
||||
| Q9 | 主模块页是否给「打开文件夹」入口 | **给** | §6.1 概览页行动区 |
|
||||
| Q10 | 大文件阈值 | **5MB 默认,可配**,且状态栏显式提示降级 | §3.1;`largeFileMb` 进设置 |
|
||||
|
||||
---
|
||||
|
||||
## 11. 开工清单(执行入口)
|
||||
|
||||
> 本节是「照做即可」的清单。**P3 与 P4 之间没有依赖倒置**:P3 是结构改造(改名 + 侧栏 + 目录树 + 最近记录),P4 是能力新增(编码 + 系统集成 + 标签页)。建议**严格 P3 → P4**:改名会碰到 P4 要改的每一个文件,同时做会让 diff 无法 review。
|
||||
|
||||
### 11.1 定稿参数(实现时直接用这些值,不要再另起炉灶)
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 模块 id / 显示名 / 图标 key | `editor` / `编辑器` / `editor`(`icons.ts` 映射到 `FileCode2` 或 `NotebookPen`,见下) |
|
||||
| 模块排序 `order` | **45**(沿用,排在终端 40 之后) |
|
||||
| 窗口 hash / label 前缀 | `#editor-window` / `editor-window-` |
|
||||
| 窗口查询参数 | `?file=<绝对路径>` / `?note=<库内相对路径>` / `?folder=<绝对路径>` |
|
||||
| Tauri 命令前缀 | `editor_`(40 条现有命令全部平移,P4 新增约 12 条) |
|
||||
| 事件名(8 个) | `editor-settings` / `editor-library-changed` / `editor-file-changed` / `editor-sync-progress` / `editor-new-note` / `editor-open-editor` / `editor-open-file` / `editor-open-folder`(最后一个是 P4 新增) |
|
||||
| Rust 模块目录 | `src-tauri/src/editor/` |
|
||||
| 前端目录 | `src/modules/editor/` |
|
||||
| store / client / types | `useEditorStore` / `src/modules/editor/editorClient.ts` / `src/types/editor.ts` |
|
||||
| 模块自身目录 | `{appData}/editor/`(settings.json / editor.db / library/) |
|
||||
| 库内私有目录 | `<库根>/.editor/`(`sync.json`) |
|
||||
| keyring 键 | `editor.webdav.password` |
|
||||
| 默认全局快捷键 | 打开编辑器 = **`Alt+E`**;新建笔记 = 空(可配) |
|
||||
| 默认库根 | `{appData}/editor/library` |
|
||||
| 默认编码 / 大文件阈值 | `UTF-8` 优先探测,兜底 `GB18030`;5MB |
|
||||
| 右键菜单键名 | `HKCU\Software\Classes\{*,Directory,Directory\Background}\shell\ThingEditor`,显示名 **「用 Thing 编辑器打开」** |
|
||||
| 图标 key / 组件 | key = `editor`;组件 **`FileCode2`**(已确认 `@lucide/vue` 有该图标;备选 `SquarePen` / `FileCode`)。侧栏新面板建议:目录 = `FolderTree`、最近 = `History`、抽屉 = `PanelRight` |
|
||||
|
||||
### 11.2 P3 执行顺序(每步都可独立验证 + 可提交)
|
||||
|
||||
| 步 | 内容 | 验证 |
|
||||
|---|---|---|
|
||||
| **P3-1** | 改名:Rust 侧(模块目录 `notes/` → `editor/`、40 条命令 `notes_*` → `editor_*`、`NoteSettings` → `EditorSettings` 等类型名、事件常量) | `cargo check` 0 warning;`cargo test --lib editor::` 58 passed |
|
||||
| **P3-2** | 改名:前端侧(`src/modules/notes/` → `editor/`、`notesStore` → `editorStore`、`notesClient` → `editorClient`、`types/notes.ts` → `editor.ts`、`STORAGE_KEYS`、`main.ts` 路由、capability 文件名与 `windows` glob、模块注册与图标) | `vue-tsc` / `eslint` / `vite build` 通过;模块列表里显示「编辑器」 |
|
||||
| **P3-3** | 迁移:`{appData}/notes/` → `{appData}/editor/`(启动时整目录 rename,幂等);`<库根>/.notes/` → `.editor/`(惰性,`ensure_schema` 时探测并 rename) | 手工验证:改名前留下的库仍能被打开、索引被重建 |
|
||||
| **P3-4** | 侧栏重构为 `库 / 目录 / 检索 / 最近` 四段;大纲与双链移到右侧抽屉 | 四段可切换;抽屉快捷键生效 |
|
||||
| **P3-5** | 本地目录树:Rust `editor_read_dir` / `editor_create_file` / `editor_create_folder` / `editor_rename_path` / `editor_delete_path`(回收站)+ 前端 `DirectoryPanel.vue` | 能浏览、新建、重命名、删除(进回收站)、在资源管理器中显示 |
|
||||
| **P3-6** | 最近记录:`recentFiles` / `recentFolders` 落 `settings.json`,`RecentPanel.vue`,失效项灰显 + 清空 | 打开文件/文件夹后出现在「最近」,重启后仍在 |
|
||||
| **P3-7** | 主模块页 Tab → 概览 / 库 / 编辑器 / 集成(同步并入库页) | 四页可切换,入口按钮就位 |
|
||||
|
||||
**P3 完成判据**:模块叫「编辑器」、侧栏有库与目录两个根、最近记录可用、`cargo test` 与 `node --test` 全绿、`vite build` 通过且模块 chunk 无异常膨胀。
|
||||
|
||||
### 11.3 P4 执行顺序
|
||||
|
||||
| 步 | 内容 | 验证 |
|
||||
|---|---|---|
|
||||
| **P4-1** | `FileDoc` 增 `readonly`;`files.rs` 增写权限探测(`OpenOptions::new().write(true).open()` 不写入) | 只读文件打开后状态栏显示「只读」,保存被拦并给出原因 |
|
||||
| **P4-2** | 编码探测链按 §5.1 收紧(BOM → 严格 UTF-8 → GB18030);新增 `editor_redecode_file(path, encoding)` | Rust 单测覆盖 BOM/UTF-8/GBK/UTF-16 |
|
||||
| **P4-3** | 状态栏编码与本行下拉 + 切换编码三选项对话框(§5.3)+ 保存时不可表示字符报错 | 手工:GBK 文件切 UTF-8 看到乱码→切回正常;含 emoji 存 GBK 被拦 |
|
||||
| **P4-4** | 系统集成:`Alt+E` 默认值;右键菜单注册/卸载(`winreg`,HKCU)+ 设置页「集成」Tab | 注册后资源管理器右键出现菜单项,点击能打开文件/文件夹 |
|
||||
| **P4-5** | 标签页(多文档):`Ctrl+W` / `Ctrl+Tab`、每标签独立 `encoding`/`eol`/视图模式、关闭确认 | 同时开 3 个不同编码的文件,互不串味 |
|
||||
|
||||
**P4 完成判据**:编码可探测可切换、右键菜单可用、`Alt+E` 生效、多标签可用;§9.3 的全部检查项重新跑一遍通过。
|
||||
|
||||
### 11.4 每个阶段都要跑的验证命令
|
||||
|
||||
```powershell
|
||||
# Rust
|
||||
& "C:\Users\<user>\.cargo\bin\cargo.exe" check --message-format short # 必须 0 warning
|
||||
& "C:\Users\<user>\.cargo\bin\cargo.exe" test --lib editor:: # 单测(P3-1 后模块名变了)
|
||||
# 前端
|
||||
& "C:\Program Files\nodejs\node.exe" node_modules/vue-tsc/bin/vue-tsc.js --noEmit
|
||||
& "C:\Program Files\nodejs\node.exe" node_modules/eslint/bin/eslint.js src
|
||||
& "C:\Program Files\nodejs\node.exe" node_modules/vite/bin/vite.js build
|
||||
& "C:\Program Files\nodejs\node.exe" --test src/modules/quickpanel/engine.test.ts src/lib/calc.test.ts src/lib/theme.test.ts src/modules/editor/editor/outline.test.ts
|
||||
```
|
||||
|
||||
> 注意:本机沙箱禁止直接 spawn 工作区外的可执行文件,必须用**绝对路径**调用
|
||||
> `cargo.exe` / `node.exe`(`node` 在 `C:\Program Files\nodejs\`)。
|
||||
> 新增依赖用 `bun add`,且 `$env:TEMP` 必须指向可写目录(详见 §9.4 的坑记录)。
|
||||
|
||||
### 11.5 改名核对脚本(P3-1/P3-2 完成后跑)
|
||||
|
||||
```powershell
|
||||
# 应无输出(除文档与 §9 的历史记录外)
|
||||
Select-String -Path (Get-ChildItem src,src-tauri/src,src-tauri/capabilities -Recurse -Include *.ts,*.vue,*.rs,*.json |
|
||||
ForEach-Object { $_.FullName }) -Pattern "notes_" | ForEach-Object { "$($_.Path):$($_.LineNumber)" }
|
||||
Select-String -Path (Get-ChildItem src -Recurse -Include *.ts,*.vue |
|
||||
ForEach-Object { $_.FullName }) -Pattern "notesStore|notesClient" | ForEach-Object { "$($_.Path):$($_.LineNumber)" }
|
||||
# 命令三方一致性(应 定义 = 导出 = 注册)
|
||||
# 见 §9.3 的接线核对做法:比对 commands.rs / mod.rs / lib.rs 两处
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:命名规范(v2)
|
||||
|
||||
- 模块 id:`editor`;显示名:`编辑器`;图标 key:`editor`。
|
||||
- 窗口 hash:`#editor-window`(可带 `?file=<abs path>` 或 `?note=<rel path>`);label 前缀:`editor-window`。
|
||||
- 事件名(**8 个**,与 v1 一一对应,最后一个为 P4 新增):`editor-settings` / `editor-library-changed` / `editor-file-changed` / `editor-sync-progress` / `editor-new-note` / `editor-open-editor` / `editor-open-file` / `editor-open-folder`。
|
||||
- 窗口 label 前缀:`editor-window-`(不是事件,列在此处避免与上表混淆)。
|
||||
- 前端组件:`DirectoryPanel.vue` / `RecentPanel.vue` / `EditorTabs.vue`(P4)/ `DrawerPanel.vue`(大纲与双链的容器)为 P3/P4 新增。
|
||||
- Rust 命令前缀:`editor_`;Rust 模块目录:`src-tauri/src/editor/`。
|
||||
- 前端 store:`useEditorStore`;类型文件:`src/types/editor.ts`;IPC 客户端:`src/modules/editor/editorClient.ts`。
|
||||
- 存储:`{appData}/editor/settings.json`;库内私有目录:`<库根>/.editor/`。
|
||||
- keyring 键:`editor.webdav.password`。
|
||||
|
||||
## 附录 B:能力边界(明确不做)
|
||||
|
||||
| 不做 | 理由 |
|
||||
|---|---|
|
||||
| 调试器 / 内嵌终端 / LSP 补全 / Git 集成 | 那是 IDE,与「notepad++ 式编辑器」的定位冲突;本项目终端模块已覆盖终端场景 |
|
||||
| 块编辑器(拖拽块、`/` 菜单) | 与「`.md` 文本是唯一真相」的模型不匹配(v1 已确认) |
|
||||
| 远端直连读写(把 WebDAV 当工作区) | 离线不可用、限流敏感、冲突面大(v1 已确认) |
|
||||
| 目录树全文索引 | 与「打开快」冲突(Q3) |
|
||||
| 字符频率统计式编码探测 | 短文本上比规则更不可靠(§5.1) |
|
||||
| 二进制文件编辑 | 编码/换行模型只对文本成立;识别为二进制时明确拒绝并提示用外部工具 |
|
||||
File renamed without changes.
File renamed without changes.
File diff suppressed because it is too large.
Load diff
File renamed without changes.
@@ -137,10 +137,10 @@ shadcn 既有(值调整) → --background / --foreground / --primary / --c
|
||||
--divider: #26262B;
|
||||
--input: #2E2E34;
|
||||
|
||||
--foreground: #F5F5F7;
|
||||
--fg-secondary: #A8A8B0;
|
||||
--muted-foreground: #7A7A82;
|
||||
--fg-disabled: #55555C;
|
||||
--foreground: #FFFFFF; /* 深色下主文字用纯白 */
|
||||
--fg-secondary: #ECECF2;
|
||||
--muted-foreground: #D2D2DA;
|
||||
--fg-disabled: #9A9AA4;
|
||||
|
||||
--primary: #2997FF;
|
||||
--primary-hover: #4AA8FF;
|
||||
Generated
+988
-66
File diff suppressed because it is too large.
Load diff
+44
-8
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "thing",
|
||||
"private": true,
|
||||
"version": "26.9.4",
|
||||
"version": "26.10.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -10,17 +10,47 @@
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"lint": "eslint src",
|
||||
"preview": "vite preview",
|
||||
"test": "node --test src/modules/quickpanel/engine.test.ts src/lib/calc.test.ts src/lib/theme.test.ts",
|
||||
"test": "node --test src/modules/quickpanel/engine.test.ts src/lib/calc.test.ts src/lib/theme.test.ts src/modules/notes/editor/outline.test.ts src/modules/notes/editor/markdownExport.test.ts",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.20.3",
|
||||
"@codemirror/commands": "^6.11.1",
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
"@codemirror/lang-go": "^6.0.1",
|
||||
"@codemirror/lang-html": "^6.4.12",
|
||||
"@codemirror/lang-java": "^6.0.2",
|
||||
"@codemirror/lang-javascript": "^6.2.5",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/lang-less": "^6.0.2",
|
||||
"@codemirror/lang-markdown": "^6.5.2",
|
||||
"@codemirror/lang-php": "^6.0.2",
|
||||
"@codemirror/lang-python": "^6.2.1",
|
||||
"@codemirror/lang-rust": "^6.0.2",
|
||||
"@codemirror/lang-sass": "^6.0.2",
|
||||
"@codemirror/lang-sql": "^6.10.0",
|
||||
"@codemirror/lang-vue": "^0.1.3",
|
||||
"@codemirror/lang-xml": "^6.1.0",
|
||||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/language": "^6.12.4",
|
||||
"@codemirror/language-data": "^6.5.2",
|
||||
"@codemirror/legacy-modes": "^6.5.4",
|
||||
"@codemirror/merge": "^6.12.2",
|
||||
"@codemirror/search": "^6.7.2",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@codemirror/view": "^6.43.13",
|
||||
"@lucide/vue": "^1.48.0",
|
||||
"@replit/codemirror-lang-csharp": "^6.2.0",
|
||||
"@replit/codemirror-lang-svelte": "^6.0.0",
|
||||
"@tailwindcss/vite": "^4.3.2",
|
||||
"@tauri-apps/api": "^2",
|
||||
"@tauri-apps/plugin-autostart": "~2",
|
||||
"@tauri-apps/plugin-dialog": "^2",
|
||||
"@tauri-apps/plugin-global-shortcut": "^2",
|
||||
"@tauri-apps/plugin-opener": "^2",
|
||||
"@tauri-apps/api": "^2.12.0",
|
||||
"@tauri-apps/plugin-autostart": "~2.6.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.0",
|
||||
"@tauri-apps/plugin-global-shortcut": "^2.4.0",
|
||||
"@tauri-apps/plugin-opener": "^2.7.0",
|
||||
"@uiw/codemirror-themes": "^4.25.12",
|
||||
"@vueuse/core": "^14.4.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-search": "^0.16.0",
|
||||
@@ -31,6 +61,11 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"codemirror-lang-elixir": "^4.0.1",
|
||||
"codemirror-lang-makefile": "^0.1.1",
|
||||
"dompurify": "^3.4.16",
|
||||
"highlight.js": "^11.12.0",
|
||||
"markdown-it": "^15.0.2",
|
||||
"pinia": "^3.0.4",
|
||||
"pinyin-pro": "^3.28.2",
|
||||
"qrcode": "^1.5.4",
|
||||
@@ -42,7 +77,8 @@
|
||||
"vue-sonner": "^2.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2",
|
||||
"@tauri-apps/cli": "^2.12.0",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^26.1.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@
|
||||
#
|
||||
# 发布产物(上传到 https://gitea.atie.fun/LFeng/Thing 的 v{Version} release):
|
||||
# thing_{v}_x64.exe 便携免安装版(无内核)
|
||||
# thing_{v}_x64.msi 安装版 MSI(去掉 tauri 默认的 _en-US 后缀)
|
||||
# thing_{v}_x64.msi 安装版 MSI(去掉 tauri 默认的 _zh-CN 后缀)
|
||||
# thing_{v}_x64-setup.exe 安装版 NSIS
|
||||
# thing-hk_{v}.zip ThingHK 硬件监控内核(mihomo 继续走代理模块内置的 GitHub 下载)
|
||||
#
|
||||
@@ -85,7 +85,7 @@ $StageDir = Join-Path $Root "release_stage\$Version"
|
||||
New-Item -ItemType Directory -Force -Path $StageDir | Out-Null
|
||||
|
||||
$exeSrc = Join-Path $TargetDir "$Product.exe"
|
||||
$msiSrc = Join-Path $BundleDir "msi\${Product}_${Version}_x64_en-US.msi"
|
||||
$msiSrc = Join-Path $BundleDir "msi\${Product}_${Version}_x64_zh-CN.msi"
|
||||
$nsisSrc = Join-Path $BundleDir "nsis\${Product}_${Version}_x64-setup.exe"
|
||||
$hkSrc = Join-Path $Root 'src-tauri\binaries\ThingHK.exe'
|
||||
|
||||
|
||||
Generated
+196
-222
@@ -85,15 +85,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "2.0.4"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
|
||||
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.2.4"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
|
||||
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
@@ -735,9 +735,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "brotli"
|
||||
version = "8.0.4"
|
||||
version = "9.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
|
||||
checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
@@ -746,9 +746,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "5.0.3"
|
||||
version = "6.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
|
||||
checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
@@ -885,12 +885,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cargo_toml"
|
||||
version = "0.22.3"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77"
|
||||
checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
|
||||
dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"toml 1.1.2+spec-1.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -931,13 +932,13 @@ checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
|
||||
|
||||
[[package]]
|
||||
name = "cfb"
|
||||
version = "0.7.3"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f"
|
||||
checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"fnv",
|
||||
"uuid",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1366,9 +1367,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cssparser"
|
||||
version = "0.36.0"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2"
|
||||
checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98"
|
||||
dependencies = [
|
||||
"cssparser-macros",
|
||||
"dtoa-short",
|
||||
@@ -1379,29 +1380,19 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cssparser-macros"
|
||||
version = "0.6.1"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331"
|
||||
checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctor"
|
||||
version = "0.8.0"
|
||||
version = "1.0.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "352d39c2f7bef1d6ad73db6f5160efcaed66d94ef8c6c573a8410c00bf909a98"
|
||||
dependencies = [
|
||||
"ctor-proc-macro",
|
||||
"dtor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctor-proc-macro"
|
||||
version = "0.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
|
||||
checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"
|
||||
|
||||
[[package]]
|
||||
name = "ctr"
|
||||
@@ -1664,9 +1655,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "6.0.0"
|
||||
version = "7.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
|
||||
checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"
|
||||
dependencies = [
|
||||
"dirs-sys 0.5.0",
|
||||
]
|
||||
@@ -1703,7 +1694,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users 0.5.2",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1754,9 +1745,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "dom_query"
|
||||
version = "0.27.0"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89"
|
||||
checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"cssparser",
|
||||
@@ -1803,21 +1794,6 @@ dependencies = [
|
||||
"dtoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dtor"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1057d6c64987086ff8ed0fd3fbf377a6b7d205cc7715868cd401705f715cbe4"
|
||||
dependencies = [
|
||||
"dtor-proc-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dtor-proc-macro"
|
||||
version = "0.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5"
|
||||
|
||||
[[package]]
|
||||
name = "dunce"
|
||||
version = "1.0.5"
|
||||
@@ -1991,7 +1967,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2573,7 +2549,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c386b0a4a70cb2d39fffd74480f985b6f0bfbcb934b6a6b6b7e630e448f242e"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"keyboard-types",
|
||||
"keyboard-types 0.7.0",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"once_cell",
|
||||
@@ -2830,9 +2806,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "html5ever"
|
||||
version = "0.38.0"
|
||||
version = "0.39.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1054432bae2f14e0061e33d23402fbaa67a921d319d56adc6bcf887ddad1cbc2"
|
||||
checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8"
|
||||
dependencies = [
|
||||
"log",
|
||||
"markup5ever",
|
||||
@@ -2985,7 +2961,7 @@ dependencies = [
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core 0.62.2",
|
||||
"windows-core 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3167,9 +3143,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "infer"
|
||||
version = "0.19.0"
|
||||
version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7"
|
||||
checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
]
|
||||
@@ -3383,21 +3359,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "json-patch"
|
||||
version = "3.0.1"
|
||||
version = "4.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08"
|
||||
checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72"
|
||||
dependencies = [
|
||||
"jsonptr",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 1.0.69",
|
||||
"thiserror 2.0.20",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonptr"
|
||||
version = "0.6.3"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70"
|
||||
checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3434,6 +3410,16 @@ dependencies = [
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyboard-types"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyring"
|
||||
version = "3.6.3"
|
||||
@@ -3822,7 +3808,7 @@ dependencies = [
|
||||
"httparse",
|
||||
"librqbit-dualstack-sockets",
|
||||
"network-interface",
|
||||
"quick-xml",
|
||||
"quick-xml 0.41.0",
|
||||
"reqwest 0.13.4",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
@@ -3968,9 +3954,9 @@ checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"
|
||||
|
||||
[[package]]
|
||||
name = "markup5ever"
|
||||
version = "0.38.0"
|
||||
version = "0.39.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8983d30f2915feeaaab2d6babdd6bc7e9ed1a00b66b5e6d74df19aa9c0e91862"
|
||||
checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de"
|
||||
dependencies = [
|
||||
"log",
|
||||
"tendril",
|
||||
@@ -4125,14 +4111,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "muda"
|
||||
version = "0.19.3"
|
||||
version = "0.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1dd04e60bc0b07438a6771710ee1698f98f6ebbc7f89b61264af1563b8aeb878"
|
||||
checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"dpi",
|
||||
"gtk",
|
||||
"keyboard-types",
|
||||
"keyboard-types 0.8.3",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-core-foundation",
|
||||
@@ -4141,7 +4127,7 @@ dependencies = [
|
||||
"png 0.18.1",
|
||||
"serde",
|
||||
"thiserror 2.0.20",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4441,6 +4427,7 @@ dependencies = [
|
||||
"objc2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
"objc2-quartz-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5080,7 +5067,7 @@ checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"indexmap 2.14.0",
|
||||
"quick-xml",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"time",
|
||||
]
|
||||
@@ -5328,6 +5315,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.11"
|
||||
@@ -5382,7 +5378,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5987,7 +5983,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6044,7 +6040,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6213,9 +6209,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "selectors"
|
||||
version = "0.36.1"
|
||||
version = "0.38.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c5d9c0c92a92d33f08817311cf3f2c29a3538a8240e94a6a3c622ce652d7e00c"
|
||||
checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cssparser",
|
||||
@@ -6625,7 +6621,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6878,9 +6874,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "swift-rs"
|
||||
version = "1.0.7"
|
||||
version = "1.0.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4057c98e2e852d51fdcfca832aac7b571f6b351ad159f9eda5db1655f8d0c4d7"
|
||||
checksum = "e45c444e496845d3f2a351146bff59aae4975b2280238df1dfaa0c7d1846f38e"
|
||||
dependencies = [
|
||||
"base64 0.21.7",
|
||||
"serde",
|
||||
@@ -7175,9 +7171,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tao"
|
||||
version = "0.35.3"
|
||||
version = "0.37.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"
|
||||
checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2",
|
||||
@@ -7195,29 +7191,29 @@ dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"ndk",
|
||||
"ndk-context",
|
||||
"ndk-sys",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-foundation",
|
||||
"objc2-ui-kit",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"raw-window-handle",
|
||||
"tao-macros",
|
||||
"unicode-segmentation",
|
||||
"url",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
"windows-version",
|
||||
"x11-dl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tao-macros"
|
||||
version = "0.1.3"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f4e16beb8b2ac17db28eab8bca40e62dbfbb34c0fcdc6d9826b11b7b5d047dfd"
|
||||
checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -7238,14 +7234,14 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
|
||||
|
||||
[[package]]
|
||||
name = "tauri"
|
||||
version = "2.11.5"
|
||||
version = "2.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "667b20e2726d572dea2de7370da16e188eb06008faf9a92fab7cdc46791190b5"
|
||||
checksum = "cb20ef8e6f97d6fe03039666cd82861f09a38b56291fa2f0f9fe140023f61c1a"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bytes",
|
||||
"cookie",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"dunce",
|
||||
"embed_plist",
|
||||
"getrandom 0.3.4",
|
||||
@@ -7285,18 +7281,18 @@ dependencies = [
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"window-vibrancy",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-build"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc9ce40b16101cb6ea63d3e221567affd1c3a9205f95d7bc574941a10636b632"
|
||||
checksum = "5b5ae674f48836f5dd2eeaf9e221c095bd3e78a8d0439c77ca93b48740a1b644"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cargo_toml",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"glob",
|
||||
"heck 0.5.0",
|
||||
"json-patch",
|
||||
@@ -7311,16 +7307,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-codegen"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08279169ff42f8fc45a1dbc9dcae888893ba95288142e5880c59b93a26d2cfc5"
|
||||
checksum = "3926b73ac01df7c14f19ff872cd56e67213a87acc0000ea37ddb300f3d11a3e3"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"brotli",
|
||||
"ico",
|
||||
"json-patch",
|
||||
"plist",
|
||||
"png 0.17.16",
|
||||
"png 0.18.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"semver",
|
||||
@@ -7338,9 +7334,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-macros"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8b394794f399a421811d06966343e7933fcae92d59f5180b9388d1174497a45"
|
||||
checksum = "d21d0fa2c0529972ea6ecaf7404fcf40efac098eda0beb06ca682f41e33a6aa5"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -7352,9 +7348,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "74be5dd4bed9afbd145e5716b5fa2ec28cbc29c34ffa61c258c9273d896c8020"
|
||||
checksum = "c9ff3ebb9fda56ceb93d46f6cbb126bae82951bf43498543a5163dde5def49a1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"glob",
|
||||
@@ -7368,9 +7364,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-autostart"
|
||||
version = "2.5.1"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "459383cebc193cdd03d1ba4acc40f2c408a7abce419d64bdcd2d745bc2886f70"
|
||||
checksum = "d464b4c2a5742cdeaf89d739f0681a8770c380053919dcd3ab9bc65fdb9f7c5f"
|
||||
dependencies = [
|
||||
"auto-launch",
|
||||
"serde",
|
||||
@@ -7382,9 +7378,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-dialog"
|
||||
version = "2.7.2"
|
||||
version = "2.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2d3c1dbe38037e7f590cdf2492594d5ceebe031e7bc7e827509b22a999d2940"
|
||||
checksum = "7527c5fd1678032d116c1a82e5d609c67370e56f858ae6cfd376bbca37fe0490"
|
||||
dependencies = [
|
||||
"log",
|
||||
"raw-window-handle",
|
||||
@@ -7400,9 +7396,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-fs"
|
||||
version = "2.5.1"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7ecc274121aca0c036a2b42d1cbe83d368d348f54e0bb8a735c2b1548e8f371"
|
||||
checksum = "466eb32466fe5021b6728b06862f9ff14a9f7e1af890047654e03a96d7c0e1bb"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"dunce",
|
||||
@@ -7424,9 +7420,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-global-shortcut"
|
||||
version = "2.3.2"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4dd9f4c5136c09cd962da0c86dc4accd4666db2ea591cf16e6597435843bd2b"
|
||||
checksum = "0bd2e1f725891a1613af8f25bf918ba3357654b0fd3f2d794c0ce76cbdd92ed2"
|
||||
dependencies = [
|
||||
"global-hotkey",
|
||||
"log",
|
||||
@@ -7439,9 +7435,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-notification"
|
||||
version = "2.3.3"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01fc2c5ff41105bd1f7242d8201fdf3efd70749b82fa013a17f2126357d194cc"
|
||||
checksum = "9237e5cc1458bf1b31ad3c8c2c8480e86b6ecf133d00648fe6c36f25821f2f79"
|
||||
dependencies = [
|
||||
"log",
|
||||
"notify-rust",
|
||||
@@ -7458,9 +7454,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-opener"
|
||||
version = "2.5.4"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17e1bea14edce6b793a04e2417e3fd924b9bc4faae83cdee7d714156cceeed29"
|
||||
checksum = "d39404b2572927e0d3ed30a7ca226037f7508d22e79c96ee6ef0d42b6a4b3345"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"glob",
|
||||
@@ -7474,7 +7470,23 @@ dependencies = [
|
||||
"tauri-plugin",
|
||||
"thiserror 2.0.20",
|
||||
"url",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-single-instance"
|
||||
version = "2.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91baf4f5db4b008fc2bcada0f7d3a49b45d911f94575ac236f225ed67554f5c0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"thiserror 2.0.20",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
@@ -7496,9 +7508,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime"
|
||||
version = "2.11.3"
|
||||
version = "2.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b0b4bc95aed361b0019067d189a1174a603d460d0f6c72606512d59fc9c12ec8"
|
||||
checksum = "c9e6d5ef76985b32ff012a43b58df205d25a285e400ca878afcacddc5d5f3238"
|
||||
dependencies = [
|
||||
"cookie",
|
||||
"dpi",
|
||||
@@ -7516,14 +7528,14 @@ dependencies = [
|
||||
"url",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime-wry"
|
||||
version = "2.11.4"
|
||||
version = "2.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f"
|
||||
checksum = "fa829eb69860cf1fb0bedb21d2d5f1effce3527d054a68ca1cd7355c654400a3"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"http",
|
||||
@@ -7541,7 +7553,7 @@ dependencies = [
|
||||
"url",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
"wry",
|
||||
]
|
||||
|
||||
@@ -7564,9 +7576,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-utils"
|
||||
version = "2.9.3"
|
||||
version = "2.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e176a18e67764923c4f1ce66f25ae4abe5f688384d5eb1a0fa6c77f3d90f887"
|
||||
checksum = "4dd257082deff79550de3409ed146104aeaf86fe38649615b04a304144939677"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"brotli",
|
||||
@@ -7632,7 +7644,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7646,7 +7658,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "thing"
|
||||
version = "26.9.4"
|
||||
version = "26.10.1"
|
||||
dependencies = [
|
||||
"aes 0.8.4",
|
||||
"async-trait",
|
||||
@@ -7654,6 +7666,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"cbc 0.1.2",
|
||||
"chardetng",
|
||||
"chrono",
|
||||
"cpal",
|
||||
"dashmap",
|
||||
@@ -7668,6 +7681,7 @@ dependencies = [
|
||||
"lofty",
|
||||
"md-5",
|
||||
"notify",
|
||||
"quick-xml 0.42.0",
|
||||
"rand 0.8.8",
|
||||
"raw-window-handle",
|
||||
"regex",
|
||||
@@ -7692,6 +7706,7 @@ dependencies = [
|
||||
"tauri-plugin-global-shortcut",
|
||||
"tauri-plugin-notification",
|
||||
"tauri-plugin-opener",
|
||||
"tauri-plugin-single-instance",
|
||||
"tauri-plugin-snap-layout",
|
||||
"tauri-specta",
|
||||
"tokio",
|
||||
@@ -7699,7 +7714,9 @@ dependencies = [
|
||||
"url",
|
||||
"walkdir",
|
||||
"windows 0.52.0",
|
||||
"windows 0.62.2",
|
||||
"windows-capture",
|
||||
"windows-core 0.62.2",
|
||||
"windows-sys 0.52.0",
|
||||
"winreg 0.52.0",
|
||||
"zip",
|
||||
@@ -7878,8 +7895,12 @@ checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"log",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tungstenite",
|
||||
"webpki-roots 0.26.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7909,21 +7930,6 @@ dependencies = [
|
||||
"toml_edit 0.20.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.9.12+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
|
||||
dependencies = [
|
||||
"indexmap 2.14.0",
|
||||
"serde_core",
|
||||
"serde_spanned 1.1.1",
|
||||
"toml_datetime 0.7.5+spec-1.1.0",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow 0.7.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "1.1.2+spec-1.1.0"
|
||||
@@ -7948,15 +7954,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "0.7.5+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.1+spec-1.1.0"
|
||||
@@ -8039,12 +8036,17 @@ version = "0.6.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
||||
dependencies = [
|
||||
"async-compression",
|
||||
"bitflags 2.13.2",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
@@ -8107,12 +8109,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tray-icon"
|
||||
version = "0.24.1"
|
||||
version = "0.25.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65ba1e5f6b9ef9fd87e21b9c6f351554dbd717960089168fcfdef854686961dc"
|
||||
checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"libappindicator",
|
||||
"muda",
|
||||
"objc2",
|
||||
@@ -8124,7 +8126,7 @@ dependencies = [
|
||||
"png 0.18.1",
|
||||
"serde",
|
||||
"thiserror 2.0.20",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8146,6 +8148,8 @@ dependencies = [
|
||||
"httparse",
|
||||
"log",
|
||||
"rand 0.8.8",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"sha1 0.10.7",
|
||||
"thiserror 1.0.69",
|
||||
"utf-8",
|
||||
@@ -8177,48 +8181,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
|
||||
dependencies = [
|
||||
"memoffset",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unic-char-property"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221"
|
||||
dependencies = [
|
||||
"unic-char-range",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unic-char-range"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc"
|
||||
|
||||
[[package]]
|
||||
name = "unic-common"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc"
|
||||
|
||||
[[package]]
|
||||
name = "unic-ucd-ident"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987"
|
||||
dependencies = [
|
||||
"unic-char-property",
|
||||
"unic-char-range",
|
||||
"unic-ucd-version",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unic-ucd-version"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4"
|
||||
dependencies = [
|
||||
"unic-common",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8288,13 +8251,13 @@ checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
|
||||
|
||||
[[package]]
|
||||
name = "urlpattern"
|
||||
version = "0.3.0"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d"
|
||||
checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b"
|
||||
dependencies = [
|
||||
"icu_properties",
|
||||
"regex",
|
||||
"serde",
|
||||
"unic-ucd-ident",
|
||||
"url",
|
||||
]
|
||||
|
||||
@@ -8561,17 +8524,33 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com"
|
||||
version = "0.38.2"
|
||||
name = "webpki-roots"
|
||||
version = "0.26.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"
|
||||
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
|
||||
dependencies = [
|
||||
"webpki-roots 1.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com"
|
||||
version = "0.39.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6"
|
||||
dependencies = [
|
||||
"webview2-com-macros",
|
||||
"webview2-com-sys",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows-implement 0.60.2",
|
||||
"windows-interface 0.59.3",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8587,13 +8566,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com-sys"
|
||||
version = "0.38.2"
|
||||
version = "0.39.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"
|
||||
checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb"
|
||||
dependencies = [
|
||||
"thiserror 2.0.20",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8618,7 +8597,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8629,16 +8608,17 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "window-vibrancy"
|
||||
version = "0.6.0"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c"
|
||||
checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580"
|
||||
dependencies = [
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
"objc2-quartz-core",
|
||||
"raw-window-handle",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-version",
|
||||
]
|
||||
|
||||
@@ -9252,12 +9232,6 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "0.7.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.4"
|
||||
@@ -9322,15 +9296,15 @@ checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
|
||||
|
||||
[[package]]
|
||||
name = "wry"
|
||||
version = "0.55.1"
|
||||
version = "0.57.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "186f9871daa55fd9c016578b810d149de58367113db7fb72b462d2323ce19514"
|
||||
checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"block2",
|
||||
"cookie",
|
||||
"crossbeam-channel",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"dom_query",
|
||||
"dpi",
|
||||
"dunce",
|
||||
@@ -9358,8 +9332,8 @@ dependencies = [
|
||||
"webkit2gtk",
|
||||
"webkit2gtk-sys",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
"windows-version",
|
||||
"x11-dl",
|
||||
]
|
||||
|
||||
+49
-4
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "thing"
|
||||
version = "26.9.4"
|
||||
version = "26.10.1"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
edition = "2021"
|
||||
@@ -30,6 +30,10 @@ async-trait = "0.1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
regex = "1"
|
||||
# 编码统计探测(Firefox 的探测器):判断「非 UTF-8 文件到底是 Shift_JIS 还是
|
||||
# GB18030」这类问题。GB18030 几乎能解码任意字节序列,「试解是否成功」不可靠,
|
||||
# 会把日文 Shift_JIS 误判成中文 GB18030。
|
||||
chardetng = "1.0"
|
||||
serde_yaml = "0.9"
|
||||
specta = { version = "=2.0.0-rc.25", features = ["derive", "function", "serde_json"] }
|
||||
specta-typescript = "0.0.12"
|
||||
@@ -38,8 +42,14 @@ chrono = "0.4"
|
||||
# blocking:音乐播放引擎在**独立 std 线程**上解码(symphonia 的 MediaSource 是同步
|
||||
# Read+Seek),需要同步 HTTP 客户端去按 Range 拉 NAS 音频流。放在 std 线程上用
|
||||
# blocking 是安全的(在 tokio 运行时线程里用才会 panic)。
|
||||
reqwest = { version = "0.12", features = ["json", "stream", "multipart", "blocking"] }
|
||||
futures-util = "0.3"
|
||||
# gzip:智能家居模块走反代(Cloudflare Tunnel)链路时,`/api/states` 是几百 KB JSON。
|
||||
# **默认不开压缩就不会发 Accept-Encoding**,CF 会回未压缩响应,远端首屏流量翻 5–10 倍
|
||||
# (见 doc/SMART_HOME_MODULE_PLAN.md §3.7-b)。
|
||||
reqwest = { version = "0.12", features = ["json", "stream", "multipart", "blocking", "gzip"] }
|
||||
# `sink`:WebSocket 客户端要把流拆成读/写两半(`SinkExt` / `StreamExt`)。
|
||||
# default 特性里**不含** `sink`(已核对 0.3.32 的 Cargo.toml),目前只是因为
|
||||
# tokio-tungstenite 自己开了它才传递可用 —— 依赖传递特性不该被当成前提,故显式打开。
|
||||
futures-util = { version = "0.3", features = ["sink"] }
|
||||
tokio = { version = "1", features = ["io-util", "time", "rt-multi-thread", "macros", "sync", "fs", "net"] }
|
||||
axum = { version = "0.7", features = ["ws"] }
|
||||
url = "2"
|
||||
@@ -100,7 +110,14 @@ aes = "0.8"
|
||||
cbc = "0.1"
|
||||
rsa = { version = "0.9", features = ["pem"] }
|
||||
rand = "0.8"
|
||||
tokio-tungstenite = "0.24"
|
||||
# WebSocket 客户端(智能家居模块 P4 的实时推送 / 规则引擎)。
|
||||
# `connect` 已随 default 启用(`cargo tree -e features -i tokio-tungstenite` 复核过:
|
||||
# 它由本项 + axum 的 `ws` 共同引入),这里显式写出来是为了让"要连"这件事在清单里可见。
|
||||
# **TLS 默认未启用** —— 反代是 HTTPS(`wss://`,D5 已定必须支持),故补
|
||||
# `rustls-tls-webpki-roots`:纯 Rust、无 C 依赖,与项目姿态一致(`native-tls` 会引入系统依赖),
|
||||
# 且复用依赖树里已存在的 rustls 0.23(经 russh),不新增编译单元。
|
||||
# 注意:自签证书的 `wss://` 仍是缺口 —— `insecure`(危险开关)目前只覆盖 REST。
|
||||
tokio-tungstenite = { version = "0.24", features = ["connect", "rustls-tls-webpki-roots"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
|
||||
walkdir = "2"
|
||||
notify = { version = "6", features = [] }
|
||||
@@ -117,6 +134,11 @@ symphonia = { version = "0.6", features = ["mp3", "aac", "alac", "isomp4"] }
|
||||
# AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | SRC_DEFAULT_QUALITY,因此**可以用源采样率
|
||||
# 直接建流**,由 Windows 自己转换到设备混音格式 —— 不需要额外引入重采样库。
|
||||
cpal = "0.18"
|
||||
# WebDAV 的 PROPFIND 响应是 XML,且命名空间前缀由服务端随意指定(D: / d: / lp1: /
|
||||
# 无前缀),因此只能按 local name 做宽容的事件流解析。quick-xml 是纯 Rust、无 C 依赖,
|
||||
# 且比 serde 反序列化更能吃下各家 NAS 不一致的字段集合(见 notes/webdav/client.rs)。
|
||||
quick-xml = "0.42.0"
|
||||
tauri-plugin-single-instance = "2.5.1"
|
||||
# HDR 截图说明:windows-capture 的 Windows Graphics Capture 后端在 HDR 显示器上
|
||||
# 可能输出 scRGB / rgba16F 或 HDR10(PQ) 格式的帧,与项目其余截图路径
|
||||
# (GDI BitBlt,sRGB 8bit)色彩空间不一致。capture 层统一转成 sRGB 8bit
|
||||
@@ -169,6 +191,9 @@ windows = { version = "0.52", features = [
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_Variant",
|
||||
"Win32_UI_Shell",
|
||||
# 快速面板「保存截图后定位并进入重命名」:SHParseDisplayName / SHOpenFolderAndSelectItems
|
||||
# 与 ITEMIDLIST 都被 Win32_UI_Shell_Common 门控(windows 0.52 源码 cfg)
|
||||
"Win32_UI_Shell_Common",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
# 翻译模块:Windows.Media.Ocr 本地识别(WinRT)
|
||||
# Foundation_Collections:OcrResult.Lines / OcrEngine.AvailableRecognizerLanguages 返回 IVectorView
|
||||
@@ -212,6 +237,26 @@ windows = { version = "0.52", features = [
|
||||
"Win32_Graphics_Dxgi_Common",
|
||||
"Win32_Graphics_Gdi",
|
||||
] }
|
||||
# 与 tauri / wry 同版本的 windows crate(**重命名**以便与上面项目自用的 0.52 并存;
|
||||
# 同名不同版本不能写在同一个表里)。仅用于 editor/drag_drop.rs 实现 IDropTarget:
|
||||
# 需要与 `WebviewWindow::hwnd()` 返回的 HWND 是同一个类型,才能直接对接。
|
||||
windows62 = { package = "windows", version = "0.62", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_System_Com",
|
||||
# 窗口级 AppUserModelID:PROPVARIANT 在 Com\StructuredStorage 下
|
||||
"Win32_System_Com_StructuredStorage",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_SystemServices",
|
||||
"Win32_UI_Shell",
|
||||
# 窗口级 AUMID:SHGetPropertyStoreForWindow / IPropertyStore(Shell\PropertiesSystem)
|
||||
"Win32_UI_Shell_PropertiesSystem",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
# PKEY_AppUserModel_ID 常量声明在 Storage\EnhancedStorage 下
|
||||
"Win32_Storage_EnhancedStorage",
|
||||
] }
|
||||
# `#[implement]` 宏展开出的代码按裸名引用 `windows_core`,因此必须直接依赖同名 crate。
|
||||
windows-core = "0.62"
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
tauri-plugin-autostart = "2"
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "diff-window",
|
||||
"description": "Capability for the compare window (singleton, label = diff-window). Dual-pane merge view + folder tree — needs the editor window's control set (self-drawn title bar, mica/acrylic effects) plus drag & drop for setting either side from Explorer.",
|
||||
"windows": ["diff-window"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-effects",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit",
|
||||
"dialog:default",
|
||||
"opener:default",
|
||||
"opener:allow-open-path",
|
||||
"opener:allow-reveal-item-in-dir",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "dsh-window",
|
||||
"description": "Capability for the dsh startup progress window (#dsh-window). Self-drawn title bar + theme; only local app commands are invoked.",
|
||||
"windows": ["dsh-window"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "editor-window",
|
||||
"description": "Capability for the editor windows (multi-open, label = editor-window-<n>). Needs the CM6 editor's window controls, events (settings/library sync) and opener.",
|
||||
"windows": ["editor-window-*"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-effects",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit",
|
||||
"dialog:default",
|
||||
"opener:default",
|
||||
"opener:allow-open-path",
|
||||
"opener:allow-reveal-item-in-dir",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -163,6 +163,30 @@ pub fn ensure_popup_window(app: &AppHandle) {
|
||||
create_popup_window(app);
|
||||
}
|
||||
|
||||
/// 把已显示的弹窗强制置前。
|
||||
///
|
||||
/// 只调 `set_focus` 不够:它内部是 `SetForegroundWindow`,受 Windows **前台锁定**限制 ——
|
||||
/// 从别的应用按 Alt+V(本进程不拥有前台)时会被静默忽略,弹窗「出来了但拿不到焦点」,
|
||||
/// 键盘导航 / 搜索都用不了。这里改用原生强制置前(模拟 Alt 释放重置前台锁定 +
|
||||
/// SetForegroundWindow + BringWindowToTop),与快速面板 / 托盘 / 下载窗口同一套做法。
|
||||
///
|
||||
/// 调用前窗口应已 `show()`。置前失败(拿不到 hwnd)时退回普通 `set_focus`。
|
||||
fn focus_force(win: &tauri::WebviewWindow) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
match win.hwnd() {
|
||||
Ok(hwnd) => crate::win32_util::force_foreground(hwnd.0 as isize),
|
||||
Err(_) => {
|
||||
let _ = win.set_focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = win.set_focus();
|
||||
}
|
||||
}
|
||||
|
||||
/// 在鼠标当前位置显示弹窗。
|
||||
/// 窗口不存在则创建(隐藏状态,等前端挂载后调用 show_window 显示)。
|
||||
/// 窗口已存在则移动到鼠标位置并显示。
|
||||
@@ -200,7 +224,7 @@ pub fn show_popup(app: &AppHandle) {
|
||||
}));
|
||||
let _ = win.show();
|
||||
mark_shown();
|
||||
let _ = win.set_focus();
|
||||
focus_force(&win);
|
||||
// 通知前端刷新数据
|
||||
let _ = app.emit(crate::constants::events::CLIPBOARD_POPUP_SHOW, ());
|
||||
return;
|
||||
@@ -232,7 +256,7 @@ pub fn show_window(app: &AppHandle) {
|
||||
}
|
||||
let _ = win.show();
|
||||
mark_shown();
|
||||
let _ = win.set_focus();
|
||||
focus_force(&win);
|
||||
// 通知前端刷新数据
|
||||
let _ = app.emit(crate::constants::events::CLIPBOARD_POPUP_SHOW, ());
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ impl SuppressState {
|
||||
// saturating:异常路径下的多余 end 不应让计数下溢,否则会永久屏蔽
|
||||
let _ = self
|
||||
.burst
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| {
|
||||
.try_update(Ordering::SeqCst, Ordering::SeqCst, |v| {
|
||||
Some(v.saturating_sub(1))
|
||||
});
|
||||
}
|
||||
|
||||
@@ -26,6 +26,16 @@ pub mod windows {
|
||||
/// 因此**不登记 capability**:远端页面不应获得任何 Tauri 权限)。
|
||||
#[allow(dead_code)]
|
||||
pub const DSH_WEB: &str = "dsh-web";
|
||||
/// 笔记 / 编辑器独立窗口前缀,实际 label = `${EDITOR_WINDOW}-<n>`(可多开)
|
||||
#[allow(dead_code)]
|
||||
pub const EDITOR_WINDOW: &str = "editor-window";
|
||||
/// dsh「启动进度」独立窗口(单例,由前端创建)。
|
||||
/// 服务就绪后由前端打开真正的 [`DSH_WEB`] 窗口并关闭它。
|
||||
#[allow(dead_code)]
|
||||
pub const DSH_WINDOW: &str = "dsh-window";
|
||||
/// 对比工具独立窗口(单例,由前端创建)。
|
||||
#[allow(dead_code)]
|
||||
pub const DIFF_WINDOW: &str = "diff-window";
|
||||
}
|
||||
|
||||
/// Tauri 事件名(与前端 constants::EVENTS 对应)
|
||||
@@ -34,8 +44,12 @@ pub mod events {
|
||||
pub const TRAY_MENU_SHOW: &str = "tray-menu-show";
|
||||
pub const TRAY_MENU_STATE_UPDATED: &str = "tray-menu-state-updated";
|
||||
pub const TRAY_TOGGLE_OSD: &str = "tray:toggle-osd";
|
||||
pub const TRAY_NEW_DOWNLOAD: &str = "tray:new-download";
|
||||
pub const TRAY_OPEN_SETTINGS: &str = "tray:open-settings";
|
||||
/// 托盘菜单「终端」:打开新建终端选择窗口(窗口由前端创建)
|
||||
pub const TRAY_OPEN_TERMINAL: &str = "tray:open-terminal";
|
||||
/// 托盘菜单「dsh」:打开 dsh 独立窗口(未启动时先显示启动进度)
|
||||
pub const TRAY_OPEN_DSH: &str = "tray:open-dsh";
|
||||
/// 托盘菜单「编辑器」:打开编辑器独立窗口(窗口由前端创建)
|
||||
pub const TRAY_OPEN_EDITOR: &str = "tray:open-editor";
|
||||
// 剪贴板
|
||||
pub const CLIPBOARD_CHANGED: &str = "clipboard-changed";
|
||||
pub const CLIPBOARD_POPUP_SHOW: &str = "clipboard-popup-show";
|
||||
@@ -134,4 +148,42 @@ pub mod events {
|
||||
/// dsh 模块:全局快捷键触发「打开独立窗口」(无负载)。
|
||||
/// 窗口由前端创建(它持有带令牌的地址与 label 判重),Rust 侧只负责注册快捷键。
|
||||
pub const DSH_OPEN_WINDOW: &str = "dsh-open-window";
|
||||
// 笔记模块:设置已保存(无负载)。各窗口据以重读设置,实现跨窗口同步(同 terminal-settings)
|
||||
pub const EDITOR_SETTINGS: &str = "editor-settings";
|
||||
// 笔记模块:库内容已变更(新建/保存/重命名/删除/切换库根,无负载)
|
||||
pub const EDITOR_LIBRARY_CHANGED: &str = "editor-library-changed";
|
||||
// 笔记模块:库内某个文件在**应用外**被改动了(负载见 editor::index_service::NoteFileEvent)。
|
||||
// 与 EDITOR_LIBRARY_CHANGED 的区别:那个是「本应用改了,重读即可」,这个是
|
||||
// 「别人改了,当前打开的文档可能已经过时」——前端据此提示而不是静默覆盖。
|
||||
pub const EDITOR_FILE_CHANGED: &str = "editor-file-changed";
|
||||
// 笔记模块:WebDAV 同步进度(负载见 editor::types::SyncProgress)。
|
||||
// 进度事件是高频的,前端按「每 X% 或每 N 条」节流显示即可;Rust 侧逐条发,
|
||||
// 因为节流放在发送端会让「最后一条」容易被丢掉(进度条停在 98%)。
|
||||
pub const EDITOR_SYNC_PROGRESS: &str = "editor-sync-progress";
|
||||
// 笔记模块:全局快捷键按下「新建笔记」(无负载,窗口由前端创建)
|
||||
pub const EDITOR_NEW_NOTE: &str = "editor-new-note";
|
||||
// 笔记模块:全局快捷键按下「打开编辑器窗口」(无负载)
|
||||
pub const EDITOR_OPEN_EDITOR: &str = "editor-open-editor";
|
||||
// 笔记模块:需要打开一个磁盘文件(负载 `{ path }`)。
|
||||
// 来源有三:① 双击关联的 .md(单实例回调把参数转交过来);② 启动命令行参数;
|
||||
// ③ 系统「打开方式」。三种都只发事件,窗口由前端创建。
|
||||
pub const EDITOR_OPEN_FILE: &str = "editor-open-file";
|
||||
// 笔记模块:需要打开一个**文件夹**(负载 `{ path }`)。
|
||||
// 来源:资源管理器右键「用 Thing 编辑器打开」(目录 / 目录背景)。
|
||||
pub const EDITOR_OPEN_FOLDER: &str = "editor-open-folder";
|
||||
// 对比模块:全局快捷键按下「打开对比窗口」(无负载)。
|
||||
// 窗口 label 策略与判重都在前端(它持有窗口),Rust 侧只负责注册快捷键。
|
||||
pub const DIFF_OPEN_WINDOW: &str = "diff-open-window";
|
||||
// 对比模块:目录扫描进度(负载见 diff::types::DiffScanProgress)。
|
||||
// 进度在**发送端**按时间节流(见 diff::commands::diff_compare_dirs):整棵树可能有
|
||||
// 上万个条目、上千次读盘,逐条 emit 会把 IPC 打满;前端只负责显示。
|
||||
pub const DIFF_SCAN_PROGRESS: &str = "diff-scan-progress";
|
||||
// ===== 智能家居(Home Assistant)实时推送与本地规则(P4)=====
|
||||
// 连接状态变化(含 WS):负载 `WsStatus`。前端据此显示顶部横幅与设置页诊断。
|
||||
pub const SMARTHOME_CONNECTION_STATUS: &str = "smarthome-connection-status";
|
||||
// 状态增量批次(**200ms 聚合后**):负载 `StateBatch`。
|
||||
// 逐条 emit 会把 WebView 打爆(一次全屋变化可能几十条),聚合是硬要求。
|
||||
pub const SMARTHOME_STATE_BATCH: &str = "smarthome-state-batch";
|
||||
// 本地规则触发:负载 `RuleFiredEvent`。
|
||||
pub const SMARTHOME_RULE_FIRED: &str = "smarthome-rule-fired";
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! 对比模块的命令层。
|
||||
//!
|
||||
//! 三件事:读取一侧的文件、把一侧的内容写回、对比两棵目录树。文本级差异计算全在前端
|
||||
//! (`@codemirror/merge`);目录级扫描在 [`super::scan`]。
|
||||
//!
|
||||
//! # 尺寸上限为什么要有两个
|
||||
//!
|
||||
//! - [`DIFF_LARGE_MB`]:**软**阈值。超过就置 `large`,前端据此关掉未变化段折叠等
|
||||
//! 高开销特性 —— 文件照样完整读出来,只是更省。
|
||||
//! - [`DIFF_HARD_LIMIT`]:**硬**上限。超过直接拒绝。对比窗口天生同时持有两侧内容
|
||||
//! (不像编辑器只有一篇),单侧 16MB 已经是「两份都塞进 WebView + CM6 状态」的
|
||||
//! 上限量级;再大不是「慢」而是「卡死」,早拒绝比让用户等一分钟再失败好。
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
|
||||
use crate::editor::files;
|
||||
|
||||
use super::scan;
|
||||
use super::types::{DiffFileDoc, DiffScanProgress, DiffSettings, DirDiffReport};
|
||||
use super::DiffManager;
|
||||
|
||||
/// 「大文件」软阈值(MB)。与编辑器设置的默认值一致。
|
||||
const DIFF_LARGE_MB: u32 = 5;
|
||||
/// 硬上限(字节):单侧超过则拒绝读取。
|
||||
const DIFF_HARD_LIMIT: u64 = 16 * 1024 * 1024;
|
||||
/// 二进制探测的头部字节数。**与 `editor::grep` 的判据一致**(头部含 NUL 即二进制),
|
||||
/// 否则会出现「搜索跳过了但对比工具显示了乱码」这种自相矛盾的行为。
|
||||
const BINARY_SNIFF_BYTES: usize = 8 * 1024;
|
||||
|
||||
/// 打开文件并读出头部,同时判断是否二进制(头部含 NUL 字节)。
|
||||
///
|
||||
/// 返回**同一个已打开的句柄**(读位置停在头部之后)与那段头部:文本文件随后要靠这个
|
||||
/// 句柄继续整读(见 `files::read_file_after_head`)—— 于是文件只被打开一次,也不会
|
||||
/// 出现「嗅探时与整读时文件已被换掉」的窗口。二进制则到此为止,绝不整读。
|
||||
fn open_with_head(path: &Path) -> Result<(std::fs::File, Vec<u8>, bool), String> {
|
||||
use std::io::Read;
|
||||
let mut file = std::fs::File::open(path).map_err(|e| format!("读取文件失败: {e}"))?;
|
||||
let mut head = vec![0u8; BINARY_SNIFF_BYTES];
|
||||
let read = file
|
||||
.read(&mut head)
|
||||
.map_err(|e| format!("读取文件失败: {e}"))?;
|
||||
head.truncate(read);
|
||||
let binary = head.contains(&0u8);
|
||||
Ok((file, head, binary))
|
||||
}
|
||||
|
||||
/// 写权限探测:以写模式打开但**不写入**(失败 → 只读)。
|
||||
///
|
||||
/// `editor::files` 里同名的函数是私有的(只服务编辑器自己的打开流程),这里重写一遍
|
||||
/// 三行而不是把它提升为 `pub(crate)`:那个是模块内部细节,把它开放出去会让「谁在读
|
||||
/// 权限探测」变得不清晰。
|
||||
fn is_writable(path: &Path) -> bool {
|
||||
std::fs::OpenOptions::new().write(true).open(path).is_ok()
|
||||
}
|
||||
|
||||
/// 读取对比窗口某一侧的文件。
|
||||
///
|
||||
/// 复用 `editor::files::read_file`(编码探测 / 换行归一 / 只读探测),并顺带登记
|
||||
/// 授权 —— 于是该文件随后可以被 [`diff_write_file`] 写回。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn diff_read_file(path: String) -> Result<DiffFileDoc, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
let meta = std::fs::metadata(p).map_err(|e| format!("读取文件信息失败: {e}"))?;
|
||||
if meta.is_dir() {
|
||||
return Err("这是一个目录 —— 请切到「文件夹」模式并把它设为某一侧".to_string());
|
||||
}
|
||||
if !meta.is_file() {
|
||||
return Err("目标不是普通文件".to_string());
|
||||
}
|
||||
if meta.len() > DIFF_HARD_LIMIT {
|
||||
return Err(format!(
|
||||
"文件过大({} MB),超出对比窗口的 {} MB 上限",
|
||||
meta.len() / (1024 * 1024),
|
||||
DIFF_HARD_LIMIT / (1024 * 1024)
|
||||
));
|
||||
}
|
||||
|
||||
// 先读头部判断二进制(二进制到此为止、不整读),并把这段头部与**同一个句柄**
|
||||
// 交给文本读取路径复用 —— 同一个文件全程只打开一次
|
||||
let (file, head, binary) = open_with_head(p)?;
|
||||
if binary {
|
||||
return Ok(DiffFileDoc::binary_of(p, &meta, is_writable(p)));
|
||||
}
|
||||
|
||||
let doc = files::read_file_after_head(file, p, &meta, &head, DIFF_LARGE_MB)?;
|
||||
// 「打开过就能保存」:读取即登记授权(写回仍会再校验一次授权与写权限)
|
||||
files::authorize(Path::new(&doc.path));
|
||||
Ok(DiffFileDoc::from_file_doc(doc))
|
||||
}
|
||||
|
||||
/// 把某一侧的内容写回磁盘。
|
||||
///
|
||||
/// `encoding` / `eol` 由前端回传**读取时探测到的值**,写回时原样还原 —— 一次「随手
|
||||
/// 保存」不该把 GBK 文件变成 UTF-8、把 CRLF 变成 LF(那会在整个 diff 里掀起风暴)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn diff_write_file(
|
||||
path: String,
|
||||
content: String,
|
||||
encoding: String,
|
||||
eol: String,
|
||||
) -> Result<DiffFileDoc, String> {
|
||||
let doc = files::write_file(&path, &content, &encoding, &eol, DIFF_LARGE_MB)?;
|
||||
Ok(DiffFileDoc::from_file_doc(doc))
|
||||
}
|
||||
|
||||
/// 探测一个路径是文件还是目录(`"dir"` / `"file"` / `"missing"`)。
|
||||
///
|
||||
/// 用途:拖入或 `?path=` 传进来的路径前端拿不到文件系统元信息,而对比窗口需要据此
|
||||
/// 决定「进文件模式还是目录模式」。**刻意不新增 Rust 侧的状态**:只读一次 `metadata`,
|
||||
/// 不写盘、不需授权。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn diff_path_kind(path: String) -> Result<String, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
match std::fs::metadata(trimmed) {
|
||||
Ok(meta) if meta.is_dir() => Ok("dir".to_string()),
|
||||
Ok(meta) if meta.is_file() => Ok("file".to_string()),
|
||||
Ok(_) => Ok("missing".to_string()),
|
||||
Err(_) => Ok("missing".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 对比两棵目录树(只读)。
|
||||
///
|
||||
/// `skip_dirs` 是**目录名**清单(大小写不敏感):默认清单由前端给出(它是界面约定,
|
||||
/// 用户能否修改是 UI 的事),后端只负责按它执行 —— 同 `editor::grep` 把默认跳过清单
|
||||
/// 留在前端的取舍。
|
||||
///
|
||||
/// 走 `spawn_blocking`:两遍目录遍历 + 最多 2000 次读盘都是同步阻塞 IO,放在 Tauri
|
||||
/// 命令线程上会占住它(范式同 `editor_search_in_path`)。
|
||||
///
|
||||
/// `scan_id` 由前端生成并随进度事件原样回传:进度事件是全局的,多选项卡并发扫描时
|
||||
/// 前端据此只认自己那一轮(见 `constants::events::DIFF_SCAN_PROGRESS`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn diff_compare_dirs(
|
||||
app: AppHandle,
|
||||
scan_id: u64,
|
||||
left: String,
|
||||
right: String,
|
||||
skip_dirs: Vec<String>,
|
||||
compare_content: bool,
|
||||
) -> Result<DirDiffReport, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
// 进度按**时间**节流(≥120ms 才发一条):整棵树可能有上万个条目、上千次读盘,
|
||||
// 逐条 emit 会把 IPC 打满;而按条目数节流在「条目少但每个都很大」时又会太稀。
|
||||
// 最后一条进度由前端在命令返回时清掉,不依赖这里补齐。
|
||||
let mut last_emit = Instant::now();
|
||||
let mut progress = |phase: scan::ScanPhase, done: u64, total: u64| {
|
||||
if last_emit.elapsed() < Duration::from_millis(120) {
|
||||
return;
|
||||
}
|
||||
last_emit = Instant::now();
|
||||
let phase = match phase {
|
||||
scan::ScanPhase::Walk => "scan",
|
||||
scan::ScanPhase::Compare => "compare",
|
||||
};
|
||||
let payload = DiffScanProgress {
|
||||
scan_id,
|
||||
phase: phase.to_string(),
|
||||
done,
|
||||
total,
|
||||
};
|
||||
let _ = app.emit(crate::constants::events::DIFF_SCAN_PROGRESS, payload);
|
||||
};
|
||||
scan::compare_dirs(&left, &right, &skip_dirs, compare_content, &mut progress)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("目录对比任务失败: {e}"))?
|
||||
}
|
||||
|
||||
/// 读取对比模块设置。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn diff_get_settings(state: State<'_, DiffManager>) -> DiffSettings {
|
||||
state.load_settings()
|
||||
}
|
||||
|
||||
/// 保存对比模块设置。
|
||||
///
|
||||
/// 保存后**就地重注册**全局快捷键(`register_shortcut` 会先注销本模块的旧键,因此
|
||||
/// 「清空快捷键」也能通过传空串生效)—— 同 `editor_save_settings`。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn diff_save_settings(
|
||||
app: AppHandle,
|
||||
state: State<'_, DiffManager>,
|
||||
settings: DiffSettings,
|
||||
) -> Result<DiffSettings, String> {
|
||||
let mut next = settings;
|
||||
next.heal();
|
||||
state.save_settings(&next)?;
|
||||
state.init_on_launch(&app);
|
||||
Ok(next)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! 对比模块(文本 / 文件 / 目录)。
|
||||
//!
|
||||
//! 架构位置:
|
||||
//!
|
||||
//! ```text
|
||||
//! 主模块页(入口 / 进度) 独立窗口(双栏差异视图)
|
||||
//! ↓ Tauri IPC ↓
|
||||
//! commands.rs 命令层
|
||||
//! ↓
|
||||
//! types.rs(回传前端的 DTO,与前端 src/modules/diff/types.ts 对齐)
|
||||
//! ↓
|
||||
//! editor::files 文件读取与编码探测(**复用**,不重复实现)
|
||||
//! ```
|
||||
//!
|
||||
//! # 为什么复用 `editor::files` 而不自己读文件
|
||||
//!
|
||||
//! 「读一个文本文件」在这里不是 `fs::read_to_string`:要探测 BOM / 严格 UTF-8 /
|
||||
//! GB18030 / Shift_JIS,要让「读到的编码」与「写回的编码」成对(GBK 文件按 UTF-8
|
||||
//! 存回去就是永久损坏),要统一换行风格并原样还原,还要探测只读。这些编辑器模块
|
||||
//! 都已经做完并踩过坑(见 `editor/files.rs` 的模块注释),对比工具没有任何理由
|
||||
//! 再实现一遍 —— 因此 `editor::files` 提升为 `pub(crate)`,本模块直接调用。
|
||||
//!
|
||||
//! # 授权模型沿用编辑器
|
||||
//!
|
||||
//! `editor::files` 的写操作要求路径在会话内被「用户显式选择过」(对话框 / 拖入 /
|
||||
//! 命令行)。本模块在**读取时顺带登记授权**,于是「在对比窗口打开过就能保存」这条
|
||||
//! 最符合直觉的规则自动成立,不需要前端再单独调用一次授权命令。
|
||||
//!
|
||||
//! # 当前进度
|
||||
//!
|
||||
//! P2 落地:单文件读取(`diff_read_file`)与写回(`diff_write_file`)。
|
||||
//! P3 落地:目录对比(`diff_compare_dirs` / `diff_path_kind`,只读)。
|
||||
//! 规划见 `doc/DIFF_MODULE_PLAN.md`。
|
||||
|
||||
mod commands;
|
||||
mod scan;
|
||||
mod types;
|
||||
|
||||
pub use commands::{
|
||||
diff_compare_dirs, diff_get_settings, diff_path_kind, diff_read_file, diff_save_settings,
|
||||
diff_write_file,
|
||||
};
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use types::DiffSettings;
|
||||
|
||||
/// 设置内存缓存有效期(与 ai / translate / terminal / editor 的 500ms 一致)。
|
||||
const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500);
|
||||
|
||||
struct SettingsCache {
|
||||
read_at: Instant,
|
||||
settings: DiffSettings,
|
||||
}
|
||||
|
||||
/// 对比模块管理器(Tauri State)。
|
||||
///
|
||||
/// 目前只承担一件事:设置的读写与全局快捷键注册。目标(左右文件 / 左右目录)**不在这里**
|
||||
/// —— 它们是前端会话状态,Rust 侧不需要知道用户在比哪两个东西。
|
||||
pub struct DiffManager {
|
||||
/// 模块自身目录:`{app_data_dir}/diff`
|
||||
module_dir: PathBuf,
|
||||
cache: Mutex<Option<SettingsCache>>,
|
||||
}
|
||||
|
||||
impl DiffManager {
|
||||
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||
let module_dir = app_data_dir.join("diff");
|
||||
let _ = std::fs::create_dir_all(&module_dir);
|
||||
Self {
|
||||
module_dir,
|
||||
cache: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_path(&self) -> PathBuf {
|
||||
self.module_dir.join("settings.json")
|
||||
}
|
||||
|
||||
/// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。
|
||||
pub fn load_settings(&self) -> DiffSettings {
|
||||
if let Ok(cache) = self.cache.lock() {
|
||||
if let Some(entry) = cache.as_ref() {
|
||||
if entry.read_at.elapsed() < SETTINGS_CACHE_TTL {
|
||||
return entry.settings.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = std::fs::read_to_string(self.settings_path())
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<DiffSettings>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
let healed = settings.heal();
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
if healed {
|
||||
if let Err(e) = self.save_settings(&settings) {
|
||||
crate::logger::log_error("diff", &format!("设置自愈落盘失败: {e}"));
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// 保存设置并刷新缓存。
|
||||
pub fn save_settings(&self, settings: &DiffSettings) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(settings)
|
||||
.map_err(|e| format!("序列化对比设置失败: {e}"))?;
|
||||
std::fs::write(self.settings_path(), json).map_err(|e| format!("写入对比设置失败: {e}"))?;
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 启动时按设置注册「打开对比窗口」全局快捷键(默认 Alt+C)。
|
||||
///
|
||||
/// 失败只记日志:快捷键被别的应用占了不该阻断启动(同 editor / translate / terminal)。
|
||||
/// 触发时**只发事件**:窗口 label 策略与判重都在前端(它持有窗口),Rust 侧不该操心。
|
||||
pub fn init_on_launch(&self, app: &tauri::AppHandle) {
|
||||
use tauri::Emitter;
|
||||
let settings = self.load_settings();
|
||||
let shortcut = settings.open_diff_shortcut.clone();
|
||||
if let Err(e) =
|
||||
crate::shortcut::register_shortcut(app, "diff-open-window", &shortcut, |app| {
|
||||
if let Err(e) = app.emit(crate::constants::events::DIFF_OPEN_WINDOW, ()) {
|
||||
crate::logger::log_warn("diff", &format!("发出打开对比窗口事件失败: {e}"));
|
||||
}
|
||||
})
|
||||
{
|
||||
crate::logger::log_warn("diff", &format!("注册「打开对比窗口」快捷键失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 模块目录(保留给将来的诊断 / 导出用)。
|
||||
#[allow(dead_code)]
|
||||
pub fn module_dir(&self) -> &Path {
|
||||
&self.module_dir
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
//! 目录对比:递归遍历两侧 + 三态分类(**只读**,本期不做写回)。
|
||||
//!
|
||||
//! # 为什么是三层判据,而不是逐字节比对
|
||||
//!
|
||||
//! 一个几万文件的目录树逐字节比对,等于把两边全读一遍 —— 慢且没必要。判据按代价递增:
|
||||
//!
|
||||
//! 1. **size 不同** → 直接判「不同」(两文件大小都不同,内容不可能相同,不必读盘);
|
||||
//! 2. **两侧都是空文件** → 直接判「相同」(长度都是 0,内容必然相同;这一条必须显式判,
|
||||
//! 否则「空文件 + 时间戳不同」会掉进下面「按时间戳判不同」的兜底,把两个空文件报成差异);
|
||||
//! 3. **size 相同且 mtime 相同** → 判「相同」(各对比工具的通行快速路径);
|
||||
//! 4. **size 相同但 mtime 不同** → 才读内容逐字节比对。
|
||||
//!
|
||||
//! 第 4 步有预算([`MAX_CONTENT_COMPARES`] 条数与 [`MAX_CONTENT_BYTES`] 单文件体积):
|
||||
//! 超出后不再读盘,按时间戳归入「不同」并把 `content_compared` 置 false ——
|
||||
//! 结论仍然是「不同」,但**明确标记它未经内容比对**,而不是给出一个看起来同样确定的答案。
|
||||
//!
|
||||
//! # 为什么返回扁平列表而不是树
|
||||
//!
|
||||
//! 递归类型在 specta 的 `Type` 派生下容易生成无穷展开的 TS 类型(`editor::types::LibraryEntry`
|
||||
//! 的注释里踩过同一个坑)。这里同样返回扁平列表(`rel_path` 用 `/` 分隔),由前端组装成树。
|
||||
//!
|
||||
//! # 只读
|
||||
//!
|
||||
//! 本模块**不写任何文件**。目录写回(复制 / 镜像 / 双向同步)是另一个量级的工程
|
||||
//! (冲突策略、部分失败回滚、覆盖确认),已与用户确认不在本期。
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::time::{Instant, UNIX_EPOCH};
|
||||
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use crate::editor::files::display_path;
|
||||
|
||||
use super::types::{DirDiffEntry, DirDiffReport, NodeInfo};
|
||||
|
||||
/// 单次对比最多回传的条目数(超出即截断并置 `truncated`)。
|
||||
///
|
||||
/// 取值权衡:条目是扁平 JSON,每条含两侧绝对路径,约 200 字节 —— 8000 条约 1.6MB 一次性
|
||||
/// 走 IPC,是「还能接受」与「再大就该让用户缩小范围」的分界。
|
||||
const MAX_ENTRIES: usize = 8000;
|
||||
/// 最多读多少个文件的内容做逐字节比对(防止「上万文件大小相同、时间戳不同」时把盘读穿)。
|
||||
const MAX_CONTENT_COMPARES: usize = 2000;
|
||||
/// 单个文件超过这个体积就不读内容比对(按时间戳判定)。
|
||||
const MAX_CONTENT_BYTES: u64 = 4 * 1024 * 1024;
|
||||
|
||||
/// 扫描阶段(进度事件用;事件名与负载见 [`super::types::DiffScanProgress`])。
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ScanPhase {
|
||||
/// 遍历目录树(此时总数无从预知)
|
||||
Walk,
|
||||
/// 读内容逐字节核对(总数 = 预算上限)
|
||||
Compare,
|
||||
}
|
||||
|
||||
/// 一次遍历的产出。
|
||||
struct Collected {
|
||||
files: HashMap<String, NodeInfo>,
|
||||
skipped_dirs: u32,
|
||||
truncated: bool,
|
||||
}
|
||||
|
||||
/// 把根路径解析成「存在的目录」的绝对路径。
|
||||
fn resolve_root(raw: &str, label: &str) -> Result<std::path::PathBuf, String> {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err(format!("{label}目录为空"));
|
||||
}
|
||||
let path = Path::new(trimmed);
|
||||
let meta = std::fs::metadata(path).map_err(|e| format!("读取{label}目录失败: {e}"))?;
|
||||
if !meta.is_dir() {
|
||||
return Err(format!("{label}不是目录(文件对比请用「文件 / 文本」模式)"));
|
||||
}
|
||||
// 规范化:统一成真实位置,避免两侧用不同写法指向同一目录(`C:\a\..\b` / 尾部斜杠)
|
||||
std::fs::canonicalize(path).map_err(|e| format!("解析{label}目录失败: {e}"))
|
||||
}
|
||||
|
||||
/// 递归收集一侧的全部条目。
|
||||
///
|
||||
/// **不跟随符号链接**(walkdir 默认):跟随会让「链接成的环」把遍历变成死循环。
|
||||
///
|
||||
/// 跳过清单用 `filter_entry` **真正剪枝**:walkdir 在返回一个目录条目的**同一次**
|
||||
/// `next()` 里就已把该目录压进遍历栈(见 walkdir 的 `handle_entry`),因此仅对命中的
|
||||
/// 目录条目 `continue` 并不会阻止继续下钻 —— 那会「跳过」得名不副实(构建目录的子项
|
||||
/// 照样进结果),还把整棵构建目录白扫一遍。
|
||||
fn collect(
|
||||
root: &Path,
|
||||
skip: &HashSet<String>,
|
||||
progress: &mut dyn FnMut(ScanPhase, u64, u64),
|
||||
) -> Collected {
|
||||
let mut files: HashMap<String, NodeInfo> = HashMap::new();
|
||||
let skipped = Cell::new(0u32);
|
||||
let truncated = Cell::new(false);
|
||||
let mut encountered: u64 = 0;
|
||||
|
||||
let walker = WalkDir::new(root)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_entry(|entry| {
|
||||
// 根自身永远放行:否则根的名字恰好命中清单时整棵树都没了
|
||||
if entry.depth() == 0 {
|
||||
return true;
|
||||
}
|
||||
if entry.file_type().is_dir() {
|
||||
let name = entry.file_name().to_string_lossy().to_lowercase();
|
||||
if skip.contains(&name) {
|
||||
skipped.set(skipped.get() + 1);
|
||||
return false; // 既不产出该目录,也不再下钻
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
|
||||
for entry in walker {
|
||||
if truncated.get() {
|
||||
break;
|
||||
}
|
||||
let Ok(entry) = entry else { continue };
|
||||
// 根自身不作为条目
|
||||
if entry.depth() == 0 {
|
||||
continue;
|
||||
}
|
||||
encountered += 1;
|
||||
// 每 512 个条目报一次(真正的节流由命令层按时间做,见 `diff_compare_dirs`)
|
||||
if encountered % 512 == 0 {
|
||||
progress(ScanPhase::Walk, encountered, 0);
|
||||
}
|
||||
if files.len() >= MAX_ENTRIES {
|
||||
truncated.set(true);
|
||||
break;
|
||||
}
|
||||
|
||||
let is_dir = entry.file_type().is_dir();
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
let Ok(meta) = entry.metadata() else { continue };
|
||||
let rel = entry
|
||||
.path()
|
||||
.strip_prefix(root)
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_else(|_| name.clone());
|
||||
|
||||
files.insert(
|
||||
rel,
|
||||
NodeInfo {
|
||||
is_dir,
|
||||
size: if is_dir { 0 } else { meta.len() },
|
||||
modified: meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0),
|
||||
path: display_path(entry.path()),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// 收尾再报一次:让「最后一截」不被 512 的步长吞掉
|
||||
progress(ScanPhase::Walk, encountered, 0);
|
||||
|
||||
Collected {
|
||||
files,
|
||||
skipped_dirs: skipped.get(),
|
||||
truncated: truncated.get(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 两个文件的内容是否逐字节相同(只在「大小相同、时间戳不同」时才调用)。
|
||||
///
|
||||
/// 分块比较而不是把两个文件整体读进内存:单文件上限 [`MAX_CONTENT_BYTES`](4MB),
|
||||
/// 整体读要一次性占两块 4MB;分块读的峰值只有缓冲区大小,遇到首个差异就能立刻返回。
|
||||
fn same_content(left: &Path, right: &Path) -> Result<bool, std::io::Error> {
|
||||
let mut a = std::io::BufReader::new(std::fs::File::open(left)?);
|
||||
let mut b = std::io::BufReader::new(std::fs::File::open(right)?);
|
||||
let mut buf_a = [0u8; 64 * 1024];
|
||||
let mut buf_b = [0u8; 64 * 1024];
|
||||
loop {
|
||||
let n = read_full(&mut a, &mut buf_a)?;
|
||||
let m = read_full(&mut b, &mut buf_b)?;
|
||||
// 长度不同(含「一个先到 EOF」)即判不同
|
||||
if n != m || buf_a[..n] != buf_b[..m] {
|
||||
return Ok(false);
|
||||
}
|
||||
if n == 0 {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 把缓冲区读到满(除非到达 EOF)。
|
||||
///
|
||||
/// `Read::read` 允许短读,直接拿短读的字节数比较会误判「不同」,因此这里循环到读满。
|
||||
fn read_full(reader: &mut impl std::io::Read, buf: &mut [u8]) -> Result<usize, std::io::Error> {
|
||||
let mut filled = 0;
|
||||
while filled < buf.len() {
|
||||
let n = reader.read(&mut buf[filled..])?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
filled += n;
|
||||
}
|
||||
Ok(filled)
|
||||
}
|
||||
|
||||
/// 对比两棵目录树。
|
||||
///
|
||||
/// `skip_dirs` 由前端给出(大小写不敏感、按目录名匹配):默认清单是**界面约定**而不是
|
||||
/// 后端常量 —— 用户能不能改这份清单是 UI 的事,后端只负责按它执行(同 `editor::grep`
|
||||
/// 把默认清单留在前端的取舍)。
|
||||
///
|
||||
/// `progress` 是进度回调(阶段, 已完成, 总数):本函数只负责在关键节点调用它,
|
||||
/// 事件名 / 节流 / 发给谁都在命令层决定(见 `super::commands`)。
|
||||
pub fn compare_dirs(
|
||||
left: &str,
|
||||
right: &str,
|
||||
skip_dirs: &[String],
|
||||
compare_content: bool,
|
||||
progress: &mut dyn FnMut(ScanPhase, u64, u64),
|
||||
) -> Result<DirDiffReport, String> {
|
||||
let started = Instant::now();
|
||||
let left_root = resolve_root(left, "左侧")?;
|
||||
let right_root = resolve_root(right, "右侧")?;
|
||||
|
||||
// 跳过清单归一成集合:命中的目录要在剪枝判定里按名做 O(1) 查表(清单有十几项、
|
||||
// 目录数可达上万,逐个线性比对不值得)
|
||||
let skip: HashSet<String> = skip_dirs
|
||||
.iter()
|
||||
.map(|s| s.trim().to_lowercase())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
|
||||
let l = collect(&left_root, &skip, &mut *progress);
|
||||
let r = collect(&right_root, &skip, &mut *progress);
|
||||
|
||||
// 两侧相对路径的并集,排序后输出(顺序稳定,前端组装树的观感才稳定)
|
||||
let mut keys: Vec<&String> = l.files.keys().chain(r.files.keys()).collect();
|
||||
keys.sort();
|
||||
keys.dedup();
|
||||
|
||||
let mut entries: Vec<DirDiffEntry> = Vec::with_capacity(keys.len());
|
||||
let mut content_budget = MAX_CONTENT_COMPARES;
|
||||
let mut compared: u64 = 0;
|
||||
|
||||
for key in keys {
|
||||
let left_node = l.files.get(key);
|
||||
let right_node = r.files.get(key);
|
||||
|
||||
let is_dir = left_node.map(|n| n.is_dir).unwrap_or(false)
|
||||
|| right_node.map(|n| n.is_dir).unwrap_or(false);
|
||||
|
||||
let mut content_compared = false;
|
||||
let status: &str = match (left_node, right_node) {
|
||||
(Some(_), None) => "left-only",
|
||||
(None, Some(_)) => "right-only",
|
||||
(Some(a), Some(b)) => {
|
||||
if a.is_dir != b.is_dir {
|
||||
// 同名但一侧是文件、另一侧是目录:无法比较内容,单独归类
|
||||
"type-mismatch"
|
||||
} else if a.is_dir {
|
||||
// 目录本身没有内容,是否「相同」由它的子条目决定;前端按子树判断
|
||||
"identical"
|
||||
} else if a.size != b.size {
|
||||
"different"
|
||||
} else if a.size == 0 {
|
||||
// 两侧都是空文件(上面的 size 不等已排除「单侧为空」):内容必然相同。
|
||||
// 不单独判的话会掉进最后的兜底,按时间戳把两个空文件报成「不同」
|
||||
"identical"
|
||||
} else if a.modified == b.modified {
|
||||
"identical"
|
||||
} else if compare_content && content_budget > 0 && a.size <= MAX_CONTENT_BYTES {
|
||||
content_budget -= 1;
|
||||
content_compared = true;
|
||||
compared += 1;
|
||||
// 核对阶段是最慢的一段(每处都要读两个文件),进度最有价值
|
||||
progress(ScanPhase::Compare, compared, MAX_CONTENT_COMPARES as u64);
|
||||
match same_content(Path::new(&a.path), Path::new(&b.path)) {
|
||||
Ok(true) => "identical",
|
||||
Ok(false) => "different",
|
||||
// 读失败(权限 / 竞态删除):按时间戳判定,不把错误伪装成结论
|
||||
Err(_) => "different",
|
||||
}
|
||||
} else {
|
||||
// 体积超限 / 预算用尽:按时间戳判定,标记未比对内容
|
||||
"different"
|
||||
}
|
||||
}
|
||||
(None, None) => unreachable!("key 来自两侧键的并集"),
|
||||
};
|
||||
|
||||
entries.push(DirDiffEntry {
|
||||
rel_path: key.clone(),
|
||||
is_dir,
|
||||
status: status.to_string(),
|
||||
left_path: left_node.map(|n| n.path.clone()).unwrap_or_default(),
|
||||
right_path: right_node.map(|n| n.path.clone()).unwrap_or_default(),
|
||||
left_size: left_node.map(|n| n.size).unwrap_or(0),
|
||||
right_size: right_node.map(|n| n.size).unwrap_or(0),
|
||||
left_modified: left_node.map(|n| n.modified).unwrap_or(0),
|
||||
right_modified: right_node.map(|n| n.modified).unwrap_or(0),
|
||||
content_compared,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(DirDiffReport {
|
||||
left_root: display_path(&left_root),
|
||||
right_root: display_path(&right_root),
|
||||
entries,
|
||||
truncated: l.truncated || r.truncated,
|
||||
skipped_dirs: l.skipped_dirs + r.skipped_dirs,
|
||||
elapsed_ms: started.elapsed().as_millis() as u64,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! 对比模块的数据模型(回传前端的 DTO)。
|
||||
//!
|
||||
//! 与前端 `src/modules/diff/types.ts` 一一对应;新增字段两侧都要改。
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::fs::Metadata;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::editor::files::{display_path, FileDoc};
|
||||
|
||||
/// 设置结构版本号。字段增减时递增,由 [`DiffSettings::heal`] 推进。
|
||||
pub const DIFF_SETTINGS_VERSION: u32 = 1;
|
||||
|
||||
/// 对比模块设置(持久化到 `{app_data_dir}/diff/settings.json`,范式同 editor / translate)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct DiffSettings {
|
||||
pub version: u32,
|
||||
/// 全局快捷键:打开 / 唤出对比窗口(空串 = 不注册)。
|
||||
///
|
||||
/// 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译 / 编辑器同一套);触发时只发
|
||||
/// `diff-open-window` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
|
||||
pub open_diff_shortcut: String,
|
||||
/// 目录对比:默认是否比对内容(大小相同、时间戳不同时读文件逐字节比对)
|
||||
pub compare_content: bool,
|
||||
/// 目录对比:默认是否跳过常见构建目录
|
||||
pub skip_build_dirs: bool,
|
||||
}
|
||||
|
||||
impl Default for DiffSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: DIFF_SETTINGS_VERSION,
|
||||
open_diff_shortcut: "Alt+C".to_string(),
|
||||
compare_content: true,
|
||||
skip_build_dirs: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DiffSettings {
|
||||
/// 自愈:推进版本号(并在首次遇到旧配置时补上默认快捷键)。返回是否发生了变化。
|
||||
///
|
||||
/// 刻意**不**把空的 `open_diff_shortcut` 补回默认:空串是「用户主动清空快捷键」的
|
||||
/// 合法表达,快捷键被静默改回来比不生效更让人困惑。只有版本号为 0(从未写过这份
|
||||
/// 配置)时才补一次 Alt+C。
|
||||
pub fn heal(&mut self) -> bool {
|
||||
if self.version >= DIFF_SETTINGS_VERSION {
|
||||
return false;
|
||||
}
|
||||
if self.version == 0 && self.open_diff_shortcut.is_empty() {
|
||||
self.open_diff_shortcut = "Alt+C".to_string();
|
||||
}
|
||||
self.version = DIFF_SETTINGS_VERSION;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// 对比窗口里**一侧**文件的状态。
|
||||
///
|
||||
/// 刻意不复用 `FileDoc`:对比窗口需要额外的 `binary` 标记(二进制文件不进入文本
|
||||
/// diff,只报「不同」),而 `FileDoc` 是编辑器模块的对外契约,为对比工具加字段会
|
||||
/// 把「谁需要什么」搅在一起。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiffFileDoc {
|
||||
/// 绝对路径(Windows 下已剥掉 `\\?\` 前缀)
|
||||
pub path: String,
|
||||
/// 显示名(文件名)
|
||||
pub name: String,
|
||||
/// 文本内容(换行已统一为 `\n`,写回时按 `eol` 还原)。二进制文件为空串
|
||||
pub content: String,
|
||||
/// 探测到的编码(`utf-8` / `utf-8-bom` / `gbk` / …)。二进制文件为空串
|
||||
pub encoding: String,
|
||||
/// 换行风格:"lf" | "crlf"。二进制文件为空串
|
||||
pub eol: String,
|
||||
/// 文件字节数
|
||||
pub size: u64,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 行数(二进制文件为 0)
|
||||
pub lines: u64,
|
||||
/// 是否超过「大文件」阈值(前端据此关掉折叠等高开销特性)
|
||||
pub large: bool,
|
||||
/// 是否只读(写权限探测失败)
|
||||
pub readonly: bool,
|
||||
/// 是否为二进制(头部含 NUL 字节):此类文件不渲染 diff
|
||||
pub binary: bool,
|
||||
}
|
||||
|
||||
impl DiffFileDoc {
|
||||
/// 由编辑器的读取结果构造(文本文件路径)。
|
||||
pub fn from_file_doc(doc: FileDoc) -> Self {
|
||||
Self {
|
||||
path: doc.path,
|
||||
name: doc.name,
|
||||
content: doc.content,
|
||||
encoding: doc.encoding,
|
||||
eol: doc.eol,
|
||||
size: doc.size,
|
||||
modified: doc.modified,
|
||||
lines: doc.lines,
|
||||
large: doc.large,
|
||||
readonly: doc.readonly,
|
||||
binary: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 二进制文件:**不读内容**(避免把无意义的字节解码成一大段乱码再走 IPC)。
|
||||
pub fn binary_of(path: &Path, meta: &Metadata, readonly: bool) -> Self {
|
||||
Self {
|
||||
path: display_path(path),
|
||||
name: path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
content: String::new(),
|
||||
encoding: String::new(),
|
||||
eol: String::new(),
|
||||
size: meta.len(),
|
||||
modified: meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0),
|
||||
lines: 0,
|
||||
large: false,
|
||||
readonly,
|
||||
binary: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 遍历时一侧的一个条目(**内部结构**,不回传前端)。
|
||||
pub struct NodeInfo {
|
||||
pub is_dir: bool,
|
||||
/// 目录为 0
|
||||
pub size: u64,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 绝对路径(回传前端用于「下钻到文件对比」)
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// 目录对比中的一个条目(扁平列表,由前端组装成树)。
|
||||
///
|
||||
/// `status` 取值:`left-only` / `right-only` / `different` / `identical` / `type-mismatch`
|
||||
/// (同名但一侧是文件、另一侧是目录)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DirDiffEntry {
|
||||
/// 相对根的路径,`/` 分隔(前端据此组装树,显示名自己从最后一段取)
|
||||
pub rel_path: String,
|
||||
/// 是否目录(type-mismatch 时为 true)
|
||||
pub is_dir: bool,
|
||||
pub status: String,
|
||||
/// 该侧的绝对路径;该侧不存在时为空串
|
||||
pub left_path: String,
|
||||
pub right_path: String,
|
||||
/// 该侧字节数;不存在为 0
|
||||
pub left_size: u64,
|
||||
pub right_size: u64,
|
||||
/// 该侧最后修改时间(Unix 毫秒);不存在为 0
|
||||
pub left_modified: u64,
|
||||
pub right_modified: u64,
|
||||
/// 结论是否**由内容逐字节比对**得出。
|
||||
///
|
||||
/// false 表示「大小相同、时间戳不同」且未读内容(体积超限 / 预算用尽),
|
||||
/// 此时 `different` 是**按时间戳**判定的 —— 界面要据此提示,不能与已确认的差异
|
||||
/// 用同一种语气呈现。
|
||||
pub content_compared: bool,
|
||||
}
|
||||
|
||||
/// 目录对比的扫描进度(**事件负载**,不是命令返回值)。
|
||||
///
|
||||
/// 前端按 `scan_id` 过滤:进度事件是全局的(Rust 不区分选项卡),多选项卡并发扫描时
|
||||
/// 只有属于本轮的那一份进度才该被采用。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiffScanProgress {
|
||||
/// 本轮扫描的标识(前端生成,随命令传入并原样回传)
|
||||
pub scan_id: u64,
|
||||
/// `scan` = 正在遍历目录;`compare` = 正在读内容逐字节核对
|
||||
pub phase: String,
|
||||
/// 已完成数(遍历 = 已过的条目数;核对 = 已比对的文件数)
|
||||
pub done: u64,
|
||||
/// 总数(遍历阶段无从预知,为 0;核对阶段为预算上限)
|
||||
pub total: u64,
|
||||
}
|
||||
|
||||
/// 一次目录对比的结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DirDiffReport {
|
||||
pub left_root: String,
|
||||
pub right_root: String,
|
||||
pub entries: Vec<DirDiffEntry>,
|
||||
/// 条目数达到上限、遍历被截断(界面提示用户缩小范围)
|
||||
pub truncated: bool,
|
||||
/// 按跳过清单略过的目录数
|
||||
pub skipped_dirs: u32,
|
||||
/// 扫描耗时(毫秒;状态栏显示)
|
||||
pub elapsed_ms: u64,
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
//! 子窗口拖放「补注入」(仅 Windows 真正生效,其它平台是 no-op)。
|
||||
//!
|
||||
//! # 为什么需要这个模块
|
||||
//!
|
||||
//! wry 只在**创建 webview 的那一刻**枚举一次子窗口、给它们注入 OLE drop target
|
||||
//! (见 wry `webview2/drag_drop.rs` 的 `DragDropController::new` 里那句
|
||||
//! `EnumChildWindows`)。而 WebView2 的 `Chrome_WidgetWin_1` /
|
||||
//! `Chrome_RenderWidgetHostHWND` 是**异步惰性创建**的:
|
||||
//!
|
||||
//! - 由 `tauri.conf.json` 在 setup 阶段创建的主窗口 —— 注入时这些子窗口已存在,正常;
|
||||
//! - 运行时经 IPC 创建的窗口(编辑器 / 对比,`new WebviewWindow`)—— 注入时子窗口
|
||||
//! 还没生出来,于是它们**永远没有 drop target**。表现就是:拖文件进去光标变成禁止
|
||||
//! 符号,Tauri 原生拖放事件与 HTML5 `drop` 都不触发(实测两个窗口的 Win32 样式完全
|
||||
//! 一致,差别只在 `OleDropTargetInterface` 落在哪些子窗口上)。
|
||||
//!
|
||||
//! # 做法
|
||||
//!
|
||||
//! 窗口创建后延迟重试,等 WebView2 子窗口出现,再照 wry 的同一手法
|
||||
//! (`RevokeDragDrop` + `RegisterDragDrop`)给**顶层窗口及其全部后代**补注入自己的
|
||||
//! `IDropTarget`;收到拖放后按 Tauri 原生拖放事件**同样的名字与载荷**发出
|
||||
//! `tauri://drag-enter|over|drop|leave` —— 前端 `onDragDropEvent` 无需任何改动。
|
||||
//!
|
||||
//! **通用**:只对显式传入 label 的窗口生效,调用方传自己的窗口 label(目前是
|
||||
//! 编辑器窗口与对比窗口),不碰主窗口。
|
||||
|
||||
use tauri::AppHandle;
|
||||
|
||||
/// 给指定窗口补注入拖放支持(Windows 专用;其它平台直接返回 `Ok`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn window_attach_drag_drop(app: AppHandle, label: String) -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
imp::spawn_attach(app, label);
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = (app, label);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::sync::{mpsc, Mutex, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use tauri::{AppHandle, Emitter, EventTarget, Manager};
|
||||
use windows62::core::{implement, Ref, BOOL};
|
||||
use windows62::Win32::Foundation::{HWND, LPARAM, POINT, POINTL};
|
||||
use windows62::Win32::Graphics::Gdi::ScreenToClient;
|
||||
use windows62::Win32::System::Com::{IDataObject, DVASPECT_CONTENT, FORMATETC, TYMED_HGLOBAL};
|
||||
use windows62::Win32::System::Ole::{
|
||||
IDropTarget, IDropTarget_Impl, RegisterDragDrop, RevokeDragDrop, CF_HDROP, DROPEFFECT,
|
||||
DROPEFFECT_COPY, DROPEFFECT_NONE,
|
||||
};
|
||||
use windows62::Win32::System::SystemServices::MODIFIERKEYS_FLAGS;
|
||||
use windows62::Win32::UI::Shell::{DragFinish, DragQueryFileW, HDROP};
|
||||
use windows62::Win32::UI::WindowsAndMessaging::{EnumChildWindows, GetClassNameW};
|
||||
|
||||
/// 重试节奏:WebView2 的渲染子窗口在窗口显示后才陆续出现,前几秒足以覆盖。
|
||||
const RETRY_INTERVAL: Duration = Duration::from_millis(400);
|
||||
/// 重试次数上限(400ms × 24 ≈ 10s,与前端窗口冷启动量级一致)。
|
||||
const MAX_RETRY: u32 = 24;
|
||||
|
||||
/// 已注入的 drop target 集合。
|
||||
///
|
||||
/// `RegisterDragDrop` 只保存裸指针,**对象必须由我们保持存活**(同 wry 的
|
||||
/// `DragDropController::drop_targets`)。接口对象是 STA 私有的、实际只在主线程
|
||||
/// 访问,这里标 `Send`/`Sync` 仅为能放进全局表。
|
||||
/// 字段本身从不读取:它的唯一作用是**持有引用**,让 `RegisterDragDrop`
|
||||
/// 存下的裸指针在窗口存活期间始终有效。
|
||||
struct TargetSet(#[allow(dead_code)] Vec<IDropTarget>);
|
||||
unsafe impl Send for TargetSet {}
|
||||
unsafe impl Sync for TargetSet {}
|
||||
|
||||
static INJECTED: OnceLock<Mutex<HashMap<String, TargetSet>>> = OnceLock::new();
|
||||
|
||||
fn injected() -> &'static Mutex<HashMap<String, TargetSet>> {
|
||||
INJECTED.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
// EnumChildWindows 的回调只带 LPARAM,用线程局部变量收集最省事(回调同步执行)。
|
||||
thread_local! {
|
||||
static FOUND: RefCell<Vec<HWND>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
unsafe extern "system" fn collect_child(hwnd: HWND, _lparam: LPARAM) -> BOOL {
|
||||
FOUND.with(|v| v.borrow_mut().push(hwnd));
|
||||
BOOL(1)
|
||||
}
|
||||
|
||||
/// 顶层窗口 + 全部后代(WebView2 的 `Chrome_*`、`WRY_WEBVIEW` 等都在其中)。
|
||||
fn window_and_descendants(hwnd: HWND) -> Vec<HWND> {
|
||||
FOUND.with(|v| v.borrow_mut().clear());
|
||||
let _ = unsafe { EnumChildWindows(Some(hwnd), Some(collect_child), LPARAM(0)) };
|
||||
let descendants: Vec<HWND> = FOUND.with(|v| v.borrow().clone());
|
||||
let mut all = Vec::with_capacity(descendants.len() + 1);
|
||||
all.push(hwnd);
|
||||
all.extend(descendants);
|
||||
all
|
||||
}
|
||||
|
||||
fn class_name(hwnd: HWND) -> String {
|
||||
let mut buf = [0u16; 128];
|
||||
let len = unsafe { GetClassNameW(hwnd, &mut buf) }.max(0) as usize;
|
||||
OsString::from_wide(&buf[..len.min(buf.len())])
|
||||
.to_string_lossy()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// 是否已经出现 WebView2 的**渲染**子窗口。
|
||||
///
|
||||
/// 判据用 `Chrome_RenderWidgetHostHWND`(Chromium 最后创建的那个),而不是
|
||||
/// 「任意 `Chrome_*`」——`Chrome_WidgetWin_0` 出现得更早,用它当"就绪"会过早
|
||||
/// 停止重试,导致真正的落点(RenderWidget)没有 drop target。
|
||||
fn has_render_host(hwnds: &[HWND]) -> bool {
|
||||
hwnds
|
||||
.iter()
|
||||
.any(|h| class_name(*h).contains("RenderWidgetHost"))
|
||||
}
|
||||
|
||||
#[implement(IDropTarget)]
|
||||
struct WindowDropTarget {
|
||||
hwnd: HWND,
|
||||
app: AppHandle,
|
||||
label: String,
|
||||
cursor_effect: Cell<DROPEFFECT>,
|
||||
enter_valid: Cell<bool>,
|
||||
}
|
||||
|
||||
impl WindowDropTarget {
|
||||
fn emit(&self, event: &str, payload: serde_json::Value) {
|
||||
if let Err(e) = self.app.emit_to(
|
||||
EventTarget::AnyLabel {
|
||||
label: self.label.clone(),
|
||||
},
|
||||
event,
|
||||
payload,
|
||||
) {
|
||||
crate::logger::log_warn("drag-drop", &format!("发送拖放事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 从 `IDataObject` 取 CF_HDROP 里的文件路径。
|
||||
///
|
||||
/// 同时把 `HDROP` 交回调用方:**只能在 `Drop` 里 `DragFinish`**,
|
||||
/// `DragEnter`/`DragOver` 阶段释放会让后续拿不到数据。
|
||||
unsafe fn collect_paths(data: Ref<'_, IDataObject>) -> Option<(HDROP, Vec<String>)> {
|
||||
let format = FORMATETC {
|
||||
cfFormat: CF_HDROP.0,
|
||||
ptd: std::ptr::null_mut(),
|
||||
dwAspect: DVASPECT_CONTENT.0,
|
||||
lindex: -1,
|
||||
tymed: TYMED_HGLOBAL.0 as u32,
|
||||
};
|
||||
let medium = data.as_ref()?.GetData(&format).ok()?;
|
||||
let hdrop = HDROP(medium.u.hGlobal.0 as _);
|
||||
let count = DragQueryFileW(hdrop, u32::MAX, None);
|
||||
let mut paths = Vec::with_capacity(count as usize);
|
||||
for index in 0..count {
|
||||
let len = DragQueryFileW(hdrop, index, None) as usize;
|
||||
let mut buf = vec![0u16; len + 1];
|
||||
DragQueryFileW(hdrop, index, Some(&mut buf));
|
||||
paths.push(OsString::from_wide(&buf[..len]).to_string_lossy().to_string());
|
||||
}
|
||||
Some((hdrop, paths))
|
||||
}
|
||||
|
||||
/// 屏幕坐标 → 客户区坐标(与 wry 一致,前端拿到的是相对 webview 的位置)。
|
||||
fn client_pos(&self, point: &POINTL) -> (i32, i32) {
|
||||
let mut pt = POINT {
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
};
|
||||
let _ = unsafe { ScreenToClient(self.hwnd, &mut pt) };
|
||||
(pt.x, pt.y)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
impl IDropTarget_Impl for WindowDropTarget_Impl {
|
||||
fn DragEnter(
|
||||
&self,
|
||||
pDataObj: Ref<'_, IDataObject>,
|
||||
_grfKeyState: MODIFIERKEYS_FLAGS,
|
||||
pt: &POINTL,
|
||||
pdwEffect: *mut DROPEFFECT,
|
||||
) -> windows62::core::Result<()> {
|
||||
let (x, y) = self.client_pos(pt);
|
||||
let found = unsafe { WindowDropTarget::collect_paths(pDataObj) };
|
||||
let valid = found.is_some();
|
||||
self.enter_valid.set(valid);
|
||||
|
||||
if let Some((_hdrop, paths)) = found {
|
||||
self.emit(
|
||||
"tauri://drag-enter",
|
||||
serde_json::json!({ "paths": paths, "position": { "x": x, "y": y } }),
|
||||
);
|
||||
}
|
||||
|
||||
let effect = if valid { DROPEFFECT_COPY } else { DROPEFFECT_NONE };
|
||||
unsafe { *pdwEffect = effect };
|
||||
self.cursor_effect.set(effect);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn DragOver(
|
||||
&self,
|
||||
_grfKeyState: MODIFIERKEYS_FLAGS,
|
||||
pt: &POINTL,
|
||||
pdwEffect: *mut DROPEFFECT,
|
||||
) -> windows62::core::Result<()> {
|
||||
if self.enter_valid.get() {
|
||||
let (x, y) = self.client_pos(pt);
|
||||
self.emit(
|
||||
"tauri://drag-over",
|
||||
serde_json::json!({ "position": { "x": x, "y": y } }),
|
||||
);
|
||||
}
|
||||
unsafe { *pdwEffect = self.cursor_effect.get() };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn DragLeave(&self) -> windows62::core::Result<()> {
|
||||
if self.enter_valid.get() {
|
||||
self.emit("tauri://drag-leave", serde_json::json!(null));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn Drop(
|
||||
&self,
|
||||
pDataObj: Ref<'_, IDataObject>,
|
||||
_grfKeyState: MODIFIERKEYS_FLAGS,
|
||||
pt: &POINTL,
|
||||
pdwEffect: *mut DROPEFFECT,
|
||||
) -> windows62::core::Result<()> {
|
||||
if self.enter_valid.get() {
|
||||
let (x, y) = self.client_pos(pt);
|
||||
if let Some((hdrop, paths)) = unsafe { WindowDropTarget::collect_paths(pDataObj) } {
|
||||
self.emit(
|
||||
"tauri://drag-drop",
|
||||
serde_json::json!({ "paths": paths, "position": { "x": x, "y": y } }),
|
||||
);
|
||||
unsafe { DragFinish(hdrop) };
|
||||
}
|
||||
}
|
||||
unsafe { *pdwEffect = DROPEFFECT_COPY };
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 在**主线程**给该窗口补注入(OLE/COM 必须在初始化过 OLE 的线程上操作)。
|
||||
/// 返回 true 表示 WebView2 子窗口已就位,后续无需再扫。
|
||||
fn inject_now(app: &AppHandle, label: &str) -> bool {
|
||||
let Some(window) = app.get_webview_window(label) else {
|
||||
crate::logger::log_warn("drag-drop", &format!("补注入:找不到窗口 {label}"));
|
||||
return true;
|
||||
};
|
||||
let Ok(hwnd) = window.hwnd() else {
|
||||
crate::logger::log_warn("drag-drop", &format!("补注入:取不到 hwnd({label})"));
|
||||
return false;
|
||||
};
|
||||
|
||||
let all = window_and_descendants(hwnd);
|
||||
let ready = has_render_host(&all);
|
||||
|
||||
let mut targets = Vec::with_capacity(all.len());
|
||||
let mut ok = 0usize;
|
||||
let mut failed = 0usize;
|
||||
for child in all {
|
||||
let target: IDropTarget = WindowDropTarget {
|
||||
hwnd: child,
|
||||
app: app.clone(),
|
||||
label: label.to_string(),
|
||||
cursor_effect: Cell::new(DROPEFFECT_NONE),
|
||||
enter_valid: Cell::new(false),
|
||||
}
|
||||
.into();
|
||||
// 与 wry 同一手法:先撤销(把它早期注入的空壳换掉),再注册自己的
|
||||
let _ = unsafe { RevokeDragDrop(child) };
|
||||
match unsafe { RegisterDragDrop(child, &target) } {
|
||||
Ok(()) => {
|
||||
ok += 1;
|
||||
targets.push(target);
|
||||
}
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!(
|
||||
"补注入:RegisterDragDrop 失败 class={} err={e}",
|
||||
class_name(child)
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("补注入:{label} 后代={} 成功={ok} 失败={failed} ready={ready}", targets.len() + failed),
|
||||
);
|
||||
|
||||
if let Ok(mut map) = injected().lock() {
|
||||
map.insert(label.to_string(), TargetSet(targets));
|
||||
}
|
||||
|
||||
ready
|
||||
}
|
||||
|
||||
/// 后台线程:等到窗口与子窗口都就位后注入;窗口提前关闭则放弃。
|
||||
pub fn spawn_attach(app: AppHandle, label: String) {
|
||||
crate::logger::log_info("drag-drop", &format!("补注入:收到请求 label={label}"));
|
||||
std::thread::spawn(move || {
|
||||
for _ in 0..MAX_RETRY {
|
||||
std::thread::sleep(RETRY_INTERVAL);
|
||||
|
||||
if app.get_webview_window(&label).is_none() {
|
||||
crate::logger::log_info("drag-drop", &format!("补注入:窗口已关闭,放弃 {label}"));
|
||||
if let Ok(mut map) = injected().lock() {
|
||||
map.remove(&label);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let (tx, rx) = mpsc::channel::<bool>();
|
||||
let app_main = app.clone();
|
||||
let label_main = label.clone();
|
||||
if let Err(e) = app.run_on_main_thread(move || {
|
||||
let _ = tx.send(inject_now(&app_main, &label_main));
|
||||
}) {
|
||||
crate::logger::log_warn("drag-drop", &format!("补注入:run_on_main_thread 失败 {e}"));
|
||||
return;
|
||||
}
|
||||
|
||||
// 主线程执行完再决定是否继续(超时按"未就绪"处理)
|
||||
if matches!(rx.recv_timeout(Duration::from_secs(2)), Ok(true)) {
|
||||
crate::logger::log_info("drag-drop", &format!("拖放补注入完成:{label}"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
crate::logger::log_warn("drag-drop", &format!("拖放补注入未完成(子窗口未就位):{label}"));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -210,12 +210,19 @@ impl DshManager {
|
||||
.clone()
|
||||
.ok_or_else(|| "未找到 npm(Node 分发中缺少 npm-cli.js)".to_string())?;
|
||||
|
||||
// 未指定版本时必须显式写成 `@latest`,**不能**只给裸包名:
|
||||
// npm 对「裸包名且该包已存在于 prefix 下的 package.json」的语义是
|
||||
// 「安装满足现有 range 的最新版」,而首次安装时 npm 自己写下的
|
||||
// `@deepseek-ai/dsh: ^0.1.7-rc.2` 一旦遇到 0.2.x 就永远不满足,
|
||||
// 于是 `npm install @deepseek-ai/dsh` 只会回一句 "up to date",
|
||||
// 版本原地不动(这正是「更新到最新」点了没反应的根因)。
|
||||
// 显式 tag/版本会覆盖 package.json 里的旧 range,npm 才会真正升级。
|
||||
let spec = version
|
||||
.as_deref()
|
||||
.map(|v| v.trim())
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(|v| format!("{DSH_PACKAGE}@{v}"))
|
||||
.unwrap_or_else(|| DSH_PACKAGE.to_string());
|
||||
.unwrap_or_else(|| format!("{DSH_PACKAGE}@latest"));
|
||||
|
||||
let install_dir = self.install_root();
|
||||
// npm 的 prefix 目录不存在时由 npm 自己创建;这里先建一次,避免
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
//! 「用 Thing 打开」的参数解析与事件投递。
|
||||
//!
|
||||
//! # 两条入口,同一份逻辑
|
||||
//!
|
||||
//! 1. **冷启动**:安装器注册的文件关联让 Windows 用 `thing.exe <文件路径>` 启动本应用;
|
||||
//! 资源管理器右键菜单(`HKCU\...\shell\ThingEditor`)同样以参数形式传入文件/文件夹;
|
||||
//! 2. **热启动**:应用已在运行时再次打开,会起第二个进程,由
|
||||
//! `tauri-plugin-single-instance` 把它的命令行参数转交给第一个实例。
|
||||
//!
|
||||
//! 两条路径的输入形态完全一样(都是命令行参数),因此共用 [`open_target_from_args`]。
|
||||
//! 解析成功后统一发事件(文件走 `editor-open-file`、文件夹走 `editor-open-folder`),
|
||||
//! **窗口由前端创建** —— Rust 侧不持有窗口 label 策略。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
/// 一个待打开目标(文件或文件夹)。
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum OpenTarget {
|
||||
File(PathBuf),
|
||||
/// 文件夹:由编辑器「本地目录」面板承载
|
||||
Folder(PathBuf),
|
||||
}
|
||||
|
||||
impl OpenTarget {
|
||||
pub fn path(&self) -> &Path {
|
||||
match self {
|
||||
Self::File(p) | Self::Folder(p) => p,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
Self::File(_) => "file",
|
||||
Self::Folder(_) => "folder",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 回传给前端的待打开目标。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OpenTargetPayload {
|
||||
/// 绝对路径
|
||||
pub path: String,
|
||||
/// `"file"` | `"folder"`
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
impl From<&OpenTarget> for OpenTargetPayload {
|
||||
fn from(target: &OpenTarget) -> Self {
|
||||
Self {
|
||||
path: target.path().to_string_lossy().to_string(),
|
||||
kind: target.kind().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 「启动时命令行指定的目标」缓存。
|
||||
///
|
||||
/// # 为什么需要缓存而不是启动时直接 `emit`
|
||||
///
|
||||
/// 冷启动的顺序是:`setup` 跑完 → 创建主窗口 → WebView 加载前端 → 前端注册监听。
|
||||
/// 在 `setup` 里 `emit` 时前端还没开始监听,事件**直接丢掉**了 —— 表现是
|
||||
/// 「双击 .md 打开了应用,但笔记没打开」。
|
||||
///
|
||||
/// 因此这里把目标存下来,由前端在注册完监听后**主动取一次**
|
||||
/// (`editor_take_pending_file`)。取走即清空,避免下次打开窗口时又被翻出来。
|
||||
static PENDING: std::sync::OnceLock<Mutex<Option<OpenTarget>>> = std::sync::OnceLock::new();
|
||||
|
||||
fn pending_slot() -> &'static Mutex<Option<OpenTarget>> {
|
||||
PENDING.get_or_init(|| Mutex::new(None))
|
||||
}
|
||||
|
||||
/// 记下「启动时想打开的目标」(由 `setup` 调用)。
|
||||
pub fn remember_pending_target(target: OpenTarget) {
|
||||
if let Ok(mut slot) = pending_slot().lock() {
|
||||
*slot = Some(target);
|
||||
}
|
||||
}
|
||||
|
||||
/// 取出并清空待打开目标(由 `editor_take_pending_file` 命令调用)。
|
||||
pub fn take_pending_target() -> Option<OpenTargetPayload> {
|
||||
pending_slot()
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut slot| slot.take())
|
||||
.map(|target| OpenTargetPayload::from(&target))
|
||||
}
|
||||
|
||||
/// 从一组命令行参数里挑出「看起来是要打开的路径」。
|
||||
///
|
||||
/// 只认「**存在**的路径」,其余一律忽略 —— 宁可漏开一个窗口,也不要因为一个开关
|
||||
/// 参数把主窗口的启动逻辑搞乱。目录优先(右键文件夹的场景)。
|
||||
pub fn open_target_from_args<I: IntoIterator<Item = String>>(args: I) -> Option<OpenTarget> {
|
||||
for arg in args {
|
||||
let trimmed = arg.trim().trim_matches('"');
|
||||
if trimmed.is_empty() || trimmed.starts_with('-') {
|
||||
continue;
|
||||
}
|
||||
let path = PathBuf::from(trimmed);
|
||||
if path.is_dir() {
|
||||
return Some(OpenTarget::Folder(path));
|
||||
}
|
||||
if path.is_file() {
|
||||
return Some(OpenTarget::File(path));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 从一组命令行参数里挑出「看起来是笔记文件」的那个路径(仅 `.md`/`.markdown`/`.mdx`)。
|
||||
///
|
||||
/// 实际启动路径用的是 [`open_target_from_args`](接受任意文件与文件夹,以支持资源
|
||||
/// 管理器右键菜单);这个更严格的入口现在**只服务于单测**,故仅测试构建时编译。
|
||||
#[cfg(test)]
|
||||
pub fn note_path_from_args<I: IntoIterator<Item = String>>(args: I) -> Option<PathBuf> {
|
||||
for arg in args {
|
||||
let trimmed = arg.trim().trim_matches('"');
|
||||
if trimmed.is_empty() || trimmed.starts_with('-') {
|
||||
continue;
|
||||
}
|
||||
let lower = trimmed.to_ascii_lowercase();
|
||||
let is_note_ext =
|
||||
lower.ends_with(".md") || lower.ends_with(".markdown") || lower.ends_with(".mdx");
|
||||
if !is_note_ext {
|
||||
continue;
|
||||
}
|
||||
let path = PathBuf::from(trimmed);
|
||||
if path.is_file() {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 通知前端「要打开这个目标」(窗口由前端创建)。
|
||||
pub fn emit_open_target(app: &tauri::AppHandle, target: &OpenTarget) {
|
||||
use tauri::Emitter;
|
||||
let payload = serde_json::json!({ "path": target.path().to_string_lossy() });
|
||||
let event = match target {
|
||||
OpenTarget::File(_) => crate::constants::events::EDITOR_OPEN_FILE,
|
||||
OpenTarget::Folder(_) => crate::constants::events::EDITOR_OPEN_FOLDER,
|
||||
};
|
||||
if let Err(e) = app.emit(event, payload) {
|
||||
crate::logger::log_warn("editor", &format!("发出打开目标事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_note(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("thing-notes-args-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, "# x").unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_markdown_path_and_ignores_flags() {
|
||||
let note = temp_note("会议.md");
|
||||
let args = vec![
|
||||
"--some-flag".to_string(),
|
||||
"not-a-file".to_string(),
|
||||
note.to_string_lossy().to_string(),
|
||||
];
|
||||
assert_eq!(note_path_from_args(args), Some(note.clone()));
|
||||
|
||||
let _ = std::fs::remove_file(¬e);
|
||||
let _ = std::fs::remove_dir_all(note.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_markdown_and_mdx_too() {
|
||||
let note = temp_note("a.markdown");
|
||||
assert_eq!(
|
||||
note_path_from_args(vec![note.to_string_lossy().to_string()]),
|
||||
Some(note.clone())
|
||||
);
|
||||
let _ = std::fs::remove_file(¬e);
|
||||
let _ = std::fs::remove_dir_all(note.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_markdown_and_missing_files() {
|
||||
// 非笔记扩展名
|
||||
assert_eq!(note_path_from_args(vec!["C:\\a\\b.txt".to_string()]), None);
|
||||
// 不存在的 .md:静默忽略(否则会开一个空窗口)
|
||||
assert_eq!(
|
||||
note_path_from_args(vec!["C:\\definitely\\missing\\x.md".to_string()]),
|
||||
None
|
||||
);
|
||||
// 空参数与开关
|
||||
assert_eq!(
|
||||
note_path_from_args(vec!["".to_string(), "-v".to_string()]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_surrounding_quotes() {
|
||||
let note = temp_note("带 空格.md");
|
||||
let quoted = format!("\"{}\"", note.to_string_lossy());
|
||||
assert_eq!(note_path_from_args(vec![quoted]), Some(note.clone()));
|
||||
let _ = std::fs::remove_file(¬e);
|
||||
let _ = std::fs::remove_dir_all(note.parent().unwrap());
|
||||
}
|
||||
|
||||
/// 右键菜单:任意扩展名的文件都要被接受(不只 .md)。
|
||||
#[test]
|
||||
fn open_target_accepts_any_file_and_folder() {
|
||||
let file = temp_note("plain.txt");
|
||||
match open_target_from_args(vec![file.to_string_lossy().to_string()]) {
|
||||
Some(OpenTarget::File(p)) => assert_eq!(p, file),
|
||||
other => panic!("应识别为文件: {other:?}"),
|
||||
}
|
||||
let dir = file.parent().unwrap().to_path_buf();
|
||||
match open_target_from_args(vec![dir.to_string_lossy().to_string()]) {
|
||||
Some(OpenTarget::Folder(p)) => assert_eq!(p, dir),
|
||||
other => panic!("应识别为文件夹: {other:?}"),
|
||||
}
|
||||
let _ = std::fs::remove_file(&file);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
//! zip 快照备份:整库打包上传 + 远端轮转 + 恢复。
|
||||
//!
|
||||
//! # 为什么「快照」比「双向同步」更该先做
|
||||
//!
|
||||
//! 规划 §3.6 的判断:对「只是要个备份」的用户,一次上传一个完整 zip 比双向同步
|
||||
//! **可靠得多** —— 同步要考虑冲突、删除传播、时钟偏差;快照只有一个动作(上传),
|
||||
//! 失败就是失败,不会在半途产生「一半新一半旧」的库。
|
||||
//!
|
||||
//! 因此本模块与 `webdav/sync.rs` 是两条独立路径,用的是同一个客户端。
|
||||
//!
|
||||
//! # 打包内容
|
||||
//!
|
||||
//! 库内全部 `.md` 与 `assets/` 下的附件,外加一份 `thing-notes-manifest.json`
|
||||
//! (记录快照时间、文件数、格式版本)。**不打包 `.editor/`**:里面是索引与同步基线,
|
||||
//! 属于本机私有数据,跟着快照跑到另一台机器上只会误导那边的基线判断。
|
||||
//!
|
||||
//! # 轮转
|
||||
//!
|
||||
//! 上传后列出远端 `backups/` 下的快照,按**文件名里的时间戳**倒序保留
|
||||
//! [`WebdavSettings::backup_keep`] 份,其余删除。用文件名排序而不是远端 mtime:
|
||||
//! 各家服务端的 mtime 精度与时钟都不一致,而文件名是我们自己写的、单调递增。
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use super::webdav::client::WebdavClient;
|
||||
use crate::editor::library;
|
||||
use crate::editor::types::{BackupReport, BackupSnapshot, WebdavSettings};
|
||||
|
||||
/// 远端存放快照的目录(相对远端根)。
|
||||
pub const BACKUP_DIR: &str = "backups";
|
||||
/// 快照文件名前缀。
|
||||
const SNAPSHOT_PREFIX: &str = "thing-notes-";
|
||||
/// 清单文件名(打包进 zip,供恢复时校验)。
|
||||
const MANIFEST_NAME: &str = "thing-notes-manifest.json";
|
||||
|
||||
/// 快照清单。
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SnapshotManifest {
|
||||
version: u32,
|
||||
created_at: String,
|
||||
files: u32,
|
||||
}
|
||||
|
||||
/// 打包库根为 zip 字节流(不触网,便于单测)。
|
||||
pub fn build_snapshot(root: &Path) -> Result<(Vec<u8>, u32), String> {
|
||||
library::ensure_library(root)?;
|
||||
let cursor = std::io::Cursor::new(Vec::new());
|
||||
let mut writer = zip::ZipWriter::new(cursor);
|
||||
let options: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated);
|
||||
|
||||
let mut files = 0u32;
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let rel = library::rel_string(root, entry.path());
|
||||
if rel.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// `.editor/` 是本机私有数据(索引 + 同步基线),不进快照
|
||||
if rel.split('/').any(|part| part.starts_with('.')) {
|
||||
continue;
|
||||
}
|
||||
let bytes = match std::fs::read(entry.path()) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
crate::logger::log_warn("editor", &format!("快照跳过 {rel}(读取失败: {e})"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
writer
|
||||
.start_file(rel.clone(), options)
|
||||
.map_err(|e| format!("写入快照条目失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
.map_err(|e| format!("写入快照内容失败: {e}"))?;
|
||||
files += 1;
|
||||
}
|
||||
|
||||
// 清单最后写:它要记录真实打包到的文件数
|
||||
let manifest = SnapshotManifest {
|
||||
version: 1,
|
||||
created_at: chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
|
||||
files,
|
||||
};
|
||||
let manifest_bytes = serde_json::to_vec_pretty(&manifest)
|
||||
.map_err(|e| format!("序列化快照清单失败: {e}"))?;
|
||||
writer
|
||||
.start_file(MANIFEST_NAME, options)
|
||||
.map_err(|e| format!("写入快照清单失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&manifest_bytes)
|
||||
.map_err(|e| format!("写入快照清单内容失败: {e}"))?;
|
||||
|
||||
let cursor = writer.finish().map_err(|e| format!("完成快照打包失败: {e}"))?;
|
||||
Ok((cursor.into_inner(), files))
|
||||
}
|
||||
|
||||
/// 上传一份快照并做轮转。返回备份报告。
|
||||
pub fn upload_snapshot(
|
||||
root: &Path,
|
||||
settings: &WebdavSettings,
|
||||
client: &WebdavClient,
|
||||
) -> Result<BackupReport, String> {
|
||||
let (bytes, files) = build_snapshot(root)?;
|
||||
let name = format!(
|
||||
"{SNAPSHOT_PREFIX}{}.zip",
|
||||
chrono::Local::now().format("%Y%m%d-%H%M%S")
|
||||
);
|
||||
let remote_path = format!("{BACKUP_DIR}/{name}");
|
||||
client.put(&remote_path, bytes.clone())?;
|
||||
|
||||
let pruned = prune_snapshots(client, settings.backup_keep)?;
|
||||
Ok(BackupReport {
|
||||
name,
|
||||
bytes: bytes.len() as u64,
|
||||
files,
|
||||
pruned,
|
||||
})
|
||||
}
|
||||
|
||||
/// 轮转:只保留最新的 `keep` 份。
|
||||
pub fn prune_snapshots(client: &WebdavClient, keep: u32) -> Result<Vec<String>, String> {
|
||||
let keep = keep.max(1) as usize;
|
||||
let mut snapshots = list_snapshots(client)?;
|
||||
if snapshots.len() <= keep {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// 文件名里的时间戳是 `%Y%m%d-%H%M%S`,字典序即时间序
|
||||
snapshots.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
let outdated = snapshots.len() - keep;
|
||||
let mut pruned = Vec::new();
|
||||
for snapshot in snapshots.into_iter().take(outdated) {
|
||||
if let Err(e) = client.delete(&format!("{BACKUP_DIR}/{}", snapshot.name)) {
|
||||
crate::logger::log_warn("editor", &format!("删除旧快照 {} 失败: {e}", snapshot.name));
|
||||
continue;
|
||||
}
|
||||
pruned.push(snapshot.name);
|
||||
}
|
||||
Ok(pruned)
|
||||
}
|
||||
|
||||
/// 列出远端已有的快照。
|
||||
pub fn list_snapshots(client: &WebdavClient) -> Result<Vec<BackupSnapshot>, String> {
|
||||
let entries = client.list(BACKUP_DIR)?;
|
||||
let Some(entries) = entries else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter(|entry| !entry.is_dir)
|
||||
.filter(|entry| {
|
||||
entry
|
||||
.rel_path
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.map(|name| name.starts_with(SNAPSHOT_PREFIX) && name.ends_with(".zip"))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.map(|entry| BackupSnapshot {
|
||||
name: entry
|
||||
.rel_path
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
size: entry.size,
|
||||
modified: entry.modified,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 从快照恢复(**不覆盖已存在的本地文件**)。
|
||||
///
|
||||
/// 保守策略的理由:恢复的典型场景是「换机器」或「误删了几篇」。前者的本地基本是空的,
|
||||
/// 后者的本地有用户最近的工作 —— 覆盖会把「误删之前写的东西」一起冲掉。
|
||||
/// 需要时用户可以先在资源管理器里移走旧库,再恢复。
|
||||
pub fn restore_snapshot(
|
||||
root: &Path,
|
||||
client: &WebdavClient,
|
||||
name: &str,
|
||||
) -> Result<(u32, u32), String> {
|
||||
if name.contains('/') || name.contains('\\') || name.contains("..") {
|
||||
return Err("快照名不合法".to_string());
|
||||
}
|
||||
let bytes = client.get(&format!("{BACKUP_DIR}/{name}"))?;
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes))
|
||||
.map_err(|e| format!("读取快照失败: {e}"))?;
|
||||
|
||||
let mut written = 0u32;
|
||||
let mut kept = 0u32;
|
||||
for index in 0..archive.len() {
|
||||
let mut file = archive
|
||||
.by_index(index)
|
||||
.map_err(|e| format!("读取快照条目失败: {e}"))?;
|
||||
let Some(entry_path) = file.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
// `enclosed_name` 会拒绝 `..` 与绝对路径 —— 恶意快照不能写到库外
|
||||
crate::logger::log_warn("editor", "快照里有越界路径,已跳过");
|
||||
continue;
|
||||
};
|
||||
let rel = entry_path.to_string_lossy().replace('\\', "/");
|
||||
if rel == MANIFEST_NAME || file.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let target = library::safe_join(root, &rel)?;
|
||||
if target.exists() {
|
||||
kept += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
std::io::Read::read_to_end(&mut file, &mut out)
|
||||
.map_err(|e| format!("读取快照内容失败: {e}"))?;
|
||||
std::fs::write(&target, out).map_err(|e| format!("写入 {rel} 失败: {e}"))?;
|
||||
written += 1;
|
||||
}
|
||||
Ok((written, kept))
|
||||
}
|
||||
|
||||
/// 一次完整的「同步 + 备份」会话入口(命令层用)。
|
||||
///
|
||||
/// 返回(同步报告, 可选备份报告)。`with_backup` 为真时在同步之后追加一次快照 ——
|
||||
/// 「先同步再备份」的顺序是刻意的:备份应当是**同步之后的一致状态**,
|
||||
/// 而不是把一次半途失败的同步结果定格下来。
|
||||
pub fn sync_then_backup(
|
||||
root: &Path,
|
||||
settings: &WebdavSettings,
|
||||
client: &WebdavClient,
|
||||
app: &tauri::AppHandle,
|
||||
with_backup: bool,
|
||||
) -> Result<(super::webdav::sync::SyncReport, Option<BackupReport>), String> {
|
||||
let (plan, mut state, remote) = super::webdav::sync::build_plan(root, settings, client)?;
|
||||
let runner = super::webdav::sync::SyncRunner::new(client, root, app, plan.actions.len());
|
||||
let report = runner.run(&plan, &mut state, &remote);
|
||||
|
||||
// 只有「没有失败」时才推进基线:失败的一轮如果把基线写下去,
|
||||
// 那些没传成功的文件会被当成「已同步」,下次同步就静默漏掉了
|
||||
if report.failed == 0 {
|
||||
state.last_sync = chrono::Local::now().timestamp_millis().max(0) as u64;
|
||||
if let Err(e) = state.save(root) {
|
||||
crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}"));
|
||||
}
|
||||
} else {
|
||||
crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!("本轮有 {} 条失败,不推进同步基线", report.failed),
|
||||
);
|
||||
// 仍然保存「成功的那些」:SyncState 是按条更新的,未处理的条目保持旧基线,
|
||||
// 于是下一轮会把它们重新算作差异并重试
|
||||
if let Err(e) = state.save(root) {
|
||||
crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
let backup = if with_backup {
|
||||
Some(upload_snapshot(root, settings, client)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok((report, backup))
|
||||
}
|
||||
|
||||
/// 本地临时快照目录(供「导出快照到本地」与调试用)。
|
||||
///
|
||||
/// 与 [`upload_snapshot`] 共用 [`build_snapshot`],区别只是落盘而不是上传 ——
|
||||
/// 「我要一份备份,但不想连远端」是个很常见的诉求(比如先手动拷到网盘)。
|
||||
pub fn snapshot_to_file(root: &Path, dest: &Path) -> Result<u64, String> {
|
||||
let (bytes, _) = build_snapshot(root)?;
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
std::fs::write(dest, &bytes).map_err(|e| format!("写入快照失败: {e}"))?;
|
||||
Ok(bytes.len() as u64)
|
||||
}
|
||||
|
||||
/// 库根的默认快照落点(用户点「导出快照到本地」时用)。
|
||||
pub fn default_snapshot_path(root: &Path) -> PathBuf {
|
||||
root.join(format!(
|
||||
"{SNAPSHOT_PREFIX}{}.zip",
|
||||
chrono::Local::now().format("%Y%m%d-%H%M%S")
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_root(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-backup-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_excludes_private_dir() {
|
||||
let root = temp_root("build");
|
||||
std::fs::write(root.join("a.md"), "# A").unwrap();
|
||||
std::fs::create_dir_all(root.join("sub")).unwrap();
|
||||
std::fs::write(root.join("sub/b.md"), "# B").unwrap();
|
||||
std::fs::write(root.join("assets/pic.png"), [1u8, 2, 3]).unwrap();
|
||||
std::fs::create_dir_all(root.join(".editor")).unwrap();
|
||||
std::fs::write(root.join(".editor/editor.db"), "索引不该进快照").unwrap();
|
||||
|
||||
let (bytes, files) = build_snapshot(&root).unwrap();
|
||||
assert_eq!(files, 3, "两篇笔记 + 一个附件");
|
||||
assert!(!bytes.is_empty());
|
||||
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let names: Vec<String> = (0..archive.len())
|
||||
.map(|i| archive.by_index(i).unwrap().name().to_string())
|
||||
.collect();
|
||||
assert!(names.contains(&"a.md".to_string()), "{names:?}");
|
||||
assert!(names.contains(&"sub/b.md".to_string()), "{names:?}");
|
||||
assert!(names.contains(&"assets/pic.png".to_string()), "{names:?}");
|
||||
assert!(names.contains(&MANIFEST_NAME.to_string()), "{names:?}");
|
||||
assert!(
|
||||
!names.iter().any(|n| n.starts_with(".editor")),
|
||||
"私有目录不该进快照: {names:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_does_not_overwrite_existing_files() {
|
||||
let root = temp_root("restore");
|
||||
std::fs::write(root.join("a.md"), "新版").unwrap();
|
||||
std::fs::write(root.join("b.md"), "旧版").unwrap();
|
||||
let (bytes, _) = build_snapshot(&root).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("a.md"), "本机已有内容").unwrap();
|
||||
|
||||
// 直接走「解包到库根」的那段逻辑(用本地 zip 代替远端下载)
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut kept = 0u32;
|
||||
for index in 0..archive.len() {
|
||||
let mut file = archive.by_index(index).unwrap();
|
||||
let Some(path) = file.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
continue;
|
||||
};
|
||||
let rel = path.to_string_lossy().replace('\\', "/");
|
||||
if rel == MANIFEST_NAME || file.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let target = library::safe_join(&root, &rel).unwrap();
|
||||
if target.exists() {
|
||||
kept += 1;
|
||||
continue;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
std::io::Read::read_to_end(&mut file, &mut out).unwrap();
|
||||
std::fs::write(&target, out).unwrap();
|
||||
}
|
||||
assert_eq!(kept, 1, "已存在的 a.md 应被跳过");
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.md")).unwrap(), "本机已有内容");
|
||||
assert_eq!(std::fs::read_to_string(root.join("b.md")).unwrap(), "旧版");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_file_writing() {
|
||||
let root = temp_root("to-file");
|
||||
std::fs::write(root.join("a.md"), "# A").unwrap();
|
||||
let dest = root.join("out.zip");
|
||||
let size = snapshot_to_file(&root, &dest).unwrap();
|
||||
assert!(size > 0);
|
||||
assert!(dest.is_file());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,977 @@
|
||||
//! 笔记模块 Tauri 命令层。
|
||||
//!
|
||||
//! 所有库操作都经 [`super::library`] 的路径安全校验、所有库外文件操作都经
|
||||
//! [`super::files`] 的授权白名单、所有 WebDAV 操作都经 [`super::webdav`] 的会话层;
|
||||
//! 命令本身只做几件事:解析当前库根 → 调下层 → 标记「本应用刚写过」→ 发事件。
|
||||
//!
|
||||
//! # 为什么每条命令都要先 `retarget`
|
||||
//!
|
||||
//! 索引服务是常驻 worker,它记着「自己挂在哪个库根上」。库根可以在设置里改,
|
||||
//! 而 worker 不知道这件事 —— 若命令层不主动告知,就会出现「侧栏显示新库、
|
||||
//! 搜索却在新库的旧索引里查」这种最难查的错。`retarget` 在库根未变时是两次
|
||||
//! 比较,成本可忽略。
|
||||
//!
|
||||
//! # 网络类命令为什么是异步的
|
||||
//!
|
||||
//! `tests_webdav` / `sync_now` / `backup_now` 会真的发 HTTP 请求(同步一个几百篇的
|
||||
//! 库可能跑几分钟)。Tauri 的同步命令会占住调用线程,因此这几个一律 `async` 并用
|
||||
//! `spawn_blocking` 把阻塞的 reqwest 调用挪到专用线程池 —— 既不卡 UI,也不卡
|
||||
//! Tauri 的命令线程池。
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
|
||||
use super::backup;
|
||||
use super::export;
|
||||
use super::files;
|
||||
use super::import;
|
||||
use super::index::{
|
||||
NoteBacklinks, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery,
|
||||
};
|
||||
use super::index_service::{self, IndexService, NoteIndexReport};
|
||||
use super::library;
|
||||
use super::templates::{self, NoteTemplate};
|
||||
use super::types::{
|
||||
BackupReport, BackupSnapshot, ImportReport, LibraryEntry, LibraryInfo, NoteDoc, EditorSettings,
|
||||
SyncProgress,
|
||||
};
|
||||
use super::webdav::{self, WebdavTestResult};
|
||||
use super::EditorManager;
|
||||
use crate::constants::events;
|
||||
|
||||
/// 通知各窗口「库内容已变更」(新建/保存/重命名/删除/切换库根后)。
|
||||
fn emit_library_changed(app: &AppHandle) {
|
||||
if let Err(e) = app.emit(events::EDITOR_LIBRARY_CHANGED, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出库变更事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 通知各窗口「设置已变更」(跨窗口同步,范式同 terminal-settings)。
|
||||
fn emit_settings_changed(app: &AppHandle) {
|
||||
if let Err(e) = app.emit(events::EDITOR_SETTINGS, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出设置变更事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前库根(按设置解析),并确保目录存在。
|
||||
fn current_root(state: &EditorManager) -> PathBuf {
|
||||
let settings = state.load_settings();
|
||||
library::resolve_library_root(state.module_dir(), &settings)
|
||||
}
|
||||
|
||||
/// 取索引服务并把它的库根对齐到当前设置。
|
||||
fn indexed<'a>(app: &AppHandle, state: &EditorManager) -> Result<&'a IndexService, String> {
|
||||
let root = current_root(state);
|
||||
let service = index_service::service(app);
|
||||
service.retarget(root)?;
|
||||
Ok(service)
|
||||
}
|
||||
|
||||
/// 组装库状态概览。
|
||||
fn library_info(state: &EditorManager) -> Result<LibraryInfo, String> {
|
||||
let settings = state.load_settings();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
let entries = library::scan(&root)?;
|
||||
Ok(LibraryInfo {
|
||||
root: root.to_string_lossy().to_string(),
|
||||
is_custom: settings
|
||||
.library_root
|
||||
.as_deref()
|
||||
.map(|s| !s.trim().is_empty())
|
||||
.unwrap_or(false),
|
||||
note_count: library::count_notes(&entries),
|
||||
})
|
||||
}
|
||||
|
||||
/// 标记「本应用刚**批量**写过」,随后把库同步进索引。
|
||||
///
|
||||
/// 用于导入 / WebDAV 同步 / 恢复 / 模板导出这类**无法逐路径枚举**的操作:写完之后
|
||||
/// 在抑制窗口内的一切文件事件都当作自己写的。
|
||||
///
|
||||
/// 顺序重要:先标记(抑制窗口从写入那一刻算起),再同步。这里走全库增量同步而不是
|
||||
/// 「只索引这一篇」的快路径:单文件快路径要额外拼一份 wikilink 的 `stems` 映射,
|
||||
/// 而不完整的映射会让 `[[某笔记]]` 解析到错误位置;全量同步靠 (mtime,size) 跳过
|
||||
/// 未变文件,万篇规模也是毫秒级,用一点开销换「索引永远自洽」。
|
||||
fn mark_written_then_index(app: &AppHandle, state: &EditorManager) {
|
||||
match indexed(app, state) {
|
||||
Ok(service) => {
|
||||
service.mark_write_all();
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("保存后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// 写入前登记「本应用即将写这一篇笔记」(按库内相对路径)。
|
||||
///
|
||||
/// **必须在 `library::write_note` 之前调用**:notify 的 Modify 事件可能与写入几乎
|
||||
/// 同时到达索引 worker,晚于写盘再登记就会漏过 —— 前端便会把自家的保存当成
|
||||
/// 「外部修改」,进而重载文档、把光标弹回第一行。
|
||||
fn mark_pending_note_write(app: &AppHandle, state: &EditorManager, rel_path: &str) {
|
||||
match indexed(app, state) {
|
||||
Ok(service) => service.mark_write_path(rel_path),
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// 把库同步进索引(不登记自我写入 —— 调用方已在写入前按路径登记过)。
|
||||
fn sync_index_after_write(app: &AppHandle, state: &EditorManager) {
|
||||
match indexed(app, state) {
|
||||
Ok(service) => {
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("保存后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 设置与库 =====
|
||||
|
||||
/// 读取笔记模块设置。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_get_settings(state: State<'_, EditorManager>) -> Result<EditorSettings, String> {
|
||||
Ok(state.load_settings())
|
||||
}
|
||||
|
||||
/// 临时草稿文件的存放目录(`{app_data_dir}/editor/scratch`),不存在则创建,返回绝对路径。
|
||||
///
|
||||
/// 「新建临时文件(草稿)」用它:**不随应用退出删除** —— 用户可能还没决定存哪儿,
|
||||
/// 收尾交给「关闭该文件时选择保存 / 删除」。
|
||||
///
|
||||
/// # 为什么不放在**安装目录**
|
||||
///
|
||||
/// 安装目录(`Program Files` 之类)对普通用户通常不可写,装到系统盘就必然失败;
|
||||
/// 而 `app_data_dir` 本来就是本模块放设置与默认库的地方,是「应用自己的可写目录」的
|
||||
/// 标准位置,且卸载时随程序数据一起清理。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_scratch_dir(state: State<'_, EditorManager>) -> Result<String, String> {
|
||||
let dir = state.module_dir().join("scratch");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建临时目录失败:{e}"))?;
|
||||
Ok(dir.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 保存笔记模块设置(自愈后落盘,并广播给各窗口)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_save_settings(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
settings: EditorSettings,
|
||||
) -> Result<EditorSettings, String> {
|
||||
let mut next = settings;
|
||||
next.heal();
|
||||
state.save_settings(&next)?;
|
||||
// 全局快捷键可能刚被改了:就地重注册(`register_shortcut` 会先注销本模块的旧键,
|
||||
// 因此「清空快捷键」也能通过传空串生效)
|
||||
state.init_on_launch(&app);
|
||||
emit_settings_changed(&app);
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// 当前库状态概览(库根 / 是否自定义 / 笔记数)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_library_info(state: State<'_, EditorManager>) -> Result<LibraryInfo, String> {
|
||||
library_info(&state)
|
||||
}
|
||||
|
||||
/// 设置库根(`None` 或空串 = 恢复默认库根)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_set_library_root(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
root: Option<String>,
|
||||
) -> Result<LibraryInfo, String> {
|
||||
let cleaned = root.and_then(|r| {
|
||||
let trimmed = r.trim().to_string();
|
||||
if trimmed.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(trimmed)
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(path) = &cleaned {
|
||||
let p = std::path::Path::new(path);
|
||||
if !p.exists() {
|
||||
return Err(format!("目录不存在:{path}"));
|
||||
}
|
||||
if !p.is_dir() {
|
||||
return Err("请选择一个文件夹作为笔记库".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = state.load_settings();
|
||||
settings.library_root = cleaned;
|
||||
state.save_settings(&settings)?;
|
||||
|
||||
emit_settings_changed(&app);
|
||||
let info = library_info(&state)?;
|
||||
emit_library_changed(&app);
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// 扫描库,返回扁平条目列表(前端组树)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_scan_library(state: State<'_, EditorManager>) -> Result<Vec<LibraryEntry>, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
library::scan(&root)
|
||||
}
|
||||
|
||||
/// 读取一篇笔记。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_note(state: State<'_, EditorManager>, rel_path: String) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
library::read_note(&root, &rel_path)
|
||||
}
|
||||
|
||||
/// 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_save_note(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
content: String,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
// 先登记「即将写这一篇」,再落盘:notify 的事件可能与写入同时抵达 worker
|
||||
mark_pending_note_write(&app, &state, &rel_path);
|
||||
let doc = library::write_note(&root, &rel_path, &content)?;
|
||||
sync_index_after_write(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 新建笔记(自动补 `.md`、重名加序号),返回新文档。
|
||||
///
|
||||
/// `template_id` 为空时用默认模板;找不到该模板时同样回退默认模板(不报错 ——
|
||||
/// 模板文件被删掉不该让「新建笔记」这个核心动作失败)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_note(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
dir_rel: String,
|
||||
name: String,
|
||||
template_id: Option<String>,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
let template = template_id.unwrap_or_default();
|
||||
// 模板为空时走「不读模板目录」的那条路径:模板目录被删/损坏也要能新建笔记
|
||||
let doc = if template.trim().is_empty() {
|
||||
library::create_note(&root, &dir_rel, &name)?
|
||||
} else {
|
||||
library::create_note_with_template(&root, &dir_rel, &name, &template)?
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 打开(或创建)今天的日记:`日记/YYYY-MM-DD.md`。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_daily_note(app: AppHandle, state: State<'_, EditorManager>) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
let name = templates::daily_note_name();
|
||||
let dir = "日记";
|
||||
let rel = format!("{dir}/{name}.md");
|
||||
let path = library::safe_join(&root, &rel)?;
|
||||
let doc = if path.is_file() {
|
||||
library::read_note(&root, &rel)?
|
||||
} else {
|
||||
// 日记用同名内置模板;没有则回退默认(模板可被用户改名,这里不能假定存在)
|
||||
let template = if templates::body_of(&root, "builtin:日记").is_some() {
|
||||
"builtin:日记"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
library::create_note_with_template(&root, dir, &name, template)?
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 新建文件夹。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_folder(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
dir_rel: String,
|
||||
name: String,
|
||||
) -> Result<(), String> {
|
||||
let root = current_root(&state);
|
||||
library::create_folder(&root, &dir_rel, &name)?;
|
||||
emit_library_changed(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 重命名条目,返回新相对路径。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_rename_entry(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
new_name: String,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
let next = library::rename_entry(&root, &rel_path, &new_name)?;
|
||||
// 改名在索引里是「旧路径消失 + 新路径出现」:增量同步一次比手工删+插更稳
|
||||
if let Ok(service) = indexed(&app, &state) {
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("改名后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
emit_library_changed(&app);
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// 删除条目(目录递归删除)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_delete_entry(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
) -> Result<(), String> {
|
||||
let root = current_root(&state);
|
||||
library::delete_entry(&root, &rel_path)?;
|
||||
if let Ok(service) = indexed(&app, &state) {
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("删除后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
emit_library_changed(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ===== 索引与检索 =====
|
||||
|
||||
/// 全量重建索引(设置页「重建索引」)。文件不受影响。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_rebuild_index(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<NoteIndexReport, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let report = service.rebuild()?;
|
||||
Ok(finish_report(service, report))
|
||||
}
|
||||
|
||||
/// 增量同步索引(打开编辑器 / 手动刷新时调用)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_sync_index(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<NoteIndexReport, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let report = service.sync()?;
|
||||
Ok(finish_report(service, report))
|
||||
}
|
||||
|
||||
/// 把同步结果补上「索引里的笔记数」再回传(前端省一次 stats 往返)。
|
||||
fn finish_report(service: &IndexService, report: super::index::NoteSyncReport) -> NoteIndexReport {
|
||||
let note_count = service.stats().map(|s| s.note_count).unwrap_or(0);
|
||||
let mut out: NoteIndexReport = report.into();
|
||||
out.note_count = note_count;
|
||||
out
|
||||
}
|
||||
|
||||
/// 全文检索 / 按标签 / 按目录筛选。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_search_notes(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
query: NoteSearchQuery,
|
||||
) -> Result<NoteSearchPage, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.search(query)
|
||||
}
|
||||
|
||||
/// 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_list_notes(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
limit: Option<i64>,
|
||||
) -> Result<Vec<NoteSearchHit>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.list(limit.unwrap_or(500))
|
||||
}
|
||||
|
||||
/// 标签及计数。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_tags(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<Vec<super::index::NoteTagCount>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.tags()
|
||||
}
|
||||
|
||||
/// 一篇笔记的链接关系(出链 + 入链)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_backlinks(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
) -> Result<NoteBacklinks, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.backlinks(&rel_path)
|
||||
}
|
||||
|
||||
/// 全库链接图(已解析的内部链接边)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_link_graph(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<Vec<LinkEdge>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let edges = service.link_graph()?;
|
||||
Ok(edges
|
||||
.into_iter()
|
||||
.map(|(from, to)| LinkEdge { from, to })
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 链接图的一条边(用 `from`/`to` 而不是元组:元组序列化成数组后前端得按下标取值,
|
||||
/// 改一次顺序就静默错位 —— 与 `terminal/history.rs` 的 `HistorySource` 同一理由)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LinkEdge {
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
}
|
||||
|
||||
/// 索引状态(设置页展示:索引数 / 文件数 / 标签数 / 索引文件路径)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_index_stats(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<NoteIndexStats, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.stats()
|
||||
}
|
||||
|
||||
// ===== 库外任意文件 =====
|
||||
|
||||
/// 把库内图片读成 `data:` URL(供编辑器内联预览)。
|
||||
///
|
||||
/// # 为什么走 data URL 而不是 asset 协议
|
||||
///
|
||||
/// 库根是用户自选目录,可以用 `convertFileSrc` + `assetProtocol.scope` 直接把磁盘路径
|
||||
/// 交给 `<img>`。但那条路要求把「用户选的任意目录」加进 asset 协议的作用域白名单 ——
|
||||
/// 那等于给 WebView 开一个「可以按路径读任意文件」的口子,而笔记模块的整个安全模型
|
||||
/// 是「库根沙箱 + 授权白名单」。走 data URL 则完全在既有沙箱内:路径必须经
|
||||
/// [`library::safe_join`](拒绝 `..` 与绝对路径),且只认图片扩展名。
|
||||
///
|
||||
/// # 为什么必须有大小上限
|
||||
///
|
||||
/// data URL 是 base64,体积约为原文件的 1.34 倍,且会进 JS 堆。一张 20MB 的图片
|
||||
/// 变成 27MB 字符串,多预览几张就能把 WebView 拖垮。超限时**不报错**,返回
|
||||
/// `None` —— 调用方(编辑器)会把该图片节点当作普通文本渲染,用户看到的就是
|
||||
/// 原始 Markdown,不会打断编辑。
|
||||
const MAX_ASSET_BYTES: u64 = 8 * 1024 * 1024;
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_asset(
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
) -> Result<Option<String>, String> {
|
||||
let root = current_root(&state);
|
||||
let path = library::safe_join(&root, &rel_path)?;
|
||||
if !path.is_file() {
|
||||
return Ok(None);
|
||||
}
|
||||
let ext = path
|
||||
.extension()
|
||||
.map(|e| e.to_string_lossy().to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
let mime = match ext.as_str() {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"webp" => "image/webp",
|
||||
"svg" => "image/svg+xml",
|
||||
"bmp" => "image/bmp",
|
||||
"avif" => "image/avif",
|
||||
// 非图片(或未识别):不预览。返回 `None` 而不是报错 —— 正文里写个
|
||||
// `` 不该让编辑器弹错误。
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let meta = std::fs::metadata(&path).map_err(|e| format!("读取附件信息失败: {e}"))?;
|
||||
if meta.len() > MAX_ASSET_BYTES {
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("附件过大,跳过内联预览:{rel_path}({} 字节)", meta.len()),
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
use base64::Engine;
|
||||
let bytes = std::fs::read(&path).map_err(|e| format!("读取附件失败: {e}"))?;
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
|
||||
Ok(Some(format!("data:{mime};base64,{encoded}")))
|
||||
}
|
||||
|
||||
/// 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。
|
||||
///
|
||||
/// 前端在注册完事件监听后调用。**不能靠启动时 `emit`** —— 那时 WebView 还没加载完,
|
||||
/// 事件会直接丢掉(见 `editor/args.rs` 的 `PENDING` 注释)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_take_pending_file() -> Result<Option<super::args::OpenTargetPayload>, String> {
|
||||
Ok(super::args::take_pending_target())
|
||||
}
|
||||
|
||||
/// 打开(读取)库外任意文件。
|
||||
///
|
||||
/// 读取本身不要求预先授权(用户可能刚通过系统对话框选完,也可能带命令行参数),
|
||||
/// 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_open_file(
|
||||
state: State<'_, EditorManager>,
|
||||
path: String,
|
||||
) -> Result<files::FileDoc, String> {
|
||||
let settings = state.load_settings();
|
||||
index_service::read_and_authorize(&path, settings.max_file_size_mb)
|
||||
}
|
||||
|
||||
/// 保存库外任意文件(按前端回传的编码与换行写回)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_write_file(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
path: String,
|
||||
content: String,
|
||||
encoding: String,
|
||||
eol: String,
|
||||
) -> Result<files::FileDoc, String> {
|
||||
let settings = state.load_settings();
|
||||
let doc = files::write_file(&path, &content, &encoding, &eol, settings.max_file_size_mb)?;
|
||||
if let Ok(service) = indexed(&app, &state) {
|
||||
// 库外文件的路径语义与库内相对路径不同,这里退回窗口式抑制;
|
||||
// 真正在库内的 `.md`(被当作普通文件打开)同样受这一窗口保护。
|
||||
service.mark_write_all();
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 以指定编码重新解码磁盘字节(切换编码用;不写回,只换一种解释方式)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_redecode_file(
|
||||
state: State<'_, EditorManager>,
|
||||
path: String,
|
||||
encoding: String,
|
||||
) -> Result<files::FileDoc, String> {
|
||||
let settings = state.load_settings();
|
||||
files::redecode_file(&path, &encoding, settings.max_file_size_mb)
|
||||
}
|
||||
|
||||
/// 显式登记一个路径为「可写」。
|
||||
///
|
||||
/// 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `editor_open_file`,
|
||||
/// 但用户确实是用系统对话框选的,属于「用户显式选择」)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_authorize_file(path: String) -> Result<(), String> {
|
||||
if path.trim().is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
files::authorize(std::path::Path::new(path.trim()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把 base64 图片写进库根的 `assets/`,返回可插入 Markdown 的相对路径。
|
||||
///
|
||||
/// 为什么走 base64 而不是直接给前端一个写文件句柄:粘贴的图片来自剪贴板,
|
||||
/// 前端拿到的本来就是 Blob/DataURL;转一次 base64 比让前端拿到「任意写权限」
|
||||
/// 安全得多(写的位置由后端决定,且只落在 `assets/`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_write_asset(
|
||||
state: State<'_, EditorManager>,
|
||||
file_name: String,
|
||||
ext: String,
|
||||
data_base64: String,
|
||||
) -> Result<String, String> {
|
||||
use base64::Engine;
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let data = base64::engine::general_purpose::STANDARD
|
||||
.decode(data_base64.trim())
|
||||
.map_err(|e| format!("图片数据解析失败: {e}"))?;
|
||||
files::write_asset(&root, &file_name, &data, &ext)
|
||||
}
|
||||
|
||||
// ===== 模板(P2) =====
|
||||
|
||||
/// 列出可用模板(用户模板优先,同名覆盖内置)。
|
||||
///
|
||||
/// 顺带确保库内 `templates/` 目录存在 —— 这样界面上「新建模板」按钮第一次点击
|
||||
/// 就能直接写文件,不需要用户先去资源管理器建目录。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_list_templates(state: State<'_, EditorManager>) -> Result<Vec<NoteTemplate>, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let _ = templates::ensure_dir(&root);
|
||||
Ok(templates::list(&root))
|
||||
}
|
||||
|
||||
/// 把内置模板导出到库内 `templates/`(已存在的不覆盖),返回新写入的名字。
|
||||
///
|
||||
/// 三种用法:
|
||||
/// - 都不传:把全部内置模板导出到 `templates/`(用户想改内置模板时的起点);
|
||||
/// - 传 `name` + `body`:新建一个自定义模板。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_add_template(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
name: Option<String>,
|
||||
body: Option<String>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let root = current_root(&state);
|
||||
let written = match (name, body) {
|
||||
(Some(name), Some(body)) => {
|
||||
let safe = templates::validate_name(&name)?;
|
||||
templates::ensure_dir(&root)?;
|
||||
let path = root.join("templates").join(format!("{safe}.md"));
|
||||
if path.exists() {
|
||||
return Err(format!("模板「{safe}」已存在"));
|
||||
}
|
||||
std::fs::write(&path, body).map_err(|e| format!("写入模板失败: {e}"))?;
|
||||
vec![safe]
|
||||
}
|
||||
// 不带参数 = 导出全部内置模板
|
||||
_ => templates::export_builtin(&root)?,
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// 读取一个模板的正文(界面上「查看 / 编辑模板」用)。
|
||||
///
|
||||
/// 内置模板也返回正文(便于「另存为自定义模板」),但 `path` 为 `None` ——
|
||||
/// 内置模板没有对应的库内文件,前端据此禁掉「直接编辑」。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_template(
|
||||
state: State<'_, EditorManager>,
|
||||
template_id: String,
|
||||
) -> Result<TemplateSource, String> {
|
||||
let root = current_root(&state);
|
||||
let body = templates::body_of(&root, &template_id)
|
||||
.ok_or_else(|| format!("模板不存在:{template_id}"))?;
|
||||
Ok(TemplateSource {
|
||||
body,
|
||||
path: templates::relative_path(&template_id),
|
||||
})
|
||||
}
|
||||
|
||||
/// 模板正文与它在库内的位置(`path` 为 `None` = 内置模板)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TemplateSource {
|
||||
pub body: String,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
// ===== 导入 / 导出(P2) =====
|
||||
|
||||
/// 从磁盘路径导入(文件 / 目录 / zip 自动判别)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_import(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
source: String,
|
||||
dest_dir: String,
|
||||
) -> Result<ImportReport, String> {
|
||||
let root = current_root(&state);
|
||||
let report = import::import_path(&root, &source, &dest_dir)?;
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// 把一篇笔记导出为独立 HTML 文件,返回落盘路径。
|
||||
///
|
||||
/// HTML 的渲染在**前端**(`markdown-it` + `DOMPurify` 都在前端),这里只负责把
|
||||
/// 已经渲染好的字符串写到用户选定的位置 —— 即「后端不碰渲染逻辑,前端不碰文件系统」。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_export_note(
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
html: String,
|
||||
dest: String,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
// 无论导出哪一篇,都要先确认它确实在库内(不接受库外相对路径)
|
||||
library::read_note(&root, &rel_path)?;
|
||||
let target = PathBuf::from(dest.trim());
|
||||
if target.as_os_str().is_empty() {
|
||||
return Err("请选择导出位置".to_string());
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建导出目录失败: {e}"))?;
|
||||
}
|
||||
let bytes = html.into_bytes();
|
||||
std::fs::write(&target, &bytes).map_err(|e| format!("写入导出文件失败: {e}"))?;
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("导出 {} → {}({} 字节)", rel_path, target.display(), bytes.len()),
|
||||
);
|
||||
Ok(target.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 把整库(或某个目录)打包成 zip,返回落盘路径。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_export_zip(
|
||||
state: State<'_, EditorManager>,
|
||||
dest: String,
|
||||
dir_rel: Option<String>,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
let dest_path = PathBuf::from(dest.trim());
|
||||
if dest_path.as_os_str().is_empty() {
|
||||
return Err("请选择导出位置".to_string());
|
||||
}
|
||||
let scope = dir_rel.unwrap_or_default();
|
||||
let (bytes, files) = export::zip_scope(&root, &scope)?;
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建导出目录失败: {e}"))?;
|
||||
}
|
||||
std::fs::write(&dest_path, &bytes).map_err(|e| format!("写入 zip 失败: {e}"))?;
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("导出 zip:{files} 个文件 → {}", dest_path.display()),
|
||||
);
|
||||
Ok(dest_path.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。
|
||||
///
|
||||
/// 与 [`editor_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
|
||||
/// 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为
|
||||
/// 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_export_snapshot_local(
|
||||
state: State<'_, EditorManager>,
|
||||
dest: Option<String>,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let target = match dest.map(|d| d.trim().to_string()) {
|
||||
Some(d) if !d.is_empty() => PathBuf::from(d),
|
||||
_ => backup::default_snapshot_path(&root),
|
||||
};
|
||||
backup::snapshot_to_file(&root, &target)?;
|
||||
Ok(target.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
// ===== WebDAV 同步 / 备份(P2) =====
|
||||
|
||||
/// 当前 WebDAV 配置状态(设置页展示;**密码只回传「是否已保存」**)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_webdav_status(state: State<'_, EditorManager>) -> Result<WebdavStatus, String> {
|
||||
let settings = state.load_settings();
|
||||
let has_password = crate::secrets::secret_read(webdav::KEYRING_PASSWORD)
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|value| !value.is_empty())
|
||||
.unwrap_or(false);
|
||||
Ok(WebdavStatus {
|
||||
configured: settings.webdav.is_configured(),
|
||||
has_password,
|
||||
remote_root: settings.webdav.remote_root.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// WebDAV 配置状态(不包含密码本身)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WebdavStatus {
|
||||
/// 地址与用户名是否已填
|
||||
pub configured: bool,
|
||||
/// keyring 里是否已存密码
|
||||
pub has_password: bool,
|
||||
pub remote_root: String,
|
||||
}
|
||||
|
||||
/// 保存 WebDAV 密码到系统凭据管理器(传空串 = 删除)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_set_webdav_password(password: String) -> Result<(), String> {
|
||||
if password.trim().is_empty() {
|
||||
return crate::secrets::secret_delete(webdav::KEYRING_PASSWORD);
|
||||
}
|
||||
crate::secrets::secret_write(webdav::KEYRING_PASSWORD, password.trim())
|
||||
}
|
||||
|
||||
/// 连接自检(建目录 + 列远端)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_test_webdav(
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<WebdavTestResult, String> {
|
||||
let settings = state.load_settings().webdav;
|
||||
run_blocking(move || webdav::test_connection(&settings)).await
|
||||
}
|
||||
|
||||
/// 立即同步(并按设置决定是否追加一次快照备份)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_sync_now(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<SyncOutcome, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
|
||||
// 让前端先看到「开始同步」(进度事件的第一条由 worker 之外发,总数为 0 表示准备中)
|
||||
let _ = app.emit(
|
||||
events::EDITOR_SYNC_PROGRESS,
|
||||
SyncProgress {
|
||||
done: 0,
|
||||
total: 0,
|
||||
current: String::new(),
|
||||
kind: "prepare".to_string(),
|
||||
message: "正在比对清单…".to_string(),
|
||||
},
|
||||
);
|
||||
|
||||
let app_for_task = app.clone();
|
||||
let outcome = run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
client.ensure_root()?;
|
||||
let (report, backup) = backup::sync_then_backup(&root, &webdav, &client, &app_for_task, true)?;
|
||||
Ok(SyncOutcome {
|
||||
report,
|
||||
backup,
|
||||
})
|
||||
})
|
||||
.await;
|
||||
|
||||
// 同步会改本地文件 → 索引必须跟着更新
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
outcome
|
||||
}
|
||||
|
||||
/// 一次同步的结果(报告 + 可选快照)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncOutcome {
|
||||
pub report: super::webdav::sync::SyncReport,
|
||||
pub backup: Option<BackupReport>,
|
||||
}
|
||||
|
||||
/// 只做一次 zip 快照备份(不上传增量)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_backup_now(
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<BackupReport, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
client.ensure_root()?;
|
||||
backup::upload_snapshot(&root, &webdav, &client)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// 列出远端已有快照。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_list_backups(
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<Vec<BackupSnapshot>, String> {
|
||||
let settings = state.load_settings().webdav;
|
||||
run_blocking(move || {
|
||||
let client = webdav::client_from(&settings)?;
|
||||
backup::list_snapshots(&client)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// 从远端快照恢复(不覆盖本地已有文件)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_restore_backup(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
name: String,
|
||||
) -> Result<ImportReport, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
let result = run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
let (written, kept) = backup::restore_snapshot(&root, &client, &name)?;
|
||||
Ok(ImportReport {
|
||||
imported: written,
|
||||
renamed: 0,
|
||||
skipped: kept,
|
||||
failures: Vec::new(),
|
||||
})
|
||||
})
|
||||
.await;
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
result
|
||||
}
|
||||
|
||||
/// 把阻塞的 WebDAV 调用挪到专用线程池,避免占住 Tauri 的命令线程。
|
||||
///
|
||||
/// `reqwest::blocking` 在 tokio 运行时线程上会 panic(它内部会尝试建一个运行时),
|
||||
/// 因此**必须**走 `spawn_blocking` 而不是直接 `.await` 一个同步函数。
|
||||
async fn run_blocking<T, F>(task: F) -> Result<T, String>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce() -> Result<T, String> + Send + 'static,
|
||||
{
|
||||
match tokio::task::spawn_blocking(task).await {
|
||||
Ok(result) => result,
|
||||
Err(e) => Err(format!("后台任务执行失败: {e}")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! 编辑器「本地目录」命令层:直接操作用户真实文件系统(不进索引、无沙箱)。
|
||||
//!
|
||||
//! # 为什么复用 `terminal::local_fs`
|
||||
//!
|
||||
//! 列举 / 新建目录 / 重命名 / **回收站删除** 在终端模块的「本地栏」已经实现过,
|
||||
//! 且把「目录/文件分流」「不弹系统错误对话框」「拒绝删除盘符根」这些细节处理好了。
|
||||
//! 这里只补它没有的两件事:
|
||||
//! 1. **新建文件**(空文本,终端本地栏只建目录);
|
||||
//! 2. **重名一律报错**——目录树是用户的真实文件系统,静默改名会让人找不到刚建的文件。
|
||||
//!
|
||||
//! # 安全边界(与终端同一姿态)
|
||||
//!
|
||||
//! 路径来自用户自己的浏览/输入,不做「限制在本目录根下」的约束(那是本地文件管理器,
|
||||
//! 限制根只会挡住用户自己)。唯一硬守卫是 **拒绝删除盘符根**(已在
|
||||
//! [`terminal::local_fs::delete`] 内实现),且删除一律走回收站。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
use super::library::validate_name;
|
||||
use crate::terminal::local_fs;
|
||||
|
||||
/// 批量删除结果(回传前端展示「成功 N 项、失败明细」)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeleteReport {
|
||||
/// 成功移入回收站的项数
|
||||
pub removed: u32,
|
||||
/// 失败明细(路径 + 原因)
|
||||
pub failed: Vec<String>,
|
||||
}
|
||||
|
||||
/// 列举本地目录(`path` 为空 = 用户主目录)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_dir(path: String) -> Result<local_fs::LocalDir, String> {
|
||||
local_fs::list_dir(&path)
|
||||
}
|
||||
|
||||
/// 在 `dir` 下新建一个空文本文件。重名报错(不自动加序号)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_file(dir: String, name: String) -> Result<String, String> {
|
||||
let target = resolve_child(&dir, &name)?;
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
std::fs::write(&target, b"").map_err(|e| format!("新建文件失败: {e}"))?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 在 `dir` 下新建一个文件夹。重名报错(不自动加序号)。
|
||||
///
|
||||
/// 命名用 `editor_create_dir` 而不是 `editor_create_folder`:后者已被**库内**建文件夹
|
||||
/// 的命令占用(`editor_create_folder(dir_rel, name)`,走库根沙箱)—— 两者操作对象不同
|
||||
/// (真实文件系统 vs 库内),必须能同时在命令表里存在。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_dir(dir: String, name: String) -> Result<String, String> {
|
||||
let target = resolve_child(&dir, &name)?;
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
local_fs::create_dir(&target.to_string_lossy())?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 同目录内重命名。目标存在则报错。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_rename_path(path: String, new_name: String) -> Result<String, String> {
|
||||
let src = Path::new(path.trim());
|
||||
if !src.exists() {
|
||||
return Err("路径不存在".to_string());
|
||||
}
|
||||
let parent = src.parent().ok_or_else(|| "无法解析父目录".to_string())?;
|
||||
let name = validate_name(&new_name)?;
|
||||
let target = parent.join(&name);
|
||||
if target == src {
|
||||
return Ok(local_fs::display_path(src));
|
||||
}
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
local_fs::rename(&path, &target.to_string_lossy())?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 删除若干本地项(**走系统回收站**,不是永久删除)。
|
||||
///
|
||||
/// 单个失败不中断其余项:用户选中的 10 个文件里有一个正被占用,另外 9 个仍应删掉。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_delete_path(paths: Vec<String>) -> Result<DeleteReport, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let (removed, failed) = local_fs::delete(&paths);
|
||||
DeleteReport {
|
||||
removed: removed as u32,
|
||||
failed,
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("删除任务失败: {e}"))
|
||||
}
|
||||
|
||||
/// 把一个文件 / 文件夹移动到目标目录下(同盘移动;重名报错)。
|
||||
///
|
||||
/// 不允许把文件夹移动到自身或其子目录下 —— 那会把目录搬进自己里面,属数据事故。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_move_path(path: String, dest_dir: String) -> Result<String, String> {
|
||||
let src = Path::new(path.trim());
|
||||
if !src.exists() {
|
||||
return Err("源路径不存在".to_string());
|
||||
}
|
||||
let dest = Path::new(dest_dir.trim());
|
||||
if !dest.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
let name = src
|
||||
.file_name()
|
||||
.ok_or_else(|| "无法解析文件名".to_string())?;
|
||||
let target = dest.join(name);
|
||||
if target == src {
|
||||
return Ok(local_fs::display_path(src));
|
||||
}
|
||||
if target.exists() {
|
||||
return Err(format!("目标目录中已存在「{}」", name.to_string_lossy()));
|
||||
}
|
||||
if src.is_dir() && dest.starts_with(src) {
|
||||
return Err("不能把文件夹移动到自身或子目录中".to_string());
|
||||
}
|
||||
local_fs::rename(&path, &target.to_string_lossy())?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 校验名字并把「目录 + 名字」拼成绝对路径。
|
||||
fn resolve_child(dir: &str, name: &str) -> Result<std::path::PathBuf, String> {
|
||||
let name = validate_name(name)?;
|
||||
let dir = Path::new(dir.trim());
|
||||
if !dir.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
Ok(dir.join(name))
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! 整库 / 目录导出为 zip。
|
||||
//!
|
||||
//! # 与快照备份的区别
|
||||
//!
|
||||
//! `backup.rs` 的 zip 是**给同步服务用的**(固定文件名前缀、上传到远端、轮转),
|
||||
//! 本模块的 zip 是**给用户拿走的**(用户选保存位置、可以只导出某个目录)。
|
||||
//! 两者都打包 `.md` 与 `assets/`,但排除规则不同:用户导出时**包含**点号开头的
|
||||
//! 普通目录(除了 `.editor/`)—— 因为「我库里有 `.foo/` 目录,为什么导出后没了」
|
||||
//! 是个更难解释的问题;而同步必须排除它们(避免把本机私有状态推给别人)。
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use super::library;
|
||||
|
||||
/// 打包范围。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Scope {
|
||||
/// 整个库
|
||||
All,
|
||||
/// 只打包库内某个目录(连同库根的 `assets/`)
|
||||
Dir,
|
||||
}
|
||||
|
||||
/// 按范围打包,返回 `(zip 字节, 文件数)`。
|
||||
pub fn zip_scope(root: &Path, dir_rel: &str) -> Result<(Vec<u8>, u32), String> {
|
||||
let scope = if dir_rel.trim().is_empty() {
|
||||
Scope::All
|
||||
} else {
|
||||
Scope::Dir
|
||||
};
|
||||
// 目录模式下先确认目标目录存在且仍在库内(`safe_join` 拒绝越界)
|
||||
let filter_prefix = if scope == Scope::Dir {
|
||||
let dir = library::safe_join(root, dir_rel)?;
|
||||
if !dir.is_dir() {
|
||||
return Err(format!("目录不存在:{dir_rel}"));
|
||||
}
|
||||
Some(library::rel_string(root, &dir))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let cursor = std::io::Cursor::new(Vec::new());
|
||||
let mut writer = zip::ZipWriter::new(cursor);
|
||||
let options: zip::write::FileOptions<'_, ()> =
|
||||
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
|
||||
let mut files = 0u32;
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let rel = library::rel_string(root, entry.path());
|
||||
if rel.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// 私有目录(索引 + 同步基线)任何情况下都不导出
|
||||
if rel == ".editor" || rel.starts_with(".editor/") {
|
||||
continue;
|
||||
}
|
||||
if let Some(prefix) = &filter_prefix {
|
||||
// 目录模式:只收该目录下的文件,外加库根 assets/
|
||||
let in_scope = rel == *prefix
|
||||
|| rel.starts_with(&format!("{prefix}/"))
|
||||
|| rel.starts_with(&format!("{}/", library::ASSETS_DIR));
|
||||
if !in_scope {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let bytes = match std::fs::read(entry.path()) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
crate::logger::log_warn("editor", &format!("导出跳过 {rel}(读取失败: {e})"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
writer
|
||||
.start_file(rel, options)
|
||||
.map_err(|e| format!("写入 zip 条目失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
.map_err(|e| format!("写入 zip 内容失败: {e}"))?;
|
||||
files += 1;
|
||||
}
|
||||
|
||||
let cursor = writer.finish().map_err(|e| format!("完成 zip 打包失败: {e}"))?;
|
||||
Ok((cursor.into_inner(), files))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn temp_lib(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-export-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
fn names(bytes: Vec<u8>) -> Vec<String> {
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
(0..archive.len())
|
||||
.map(|i| archive.by_index(i).unwrap().name().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_export_skips_private_dir_only() {
|
||||
let root = temp_lib("all");
|
||||
std::fs::create_dir_all(root.join(".editor")).unwrap();
|
||||
std::fs::create_dir_all(root.join(".custom")).unwrap();
|
||||
std::fs::write(root.join("a.md"), "A").unwrap();
|
||||
std::fs::write(root.join(".editor/editor.db"), "x").unwrap();
|
||||
std::fs::write(root.join(".custom/keep.md"), "保留").unwrap();
|
||||
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
|
||||
|
||||
let (bytes, count) = zip_scope(&root, "").unwrap();
|
||||
assert_eq!(count, 3, "a.md + .custom/keep.md + assets/p.png");
|
||||
let list = names(bytes);
|
||||
assert!(list.contains(&"a.md".to_string()), "{list:?}");
|
||||
assert!(
|
||||
list.contains(&".custom/keep.md".to_string()),
|
||||
"普通点号目录应被导出: {list:?}"
|
||||
);
|
||||
assert!(
|
||||
!list.iter().any(|n| n.starts_with(".editor")),
|
||||
"私有目录不该导出: {list:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dir_export_limits_scope_but_keeps_assets() {
|
||||
let root = temp_lib("dir");
|
||||
std::fs::create_dir_all(root.join("work")).unwrap();
|
||||
std::fs::create_dir_all(root.join("personal")).unwrap();
|
||||
std::fs::write(root.join("work/a.md"), "A").unwrap();
|
||||
std::fs::write(root.join("personal/b.md"), "B").unwrap();
|
||||
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
|
||||
|
||||
let (bytes, count) = zip_scope(&root, "work").unwrap();
|
||||
assert_eq!(count, 2, "work/a.md + assets/p.png");
|
||||
let list = names(bytes);
|
||||
assert!(list.contains(&"work/a.md".to_string()), "{list:?}");
|
||||
assert!(list.contains(&"assets/p.png".to_string()), "{list:?}");
|
||||
assert!(
|
||||
!list.contains(&"personal/b.md".to_string()),
|
||||
"范围外文件不该导出: {list:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dir_export_rejects_escape_and_missing() {
|
||||
let root = temp_lib("escape");
|
||||
assert!(zip_scope(&root, "../..").is_err(), "越界路径必须被拒");
|
||||
assert!(zip_scope(&root, "不存在").is_err());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
//! 任意文本 / 代码文件的读写:编码探测、换行探测、授权路径白名单。
|
||||
//!
|
||||
//! # 与笔记库的分工
|
||||
//!
|
||||
//! 库内笔记走 `library.rs`(相对路径 + 树形结构 + front-matter);本模块服务的是
|
||||
//! **库外的任意文件**:用户用 `Ctrl+O` 或拖拽打开的一个 `.py`、`.json`、`.log`。
|
||||
//! 两者的安全模型完全不同 —— 库是「一个根目录内的沙箱」,而任意文件是「用户显式
|
||||
//! 点过的那个路径」。因此这里的守卫不是路径前缀,而是**授权集合**(见下)。
|
||||
//!
|
||||
//! # 为什么要有授权白名单
|
||||
//!
|
||||
//! 前端传来的路径一律不可信:一个被污染的 WebView(XSS、恶意依赖)如果能调
|
||||
//! `editor_write_file('/Windows/System32/...')`,那就不是编辑器而是任意文件写入漏洞。
|
||||
//! 做法:只有经过 [`authorize`] 登记过的路径才允许读**写**(读也一并限制,避免拿它
|
||||
//! 当任意文件读取接口探测磁盘)。授权的三个来源都是用户动作:系统文件对话框、
|
||||
//! 命令行参数、库本身。
|
||||
//!
|
||||
//! **读**比写宽松一档:读只要求「存在且是文件」,写入才强制授权。原因是打开一篇
|
||||
//! 从设置页点进来的文件不该因为「窗口重启过、授权表空了」而失败。
|
||||
//!
|
||||
//! # 编码与换行:读写成对
|
||||
//!
|
||||
//! GBK 文件被当成 UTF-8 读出来是乱码,再按 UTF-8 存回去就是**永久损坏**(原字节
|
||||
//! 已经不可逆地丢了)。因此读的时候把「编码 + 有无 BOM + 换行风格」一并记下来,
|
||||
//! 写回时原样还原;用户显式改编码时才按新编码写。换行同理:CRLF 文件存回去必须
|
||||
//! 还是 CRLF,否则一次「随手保存」就会在整个 diff 里掀起风暴。
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fs::Metadata;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
/// 会话内已授权(用户显式打开过)的路径集合。
|
||||
///
|
||||
/// 进程级静态而非 Tauri State:授权是「这一次运行期间用户点过什么」的事实,
|
||||
/// 与库根、设置无关,也不需要跨窗口同步(每个源窗口都会自己调 `authorize`)。
|
||||
static AUTHORIZED: std::sync::OnceLock<Mutex<HashSet<PathBuf>>> = std::sync::OnceLock::new();
|
||||
|
||||
fn authorized() -> &'static Mutex<HashSet<PathBuf>> {
|
||||
AUTHORIZED.get_or_init(|| Mutex::new(HashSet::new()))
|
||||
}
|
||||
|
||||
/// 换行风格。
|
||||
pub const EOL_LF: &str = "lf";
|
||||
pub const EOL_CRLF: &str = "crlf";
|
||||
|
||||
/// 一个已打开文件的完整状态(前端据此显示编码/换行,并原样写回)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileDoc {
|
||||
/// 绝对路径(Windows 下已剥掉 `\\?\` 前缀)
|
||||
pub path: String,
|
||||
/// 显示名(文件名)
|
||||
pub name: String,
|
||||
/// 文本内容(换行已统一为 `\n`,写回时按 `eol` 还原)
|
||||
pub content: String,
|
||||
/// 探测到的编码(`utf-8` / `utf-8-bom` / `gbk` / …)
|
||||
pub encoding: String,
|
||||
/// 换行风格:"lf" | "crlf"
|
||||
pub eol: String,
|
||||
/// 文件字节数
|
||||
pub size: u64,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 是否超过「大文件」阈值(前端据此关闭 Live Preview / 折叠 / 补全)
|
||||
pub large: bool,
|
||||
/// 行数(前端状态栏显示;大文件也只需要扫一遍换行,成本可忽略)
|
||||
pub lines: u64,
|
||||
/// 是否只读(打开时探测写权限失败;前端据此拦截保存并给出原因)
|
||||
pub readonly: bool,
|
||||
}
|
||||
|
||||
/// 探测写权限:以写模式打开但**不写入**(失败 → 只读)。
|
||||
///
|
||||
/// 比「打开成功但保存时才报错」体验好得多:只读文件一打开就能看到状态栏标记。
|
||||
fn is_writable(path: &Path) -> bool {
|
||||
std::fs::OpenOptions::new().write(true).open(path).is_ok()
|
||||
}
|
||||
|
||||
/// 登记一个路径为「已授权可写」。
|
||||
pub fn authorize(path: &Path) {
|
||||
let key = normalize_key(path);
|
||||
if let Ok(mut set) = authorized().lock() {
|
||||
set.insert(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// 该路径是否已授权(写操作的前置条件)。
|
||||
pub fn is_authorized(path: &Path) -> bool {
|
||||
let key = normalize_key(path);
|
||||
authorized()
|
||||
.lock()
|
||||
.map(|set| set.contains(&key))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 授权集合的比对键:**尽力规范化**(解析符号链接与 `..`)。
|
||||
///
|
||||
/// 规范化失败(文件不存在)时退回原路径 —— 那说明写操作本来就会失败,
|
||||
/// 这里没必要为了「统一键」而提前报错。
|
||||
fn normalize_key(path: &Path) -> PathBuf {
|
||||
std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// 把路径转成可显示、可回传的字符串(剥掉 Windows 的 `\\?\` 扩展长度前缀)。
|
||||
pub fn display_path(path: &Path) -> String {
|
||||
let s = path.to_string_lossy().to_string();
|
||||
match s.strip_prefix(r"\\?\") {
|
||||
Some(rest) => rest.to_string(),
|
||||
None => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// 探测编码:返回规范名(`utf-8` / `utf-8-bom` / `gbk` / `gb18030` / `big5` / `shift_jis` / …)。
|
||||
///
|
||||
/// # 判定顺序(每一步都有理由)
|
||||
///
|
||||
/// 1. **BOM**:UTF-8 BOM / UTF-16 的 BOM 是无歧义的事实,直接采信;
|
||||
/// 2. **严格 UTF-8 校验**:能完整解成 UTF-8 就是 UTF-8。优先级高于任何统计猜测 ——
|
||||
/// 中文 GBK 字节序列几乎不可能恰好是合法 UTF-8,反向的误判同样罕见;
|
||||
/// 3. **chardetng 统计探测**:区分 Shift_JIS / Big5 / EUC-KR / GB18030 等 CJK 编码。
|
||||
/// 这一步不能省:GB18030 几乎能解码任意字节序列,若只靠「试解是否成功」,
|
||||
/// 日文 Shift_JIS 文件会被静默当成中文 GB18030;
|
||||
/// 4. 探测器给不出我们支持的编码 → 退回 GB18030 兜底;仍不行则按 UTF-8 有损解码
|
||||
/// (宁可显示替换字符,也不要打不开文件)。
|
||||
pub fn detect_encoding(bytes: &[u8]) -> String {
|
||||
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
|
||||
return "utf-8-bom".to_string();
|
||||
}
|
||||
if bytes.starts_with(&[0xFF, 0xFE]) {
|
||||
return "utf-16le".to_string();
|
||||
}
|
||||
if bytes.starts_with(&[0xFE, 0xFF]) {
|
||||
return "utf-16be".to_string();
|
||||
}
|
||||
if std::str::from_utf8(bytes).is_ok() {
|
||||
return "utf-8".to_string();
|
||||
}
|
||||
// 非 UTF-8:先用统计探测区分 CJK 编码(Shift_JIS / Big5 / EUC-KR / GB18030 …)。
|
||||
// 不能直接拿 GB18030 兜底 —— GB18030 几乎能解码任意字节序列,试解永远「成功」,
|
||||
// 会把日文 Shift_JIS 文件静默当成中文 GB18030(用户实测到的问题)。
|
||||
if let Some(name) = detect_with_chardetng(bytes) {
|
||||
return name;
|
||||
}
|
||||
// 探测器给不出我们支持的编码:退回 GB18030(GBK 的每个序列在它之下都合法)
|
||||
if crate::terminal::encoding::is_supported("gb18030") {
|
||||
return "gb18030".to_string();
|
||||
}
|
||||
"utf-8".to_string()
|
||||
}
|
||||
|
||||
/// 用 `chardetng` 统计探测非 UTF-8 文本的编码,并映射回本模块的规范编码名。
|
||||
///
|
||||
/// 只接受我们**支持**的编码(见 `terminal::encoding::SUPPORTED`):探测器给出的
|
||||
/// 单字节西文编码(`windows-125x` / `ISO-8859-x` / `KOI8-*`)统一归到 `latin1`
|
||||
/// (它们都是单字节、逐字节一一映射,不会产生替换字符);其余未知的一律返回
|
||||
/// `None`,由调用方走兜底 —— 宁可退回 GB18030,也不要返回一个解出来全是 `` 的名字。
|
||||
fn detect_with_chardetng(bytes: &[u8]) -> Option<String> {
|
||||
use chardetng::{EncodingDetector, Iso2022JpDetection, Utf8Detection};
|
||||
|
||||
let mut detector = EncodingDetector::new(Iso2022JpDetection::Deny);
|
||||
detector.feed(bytes, true);
|
||||
// 调用前已排除「合法 UTF-8」,因此不允许探测器再返回 UTF-8
|
||||
let guessed = detector.guess(None, Utf8Detection::Deny);
|
||||
let name = guessed.name().to_ascii_lowercase();
|
||||
|
||||
if name.starts_with("windows-125")
|
||||
|| name.starts_with("iso-8859")
|
||||
|| name.starts_with("koi8")
|
||||
|| name == "ibm866"
|
||||
{
|
||||
return Some("latin1".to_string());
|
||||
}
|
||||
let normalized = crate::terminal::encoding::normalize(&name);
|
||||
if crate::terminal::encoding::is_supported(&normalized) {
|
||||
return Some(normalized);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 按编码把字节解成字符串(BOM 已剥离)。
|
||||
pub(crate) fn decode_bytes(bytes: &[u8], encoding: &str) -> String {
|
||||
match encoding {
|
||||
"utf-8-bom" => {
|
||||
let body = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
|
||||
String::from_utf8_lossy(body).into_owned()
|
||||
}
|
||||
"utf-16le" | "utf-16be" => {
|
||||
// UTF-16 走 encoding_rs;BOM 由它自己处理
|
||||
crate::terminal::encoding::decode(bytes, "utf-16le")
|
||||
}
|
||||
other => crate::terminal::encoding::decode(bytes, other),
|
||||
}
|
||||
}
|
||||
|
||||
/// 按编码把字符串编成字节(必要时写回 BOM)。
|
||||
///
|
||||
/// **不可表示字符绝不静默替换成 `?`**(那是不可逆的数据损坏):先整串试编一次,
|
||||
/// 若往返比对不一致(说明有字符编不进去),再逐字符定位并报错,让用户改用 UTF-8
|
||||
/// 或删除这些字符。
|
||||
pub(crate) fn encode_text(text: &str, encoding: &str) -> Result<Vec<u8>, String> {
|
||||
match encoding {
|
||||
"utf-8-bom" => {
|
||||
let mut out = vec![0xEF, 0xBB, 0xBF];
|
||||
out.extend_from_slice(text.as_bytes());
|
||||
Ok(out)
|
||||
}
|
||||
other => {
|
||||
let normalized = crate::terminal::encoding::normalize(other);
|
||||
if !crate::terminal::encoding::is_supported(&normalized) {
|
||||
return Err(format!("不支持的编码:{other}"));
|
||||
}
|
||||
let encoded = crate::terminal::encoding::encode(text, &normalized);
|
||||
// UTF-8 能表示任何字符串,无需比对
|
||||
if normalized != "utf-8"
|
||||
&& crate::terminal::encoding::decode(&encoded, &normalized) != text
|
||||
{
|
||||
let bad = find_unencodable(text, &normalized);
|
||||
let preview = bad
|
||||
.iter()
|
||||
.take(8)
|
||||
.map(|(index, ch)| format!("第 {index} 个「{ch}」"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("、");
|
||||
let tail = if bad.len() > 8 {
|
||||
format!(",等共 {} 个字符", bad.len())
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
return Err(format!(
|
||||
"编码「{other}」无法表示:{preview}{tail}。请改用 UTF-8,或删除这些字符后再保存"
|
||||
));
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 找出目标编码无法表示的字符(位置按字符计,从 1 开始)。仅在错误路径上跑。
|
||||
fn find_unencodable(text: &str, encoding: &str) -> Vec<(usize, char)> {
|
||||
let mut out = Vec::new();
|
||||
for (index, ch) in text.chars().enumerate() {
|
||||
let mut buf = [0u8; 4];
|
||||
let s = ch.encode_utf8(&mut buf);
|
||||
let encoded = crate::terminal::encoding::encode(s, encoding);
|
||||
if crate::terminal::encoding::decode(&encoded, encoding) != &*s {
|
||||
out.push((index + 1, ch));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 探测换行风格(`\r\n` 只要出现一次就判定为 CRLF —— 混合换行的文件按主流风格写回)。
|
||||
fn detect_eol(text: &str) -> String {
|
||||
if text.contains("\r\n") {
|
||||
EOL_CRLF.to_string()
|
||||
} else {
|
||||
EOL_LF.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取任意文件(自动探测编码)。
|
||||
pub fn read_file(path: &str, max_mb: u32) -> Result<FileDoc, String> {
|
||||
read_file_inner(path, max_mb, None)
|
||||
}
|
||||
|
||||
/// 以指定编码**重新解码磁盘字节**(不写回,只换一种解释方式)。
|
||||
///
|
||||
/// 语义(规划 §5.3):切换编码是「换一种方式解释**磁盘字节**」,而不是「重新解释
|
||||
/// 缓冲区文本」—— 因此必须回到磁盘字节重新解码,而不是把编辑器里已有的字符串再转一次。
|
||||
pub fn redecode_file(path: &str, encoding: &str, max_mb: u32) -> Result<FileDoc, String> {
|
||||
read_file_inner(path, max_mb, Some(encoding))
|
||||
}
|
||||
|
||||
/// 读取实现。`forced_encoding` 为 `None` 时走探测链(BOM → 严格 UTF-8 → GB18030)。
|
||||
fn read_file_inner(
|
||||
path: &str,
|
||||
max_mb: u32,
|
||||
forced_encoding: Option<&str>,
|
||||
) -> Result<FileDoc, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
if p.is_dir() {
|
||||
return Err("这是一个目录,请选择文件".to_string());
|
||||
}
|
||||
let meta = std::fs::metadata(p).map_err(|e| format!("读取文件信息失败: {e}"))?;
|
||||
if !meta.is_file() {
|
||||
return Err("目标不是普通文件".to_string());
|
||||
}
|
||||
let bytes = std::fs::read(p).map_err(|e| format!("读取文件失败: {e}"))?;
|
||||
build_doc(p, &meta, bytes, max_mb, forced_encoding)
|
||||
}
|
||||
|
||||
/// 读取文件,复用调用方**已经读过**的头部(不重开文件、也不重读开头)。
|
||||
///
|
||||
/// 用途是对比模块:它必须「先读头部判断二进制、是文本才整读」(二进制要尽早放弃,
|
||||
/// 不能整读),若先自己嗅探再调 `read_file`,同一个文件会被打开两次、开头读两遍。
|
||||
/// 这里让调用方把**同一个句柄**(读位置已停在 `head` 之后)连同那段头部一起递进来,
|
||||
/// 于是全程只打开一次;也顺带消掉「嗅探时与整读时文件已被换掉」的那个窗口。
|
||||
///
|
||||
/// `meta` 同样由调用方传入(它刚读过一次 `metadata`,两边都省一次 stat)。
|
||||
pub(crate) fn read_file_after_head(
|
||||
mut reader: impl std::io::Read,
|
||||
path: &Path,
|
||||
meta: &Metadata,
|
||||
head: &[u8],
|
||||
max_mb: u32,
|
||||
) -> Result<FileDoc, String> {
|
||||
let mut bytes = Vec::with_capacity(head.len());
|
||||
bytes.extend_from_slice(head);
|
||||
reader
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| format!("读取文件失败: {e}"))?;
|
||||
build_doc(path, meta, bytes, max_mb, None)
|
||||
}
|
||||
|
||||
/// 读取链路的公共尾部:由「磁盘字节 + 元信息」组装 [`FileDoc`]。
|
||||
///
|
||||
/// 两个调用方共用 —— [`read_file_inner`](自己整读)与 [`read_file_after_head`]
|
||||
/// (头部由调用方提供)。把这段独立出来是为了让「字节从哪来」与「字节怎么解释」解耦,
|
||||
/// 而不是让解码 / 换行 / 元信息这段逻辑出现两份。
|
||||
fn build_doc(
|
||||
p: &Path,
|
||||
meta: &Metadata,
|
||||
bytes: Vec<u8>,
|
||||
max_mb: u32,
|
||||
forced_encoding: Option<&str>,
|
||||
) -> Result<FileDoc, String> {
|
||||
let encoding = match forced_encoding {
|
||||
Some(enc) if !enc.trim().is_empty() => {
|
||||
let requested = enc.trim();
|
||||
let normalized = if requested.eq_ignore_ascii_case("utf-8-bom") {
|
||||
"utf-8-bom".to_string()
|
||||
} else {
|
||||
crate::terminal::encoding::normalize(requested)
|
||||
};
|
||||
if normalized != "utf-8-bom" && !crate::terminal::encoding::is_supported(&normalized) {
|
||||
return Err(format!("不支持的编码:{requested}"));
|
||||
}
|
||||
normalized
|
||||
}
|
||||
_ => detect_encoding(&bytes),
|
||||
};
|
||||
let raw = decode_bytes(&bytes, &encoding);
|
||||
let eol = detect_eol(&raw);
|
||||
// 统一成 `\n` 交给编辑器:CM6 的一份文档只应有一种换行,混合换行会让
|
||||
// 「行号 / 选区 / 大纲」三处计算各按各的口径,写法回时再还原
|
||||
let content = raw.replace("\r\n", "\n");
|
||||
let limit = (max_mb.max(1) as u64) * 1024 * 1024;
|
||||
|
||||
Ok(FileDoc {
|
||||
path: display_path(p),
|
||||
name: p
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
lines: content.lines().count() as u64,
|
||||
content,
|
||||
encoding,
|
||||
eol,
|
||||
size: meta.len(),
|
||||
modified: meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0),
|
||||
large: meta.len() > limit,
|
||||
readonly: !is_writable(p),
|
||||
})
|
||||
}
|
||||
|
||||
/// 写入任意文件。
|
||||
///
|
||||
/// `encoding` 为空串时沿用「读时探测到的编码」由前端回传的那个值 —— 调用方
|
||||
/// (编辑器)始终带着它,这里不接受「猜一个」。
|
||||
pub fn write_file(
|
||||
path: &str,
|
||||
content: &str,
|
||||
encoding: &str,
|
||||
eol: &str,
|
||||
max_mb: u32,
|
||||
) -> Result<FileDoc, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
if !is_authorized(p) {
|
||||
return Err("该文件未经授权,无法写入(请通过「打开文件」重新选择)".to_string());
|
||||
}
|
||||
if !is_writable(p) {
|
||||
return Err("文件为只读,无法保存".to_string());
|
||||
}
|
||||
|
||||
let enc = if encoding.trim().is_empty() {
|
||||
"utf-8".to_string()
|
||||
} else {
|
||||
crate::terminal::encoding::normalize(encoding)
|
||||
};
|
||||
let text = if eol == EOL_CRLF {
|
||||
content.replace("\r\n", "\n").replace('\n', "\r\n")
|
||||
} else {
|
||||
content.replace("\r\n", "\n")
|
||||
};
|
||||
let bytes = encode_text(&text, &enc)?;
|
||||
|
||||
std::fs::write(p, &bytes).map_err(|e| format!("保存文件失败: {e}"))?;
|
||||
read_file(trimmed, max_mb)
|
||||
}
|
||||
|
||||
/// 把图片等二进制内容写入库根的 `assets/`(粘贴图片用)。
|
||||
///
|
||||
/// 返回**相对库根的路径**(统一 `/` 分隔),前端据此插入 Markdown 图片引用;
|
||||
/// 不使用绝对路径,保证笔记换个机器 / 换个库根也能打开。
|
||||
pub fn write_asset(
|
||||
root: &Path,
|
||||
file_name: &str,
|
||||
data: &[u8],
|
||||
ext: &str,
|
||||
) -> Result<String, String> {
|
||||
let assets = root.join(super::library::ASSETS_DIR);
|
||||
std::fs::create_dir_all(&assets).map_err(|e| format!("创建附件目录失败: {e}"))?;
|
||||
|
||||
let stem = super::library::validate_name(file_name)?;
|
||||
let stem = Path::new(&stem)
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "image".to_string());
|
||||
let ext = ext.trim().trim_start_matches('.').to_ascii_lowercase();
|
||||
let ext = if ext.is_empty() { "png".to_string() } else { ext };
|
||||
|
||||
let mut candidate = format!("{stem}.{ext}");
|
||||
let mut index = 1;
|
||||
while assets.join(&candidate).exists() {
|
||||
candidate = format!("{stem}-{index}.{ext}");
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名附件过多,请清理 assets 目录".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
std::fs::write(assets.join(&candidate), data).map_err(|e| format!("写入附件失败: {e}"))?;
|
||||
Ok(format!("{}/{candidate}", super::library::ASSETS_DIR))
|
||||
}
|
||||
|
||||
// ===== 测试 =====
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detects_bom_and_plain_utf8() {
|
||||
assert_eq!(detect_encoding(b"hello"), "utf-8");
|
||||
assert_eq!(detect_encoding("\u{feff}hello".as_bytes()), "utf-8-bom");
|
||||
assert_eq!(detect_encoding(&[0xFF, 0xFE, 0x41, 0x00]), "utf-16le");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_non_utf8_chinese_as_gbk_family() {
|
||||
// 中文:合法 UTF-8 校验必然失败,探测应落在 GBK 家族(gbk 或 gb18030)
|
||||
let text = "这是一段中文测试文本,用于验证编码探测。";
|
||||
let gbk = crate::terminal::encoding::encode(text, "gbk");
|
||||
let detected = detect_encoding(&gbk);
|
||||
assert!(
|
||||
detected == "gbk" || detected == "gb18030",
|
||||
"中文应探测为 GBK 家族,实际为 {detected}"
|
||||
);
|
||||
// GB18030 是 GBK 的超集,用它解码同样能还原
|
||||
assert_eq!(decode_bytes(&gbk, "gb18030"), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_shift_jis_not_gb18030() {
|
||||
// 日文 Shift_JIS:GB18030 也能「解码成功」,这正是旧实现误判成中文的原因
|
||||
let text = "これは日本語のテキストです。テスト用のサンプル文です。";
|
||||
let sjis = crate::terminal::encoding::encode(text, "shift_jis");
|
||||
let detected = detect_encoding(&sjis);
|
||||
assert_eq!(
|
||||
detected, "shift_jis",
|
||||
"日文 Shift_JIS 不应被误判(实际 {detected})"
|
||||
);
|
||||
assert_eq!(decode_bytes(&sjis, "shift_jis"), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eol_roundtrip_preserves_crlf() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("crlf.txt");
|
||||
std::fs::write(&path, b"a\r\nb\r\n").unwrap();
|
||||
|
||||
let doc = read_file(&display_path(&path), 5).unwrap();
|
||||
assert_eq!(doc.eol, EOL_CRLF);
|
||||
assert_eq!(doc.content, "a\nb\n");
|
||||
assert_eq!(doc.lines, 2);
|
||||
|
||||
authorize(&path);
|
||||
let saved = write_file(&display_path(&path), "a\nb\nc\n", "utf-8", EOL_CRLF, 5).unwrap();
|
||||
assert_eq!(saved.content, "a\nb\nc\n");
|
||||
// 落盘字节必须还是 CRLF(否则一次保存就污染整个 diff)
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"a\r\nb\r\nc\r\n");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_requires_authorization() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("unauthorized.txt");
|
||||
std::fs::write(&path, b"x").unwrap();
|
||||
let err = write_file(&display_path(&path), "y", "utf-8", EOL_LF, 5).unwrap_err();
|
||||
assert!(err.contains("未经授权"), "{err}");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gbk_write_uses_original_encoding() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("gbk.txt");
|
||||
std::fs::write(&path, crate::terminal::encoding::encode("中文", "gbk")).unwrap();
|
||||
|
||||
let doc = read_file(&display_path(&path), 5).unwrap();
|
||||
assert_eq!(doc.content, "中文");
|
||||
authorize(&path);
|
||||
write_file(&display_path(&path), "中文内容", &doc.encoding, &doc.eol, 5).unwrap();
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert_eq!(crate::terminal::encoding::decode(&bytes, "gbk"), "中文内容");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_flag_uses_megabyte_limit() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("big.txt");
|
||||
std::fs::write(&path, vec![b'a'; 2048]).unwrap();
|
||||
assert!(read_file(&display_path(&path), 1).unwrap().large == false);
|
||||
// 阈值按 MB 计,2048 字节在 0 上限下被夹到 1MB,仍不算大文件
|
||||
assert!(!read_file(&display_path(&path), 0).unwrap().large);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,890 @@
|
||||
//! 「在路径中查找」(Find in Path):对真实文件系统做逐行文本 / 正则检索。
|
||||
//!
|
||||
//! # 为什么不用 `index.rs` 的 FTS5 索引
|
||||
//!
|
||||
//! 索引是**笔记库专用**的加速层:它只覆盖 `.md`、只回传片段(没有行号),且不支持
|
||||
//! 正则。而「在目录 / 库中查找」需要的是**逐行命中 + 行号 + 正则**——这正是 IDEA
|
||||
//! 的 Find in Path 语义(真 grep,不是索引查询)。因此这里直接扫盘,与索引解耦:
|
||||
//! 索引挂掉 / 还没同步完,搜索依然可用。
|
||||
//!
|
||||
//! # 边界(防卡死是第一位的)
|
||||
//!
|
||||
//! - 跳过目录名清单里的目录(默认见 [`DEFAULT_SKIP_DIRS`])与超过大小上限的文件;
|
||||
//! - 跳过二进制文件(前 8KB 含 NUL 字节);
|
||||
//! - **完整统计**所有命中行(`total` / `total_files`),预览结构只构建前 `limit` 条
|
||||
//! (`returned`),`truncated` = 统计到的总数超过回传的预览数。
|
||||
//!
|
||||
//! 「计数便宜、预览贵」:就算超过上限,也只继续 `regex.find` 计数,不再做字符开窗 ——
|
||||
//! 于是「全库一共多少处命中」永远是准的,而 UI 可以分页展示回传的那部分。
|
||||
//!
|
||||
//! # 按文件自己的编码读
|
||||
//!
|
||||
//! 每个文件先用 `detect_encoding` 探测(BOM / UTF-8 合法性 / `chardetng` 统计),再按
|
||||
//! 该编码解码 —— 于是 GBK / Big5 / Shift_JIS / UTF-16 的正文与预览都是**可读的原文字**,
|
||||
//! 而不是一堆 U+FFFD。替换同样按原编码写回(复用 `files.rs` 里那套已带往返校验的
|
||||
//! `encode_text`),因此不会把 GBK 文件改成 UTF-8。
|
||||
//!
|
||||
//! # 每行只出一条命中
|
||||
//!
|
||||
//! 一行里出现多次匹配时,只回传**第一处**(`match_start` / `match_end` 指向它)。
|
||||
//! 这是 grep 类工具的常规做法:结果列表以「行」为单位才能扫读,一行列十条几乎相同
|
||||
//! 的预览反而是噪声。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use regex::{Regex, RegexBuilder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use crate::editor::files::{decode_bytes, detect_encoding, encode_text};
|
||||
|
||||
/// 单文件大小上限(超过则跳过:这类文件多是日志 / 数据,检索无意义且极慢)
|
||||
const MAX_FILE_BYTES: u64 = 8 * 1024 * 1024;
|
||||
/// 单行预览最大字符数(超出时围绕命中位置开窗)
|
||||
const PREVIEW_MAX_CHARS: usize = 220;
|
||||
/// 命中前保留的上下文字符数(开窗时)
|
||||
const PREVIEW_LEAD_CHARS: usize = 60;
|
||||
/// 每个文件最多回传的命中行数(防止单个大文件刷满结果)
|
||||
const MAX_MATCHES_PER_FILE: usize = 200;
|
||||
/// 二进制探测读取的头部字节数
|
||||
const BINARY_SNIFF_BYTES: usize = 8 * 1024;
|
||||
|
||||
/// 默认跳过的目录名(`|` 分隔,大小写不敏感)。
|
||||
///
|
||||
/// 这是**唯一**的跳过依据:早期实现还会无条件跳过所有点目录,那样用户在搜索卡片里
|
||||
/// 把 `.git` 从清单里删掉也搜不进去 —— 控件就成了摆设。默认清单已覆盖常见组合。
|
||||
///
|
||||
/// 与前端 `EditorSearch.vue` 的默认值必须一致(前端是展示源,这里是字段缺省时的兜底)。
|
||||
const DEFAULT_SKIP_DIRS: &str = "debug|.vs|.git|.svn|.hg|.idea|.vscode|node_modules|target|dist|build|out|.cache|__pycache__|.venv|venv|vendor|.next|coverage|.tmp-build";
|
||||
|
||||
/// 把 `|` / `,` 分隔的清单拆开(去空白、去空项)。跳过目录名与文件名通配共用这个约定。
|
||||
fn split_list(raw: &str) -> Vec<String> {
|
||||
raw.split(['|', ','])
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 跳过目录名集合(已转小写)。
|
||||
///
|
||||
/// `None` = 用内置默认清单;`Some("")` = **不跳过任何目录**(用户清空输入框就是明确
|
||||
/// 要求全盘搜,包括 `node_modules`)。
|
||||
fn skip_dir_set(raw: &Option<String>) -> Vec<String> {
|
||||
let list = match raw {
|
||||
Some(s) => split_list(s),
|
||||
None => split_list(DEFAULT_SKIP_DIRS),
|
||||
};
|
||||
list.iter().map(|s| s.to_lowercase()).collect()
|
||||
}
|
||||
|
||||
/// 文件名通配过滤器(`None` = 不过滤)。
|
||||
///
|
||||
/// `*` / `*.*` 按 Windows 习惯当「全部文件」,不按字面 glob 处理 —— 否则 `Makefile`
|
||||
/// 这类无扩展名的文件会被默认值意外排除。多项用 `|` 或 `,` 分隔,大小写不敏感。
|
||||
fn build_file_filter(raw: &Option<String>) -> Option<Regex> {
|
||||
let parts = match raw {
|
||||
Some(s) => split_list(s),
|
||||
None => return None,
|
||||
};
|
||||
if parts.is_empty() || parts.iter().any(|p| p == "*" || p == "*.*") {
|
||||
return None;
|
||||
}
|
||||
let body = parts
|
||||
.iter()
|
||||
.map(|p| glob_to_regex(p))
|
||||
.collect::<Vec<_>>()
|
||||
.join("|");
|
||||
RegexBuilder::new(&format!("^(?:{body})$"))
|
||||
.case_insensitive(true)
|
||||
.build()
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// 单个通配片段 → 正则(只匹配文件名,所以 `*` 不必排除路径分隔符)。
|
||||
fn glob_to_regex(pattern: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for ch in pattern.chars() {
|
||||
match ch {
|
||||
'*' => out.push_str(".*"),
|
||||
'?' => out.push('.'),
|
||||
other => out.push_str(®ex::escape(&other.to_string())),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 查找请求(`dir` 为绝对路径:当前目录或笔记库根)。
|
||||
#[derive(Debug, Clone, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchQuery {
|
||||
/// 检索根目录(绝对路径)
|
||||
pub dir: String,
|
||||
/// 关键词(`regex` 为真时按正则解释)
|
||||
pub pattern: String,
|
||||
/// 区分大小写(默认关:与 CM6 搜索一致)
|
||||
pub case_sensitive: bool,
|
||||
/// 全词匹配
|
||||
pub whole_word: bool,
|
||||
/// 按正则解释关键词
|
||||
pub regex: bool,
|
||||
/// 回传预览条数上限(缺省 1000,夹在 1..=5000)。总数不受它影响 ——
|
||||
/// 超过上限的命中只计数不构建预览,由前端分页展示回传的部分
|
||||
pub limit: Option<i64>,
|
||||
/// 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件)
|
||||
pub file_types: Option<String>,
|
||||
/// 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单)
|
||||
pub skip_dirs: Option<String>,
|
||||
}
|
||||
|
||||
/// 一处命中(以「行」为单位)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchMatch {
|
||||
/// 行号(1 起)
|
||||
pub line: i64,
|
||||
/// 行内字符列(1 起,指向首个匹配)
|
||||
pub column: i64,
|
||||
/// 该行预览(超长时围绕命中开窗,两端以 `…` 标记)
|
||||
pub preview: String,
|
||||
/// 命中在 `preview` 中的起始字符下标(前端高亮用)
|
||||
pub match_start: i64,
|
||||
/// 命中在 `preview` 中的结束字符下标(不含)
|
||||
pub match_end: i64,
|
||||
}
|
||||
|
||||
/// 一个文件内的全部命中。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchFileHits {
|
||||
/// 文件绝对路径
|
||||
pub path: String,
|
||||
/// 文件名(结果列表展示)
|
||||
pub name: String,
|
||||
/// 该文件内**全部**命中行数(`matches` 可能因回传上限只含前一部分)
|
||||
pub total_in_file: i64,
|
||||
pub matches: Vec<PathSearchMatch>,
|
||||
}
|
||||
|
||||
/// 一次「在路径中查找」的结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchResult {
|
||||
/// 按文件分组的命中(文件按遍历顺序;超出回传上限的文件不在此列)
|
||||
pub files: Vec<PathSearchFileHits>,
|
||||
/// 全树命中行总数(统计完整,不受 `limit` 影响)
|
||||
pub total: i64,
|
||||
/// 全树至少命中一行的文件总数(≥ `files.len()`)
|
||||
pub total_files: i64,
|
||||
/// 实际回传的预览条数(`files` 里 `matches` 长度之和,≤ `total`)
|
||||
pub returned: i64,
|
||||
/// `total > returned`:还有命中未回传预览
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// 替换请求(`dir` 为绝对路径:当前目录或笔记库根)。
|
||||
#[derive(Debug, Clone, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceQuery {
|
||||
/// 检索根目录(绝对路径)
|
||||
pub dir: String,
|
||||
/// 关键词(`regex` 为真时按正则解释)
|
||||
pub pattern: String,
|
||||
/// 替换串(`regex` 关闭时按**字面量**写入,不做 `$1` 展开)
|
||||
pub replacement: String,
|
||||
/// 区分大小写(默认关)
|
||||
pub case_sensitive: bool,
|
||||
/// 全词匹配
|
||||
pub whole_word: bool,
|
||||
/// 按正则解释关键词
|
||||
pub regex: bool,
|
||||
/// 替换总数上限(缺省 1000,夹在 1..=5000)
|
||||
pub limit: Option<i64>,
|
||||
/// 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件)
|
||||
pub file_types: Option<String>,
|
||||
/// 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单)
|
||||
pub skip_dirs: Option<String>,
|
||||
}
|
||||
|
||||
/// 一个被修改的文件。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceFileResult {
|
||||
pub path: String,
|
||||
pub name: String,
|
||||
pub replacements: i64,
|
||||
}
|
||||
|
||||
/// 被跳过的文件(非 UTF-8 / 写不进去)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceSkipped {
|
||||
pub path: String,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
/// 一次「在路径中替换」的结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceResult {
|
||||
/// 实际被改写的文件(含各自的替换处数)
|
||||
pub files: Vec<PathReplaceFileResult>,
|
||||
pub files_changed: i64,
|
||||
pub replacements: i64,
|
||||
/// 达到上限提前停止:此时**只改了前面一部分文件**
|
||||
pub truncated: bool,
|
||||
pub skipped: Vec<PathReplaceSkipped>,
|
||||
}
|
||||
|
||||
/// 在目录内逐行检索,按文件分组返回。
|
||||
pub fn search_in_path(query: PathSearchQuery) -> Result<PathSearchResult, String> {
|
||||
let pattern = query.pattern.trim();
|
||||
let dir = Path::new(query.dir.trim());
|
||||
if !dir.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
if pattern.is_empty() {
|
||||
return Ok(PathSearchResult {
|
||||
files: Vec::new(),
|
||||
total: 0,
|
||||
total_files: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
|
||||
let regex = build_regex(pattern, &query)?;
|
||||
let limit = query.limit.unwrap_or(1000).clamp(1, 5000) as usize;
|
||||
let skip_dirs = skip_dir_set(&query.skip_dirs);
|
||||
let file_filter = build_file_filter(&query.file_types);
|
||||
|
||||
let mut files: Vec<PathSearchFileHits> = Vec::new();
|
||||
let mut total = 0usize;
|
||||
let mut total_files = 0usize;
|
||||
let mut returned = 0usize;
|
||||
|
||||
// 不再「达限即停」:命中行数与文件数要统计完整树(用户要的是准确的总量),
|
||||
// 超过 `limit` 之后只继续计数,不再构建预览结构(开窗/换算才是贵的)。
|
||||
for_each_candidate_file(dir, &skip_dirs, file_filter.as_ref(), |path, bytes| {
|
||||
// 按文件**自己的编码**解码:GBK / Big5 / Shift_JIS / UTF-16 的正文与预览都是
|
||||
// 可读的原文字,而不是一堆 U+FFFD
|
||||
let text = decode_bytes(bytes, &detect_encoding(bytes));
|
||||
let mut hits: Vec<PathSearchMatch> = Vec::new();
|
||||
let mut in_file = 0usize;
|
||||
for (index, raw) in text.split('\n').enumerate() {
|
||||
let line = raw.strip_suffix('\r').unwrap_or(raw);
|
||||
let Some(m) = regex.find(line) else { continue };
|
||||
in_file += 1;
|
||||
if returned < limit && hits.len() < MAX_MATCHES_PER_FILE {
|
||||
hits.push(make_match(line, m.start(), m.end(), (index + 1) as i64));
|
||||
returned += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if in_file > 0 {
|
||||
total += in_file;
|
||||
total_files += 1;
|
||||
// 预览为空的文件(上限已满)不进 `files`:UI 上一个没有行的文件头是噪声
|
||||
if !hits.is_empty() {
|
||||
files.push(PathSearchFileHits {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
name: file_name_of(path),
|
||||
total_in_file: in_file as i64,
|
||||
matches: hits,
|
||||
});
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
|
||||
Ok(PathSearchResult {
|
||||
files,
|
||||
total: total as i64,
|
||||
total_files: total_files as i64,
|
||||
returned: returned as i64,
|
||||
truncated: total > returned,
|
||||
})
|
||||
}
|
||||
|
||||
/// 在目录内逐文件替换。
|
||||
///
|
||||
/// # 安全模型(这是会**改用户磁盘文件**的操作,每条都是刻意的)
|
||||
///
|
||||
/// - **按文件自己的编码读与写**:`detect_encoding` 探测 → `decode_bytes` 解码 →
|
||||
/// `encode_text` 编码写回,所以 GBK 文件写回去还是 GBK,不会被改成 UTF-8。
|
||||
/// - **编码不可字节级还原就跳过**:编码探测对某些文件是有歧义的(同一段内容在
|
||||
/// GBK / GB18030 下能编出不同字节,UTF-16 的 BOM 也不一定补得回来)。写回前先验
|
||||
/// 「原文按该编码重新编码 == 原字节」,不等就整文件跳过 —— 否则重编码会顺手改掉
|
||||
/// 未命中的字节,那是用户无从察觉的数据损坏。
|
||||
/// - **替换内容编不进去就跳过**:交给 `encode_text` 判定(它绝不把不可表示字符静默
|
||||
/// 变成 `?`),失败原因逐个回报到 `skipped`。
|
||||
/// - **只写真正变了的文件**:没匹配到就 `return`,不徒增 mtime、不触发文件监听事件。
|
||||
/// - **上限停在文件边界**:替换总数达到 `limit` 就停止并回传 `truncated`。绝不写
|
||||
/// 「一个文件只改了一半」,所以允许总数略微超过上限。
|
||||
/// - **失败即记录**:只读 / 被占用等写入失败不影响其它文件,逐个回报 `skipped`。
|
||||
pub fn replace_in_path(query: PathReplaceQuery) -> Result<PathReplaceResult, String> {
|
||||
let pattern = query.pattern.trim();
|
||||
let dir = Path::new(query.dir.trim());
|
||||
if !dir.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
|
||||
let mut result = PathReplaceResult {
|
||||
files: Vec::new(),
|
||||
files_changed: 0,
|
||||
replacements: 0,
|
||||
truncated: false,
|
||||
skipped: Vec::new(),
|
||||
};
|
||||
if pattern.is_empty() {
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
let regex = build_regex(pattern, &query)?;
|
||||
let limit = query.limit.unwrap_or(1000).clamp(1, 5000) as usize;
|
||||
let skip_dirs = skip_dir_set(&query.skip_dirs);
|
||||
let file_filter = build_file_filter(&query.file_types);
|
||||
// 正则关闭时按字面量写入(不让 `$1` / `$foo` 被意外展开 —— 用户在做纯文本替换);
|
||||
// 开启时才做捕获组展开,并把 CM6 风格的 `$&`(整个匹配)统一成 Rust regex 的 `$0`
|
||||
let expand = query.regex;
|
||||
let replacement = if expand {
|
||||
query.replacement.replace("$&", "$0")
|
||||
} else {
|
||||
query.replacement.clone()
|
||||
};
|
||||
|
||||
for_each_candidate_file(dir, &skip_dirs, file_filter.as_ref(), |path, bytes| {
|
||||
if result.replacements as usize >= limit {
|
||||
result.truncated = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
let encoding = detect_encoding(bytes);
|
||||
let text = decode_bytes(bytes, &encoding);
|
||||
// 编码必须能字节级还原原文,否则重编码会改动未命中的字节(见函数文档)
|
||||
match encode_text(&text, &encoding) {
|
||||
Ok(same) if same == bytes => {}
|
||||
Ok(_) => {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: format!("编码「{encoding}」无法字节级还原原文,已跳过(避免改动未命中的字节)"),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
Err(e) => {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: e,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
let count = regex.find_iter(&text).count();
|
||||
if count == 0 {
|
||||
return true;
|
||||
}
|
||||
let next = if expand {
|
||||
regex.replace_all(&text, replacement.as_str())
|
||||
} else {
|
||||
regex.replace_all(&text, regex::NoExpand(replacement.as_str()))
|
||||
};
|
||||
let out = match encode_text(&next, &encoding) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: e,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = std::fs::write(path, &out) {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: format!("写入失败:{e}"),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
result.replacements += count as i64;
|
||||
result.files_changed += 1;
|
||||
result.files.push(PathReplaceFileResult {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
name: file_name_of(path),
|
||||
replacements: count as i64,
|
||||
});
|
||||
true
|
||||
});
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 遍历 `dir` 下的候选文件(剪枝 + 尺寸 + 二进制 + 文件名通配),逐个把字节交给 `visit`。
|
||||
///
|
||||
/// `visit` 返回 `false` 表示调用方要求提前结束(例如命中总数已达上限)。
|
||||
///
|
||||
/// 抽出来给「查找」与「替换」共用:两者的**取舍必须完全一致**(跳哪些目录、多大算大、
|
||||
/// 什么算二进制、按什么文件名过滤),否则会出现「搜得到、替换却跳过」这种自相矛盾的行为。
|
||||
fn for_each_candidate_file(
|
||||
dir: &Path,
|
||||
skip_dirs: &[String],
|
||||
file_filter: Option<&Regex>,
|
||||
mut visit: impl FnMut(&Path, &[u8]) -> bool,
|
||||
) {
|
||||
for entry in WalkDir::new(dir)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_entry(|e| !should_skip(e, skip_dirs))
|
||||
{
|
||||
let Ok(entry) = entry else { continue };
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
if let Some(filter) = file_filter {
|
||||
let name = entry.file_name().to_string_lossy();
|
||||
if !filter.is_match(&name) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Ok(meta) = entry.metadata() else { continue };
|
||||
if meta.len() > MAX_FILE_BYTES {
|
||||
continue;
|
||||
}
|
||||
let Ok(bytes) = std::fs::read(entry.path()) else { continue };
|
||||
// 二进制文件(头部含 NUL)直接跳过:只会读到一堆乱码预览
|
||||
if bytes[..bytes.len().min(BINARY_SNIFF_BYTES)].contains(&0u8) {
|
||||
continue;
|
||||
}
|
||||
if !visit(entry.path(), &bytes) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 文件名(结果列表展示用)。
|
||||
fn file_name_of(path: &Path) -> String {
|
||||
path.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 查找 / 替换请求共有的匹配选项。
|
||||
///
|
||||
/// 抽成 trait 是为了让两处 `build_regex` 调用**不可能**把选项传串位 —— 查找与替换必须
|
||||
/// 用完全一样的规则构造正则,否则会出现「搜到的和替换的不是同一批」这种最坏情况。
|
||||
trait MatchOptions {
|
||||
fn regex_mode(&self) -> bool;
|
||||
fn whole_word(&self) -> bool;
|
||||
fn case_sensitive(&self) -> bool;
|
||||
}
|
||||
|
||||
impl MatchOptions for PathSearchQuery {
|
||||
fn regex_mode(&self) -> bool {
|
||||
self.regex
|
||||
}
|
||||
fn whole_word(&self) -> bool {
|
||||
self.whole_word
|
||||
}
|
||||
fn case_sensitive(&self) -> bool {
|
||||
self.case_sensitive
|
||||
}
|
||||
}
|
||||
|
||||
impl MatchOptions for PathReplaceQuery {
|
||||
fn regex_mode(&self) -> bool {
|
||||
self.regex
|
||||
}
|
||||
fn whole_word(&self) -> bool {
|
||||
self.whole_word
|
||||
}
|
||||
fn case_sensitive(&self) -> bool {
|
||||
self.case_sensitive
|
||||
}
|
||||
}
|
||||
|
||||
/// 组装正则:`regex` 关闭时转义为字面量,`whole_word` 时包一层词边界。
|
||||
fn build_regex(pattern: &str, options: &impl MatchOptions) -> Result<Regex, String> {
|
||||
let core = if options.regex_mode() {
|
||||
pattern.to_string()
|
||||
} else {
|
||||
regex::escape(pattern)
|
||||
};
|
||||
let body = if options.whole_word() {
|
||||
format!(r"\b(?:{core})\b")
|
||||
} else {
|
||||
core
|
||||
};
|
||||
RegexBuilder::new(&body)
|
||||
.case_insensitive(!options.case_sensitive())
|
||||
.build()
|
||||
.map_err(|e| format!("正则表达式无效:{e}"))
|
||||
}
|
||||
|
||||
/// 目录遍历剪枝:按**清单里的名字**跳过(大小写不敏感)。根目录(depth 0)永不跳过。
|
||||
fn should_skip(entry: &walkdir::DirEntry, skip_dirs: &[String]) -> bool {
|
||||
if entry.depth() == 0 || !entry.file_type().is_dir() {
|
||||
return false;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_lowercase();
|
||||
skip_dirs.iter().any(|s| *s == name)
|
||||
}
|
||||
|
||||
/// 构造一行命中:超长行围绕命中开窗,并把命中位置换算成预览内的字符下标。
|
||||
fn make_match(line: &str, match_start: usize, match_end: usize, line_no: i64) -> PathSearchMatch {
|
||||
let chars: Vec<char> = line.chars().collect();
|
||||
let start_ch = char_index(line, match_start);
|
||||
let end_ch = char_index(line, match_end);
|
||||
|
||||
let window_start = start_ch.saturating_sub(PREVIEW_LEAD_CHARS);
|
||||
let window_end = (window_start + PREVIEW_MAX_CHARS)
|
||||
.max(end_ch)
|
||||
.min(chars.len());
|
||||
let body: String = chars[window_start..window_end].iter().collect();
|
||||
let prefix = if window_start > 0 { "…" } else { "" };
|
||||
let suffix = if window_end < chars.len() { "…" } else { "" };
|
||||
let preview = format!("{prefix}{body}{suffix}");
|
||||
|
||||
let lead = prefix.chars().count() as i64;
|
||||
let preview_len = preview.chars().count() as i64;
|
||||
let match_from = ((start_ch - window_start) as i64 + lead).clamp(0, preview_len);
|
||||
let match_to = ((end_ch - window_start) as i64 + lead).clamp(match_from, preview_len);
|
||||
|
||||
PathSearchMatch {
|
||||
line: line_no,
|
||||
column: (start_ch + 1) as i64,
|
||||
preview,
|
||||
match_start: match_from,
|
||||
match_end: match_to,
|
||||
}
|
||||
}
|
||||
|
||||
/// 字节下标 → 字符下标(`regex` 给的是字节偏移,前端高亮要字符下标)。
|
||||
fn char_index(s: &str, byte: usize) -> usize {
|
||||
let byte = byte.min(s.len());
|
||||
s[..byte].chars().count()
|
||||
}
|
||||
|
||||
/// 「在路径中查找」命令。
|
||||
///
|
||||
/// 走 `spawn_blocking`:一次目录扫描是同步阻塞 IO,放在 Tauri 命令线程上会占住它
|
||||
/// (范式同 `editor_delete_path` / `editor_sync_now`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_search_in_path(query: PathSearchQuery) -> Result<PathSearchResult, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || search_in_path(query))
|
||||
.await
|
||||
.map_err(|e| format!("检索任务失败: {e}"))?
|
||||
}
|
||||
|
||||
/// 「在路径中替换」命令。
|
||||
///
|
||||
/// 与查找同理走 `spawn_blocking`(整棵树的重写是同步阻塞 IO)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_replace_in_path(query: PathReplaceQuery) -> Result<PathReplaceResult, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || replace_in_path(query))
|
||||
.await
|
||||
.map_err(|e| format!("替换任务失败: {e}"))?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 每个用例独占一个临时目录(测试并行跑,不能共用)。
|
||||
///
|
||||
/// 用 crate 的 `target/test-tmp/` 而不是 `std::env::temp_dir()`:系统临时目录在受限
|
||||
/// 环境下未必可写(本机就是这样 —— 连既有的 `files.rs` 用例也会 `PermissionDenied`),
|
||||
/// 而 `target/` 一定可写,且已被 gitignore。
|
||||
fn temp_dir(name: &str) -> std::path::PathBuf {
|
||||
let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("target")
|
||||
.join("test-tmp")
|
||||
.join(format!("grep-{name}"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// 字面量(非正则)替换请求。
|
||||
fn literal(dir: &Path, pattern: &str, replacement: &str) -> PathReplaceQuery {
|
||||
PathReplaceQuery {
|
||||
dir: dir.to_string_lossy().to_string(),
|
||||
pattern: pattern.to_string(),
|
||||
replacement: replacement.to_string(),
|
||||
case_sensitive: true,
|
||||
whole_word: false,
|
||||
regex: false,
|
||||
limit: None,
|
||||
file_types: None,
|
||||
skip_dirs: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 同上的查找请求。
|
||||
fn search_query(dir: &Path, pattern: &str) -> PathSearchQuery {
|
||||
PathSearchQuery {
|
||||
dir: dir.to_string_lossy().to_string(),
|
||||
pattern: pattern.to_string(),
|
||||
case_sensitive: true,
|
||||
whole_word: false,
|
||||
regex: false,
|
||||
limit: None,
|
||||
file_types: None,
|
||||
skip_dirs: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_replace_keeps_bom_and_crlf() {
|
||||
let dir = temp_dir("bom-crlf");
|
||||
let file = dir.join("a.txt");
|
||||
let mut bytes = vec![0xEF, 0xBB, 0xBF];
|
||||
bytes.extend_from_slice(b"foo\r\nfoo\r\n");
|
||||
std::fs::write(&file, &bytes).unwrap();
|
||||
|
||||
let result = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
|
||||
assert_eq!(result.replacements, 2);
|
||||
assert_eq!(result.files_changed, 1);
|
||||
assert!(!result.truncated);
|
||||
assert!(result.skipped.is_empty());
|
||||
|
||||
let mut expected = vec![0xEF, 0xBB, 0xBF];
|
||||
expected.extend_from_slice(b"bar\r\nbar\r\n");
|
||||
assert_eq!(
|
||||
std::fs::read(&file).unwrap(),
|
||||
expected,
|
||||
"BOM 与 CRLF 必须原样保留"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_replacement_does_not_expand_captures() {
|
||||
let dir = temp_dir("literal-dollar");
|
||||
let file = dir.join("a.txt");
|
||||
std::fs::write(&file, "foo\n").unwrap();
|
||||
|
||||
replace_in_path(literal(&dir, "foo", "$1x")).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&file).unwrap(),
|
||||
"$1x\n",
|
||||
"正则关闭时替换串必须按字面量写入"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regex_mode_expands_groups_and_normalizes_ampersand() {
|
||||
let dir = temp_dir("regex-groups");
|
||||
let a = dir.join("a.txt");
|
||||
let b = dir.join("b.txt");
|
||||
std::fs::write(&a, "user@host\n").unwrap();
|
||||
std::fs::write(&b, "word\n").unwrap();
|
||||
|
||||
let mut groups = literal(&dir, r"(\w+)@(\w+)", "$2.$1");
|
||||
groups.regex = true;
|
||||
replace_in_path(groups).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&a).unwrap(), "host.user\n");
|
||||
|
||||
// `$&`(CM6 风格的「整个匹配」)要等价于 Rust 的 `$0`
|
||||
let mut whole = literal(&dir, "word", "[$&]");
|
||||
whole.regex = true;
|
||||
replace_in_path(whole).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&b).unwrap(), "[word]\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn searches_and_replaces_gbk_file_keeping_its_encoding() {
|
||||
let dir = temp_dir("gbk");
|
||||
let file = dir.join("a.txt");
|
||||
let original = crate::terminal::encoding::encode("中文 foo\n", "gbk");
|
||||
std::fs::write(&file, &original).unwrap();
|
||||
assert!(
|
||||
std::str::from_utf8(&original).is_err(),
|
||||
"前提:原文不是合法 UTF-8"
|
||||
);
|
||||
|
||||
// 查找:预览要按原编码解出中文,而不是一堆 U+FFFD
|
||||
let found = search_in_path(search_query(&dir, "foo")).unwrap();
|
||||
assert_eq!(found.total, 1);
|
||||
let preview = &found.files[0].matches[0].preview;
|
||||
assert!(preview.contains("中文"), "预览应按原编码解出中文,实际:{preview}");
|
||||
assert!(!preview.contains('\u{FFFD}'), "预览不应出现替换字符");
|
||||
|
||||
// 替换:写回去仍然是 GBK
|
||||
let replaced = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
|
||||
assert_eq!(replaced.replacements, 1);
|
||||
assert!(
|
||||
replaced.skipped.is_empty(),
|
||||
"GBK 文件应能正常替换,实际跳过:{:?}",
|
||||
replaced.skipped
|
||||
);
|
||||
let after = std::fs::read(&file).unwrap();
|
||||
assert_eq!(
|
||||
decode_bytes(&after, &detect_encoding(&after)),
|
||||
"中文 bar\n",
|
||||
"应能按原编码读回替换后的内容"
|
||||
);
|
||||
assert!(
|
||||
std::str::from_utf8(&after).is_err(),
|
||||
"不能把 GBK 文件写成 UTF-8"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_replace_when_replacement_is_not_encodable() {
|
||||
let dir = temp_dir("unencodable");
|
||||
let file = dir.join("a.txt");
|
||||
let original = crate::terminal::encoding::encode("中文 foo\n", "gbk");
|
||||
std::fs::write(&file, &original).unwrap();
|
||||
|
||||
// emoji 编不进 GBK:必须跳过并回报,绝不能写成 `?`
|
||||
let result = replace_in_path(literal(&dir, "foo", "🙂")).unwrap();
|
||||
assert_eq!(result.replacements, 0);
|
||||
assert_eq!(result.skipped.len(), 1, "应回报为跳过");
|
||||
assert_eq!(
|
||||
std::fs::read(&file).unwrap(),
|
||||
original,
|
||||
"编码装不下替换内容时,文件必须一个字节都不动"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn respects_custom_skip_dirs_and_file_types() {
|
||||
let dir = temp_dir("filters");
|
||||
// 目录名刻意不落在默认清单里(`vendor` / `build` 之类都在清单里)
|
||||
let sub = dir.join("innersrc");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
std::fs::write(dir.join("a.md"), "foo\n").unwrap();
|
||||
std::fs::write(dir.join("b.txt"), "foo\n").unwrap();
|
||||
std::fs::write(sub.join("c.md"), "foo\n").unwrap();
|
||||
|
||||
// `innersrc` 不在默认清单里 → 三处都命中
|
||||
assert_eq!(search_in_path(search_query(&dir, "foo")).unwrap().total, 3);
|
||||
|
||||
// 只搜 *.md
|
||||
let mut by_type = search_query(&dir, "foo");
|
||||
by_type.file_types = Some("*.md".to_string());
|
||||
assert_eq!(search_in_path(by_type).unwrap().total, 2, "应只命中 .md");
|
||||
|
||||
// 跳过 innersrc
|
||||
let mut skip = search_query(&dir, "foo");
|
||||
skip.skip_dirs = Some("innersrc".to_string());
|
||||
assert_eq!(
|
||||
search_in_path(skip).unwrap().total,
|
||||
2,
|
||||
"innersrc 下的应被跳过"
|
||||
);
|
||||
|
||||
// 默认清单跳过 .git
|
||||
let git = dir.join(".git");
|
||||
std::fs::create_dir_all(&git).unwrap();
|
||||
std::fs::write(git.join("cfg"), "foo\n").unwrap();
|
||||
assert_eq!(
|
||||
search_in_path(search_query(&dir, "foo")).unwrap().total,
|
||||
3,
|
||||
"默认清单应跳过 .git"
|
||||
);
|
||||
|
||||
// 清空清单 = 不跳过任何目录(清单是唯一依据)
|
||||
let mut no_skip = search_query(&dir, "foo");
|
||||
no_skip.skip_dirs = Some(String::new());
|
||||
assert_eq!(
|
||||
search_in_path(no_skip).unwrap().total,
|
||||
4,
|
||||
"清空清单后连 .git 也要搜"
|
||||
);
|
||||
|
||||
// `*.*` 按「全部文件」处理:无扩展名的 Makefile 不能被排除
|
||||
std::fs::write(dir.join("Makefile"), "foo\n").unwrap();
|
||||
let mut star = search_query(&dir, "foo");
|
||||
star.file_types = Some("*.*".to_string());
|
||||
assert_eq!(
|
||||
search_in_path(star).unwrap().total,
|
||||
4,
|
||||
"*.* 应包含无扩展名文件"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limit_stops_at_file_boundary_without_half_writes() {
|
||||
let dir = temp_dir("limit");
|
||||
for name in ["1.txt", "2.txt", "3.txt"] {
|
||||
std::fs::write(dir.join(name), "foo\nfoo\n").unwrap();
|
||||
}
|
||||
|
||||
let mut query = literal(&dir, "foo", "bar");
|
||||
query.limit = Some(2);
|
||||
let result = replace_in_path(query).unwrap();
|
||||
|
||||
assert!(result.truncated, "达到上限应回报 truncated");
|
||||
assert_eq!(result.files_changed, 1, "上限停在文件边界,只应改完一个文件");
|
||||
assert_eq!(result.replacements, 2);
|
||||
|
||||
// 其余两个文件必须完全没动(绝不能出现「只改了一半」的文件)
|
||||
let untouched = ["1.txt", "2.txt", "3.txt"]
|
||||
.iter()
|
||||
.filter(|n| std::fs::read_to_string(dir.join(n)).unwrap() == "foo\nfoo\n")
|
||||
.count();
|
||||
assert_eq!(untouched, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_binary_files_and_pruned_dirs() {
|
||||
let dir = temp_dir("binary-prune");
|
||||
let bin = dir.join("bin.dat");
|
||||
std::fs::write(&bin, b"foo\0foo").unwrap();
|
||||
let git = dir.join(".git");
|
||||
std::fs::create_dir_all(&git).unwrap();
|
||||
std::fs::write(git.join("cfg"), "foo\n").unwrap();
|
||||
|
||||
let result = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
|
||||
assert_eq!(result.replacements, 0, "二进制文件与 .git 都不该被改写");
|
||||
assert_eq!(std::fs::read(&bin).unwrap(), b"foo\0foo");
|
||||
assert_eq!(std::fs::read_to_string(git.join("cfg")).unwrap(), "foo\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_and_replace_agree_on_matches() {
|
||||
let dir = temp_dir("agree");
|
||||
std::fs::write(dir.join("a.txt"), "Alpha alpha ALPHA\n").unwrap();
|
||||
|
||||
let found = search_in_path(search_query(&dir, "Alpha")).unwrap();
|
||||
assert_eq!(found.total, 1);
|
||||
|
||||
let replaced = replace_in_path(literal(&dir, "Alpha", "Beta")).unwrap();
|
||||
assert_eq!(replaced.replacements, 1, "替换处数必须与检索结果一致");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.join("a.txt")).unwrap(),
|
||||
"Beta alpha ALPHA\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_counts_all_hits_beyond_limit() {
|
||||
let dir = temp_dir("count-all");
|
||||
for name in ["1.txt", "2.txt", "3.txt"] {
|
||||
std::fs::write(dir.join(name), "foo\nfoo\n").unwrap();
|
||||
}
|
||||
|
||||
let mut query = search_query(&dir, "foo");
|
||||
query.limit = Some(2);
|
||||
let result = search_in_path(query).unwrap();
|
||||
|
||||
assert_eq!(result.total, 6, "总数统计完整树,不受 limit 影响");
|
||||
assert_eq!(result.total_files, 3, "文件数同样统计完整树");
|
||||
assert_eq!(result.returned, 2, "预览只回传 limit 条");
|
||||
assert!(result.truncated, "total > returned 应标记截断");
|
||||
assert_eq!(result.files.len(), 1, "超出上限的文件不再回传预览");
|
||||
assert_eq!(result.files[0].name, "1.txt");
|
||||
assert_eq!(result.files[0].total_in_file, 2);
|
||||
assert_eq!(result.files[0].matches.len(), 2);
|
||||
|
||||
// limit 足够时 truncated 为假,且 returned == total
|
||||
let full = search_in_path(search_query(&dir, "foo")).unwrap();
|
||||
assert_eq!(full.returned, full.total);
|
||||
assert!(!full.truncated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
//! 导入:本地 Markdown 目录 / 单文件 / zip 包 → 笔记库。
|
||||
//!
|
||||
//! # 永不覆盖
|
||||
//!
|
||||
//! 导入的唯一硬规则是**不覆盖库内已有文件**:重名时加序号(`笔记 2.md`)。
|
||||
//! 理由很直接 —— 导入是个批量动作,用户不会记得库里已经有哪些名字;一旦某个
|
||||
//! 同名笔记被静默替换,就是一次不可撤销的数据丢失。「多一个文件」远比「少一篇笔记」
|
||||
//! 可接受。
|
||||
//!
|
||||
//! # zip 的路径安全
|
||||
//!
|
||||
//! zip 条目名可以包含 `..` 或绝对路径(经典的 Zip Slip)。这里用
|
||||
//! `enclosed_name()` 让 zip crate 做规范化与拒绝,再过一道 [`library::safe_join`]。
|
||||
//! 两层都做不是冗余:前者防的是「解包到库外」,后者防的是「库内路径被拼成绝对路径」。
|
||||
//!
|
||||
//! # 保留目录结构
|
||||
//!
|
||||
//! 导入目录时保留其相对结构(`笔记/2026/a.md` → `<目标目录>/笔记/2026/a.md`):
|
||||
//! 用户选一个目录导入,期待的是「把这棵子树搬进来」,而不是把几十篇笔记拍平到一层。
|
||||
//! 但**跳过隐藏目录与 `node_modules`**(与同步的排除规则同一口径)。
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::library;
|
||||
use super::types::ImportReport;
|
||||
|
||||
/// 测试里要用 `ZipWriter::write_all`(`Write` 是 trait 方法,必须进作用域)。
|
||||
#[cfg(test)]
|
||||
use std::io::Write as _;
|
||||
|
||||
/// 单次导入的文件数上限(防御性:避免误选 `C:\` 之类的目录把应用拖死)。
|
||||
const MAX_IMPORT_FILES: usize = 20_000;
|
||||
|
||||
/// 从磁盘路径导入(文件 / 目录 / zip,自动判别)。
|
||||
///
|
||||
/// `dest_dir` 为库内相对目录(空串 = 库根)。
|
||||
pub fn import_path(root: &Path, source: &str, dest_dir: &str) -> Result<ImportReport, String> {
|
||||
let path = PathBuf::from(source.trim());
|
||||
if !path.exists() {
|
||||
return Err(format!("路径不存在:{source}"));
|
||||
}
|
||||
library::ensure_library(root)?;
|
||||
// 目标目录先建出来(导入到新建的目录时它可能还不存在)
|
||||
let dest = library::safe_join(root, dest_dir)?;
|
||||
std::fs::create_dir_all(&dest).map_err(|e| format!("创建目标目录失败: {e}"))?;
|
||||
|
||||
let mut report = ImportReport::default();
|
||||
|
||||
if path.is_file() {
|
||||
let is_zip = path
|
||||
.extension()
|
||||
.map(|e| e.eq_ignore_ascii_case("zip"))
|
||||
.unwrap_or(false);
|
||||
if is_zip {
|
||||
import_zip(root, &path, &dest, &mut report)?;
|
||||
} else {
|
||||
import_single(root, &path, &dest, &mut report)?;
|
||||
}
|
||||
} else {
|
||||
import_dir(root, &path, &dest, &mut report)?;
|
||||
}
|
||||
|
||||
// 导入后刷新索引交给命令层(它有 AppHandle 与索引服务)
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// 导入单个文件(非 Markdown 的图片类文件放进 `assets/`)。
|
||||
fn import_single(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let name = file
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
return Err("无法解析文件名".to_string());
|
||||
}
|
||||
if !is_markdown(&name) {
|
||||
// 单选的图片/附件:放进 assets,不当笔记
|
||||
return import_asset(root, file, &name, report);
|
||||
}
|
||||
copy_note(file, dest, &name, report)
|
||||
}
|
||||
|
||||
/// 递归导入目录(保留相对结构)。
|
||||
fn import_dir(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let mut count = 0usize;
|
||||
for entry in walkdir::WalkDir::new(dir)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
let rel_from_source = match path.strip_prefix(dir) {
|
||||
Ok(rel) => rel,
|
||||
Err(_) => continue,
|
||||
};
|
||||
// 跳过隐藏项与 node_modules(与同步排除口径一致)
|
||||
let rel_text = rel_from_source.to_string_lossy().replace('\\', "/");
|
||||
if rel_text
|
||||
.split('/')
|
||||
.any(|part| part.starts_with('.') || part.eq_ignore_ascii_case("node_modules"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
count += 1;
|
||||
if count > MAX_IMPORT_FILES {
|
||||
return Err(format!("导入文件过多(超过 {MAX_IMPORT_FILES}),请分批导入"));
|
||||
}
|
||||
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if is_markdown(&name) {
|
||||
// 保持子目录结构
|
||||
let sub = rel_from_source
|
||||
.parent()
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default();
|
||||
let target_dir = if sub.is_empty() {
|
||||
dest.to_path_buf()
|
||||
} else {
|
||||
let joined = library::safe_join(root, &relative_to(root, dest, &sub))?;
|
||||
std::fs::create_dir_all(&joined).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
joined
|
||||
};
|
||||
copy_note(path, &target_dir, &name, report)?;
|
||||
} else if is_asset(&name) {
|
||||
if let Err(e) = import_asset(root, path, &name, report) {
|
||||
push_failure(report, &rel_text, &e);
|
||||
}
|
||||
} else {
|
||||
report.skipped += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 由「库内目标目录 + 源侧子目录」拼出库内相对路径。
|
||||
fn relative_to(root: &Path, dest: &Path, sub: &str) -> String {
|
||||
let prefix = library::rel_string(root, dest);
|
||||
if prefix.is_empty() {
|
||||
sub.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{sub}")
|
||||
}
|
||||
}
|
||||
|
||||
/// 导入 zip 包(保留包内结构)。
|
||||
fn import_zip(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let handle = std::fs::File::open(file).map_err(|e| format!("打开 zip 失败: {e}"))?;
|
||||
let mut archive = zip::ZipArchive::new(handle).map_err(|e| format!("读取 zip 失败: {e}"))?;
|
||||
let dest_prefix = library::rel_string(root, dest);
|
||||
|
||||
for index in 0..archive.len() {
|
||||
let mut entry = archive
|
||||
.by_index(index)
|
||||
.map_err(|e| format!("读取 zip 条目失败: {e}"))?;
|
||||
// Zip Slip 的第一道防线:`enclosed_name` 拒绝 `..`/绝对路径
|
||||
let Some(inner) = entry.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
push_failure(report, &format!("条目 #{index}"), "路径越界,已跳过");
|
||||
continue;
|
||||
};
|
||||
if entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let rel = inner.to_string_lossy().replace('\\', "/");
|
||||
// macOS 压缩包常见的 `__MACOSX/` 与隐藏文件
|
||||
if rel
|
||||
.split('/')
|
||||
.any(|part| part.starts_with('.') || part.eq_ignore_ascii_case("__MACOSX"))
|
||||
{
|
||||
report.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let name = inner
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut bytes = Vec::new();
|
||||
entry
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| format!("读取 zip 内容失败: {e}"))?;
|
||||
|
||||
if is_markdown(&name) {
|
||||
let sub = inner
|
||||
.parent()
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default();
|
||||
let target_rel = if sub.is_empty() {
|
||||
join_rel(&dest_prefix, &name)
|
||||
} else {
|
||||
join_rel(&dest_prefix, &format!("{sub}/{name}"))
|
||||
};
|
||||
match write_unique(root, &target_rel, &bytes) {
|
||||
Ok(renamed) => {
|
||||
report.imported += 1;
|
||||
if renamed {
|
||||
report.renamed += 1;
|
||||
}
|
||||
}
|
||||
Err(e) => push_failure(report, &rel, &e),
|
||||
}
|
||||
} else if is_asset(&name) {
|
||||
match write_asset_unique(root, &name, &bytes) {
|
||||
Ok(_) => report.imported += 1,
|
||||
Err(e) => push_failure(report, &rel, &e),
|
||||
}
|
||||
} else {
|
||||
report.skipped += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 拷贝一篇 Markdown(重名加序号,**不覆盖**)。
|
||||
fn copy_note(
|
||||
file: &Path,
|
||||
dest_dir: &Path,
|
||||
name: &str,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let bytes = std::fs::read(file).map_err(|e| format!("读取 {name} 失败: {e}"))?;
|
||||
// 目标目录已在库内,这里直接构造候选名并落盘(仍走 safe_join 的等价校验)
|
||||
let mut candidate = name.to_string();
|
||||
let mut index = 1;
|
||||
while dest_dir.join(&candidate).exists() {
|
||||
candidate = numbered(name, index);
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名文件过多".to_string());
|
||||
}
|
||||
}
|
||||
let renamed = candidate != name;
|
||||
std::fs::write(dest_dir.join(&candidate), &bytes).map_err(|e| format!("写入 {candidate} 失败: {e}"))?;
|
||||
report.imported += 1;
|
||||
if renamed {
|
||||
report.renamed += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把附件写进库根 `assets/`(重名加序号)。
|
||||
fn import_asset(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
name: &str,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let bytes = std::fs::read(file).map_err(|e| format!("读取 {name} 失败: {e}"))?;
|
||||
write_asset_unique(root, name, &bytes)?;
|
||||
report.imported += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 写入 `assets/`(重名加序号)。
|
||||
fn write_asset_unique(root: &Path, name: &str, bytes: &[u8]) -> Result<String, String> {
|
||||
let assets = root.join(library::ASSETS_DIR);
|
||||
std::fs::create_dir_all(&assets).map_err(|e| format!("创建附件目录失败: {e}"))?;
|
||||
let safe = library::validate_name(name)?;
|
||||
let mut candidate = safe.clone();
|
||||
let mut index = 1;
|
||||
while assets.join(&candidate).exists() {
|
||||
candidate = numbered(&safe, index);
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名附件过多".to_string());
|
||||
}
|
||||
}
|
||||
std::fs::write(assets.join(&candidate), bytes).map_err(|e| format!("写入附件失败: {e}"))?;
|
||||
Ok(candidate)
|
||||
}
|
||||
|
||||
/// 按库内相对路径写入(重名加序号),返回是否被改名。
|
||||
fn write_unique(root: &Path, rel: &str, bytes: &[u8]) -> Result<bool, String> {
|
||||
let target = library::safe_join(root, rel)?;
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
let name = target
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
let mut candidate = name.clone();
|
||||
let mut index = 1;
|
||||
let mut renamed = false;
|
||||
while target.parent().map(|p| p.join(&candidate).exists()).unwrap_or(false) {
|
||||
candidate = numbered(&name, index);
|
||||
index += 1;
|
||||
renamed = true;
|
||||
if index > 9999 {
|
||||
return Err("同名文件过多".to_string());
|
||||
}
|
||||
}
|
||||
let final_path = match target.parent() {
|
||||
Some(parent) => parent.join(&candidate),
|
||||
None => target.clone(),
|
||||
};
|
||||
std::fs::write(&final_path, bytes).map_err(|e| format!("写入 {candidate} 失败: {e}"))?;
|
||||
Ok(renamed)
|
||||
}
|
||||
|
||||
/// 拼相对路径(空前缀时不带斜杠)。
|
||||
fn join_rel(prefix: &str, name: &str) -> String {
|
||||
if prefix.is_empty() {
|
||||
name.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{name}")
|
||||
}
|
||||
}
|
||||
|
||||
/// `笔记.md` → `笔记 2.md`
|
||||
fn numbered(name: &str, index: u32) -> String {
|
||||
match name.rfind('.') {
|
||||
Some(dot) => format!("{} {}{}", &name[..dot], index + 1, &name[dot..]),
|
||||
None => format!("{name} {}", index + 1),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_markdown(name: &str) -> bool {
|
||||
name.to_ascii_lowercase().ends_with(".md")
|
||||
|| name.to_ascii_lowercase().ends_with(".markdown")
|
||||
}
|
||||
|
||||
/// 附件类型的白名单(图片、PDF、压缩包以外的常见附件)。
|
||||
///
|
||||
/// 用白名单而不是「非 md 即附件」:导入一个目录时往往会混进 `.DS_Store`、
|
||||
/// `Thumbs.db`、`.gitignore` 之类;把它们全塞进 `assets/` 只会制造垃圾。
|
||||
fn is_asset(name: &str) -> bool {
|
||||
const EXT: &[&str] = &[
|
||||
"png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "avif", "pdf", "mp3", "wav", "mp4",
|
||||
"webm", "zip",
|
||||
];
|
||||
match name.rsplit('.').next() {
|
||||
Some(ext) => EXT.contains(&ext.to_ascii_lowercase().as_str()),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn push_failure(report: &mut ImportReport, name: &str, error: &str) {
|
||||
if report.failures.len() < 20 {
|
||||
report.failures.push(format!("{name}:{error}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_lib(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-import-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_single_file_renames_instead_of_overwriting() {
|
||||
let root = temp_lib("single");
|
||||
let src_dir = std::env::temp_dir().join(format!("thing-notes-src-single-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&src_dir);
|
||||
std::fs::create_dir_all(&src_dir).unwrap();
|
||||
std::fs::write(src_dir.join("a.md"), "导入的内容").unwrap();
|
||||
// 库内已有一篇同名
|
||||
std::fs::write(root.join("a.md"), "库里原有的").unwrap();
|
||||
|
||||
let report = import_path(&root, &src_dir.join("a.md").to_string_lossy(), "").unwrap();
|
||||
assert_eq!(report.imported, 1);
|
||||
assert_eq!(report.renamed, 1);
|
||||
// 原有内容必须没被覆盖
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.md")).unwrap(), "库里原有的");
|
||||
assert_eq!(std::fs::read_to_string(root.join("a 2.md")).unwrap(), "导入的内容");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_dir_all(&src_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_directory_keeps_structure_and_skips_junk() {
|
||||
let root = temp_lib("dir");
|
||||
let src = std::env::temp_dir().join(format!("thing-notes-src-dir-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
std::fs::create_dir_all(src.join("sub")).unwrap();
|
||||
std::fs::create_dir_all(src.join(".git")).unwrap();
|
||||
std::fs::write(src.join("top.md"), "top").unwrap();
|
||||
std::fs::write(src.join("sub/deep.md"), "deep").unwrap();
|
||||
std::fs::write(src.join("sub/note.txt"), "不是 md").unwrap();
|
||||
std::fs::write(src.join(".git/config"), "不该导入").unwrap();
|
||||
std::fs::write(src.join("pic.png"), [1u8, 2, 3]).unwrap();
|
||||
|
||||
let report = import_path(&root, &src.to_string_lossy(), "导入").unwrap();
|
||||
assert_eq!(report.imported, 3, "两篇 md + 一张图片: {report:?}");
|
||||
assert_eq!(report.skipped, 1, "note.txt 应被跳过: {report:?}");
|
||||
assert!(root.join("导入/top.md").is_file());
|
||||
assert!(root.join("导入/sub/deep.md").is_file(), "应保留子目录结构");
|
||||
assert!(root.join("assets/pic.png").is_file());
|
||||
assert!(!root.join("导入/.git").exists());
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_zip_keeps_structure_and_rejects_traversal() {
|
||||
let root = temp_lib("zip");
|
||||
let zip_path = std::env::temp_dir().join(format!("thing-notes-src-{}.zip", std::process::id()));
|
||||
{
|
||||
let file = std::fs::File::create(&zip_path).unwrap();
|
||||
let mut writer = zip::ZipWriter::new(file);
|
||||
let options: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default();
|
||||
writer.start_file("notes/a.md", options).unwrap();
|
||||
writer.write_all(b"# A").unwrap();
|
||||
// 恶意条目:逃出库根
|
||||
writer.start_file("../escape.md", options).unwrap();
|
||||
writer.write_all("坏".as_bytes()).unwrap();
|
||||
writer.start_file("__MACOSX/x.md", options).unwrap();
|
||||
writer.write_all(b"mac").unwrap();
|
||||
writer.finish().unwrap();
|
||||
}
|
||||
|
||||
let report = import_path(&root, &zip_path.to_string_lossy(), "").unwrap();
|
||||
assert_eq!(report.imported, 1, "{report:?}");
|
||||
assert!(root.join("notes/a.md").is_file());
|
||||
// `enclosed_name()` 会把 `../escape.md` 归一化成 `escape.md`(去掉了越界前缀),
|
||||
// 关键是**没有写到库根之外**
|
||||
let parent = root.parent().unwrap();
|
||||
assert!(!parent.join("escape.md").exists(), "不能写到库根之外");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_file(&zip_path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_names_keep_extension() {
|
||||
assert_eq!(numbered("a.md", 1), "a 2.md");
|
||||
assert_eq!(numbered("无扩展名", 0), "无扩展名 1");
|
||||
assert_eq!(numbered("a.b.md", 2), "a.b 3.md");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asset_whitelist_rejects_junk() {
|
||||
assert!(is_asset("pic.png"));
|
||||
assert!(is_asset("PIC.PNG"));
|
||||
assert!(is_asset("doc.pdf"));
|
||||
assert!(!is_asset("Thumbs.db"));
|
||||
assert!(!is_asset(".DS_Store"));
|
||||
assert!(!is_asset("noext"));
|
||||
}}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,592 @@
|
||||
//! 索引服务:单线程 worker + notify 文件监听。
|
||||
//!
|
||||
//! # 为什么索引必须由一个线程独占
|
||||
//!
|
||||
//! `rusqlite::Connection` 不是 `Sync` 的共享对象,而本模块有三个**并发**入口:
|
||||
//! ① 前端的搜索/统计命令(Tauri 命令线程池,可能同时进来好几个);
|
||||
//! ② 保存笔记后的增量更新;③ 文件监听器(notify 自己的回调线程)。
|
||||
//!
|
||||
//! 三种做法各有代价:给连接套 `Mutex` 会让「全库重建索引」这类慢操作**堵住搜索**
|
||||
//! (UI 直接卡住);每次操作现开一个连接则丢失 prepared statement 缓存,还会在
|
||||
//! WAL 上堆出一串写锁竞争。这里选第三条:**一个专职线程独占连接**,所有操作通过
|
||||
//! 消息通道排队进来。慢操作只排队、不阻塞调用方(命令层是异步等待回复),
|
||||
//! 连接始终只有一个,顺序天然可预期。
|
||||
//!
|
||||
//! # 监听器为什么也挂在这个线程上
|
||||
//!
|
||||
//! `notify` 的事件要落到索引上(外部新增/改动文件后立刻可搜),而**只有这个线程
|
||||
//! 能写索引**。让监听回调投递一条 `SyncPath` 消息给 worker,就地把那一个文件同步掉,
|
||||
//! 比「回调里发前端事件 → 前端再调一次同步命令」少一次往返,也不会因为前端窗口
|
||||
//! 关着而漏掉索引更新。
|
||||
//!
|
||||
//! 自我保存识别([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发
|
||||
//! `Modify(Data)`,若把这类事件也当成「外部修改」,前端就会在用户自己打字时反复
|
||||
//! 重载文档 / 弹提示。识别按**库内相对路径**在写入前登记(见 `mark_write_path`),
|
||||
//! 结果写进事件的 `from_app`,由前端决定是否提示 —— 而不是在这里静默丢弃事件。
|
||||
//! 静默丢弃一旦因时序漏判,前端就会把自家的保存当成外部改动而重载。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
|
||||
use super::files;
|
||||
use super::index::{content_hash, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery, NoteSyncReport, EditorIndex};
|
||||
use super::library;
|
||||
use crate::constants::events;
|
||||
|
||||
/// 自我写入(自己刚保存)与外部改动之间的**去重窗口**。
|
||||
///
|
||||
/// 取 1200ms:一次写入可能被 notify 拆成多条事件(`Modify(Data)` 常伴一条元数据事件),
|
||||
/// 命中的第一条之后,这段时间内的同路径事件一并算作「自己写的」,既不重复处理,
|
||||
/// 又不会把窗口拉得太长去吞掉用户紧接着在外部编辑器里的另一次保存。
|
||||
const SUPPRESS_MS: u64 = 1200;
|
||||
|
||||
/// 自我写入登记在「尚未被任何文件事件命中」时的最长存活时间。
|
||||
///
|
||||
/// 比去重窗口宽得多:notify 的派发延迟可能到秒级,窗口太窄会把「自己刚写的」误判成
|
||||
/// 外部修改(重载文档、光标弹回第一行)—— 这正是要避免的事故。登记项一旦被**第一个**
|
||||
/// 匹配事件消费,就只保留 [`SUPPRESS_MS`] 的去重窗口,不会长期吞掉真正的外部改动。
|
||||
const SELF_WRITE_TTL_MS: u64 = 30_000;
|
||||
|
||||
/// 单个文件事件的去抖说明。
|
||||
///
|
||||
/// worker 是「来一条处理一条」,去抖由三层共同承担:notify 自身的派发合并、
|
||||
/// 前端 `editor-library-changed` 的 400ms 防抖、以及自我保存抑制窗口。
|
||||
/// 之所以不在这里再加一个定时器:多一层延迟就多一个「事件丢了谁负责」的疑问,
|
||||
/// 而下游每一层都是幂等的(重复同步同一个文件只是重算一次 hash)。
|
||||
const _DEBOUNCE_NOTE_MS: u64 = 250;
|
||||
|
||||
/// 库文件变化的分类(前端据此决定「重载当前笔记」还是「只刷新树」)。
|
||||
///
|
||||
/// 只有 `removed` 是确定事实(文件不在了);「新建」与「修改」在单文件事件层面
|
||||
/// **无法区分**(notify 给的 `Create` 与 `Modify` 在一次保存里会同时出现),
|
||||
/// 因此统一报 [`CHANGE_MODIFIED`],由前端按「路径在不在当前树里」自行判断。
|
||||
pub const CHANGE_MODIFIED: &str = "modified";
|
||||
pub const CHANGE_REMOVED: &str = "removed";
|
||||
|
||||
/// 广播给各窗口的库文件变化事件。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteFileEvent {
|
||||
/// 相对库根的路径(`/` 分隔)
|
||||
pub rel_path: String,
|
||||
/// 磁盘上的绝对路径。
|
||||
///
|
||||
/// 前端需要它来判断「这个事件说的是不是我正在编辑的那个库外文件」——
|
||||
/// 相对库根路径对库外文件没有意义(它根本不在库里),只留 `rel_path`
|
||||
/// 会让「打开 D:\x\a.md 时有人在别处改了它」永远匹配不上。
|
||||
pub abs_path: String,
|
||||
/// "modified" | "removed"
|
||||
pub kind: String,
|
||||
/// 事件发生时间(Unix 毫秒)
|
||||
pub at: u64,
|
||||
/// 是否是本应用自己写入造成的(前端据此跳过「外部修改」提示)
|
||||
pub from_app: bool,
|
||||
}
|
||||
|
||||
/// 一次索引同步的结果(命令返回值)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteIndexReport {
|
||||
pub indexed: i64,
|
||||
pub removed: i64,
|
||||
pub skipped: i64,
|
||||
/// 同步后索引里的笔记数(前端直接显示,省一次统计往返)
|
||||
pub note_count: i64,
|
||||
}
|
||||
|
||||
impl From<NoteSyncReport> for NoteIndexReport {
|
||||
fn from(report: NoteSyncReport) -> Self {
|
||||
Self {
|
||||
indexed: report.indexed,
|
||||
removed: report.removed,
|
||||
skipped: report.skipped,
|
||||
note_count: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// worker 请求。
|
||||
enum Request {
|
||||
/// 增量同步整个库
|
||||
Sync(Sender<Result<NoteSyncReport, String>>),
|
||||
/// 全量重建
|
||||
Rebuild(Sender<Result<NoteSyncReport, String>>),
|
||||
/// 同步单个文件(监听器投递;文件不存在则从索引移除)
|
||||
SyncPath(PathBuf),
|
||||
/// 全文检索
|
||||
Search(NoteSearchQuery, Sender<Result<NoteSearchPage, String>>),
|
||||
/// 快速打开清单
|
||||
List(i64, Sender<Result<Vec<NoteSearchHit>, String>>),
|
||||
/// 标签清单
|
||||
Tags(Sender<Result<Vec<super::index::NoteTagCount>, String>>),
|
||||
/// 一篇笔记的出链 / 入链
|
||||
Backlinks(String, Sender<Result<super::index::NoteBacklinks, String>>),
|
||||
/// 全库链接图
|
||||
LinkGraph(Sender<Result<Vec<(String, String)>, String>>),
|
||||
/// 索引状态
|
||||
Stats(Sender<Result<NoteIndexStats, String>>),
|
||||
/// 重建监听器(库根变化后)
|
||||
Retarget(PathBuf, Sender<Result<(), String>>),
|
||||
}
|
||||
|
||||
/// 一条「本应用自己写入」的登记。
|
||||
struct SelfWrite {
|
||||
/// 库内相对路径(`/` 分隔,与 [`library::rel_string`] 的输出一致)
|
||||
rel: String,
|
||||
/// 登记时刻(写入之前,见 [`IndexService::mark_write_path`])
|
||||
marked: Instant,
|
||||
/// 首次被文件事件命中的时刻(`None` = 还没等到它的事件)
|
||||
matched: Option<Instant>,
|
||||
}
|
||||
|
||||
/// 丢弃过期的自我写入登记。
|
||||
///
|
||||
/// - **已命中**:保留 [`SUPPRESS_MS`] —— 覆盖同一次写入产生的重复事件。
|
||||
/// - **未命中**:保留 [`SELF_WRITE_TTL_MS`] —— 等它的文件事件到达(notify 延迟可能到秒级)。
|
||||
fn prune_self_writes(paths: &mut Vec<SelfWrite>) {
|
||||
let dedupe = Duration::from_millis(SUPPRESS_MS);
|
||||
let wait = Duration::from_millis(SELF_WRITE_TTL_MS);
|
||||
paths.retain(|entry| match entry.matched {
|
||||
Some(at) => at.elapsed() < dedupe,
|
||||
None => entry.marked.elapsed() < wait,
|
||||
});
|
||||
}
|
||||
|
||||
/// 索引服务的句柄(命令层只拿到这个)。
|
||||
pub struct IndexService {
|
||||
tx: Sender<Request>,
|
||||
/// 批量自我写入的时间点(导入 / WebDAV 同步 / 恢复 / 模板导出这类无法逐路径枚举的操作)。
|
||||
/// 窗口内的一切文件事件都当作「自己写的」,不向前端提示外部修改。
|
||||
bulk_write: Mutex<Option<Instant>>,
|
||||
/// 单个文件的自我写入登记。
|
||||
/// 比批量窗口精确:保存 A 不会再顺带吞掉 B 的外部改动事件。
|
||||
write_paths: Mutex<Vec<SelfWrite>>,
|
||||
}
|
||||
|
||||
static SERVICE: std::sync::OnceLock<IndexService> = std::sync::OnceLock::new();
|
||||
|
||||
/// 取索引服务(首次调用时启动 worker 线程与监听器)。
|
||||
pub fn service(app: &AppHandle) -> &'static IndexService {
|
||||
SERVICE.get_or_init(|| IndexService::start(app.clone()))
|
||||
}
|
||||
|
||||
impl IndexService {
|
||||
fn start(app: AppHandle) -> Self {
|
||||
let (tx, rx) = mpsc::channel::<Request>();
|
||||
let handle_tx = tx.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("editor-index".to_string())
|
||||
.spawn(move || worker_loop(app, rx, handle_tx))
|
||||
.expect("启动笔记索引线程失败");
|
||||
Self {
|
||||
tx,
|
||||
bulk_write: Mutex::new(None),
|
||||
write_paths: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 标记「刚刚由本应用**批量**写入了文件」(导入 / 同步 / 恢复 / 模板导出)。
|
||||
/// 这类操作无法逐路径枚举,窗口内一律视为自我写入。
|
||||
pub fn mark_write_all(&self) {
|
||||
if let Ok(mut slot) = self.bulk_write.lock() {
|
||||
*slot = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
/// 登记「本应用即将写入这个库内相对路径」。
|
||||
///
|
||||
/// **必须在真正的 `fs::write` 之前调用**:notify 的 Modify 事件可能与写入几乎同时
|
||||
/// 到达 worker,若等写盘回来再登记,事件可能已经被处理并误判为「外部修改」。
|
||||
pub fn mark_write_path(&self, rel: &str) {
|
||||
if rel.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Ok(mut paths) = self.write_paths.lock() {
|
||||
prune_self_writes(&mut paths);
|
||||
paths.push(SelfWrite {
|
||||
rel: rel.to_string(),
|
||||
marked: Instant::now(),
|
||||
matched: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 这个库内相对路径是不是「本应用自己刚写的」。
|
||||
///
|
||||
/// 命中**一次就算消费**:优先匹配还没命中过的登记(一次写入对应一次命中),
|
||||
/// 找不到才回退到刚命中过的(覆盖同一次写入的重复事件)。这样即便 notify 延迟到
|
||||
/// 秒级,登记项仍在(见 [`SELF_WRITE_TTL_MS`]),不会把自家的保存误判成外部修改。
|
||||
fn recently_written(&self, rel: &str) -> bool {
|
||||
let bulk = self
|
||||
.bulk_write
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|slot| *slot)
|
||||
.map(|at| at.elapsed() < Duration::from_millis(SUPPRESS_MS))
|
||||
.unwrap_or(false);
|
||||
if bulk {
|
||||
return true;
|
||||
}
|
||||
let Ok(mut paths) = self.write_paths.lock() else {
|
||||
return false;
|
||||
};
|
||||
prune_self_writes(&mut paths);
|
||||
let index = paths
|
||||
.iter()
|
||||
.position(|entry| entry.rel == rel && entry.matched.is_none())
|
||||
.or_else(|| paths.iter().position(|entry| entry.rel == rel));
|
||||
let Some(index) = index else {
|
||||
return false;
|
||||
};
|
||||
let entry = &mut paths[index];
|
||||
entry.matched.get_or_insert_with(Instant::now);
|
||||
true
|
||||
}
|
||||
|
||||
/// 增量同步整个库。
|
||||
pub fn sync(&self) -> Result<NoteSyncReport, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Sync(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全量重建索引。
|
||||
pub fn rebuild(&self) -> Result<NoteSyncReport, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Rebuild(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全文检索。
|
||||
pub fn search(&self, query: NoteSearchQuery) -> Result<NoteSearchPage, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Search(query, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 快速打开清单。
|
||||
pub fn list(&self, limit: i64) -> Result<Vec<NoteSearchHit>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::List(limit, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 标签清单。
|
||||
pub fn tags(&self) -> Result<Vec<super::index::NoteTagCount>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Tags(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 索引状态。
|
||||
pub fn stats(&self) -> Result<NoteIndexStats, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Stats(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 一篇笔记的出链 / 入链。
|
||||
pub fn backlinks(&self, rel_path: &str) -> Result<super::index::NoteBacklinks, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Backlinks(rel_path.to_string(), tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全库链接图(已解析的内部链接边)。
|
||||
pub fn link_graph(&self) -> Result<Vec<(String, String)>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::LinkGraph(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 切换库根(重新打开索引 + 重建监听器)。
|
||||
pub fn retarget(&self, root: PathBuf) -> Result<(), String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Retarget(root, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
}
|
||||
|
||||
/// worker 主循环:独占 [`EditorIndex`],串行处理所有请求。
|
||||
fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>) {
|
||||
let mut index: Option<EditorIndex> = None;
|
||||
let mut watcher: Option<RecommendedWatcher> = None;
|
||||
let mut watched_root: Option<PathBuf> = None;
|
||||
let mut root: Option<PathBuf> = None;
|
||||
|
||||
while let Ok(request) = rx.recv() {
|
||||
match request {
|
||||
Request::Sync(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.sync()));
|
||||
}
|
||||
Request::Rebuild(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.rebuild()));
|
||||
}
|
||||
Request::Search(query, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.search(query)));
|
||||
}
|
||||
Request::List(limit, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.list_notes(limit)));
|
||||
}
|
||||
Request::Tags(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.tags()));
|
||||
}
|
||||
Request::Backlinks(rel_path, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| {
|
||||
idx.backlinks(&rel_path)
|
||||
}));
|
||||
}
|
||||
Request::LinkGraph(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.link_graph()));
|
||||
}
|
||||
Request::Stats(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.stats()));
|
||||
}
|
||||
Request::Retarget(next, reply) => {
|
||||
// 库根未变:直接返回,不重开索引、不重建监听器。
|
||||
// 早期实现每次都 `index = None` + 重挂 watcher,于是**每次自动保存**都要重开
|
||||
// SQLite 连接、重建 notify 监听,既慢,又让「写入 → 事件」挤进这段重建窗口,
|
||||
// 制造出「自己保存却被当成外部修改」的竞态。
|
||||
if root.as_deref() == Some(next.as_path()) {
|
||||
let _ = reply.send(Ok(()));
|
||||
continue;
|
||||
}
|
||||
// 库根切换:丢掉旧索引实例,下次操作按新库根重新打开
|
||||
index = None;
|
||||
root = Some(next.clone());
|
||||
let result = match ensure_index(&app, &mut index, &next) {
|
||||
Ok(_) => {
|
||||
watched_root = None; // 触发重建监听器
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
// 新库的监听器要在回复之后建:先让前端拿到「已切换」的结果
|
||||
ensure_watcher(&mut watcher, &mut watched_root, &next, &handle_tx);
|
||||
}
|
||||
Request::SyncPath(path) => {
|
||||
if let Some(current) = root.clone() {
|
||||
// 索引尚未建立时先建(首次操作前就被外部改动的情况)
|
||||
if index.is_none() {
|
||||
if let Err(e) = ensure_index(&app, &mut index, ¤t) {
|
||||
crate::logger::log_warn("editor", &format!("索引不可用: {e}"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
ensure_watcher(&mut watcher, &mut watched_root, ¤t, &handle_tx);
|
||||
sync_one(&app, index.as_mut(), ¤t, &path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 借出索引(必要时按 `root` 打开),并把结果映射成 `Result<_, String>`。
|
||||
fn with_index<T>(
|
||||
app: &AppHandle,
|
||||
index: &mut Option<EditorIndex>,
|
||||
root: &mut Option<PathBuf>,
|
||||
run: impl FnOnce(&mut EditorIndex) -> Result<T, String>,
|
||||
) -> Result<T, String> {
|
||||
let Some(current) = root.clone() else {
|
||||
// 不在这里猜库根:命令层每次操作前都会 `retarget` 到当前库根,
|
||||
// 猜错的后果是索引挂到别的目录上(用户切过库时尤其明显)。
|
||||
return Err("索引尚未指向任何笔记库(请先打开笔记窗口)".to_string());
|
||||
};
|
||||
ensure_index(app, index, ¤t)?;
|
||||
match index.as_mut() {
|
||||
Some(idx) => run(idx),
|
||||
None => Err("索引未就绪".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保索引实例存在且指向 `root`(不匹配则重新打开)。
|
||||
fn ensure_index(app: &AppHandle, index: &mut Option<EditorIndex>, root: &Path) -> Result<(), String> {
|
||||
if let Some(existing) = index.as_ref() {
|
||||
if existing.root() == root {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if let Err(e) = library::ensure_library(root) {
|
||||
crate::logger::log_warn("editor", &e);
|
||||
}
|
||||
let opened = EditorIndex::open(root)?;
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("索引已就绪: {}", opened.db_path().display()),
|
||||
);
|
||||
// 首次打开时不自动全量同步:库可能很大,交给命令层(打开编辑器 / 重建索引时)触发
|
||||
let _ = app;
|
||||
*index = Some(opened);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 确保监听器挂在 `root` 上。
|
||||
fn ensure_watcher(
|
||||
watcher: &mut Option<RecommendedWatcher>,
|
||||
watched_root: &mut Option<PathBuf>,
|
||||
root: &Path,
|
||||
tx: &Sender<Request>,
|
||||
) {
|
||||
if let Err(e) = ensure_watcher_inner(watcher, watched_root, root, tx) {
|
||||
crate::logger::log_warn("editor", &e);
|
||||
}
|
||||
}
|
||||
|
||||
/// 建/换监听器(`root` 未变则不动)。
|
||||
fn ensure_watcher_inner(
|
||||
watcher: &mut Option<RecommendedWatcher>,
|
||||
watched_root: &mut Option<PathBuf>,
|
||||
root: &Path,
|
||||
tx: &Sender<Request>,
|
||||
) -> Result<(), String> {
|
||||
if watched_root.as_deref() == Some(root) && watcher.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let sender = tx.clone();
|
||||
let mut next = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
|
||||
let Ok(event) = event else { return };
|
||||
for path in event_paths(&event) {
|
||||
let _ = sender.send(Request::SyncPath(path));
|
||||
}
|
||||
})
|
||||
.map_err(|e| format!("创建库监听器失败: {e}"))?;
|
||||
|
||||
next.watch(root, RecursiveMode::Recursive)
|
||||
.map_err(|e| format!("监听笔记库失败: {e}"))?;
|
||||
|
||||
// 替换旧监听器(drop 即 unwatch)
|
||||
*watcher = Some(next);
|
||||
*watched_root = Some(root.to_path_buf());
|
||||
crate::logger::log_info("editor", &format!("库监听已启动: {}", root.display()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.editor/` 自身)。
|
||||
///
|
||||
/// 重命名会给出两个路径(旧、新),这里都收下:旧路径在同步时会发现「文件不存在」
|
||||
/// 而被当作删除处理,新路径自然成为新增 —— 无需专门分辨 RenameMode。
|
||||
fn event_paths(event: ¬ify::Event) -> Vec<PathBuf> {
|
||||
if matches!(event.kind, EventKind::Access(_) | EventKind::Other) {
|
||||
return Vec::new();
|
||||
}
|
||||
event
|
||||
.paths
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
let name = p.file_name().map(|n| n.to_string_lossy().to_string());
|
||||
// 只跟踪 .md 与目录事件(目录事件用于捕捉「整目录移入」)
|
||||
let is_md = name
|
||||
.as_deref()
|
||||
.map(|n| n.to_ascii_lowercase().ends_with(".md"))
|
||||
.unwrap_or(false);
|
||||
let is_meta = p
|
||||
.components()
|
||||
.any(|c| c.as_os_str().to_string_lossy().starts_with('.'));
|
||||
is_md && !is_meta
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 就地同步单个文件(含自我保存抑制与前端事件广播)。
|
||||
///
|
||||
/// 事件是否「本应用自己写的」按**库内相对路径**判定(见 [`IndexService::mark_write_path`]),
|
||||
/// 而不是一个全局时间窗 —— 全局窗会把「保存 A 之后 1.2s 内 B 被外部改动」也一并吞掉。
|
||||
fn sync_one(app: &AppHandle, index: Option<&mut EditorIndex>, root: &Path, path: &Path) {
|
||||
let Some(index) = index else { return };
|
||||
let rel = library::rel_string(root, path);
|
||||
if rel.is_empty() || rel.starts_with('.') || rel.starts_with("assets/") {
|
||||
return;
|
||||
}
|
||||
|
||||
// 自我保存抑制:只影响「是否提示用户」,索引照常更新
|
||||
let self_write = SERVICE
|
||||
.get()
|
||||
.map(|service| service.recently_written(&rel))
|
||||
.unwrap_or(false);
|
||||
|
||||
let kind = if path.is_file() {
|
||||
if let Ok(bytes) = std::fs::read(path) {
|
||||
let content = String::from_utf8_lossy(&bytes);
|
||||
let meta = std::fs::metadata(path).ok();
|
||||
let mtime = meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.modified().ok())
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0);
|
||||
let stems = std::collections::HashMap::new();
|
||||
if let Err(e) = index.upsert_note(
|
||||
&rel,
|
||||
&content,
|
||||
mtime,
|
||||
meta.as_ref().map(|m| m.len()).unwrap_or(0),
|
||||
&content_hash(&bytes),
|
||||
&stems,
|
||||
) {
|
||||
crate::logger::log_warn("editor", &format!("增量索引 {rel} 失败: {e}"));
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
// 无法分辨「新建」与「修改」时统一报 modified:前端对两者的处理相同
|
||||
// (重载树)。真正需要区分时以库扫描结果为准。
|
||||
CHANGE_MODIFIED
|
||||
} else {
|
||||
if let Err(e) = index.remove_note(&rel) {
|
||||
crate::logger::log_warn("editor", &format!("移除索引 {rel} 失败: {e}"));
|
||||
}
|
||||
CHANGE_REMOVED
|
||||
};
|
||||
|
||||
// 事件一律发出,用 `from_app` 如实标注来源,由前端决定是否提示/重载。
|
||||
// 早期实现是「自己写的就静默不发」,一旦自我写入判定因时序漏过,前端就会把自家
|
||||
// 的保存当成外部修改而重载文档(光标弹回第一行)—— 判定留在前端更稳。
|
||||
let payload = NoteFileEvent {
|
||||
rel_path: rel,
|
||||
abs_path: files::display_path(path),
|
||||
kind: kind.to_string(),
|
||||
at: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0),
|
||||
from_app: self_write,
|
||||
};
|
||||
if let Err(e) = app.emit(events::EDITOR_FILE_CHANGED, payload) {
|
||||
crate::logger::log_warn("editor", &format!("发出文件变化事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 授权 + 读取(供命令层调用,收敛「读文件必须先登记授权」这条规则)。
|
||||
pub fn read_and_authorize(path: &str, max_mb: u32) -> Result<files::FileDoc, String> {
|
||||
let doc = files::read_file(path, max_mb)?;
|
||||
files::authorize(Path::new(&doc.path));
|
||||
Ok(doc)
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
//! 笔记库的文件系统层:路径安全解析、扫描、读写、增删改移。
|
||||
//!
|
||||
//! # 真相在文件,不在数据库
|
||||
//!
|
||||
//! 笔记就是库根下的 `.md` 文件树。本文件的每个函数都以「相对库根的路径」为
|
||||
//! 输入/输出,**所有路径都先过 [`safe_join`]**:拒绝绝对路径、盘符与 `..`,
|
||||
//! 保证任何操作都无法越出库根(前端传来的路径一律不可信)。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use super::types::{LibraryEntry, NoteDoc, EditorSettings};
|
||||
|
||||
/// 默认库根相对模块目录的名字:`{app_data_dir}/editor/library`
|
||||
pub const DEFAULT_LIBRARY_DIR: &str = "library";
|
||||
/// 附件(粘贴图片等)目录名,位于库根下
|
||||
pub const ASSETS_DIR: &str = "assets";
|
||||
/// 库内私有目录名(索引 + 同步基线),**永不参与同步 / 导出 / 快照**。
|
||||
pub const PRIVATE_DIR: &str = ".editor";
|
||||
/// v1「笔记模块」的私有目录名;首次打开时惰性迁移到 [`PRIVATE_DIR`]。
|
||||
const LEGACY_PRIVATE_DIR: &str = ".notes";
|
||||
/// 扫描深度上限(防御性:软链接成环时不会无限递归)。
|
||||
/// 对 `index.rs` 公开:两处扫描(侧栏树 / 索引)必须用同一个深度口径,
|
||||
/// 否则会出现「树里看不到、搜索却搜得到」这种自相矛盾的状态。
|
||||
pub const MAX_DEPTH: usize = 24;
|
||||
|
||||
/// 新建笔记的正文模板(front-matter + 一级标题)。
|
||||
fn note_template(title: &str) -> String {
|
||||
let now = chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
|
||||
format!(
|
||||
"---\ntitle: {title}\ncreated: {now}\nupdated: {now}\ntags: []\n---\n\n# {title}\n\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// 默认库根路径(未配置自定义库根时使用)。
|
||||
pub fn default_library_root(module_dir: &Path) -> PathBuf {
|
||||
module_dir.join(DEFAULT_LIBRARY_DIR)
|
||||
}
|
||||
|
||||
/// 由设置解析出当前生效的库根。
|
||||
pub fn resolve_library_root(module_dir: &Path, settings: &EditorSettings) -> PathBuf {
|
||||
match &settings.library_root {
|
||||
Some(root) if !root.trim().is_empty() => PathBuf::from(root.trim()),
|
||||
_ => default_library_root(module_dir),
|
||||
}
|
||||
}
|
||||
|
||||
/// 惰性迁移旧私有目录 `.notes/` → `.editor/`(幂等)。
|
||||
///
|
||||
/// 索引可重建,但迁移能保住同步基线(`sync.json`),因此优先整目录重命名。
|
||||
/// 迁移后残留的旧索引文件(`notes.db*`)直接删除 —— 下次打开会按新库根重建。
|
||||
pub fn migrate_private_dir(root: &Path) {
|
||||
let old = root.join(LEGACY_PRIVATE_DIR);
|
||||
let new = root.join(PRIVATE_DIR);
|
||||
if !old.is_dir() || new.exists() {
|
||||
return;
|
||||
}
|
||||
match std::fs::rename(&old, &new) {
|
||||
Ok(()) => {
|
||||
for stale in ["notes.db", "notes.db-wal", "notes.db-shm"] {
|
||||
let _ = std::fs::remove_file(new.join(stale));
|
||||
}
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("已迁移库内私有目录 {LEGACY_PRIVATE_DIR}/ → {PRIVATE_DIR}/"),
|
||||
);
|
||||
}
|
||||
Err(e) => crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!("迁移库内私有目录失败(将按新目录重建): {e}"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保库根与其 `assets/` 子目录存在(顺带惰性迁移旧私有目录)。
|
||||
pub fn ensure_library(root: &Path) -> Result<(), String> {
|
||||
migrate_private_dir(root);
|
||||
std::fs::create_dir_all(root).map_err(|e| format!("创建笔记库目录失败: {e}"))?;
|
||||
std::fs::create_dir_all(root.join(ASSETS_DIR))
|
||||
.map_err(|e| format!("创建附件目录失败: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把「相对库根的路径」解析为绝对路径,并拒绝任何逃逸。
|
||||
///
|
||||
/// 空串表示库根本身。统一接受 `/` 与 `\` 两种分隔符输入,输出用系统分隔符。
|
||||
pub fn safe_join(root: &Path, rel: &str) -> Result<PathBuf, String> {
|
||||
let normalized = rel.trim().replace('\\', "/");
|
||||
if normalized.starts_with('/') || normalized.contains(':') {
|
||||
return Err("仅支持库内相对路径".to_string());
|
||||
}
|
||||
let mut out = root.to_path_buf();
|
||||
for part in normalized.split('/') {
|
||||
if part.is_empty() || part == "." {
|
||||
continue;
|
||||
}
|
||||
if part == ".." {
|
||||
return Err("路径不能包含上级目录(..)".to_string());
|
||||
}
|
||||
out.push(part);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 绝对路径 → 相对库根的路径(统一 `/` 分隔)。
|
||||
pub fn rel_string(root: &Path, path: &Path) -> String {
|
||||
path.strip_prefix(root)
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 校验用户输入的条目名(新建/重命名)。
|
||||
///
|
||||
/// 拒绝路径分隔符、Windows 保留字符与控制字符 —— 名称只应是「一个名字」,
|
||||
/// 不含任何路径语义。
|
||||
pub fn validate_name(name: &str) -> Result<String, String> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err("名称不能为空".to_string());
|
||||
}
|
||||
if name == "." || name == ".." {
|
||||
return Err("名称不合法".to_string());
|
||||
}
|
||||
if name.chars().count() > 120 {
|
||||
return Err("名称过长".to_string());
|
||||
}
|
||||
if name
|
||||
.chars()
|
||||
.any(|c| c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*'))
|
||||
{
|
||||
return Err("名称不能包含 < > : \" / \\ | ? * 等字符".to_string());
|
||||
}
|
||||
Ok(name.to_string())
|
||||
}
|
||||
|
||||
fn is_note_file(name: &str) -> bool {
|
||||
name.to_ascii_lowercase().ends_with(".md")
|
||||
}
|
||||
|
||||
fn modified_ms(meta: &std::fs::Metadata) -> u64 {
|
||||
meta.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// 扫描整个库,返回扁平条目列表(目录在前、各自按名称排序;前端自行组树)。
|
||||
pub fn scan(root: &Path) -> Result<Vec<LibraryEntry>, String> {
|
||||
let mut out = Vec::new();
|
||||
if !root.is_dir() {
|
||||
return Ok(out);
|
||||
}
|
||||
walk(root, root, &mut out, 0);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn walk(root: &Path, dir: &Path, out: &mut Vec<LibraryEntry>, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
let read = match std::fs::read_dir(dir) {
|
||||
Ok(r) => r,
|
||||
Err(_) => return,
|
||||
};
|
||||
|
||||
let mut dirs: Vec<(String, PathBuf)> = Vec::new();
|
||||
let mut files: Vec<(String, PathBuf)> = Vec::new();
|
||||
for entry in read.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
// 隐藏项(含 `.editor` 之类的私有目录)一律不进库树
|
||||
if name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let file_type = match entry.file_type() {
|
||||
Ok(t) => t,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let path = entry.path();
|
||||
if file_type.is_dir() {
|
||||
// 根级 assets 是图片仓库,不作为笔记目录展示,避免噪声
|
||||
if depth == 0 && name == ASSETS_DIR {
|
||||
continue;
|
||||
}
|
||||
dirs.push((name, path));
|
||||
} else if file_type.is_file() && is_note_file(&name) {
|
||||
files.push((name, path));
|
||||
}
|
||||
}
|
||||
|
||||
dirs.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
for (name, path) in dirs {
|
||||
let meta = std::fs::metadata(&path).ok();
|
||||
out.push(LibraryEntry {
|
||||
name,
|
||||
rel_path: rel_string(root, &path),
|
||||
parent_rel: rel_string(root, dir),
|
||||
is_dir: true,
|
||||
modified: meta.as_ref().map(modified_ms).unwrap_or(0),
|
||||
size: 0,
|
||||
});
|
||||
walk(root, &path, out, depth + 1);
|
||||
}
|
||||
for (name, path) in files {
|
||||
let meta = std::fs::metadata(&path).ok();
|
||||
out.push(LibraryEntry {
|
||||
name,
|
||||
rel_path: rel_string(root, &path),
|
||||
parent_rel: rel_string(root, dir),
|
||||
is_dir: false,
|
||||
modified: meta.as_ref().map(modified_ms).unwrap_or(0),
|
||||
size: meta.as_ref().map(|m| m.len()).unwrap_or(0),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 统计库内 `.md` 文件数量。
|
||||
pub fn count_notes(entries: &[LibraryEntry]) -> u32 {
|
||||
entries.iter().filter(|e| !e.is_dir).count() as u32
|
||||
}
|
||||
|
||||
/// 构造一篇文档的返回结构。
|
||||
fn to_doc(root: &Path, path: &Path, content: String) -> NoteDoc {
|
||||
let modified = std::fs::metadata(path).map(|m| modified_ms(&m)).unwrap_or(0);
|
||||
NoteDoc {
|
||||
rel_path: rel_string(root, path),
|
||||
name: path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
content,
|
||||
modified,
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取一篇笔记(相对库根路径)。非 UTF-8 字节按 lossy 处理,不报错。
|
||||
pub fn read_note(root: &Path, rel: &str) -> Result<NoteDoc, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.is_file() {
|
||||
return Err(format!("笔记不存在:{rel}"));
|
||||
}
|
||||
let bytes = std::fs::read(&path).map_err(|e| format!("读取笔记失败: {e}"))?;
|
||||
Ok(to_doc(root, &path, String::from_utf8_lossy(&bytes).into_owned()))
|
||||
}
|
||||
|
||||
/// 写入一篇笔记(已存在的文件才允许写;不自动创建目录,由 create_note 负责)。
|
||||
pub fn write_note(root: &Path, rel: &str, content: &str) -> Result<NoteDoc, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.is_file() {
|
||||
return Err(format!("笔记不存在:{rel}"));
|
||||
}
|
||||
std::fs::write(&path, content).map_err(|e| format!("保存笔记失败: {e}"))?;
|
||||
Ok(to_doc(root, &path, content.to_string()))
|
||||
}
|
||||
|
||||
/// 在指定目录下新建笔记:自动补 `.md`、重名自动加序号。
|
||||
///
|
||||
/// 用**内置**的 front-matter 模板(不读 `templates/`)。保留这个无模板参数的入口是
|
||||
/// 为了「模板目录被删/损坏时仍然能新建笔记」这条底线,单测也走它。
|
||||
pub fn create_note(root: &Path, dir_rel: &str, name: &str) -> Result<NoteDoc, String> {
|
||||
create_note_with_template(root, dir_rel, name, "")
|
||||
}
|
||||
|
||||
/// 在指定目录下新建笔记,正文由模板渲染(`template_id` 为空 = 用内置默认模板)。
|
||||
///
|
||||
/// 模板渲染失败(模板文件被删、权限不足)时回退到内置模板而不是报错:
|
||||
/// 「新建笔记」这个动作不该因为一个辅助文件的问题而不可用。
|
||||
pub fn create_note_with_template(
|
||||
root: &Path,
|
||||
dir_rel: &str,
|
||||
name: &str,
|
||||
template_id: &str,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let dir = safe_join(root, dir_rel)?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
|
||||
let mut file_name = validate_name(name)?;
|
||||
if !is_note_file(&file_name) {
|
||||
file_name.push_str(".md");
|
||||
}
|
||||
let title = file_name.trim_end_matches(".md").to_string();
|
||||
|
||||
// 重名自动加序号,避免「新建即报错」
|
||||
let mut candidate = file_name.clone();
|
||||
let mut index = 1;
|
||||
while dir.join(&candidate).exists() {
|
||||
candidate = format!("{title} {index}.md");
|
||||
index += 1;
|
||||
if index > 999 {
|
||||
return Err("同名文件过多,请换一个名称".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// 模板渲染:模板 ID 无效时 `render_for_new_note` 自己会回退到内置空白模板
|
||||
let content = if template_id.trim().is_empty() {
|
||||
note_template(&title)
|
||||
} else {
|
||||
super::templates::render_for_new_note(root, template_id, &title, dir_rel)
|
||||
};
|
||||
|
||||
let path = dir.join(&candidate);
|
||||
std::fs::write(&path, content).map_err(|e| format!("新建笔记失败: {e}"))?;
|
||||
read_note(root, &rel_string(root, &path))
|
||||
}
|
||||
|
||||
/// 在指定目录下新建文件夹。
|
||||
pub fn create_folder(root: &Path, dir_rel: &str, name: &str) -> Result<String, String> {
|
||||
let dir = safe_join(root, dir_rel)?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
let folder_name = validate_name(name)?;
|
||||
let path = dir.join(&folder_name);
|
||||
if path.exists() {
|
||||
return Err(format!("「{folder_name}」已存在"));
|
||||
}
|
||||
std::fs::create_dir_all(&path).map_err(|e| format!("新建文件夹失败: {e}"))?;
|
||||
Ok(rel_string(root, &path))
|
||||
}
|
||||
|
||||
/// 重命名库内条目;返回新的相对路径。
|
||||
///
|
||||
/// 文件若未带扩展名,沿用原扩展名(避免 `a.md` 改成 `a` 变成无扩展名文件)。
|
||||
pub fn rename_entry(root: &Path, rel: &str, new_name: &str) -> Result<String, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.exists() {
|
||||
return Err("条目不存在".to_string());
|
||||
}
|
||||
let mut name = validate_name(new_name)?;
|
||||
if path.is_file() {
|
||||
let old_ext = path.extension().map(|e| e.to_string_lossy().to_string());
|
||||
if let Some(ext) = old_ext {
|
||||
if !name.to_ascii_lowercase().ends_with(&format!(".{}", ext.to_ascii_lowercase())) {
|
||||
name.push('.');
|
||||
name.push_str(&ext);
|
||||
}
|
||||
}
|
||||
}
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| "无法解析父目录".to_string())?;
|
||||
let target = parent.join(&name);
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
std::fs::rename(&path, &target).map_err(|e| format!("重命名失败: {e}"))?;
|
||||
Ok(rel_string(root, &target))
|
||||
}
|
||||
|
||||
/// 删除库内条目(目录递归删除)。
|
||||
pub fn delete_entry(root: &Path, rel: &str) -> Result<(), String> {
|
||||
if rel.trim().is_empty() {
|
||||
return Err("不能删除库根".to_string());
|
||||
}
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.exists() {
|
||||
return Err("条目不存在".to_string());
|
||||
}
|
||||
if path.is_dir() {
|
||||
std::fs::remove_dir_all(&path).map_err(|e| format!("删除目录失败: {e}"))?;
|
||||
} else {
|
||||
std::fs::remove_file(&path).map_err(|e| format!("删除文件失败: {e}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//! 笔记 / 编辑器模块。
|
||||
//!
|
||||
//! 架构位置:
|
||||
//!
|
||||
//! ```text
|
||||
//! 主模块页(设置 / 库管理) 独立窗口(CM6 编辑器)
|
||||
//! ↓ Tauri IPC ↓
|
||||
//! commands.rs 命令层
|
||||
//! ↓
|
||||
//! EditorManager(本文件):设置读写 / 库根解析
|
||||
//! ↓
|
||||
//! library.rs 文件系统(路径安全 / 扫描 / 读写 / 增删改移)
|
||||
//! ```
|
||||
//!
|
||||
//! # 真相在文件
|
||||
//!
|
||||
//! 笔记 = 库根下的 `.md` 文件树。Rust 侧只做文件 IO 与设置持久化,
|
||||
//! **不引入私有格式**;SQLite 索引(`index.rs`)只是可重建的加速层。
|
||||
//!
|
||||
//! # 三个入口的职责边界
|
||||
//!
|
||||
//! ```text
|
||||
//! library.rs 库内笔记:相对路径 + 树 + front-matter(安全模型 = 根目录沙箱)
|
||||
//! files.rs 库外任意文件:绝对路径 + 编码/换行(安全模型 = 授权白名单)
|
||||
//! index_service.rs 索引与监听:独占 SQLite 连接的单线程 worker + notify
|
||||
//! ```
|
||||
//!
|
||||
//! 设置持久化:`{app_data_dir}/editor/settings.json`(范式同 ai / translate)。
|
||||
//! 默认库根:`{app_data_dir}/editor/library`;用户可在设置里改。
|
||||
|
||||
mod args;
|
||||
mod backup;
|
||||
mod commands;
|
||||
mod dirs;
|
||||
mod export;
|
||||
pub(crate) mod files;
|
||||
mod grep;
|
||||
mod import;
|
||||
mod index;
|
||||
mod index_service;
|
||||
mod library;
|
||||
mod shell_menu;
|
||||
mod templates;
|
||||
mod types;
|
||||
mod webdav;
|
||||
|
||||
pub use commands::{
|
||||
editor_add_template, editor_authorize_file, editor_backlinks, editor_backup_now,
|
||||
editor_create_folder, editor_create_note, editor_daily_note, editor_delete_entry,
|
||||
editor_export_note, editor_export_snapshot_local, editor_export_zip, editor_get_settings,
|
||||
editor_import, editor_index_stats, editor_library_info, editor_link_graph, editor_list_backups,
|
||||
editor_list_notes, editor_list_templates, editor_open_file, editor_read_asset, editor_read_note,
|
||||
editor_read_template, editor_rebuild_index, editor_redecode_file, editor_rename_entry,
|
||||
editor_restore_backup,
|
||||
editor_save_note, editor_save_settings, editor_scan_library, editor_scratch_dir, editor_search_notes,
|
||||
editor_set_library_root, editor_set_webdav_password, editor_sync_index, editor_sync_now,
|
||||
editor_tags, editor_take_pending_file, editor_test_webdav, editor_webdav_status,
|
||||
editor_write_asset, editor_write_file,
|
||||
};
|
||||
pub use args::{emit_open_target, open_target_from_args, remember_pending_target};
|
||||
pub use dirs::{
|
||||
editor_create_dir, editor_create_file, editor_delete_path, editor_move_path, editor_read_dir,
|
||||
editor_rename_path,
|
||||
};
|
||||
pub use grep::{editor_replace_in_path, editor_search_in_path};
|
||||
pub use shell_menu::{
|
||||
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
|
||||
};
|
||||
use types::EditorSettings;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// 设置内存缓存有效期(与 ai / translate / terminal 的 500ms 一致)。
|
||||
const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500);
|
||||
|
||||
struct SettingsCache {
|
||||
read_at: Instant,
|
||||
settings: EditorSettings,
|
||||
}
|
||||
|
||||
/// 笔记 / 编辑器模块管理器(Tauri State)。
|
||||
pub struct EditorManager {
|
||||
/// 模块自身目录:`{app_data_dir}/editor`
|
||||
module_dir: PathBuf,
|
||||
cache: Mutex<Option<SettingsCache>>,
|
||||
}
|
||||
|
||||
/// 一次性迁移 `{app_data_dir}/notes/` → `{app_data_dir}/editor/`(幂等)。
|
||||
///
|
||||
/// 仅当旧目录存在且新目录不存在时整目录重命名;两者都在则各自独立
|
||||
/// (说明已在用新目录,旧目录留着不动,避免误删用户数据)。
|
||||
fn migrate_legacy_module_dir(app_data_dir: &Path, module_dir: &Path) {
|
||||
let legacy = app_data_dir.join("notes");
|
||||
if legacy.is_dir() && !module_dir.exists() {
|
||||
match std::fs::rename(&legacy, module_dir) {
|
||||
Ok(()) => crate::logger::log_info("editor", "已迁移模块目录 notes/ → editor/"),
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("迁移模块目录失败: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EditorManager {
|
||||
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||
let module_dir = app_data_dir.join("editor");
|
||||
migrate_legacy_module_dir(&app_data_dir, &module_dir);
|
||||
let _ = std::fs::create_dir_all(&module_dir);
|
||||
Self {
|
||||
module_dir,
|
||||
cache: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// 模块自身目录(库根默认值基于它解析)。
|
||||
pub fn module_dir(&self) -> &Path {
|
||||
&self.module_dir
|
||||
}
|
||||
|
||||
/// 启动时按设置注册全局快捷键。
|
||||
///
|
||||
/// 失败只记日志:快捷键被别的应用占了不该阻断启动(与 translate / terminal 同一姿态)。
|
||||
/// 触发时**只发事件**,窗口与「新建哪一篇」由前端决定 —— Rust 侧不持有窗口 label
|
||||
/// 策略,也不该知道当前打开的库是哪一篇(那是前端 store 的事)。
|
||||
pub fn init_on_launch(&self, app: &tauri::AppHandle) {
|
||||
use tauri::Emitter;
|
||||
let settings = self.load_settings();
|
||||
|
||||
let new_note = settings.new_note_shortcut.clone();
|
||||
if let Err(e) = crate::shortcut::register_shortcut(app, "editor-new-note", &new_note, |app| {
|
||||
if let Err(e) = app.emit(crate::constants::events::EDITOR_NEW_NOTE, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出新建笔记事件失败: {e}"));
|
||||
}
|
||||
}) {
|
||||
crate::logger::log_warn("editor", &format!("注册「新建笔记」快捷键失败: {e}"));
|
||||
}
|
||||
|
||||
let open_editor = settings.open_editor_shortcut.clone();
|
||||
if let Err(e) =
|
||||
crate::shortcut::register_shortcut(app, "editor-open-editor", &open_editor, |app| {
|
||||
if let Err(e) = app.emit(crate::constants::events::EDITOR_OPEN_EDITOR, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出打开编辑器事件失败: {e}"));
|
||||
}
|
||||
})
|
||||
{
|
||||
crate::logger::log_warn("editor", &format!("注册「打开编辑器」快捷键失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_path(&self) -> PathBuf {
|
||||
self.module_dir.join("settings.json")
|
||||
}
|
||||
|
||||
/// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。
|
||||
pub fn load_settings(&self) -> EditorSettings {
|
||||
if let Ok(cache) = self.cache.lock() {
|
||||
if let Some(entry) = cache.as_ref() {
|
||||
if entry.read_at.elapsed() < SETTINGS_CACHE_TTL {
|
||||
return entry.settings.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = std::fs::read_to_string(self.settings_path())
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<EditorSettings>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
let healed = settings.heal();
|
||||
// 刷新「最近记录」的存在性(只读,不触发落盘)
|
||||
settings.refresh_recent_exists();
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
if healed {
|
||||
if let Err(e) = self.save_settings(&settings) {
|
||||
crate::logger::log_error("editor", &format!("设置自愈落盘失败: {e}"));
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// 保存设置并刷新缓存。
|
||||
pub fn save_settings(&self, settings: &EditorSettings) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(settings)
|
||||
.map_err(|e| format!("序列化笔记设置失败: {e}"))?;
|
||||
std::fs::write(self.settings_path(), json)
|
||||
.map_err(|e| format!("写入笔记设置失败: {e}"))?;
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Windows 资源管理器右键菜单(HKCU,**免管理员**)。
|
||||
//!
|
||||
//! # 为什么走用户级注册表
|
||||
//!
|
||||
//! 文件关联由安装器写 `HKLM`/`OpenWithProgids`;而「右键 → 用 Thing 编辑器打开」
|
||||
//! 只需 `HKCU\Software\Classes\{*,Directory,Directory\Background}\shell\ThingEditor`,
|
||||
//! 用户级即可生效、无需提权(范式同 `mihomo_manager/system_proxy.rs`)。
|
||||
//!
|
||||
//! # 为什么默认不自动注册
|
||||
//!
|
||||
//! 注册表项里写的是**绝对 exe 路径**:打包安装后指向安装目录(稳定),但
|
||||
//! `tauri dev` 下指向 `target\debug\thing.exe` —— 一旦清理 target 就成了死链。
|
||||
//! 因此注册/卸载都只在设置页按钮下发生,且注册前校验 exe 存在。
|
||||
//!
|
||||
//! # 三处菜单
|
||||
//!
|
||||
//! | 键 | 场景 | 参数 |
|
||||
//! |---|---|---|
|
||||
//! | `*` | 任意文件 | `%1` |
|
||||
//! | `Directory` | 文件夹 | `%1` |
|
||||
//! | `Directory\Background` | 目录背景空白处 | `%V`(当前目录) |
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
/// 右键菜单键名与显示名。
|
||||
const MENU_KEY: &str = "ThingEditor";
|
||||
const MENU_LABEL: &str = "用 Thing 编辑器打开";
|
||||
|
||||
/// 右键菜单状态(回传设置页展示)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ContextMenuStatus {
|
||||
/// 是否已注册(以 `*` 键为准)
|
||||
pub registered: bool,
|
||||
/// 当前可执行文件绝对路径(注册表里写入的就是它)
|
||||
pub exe_path: String,
|
||||
/// 是否开发模式(exe 路径不稳定,UI 需给出提示)
|
||||
pub is_dev: bool,
|
||||
}
|
||||
|
||||
fn exe_path() -> String {
|
||||
std::env::current_exe()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 读取当前状态。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_context_menu_status() -> ContextMenuStatus {
|
||||
ContextMenuStatus {
|
||||
registered: imp::registered(),
|
||||
exe_path: exe_path(),
|
||||
is_dev: cfg!(debug_assertions),
|
||||
}
|
||||
}
|
||||
|
||||
/// 注册右键菜单(写 HKCU)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_register_context_menu() -> Result<ContextMenuStatus, String> {
|
||||
imp::register()?;
|
||||
Ok(editor_context_menu_status())
|
||||
}
|
||||
|
||||
/// 卸载右键菜单(删 HKCU 对应项)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_unregister_context_menu() -> Result<ContextMenuStatus, String> {
|
||||
imp::unregister()?;
|
||||
Ok(editor_context_menu_status())
|
||||
}
|
||||
|
||||
// ===== Windows 实现 =====
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{exe_path, MENU_KEY, MENU_LABEL};
|
||||
use std::path::Path;
|
||||
|
||||
const ROOTS: [&str; 3] = ["*", "Directory", "Directory\\Background"];
|
||||
|
||||
fn key_path(root: &str) -> String {
|
||||
format!("Software\\Classes\\{root}\\shell\\{MENU_KEY}")
|
||||
}
|
||||
|
||||
pub fn registered() -> bool {
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
use winreg::RegKey;
|
||||
RegKey::predef(HKEY_CURRENT_USER)
|
||||
.open_subkey(key_path("*"))
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
pub fn register() -> Result<(), String> {
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
use winreg::RegKey;
|
||||
|
||||
let exe = exe_path();
|
||||
if exe.is_empty() {
|
||||
return Err("无法确定可执行文件路径".to_string());
|
||||
}
|
||||
if !Path::new(&exe).is_file() {
|
||||
return Err(format!("可执行文件不存在:{exe}(开发模式下请先构建)"));
|
||||
}
|
||||
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
for root in ROOTS {
|
||||
let path = key_path(root);
|
||||
let (key, _) = hkcu
|
||||
.create_subkey(&path)
|
||||
.map_err(|e| format!("写入注册表失败({root}): {e}"))?;
|
||||
key.set_value("", &MENU_LABEL)
|
||||
.map_err(|e| format!("写入菜单名称失败({root}): {e}"))?;
|
||||
key.set_value("Icon", &exe)
|
||||
.map_err(|e| format!("写入菜单图标失败({root}): {e}"))?;
|
||||
// Directory\Background 传入的是「当前目录」,用 %V;其余用 %1
|
||||
let arg = if root.ends_with("Background") { "%V" } else { "%1" };
|
||||
let (cmd_key, _) = hkcu
|
||||
.create_subkey(format!("{path}\\command"))
|
||||
.map_err(|e| format!("写入菜单命令失败({root}): {e}"))?;
|
||||
cmd_key
|
||||
.set_value("", &format!("\"{exe}\" \"{arg}\""))
|
||||
.map_err(|e| format!("写入菜单命令行失败({root}): {e}"))?;
|
||||
}
|
||||
crate::logger::log_info("editor", &format!("已注册右键菜单,指向 {exe}"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn unregister() -> Result<(), String> {
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
use winreg::RegKey;
|
||||
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
for root in ROOTS {
|
||||
let path = key_path(root);
|
||||
match hkcu.delete_subkey_all(&path) {
|
||||
Ok(()) => {}
|
||||
// 本就不存在视为成功(幂等)
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(format!("删除注册表项失败({root}): {e}")),
|
||||
}
|
||||
}
|
||||
crate::logger::log_info("editor", "已卸载右键菜单");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 非 Windows:明确告知不支持 =====
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod imp {
|
||||
pub fn registered() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn register() -> Result<(), String> {
|
||||
Err("资源管理器右键菜单仅支持 Windows".to_string())
|
||||
}
|
||||
|
||||
pub fn unregister() -> Result<(), String> {
|
||||
Err("资源管理器右键菜单仅支持 Windows".to_string())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
//! 新建笔记的模板:内置默认模板 + 用户模板目录。
|
||||
//!
|
||||
//! # 模板为什么要落成 `.md` 文件
|
||||
//!
|
||||
//! 与「笔记的真相是文件」同一条原则:模板也是用户会想改的东西,做成 JSON 里的一段
|
||||
//! 字符串,用户既看不到也改不了。落成 `.md` 文件后,用任意编辑器改,改完立刻生效。
|
||||
//!
|
||||
//! # 两个来源
|
||||
//!
|
||||
//! - **内置**:编译进二进制(`include_str!`),保证全新机器上「新建笔记」永远有东西可用;
|
||||
//! - **用户**:`{库根}/templates/*.md`。库是可切换的,模板跟着库走 —— 一个技术笔记库
|
||||
//! 和一个日记库本来就该有不同的模板集。
|
||||
//!
|
||||
//! 同名时用户模板覆盖内置模板。内置模板不写进库根(否则用户第一次新建笔记就会
|
||||
//! 发现库里多出一堆他没建过的文件)。
|
||||
//!
|
||||
//! # 变量替换
|
||||
//!
|
||||
//! 只支持少量、无歧义的占位符(`{{date}}` / `{{time}}` / `{{title}}` / `{{datetime}}`)。
|
||||
//! **不做条件、循环、包含** —— 那是一条通往「半个模板引擎」的路,收益远小于维护成本。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use super::library;
|
||||
|
||||
/// 一个模板。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteTemplate {
|
||||
/// 标识(内置用 `builtin:<文件名>`,用户模板用 `user:<文件名>`)
|
||||
pub id: String,
|
||||
/// 显示名(文件名去掉扩展名)
|
||||
pub name: String,
|
||||
/// 说明(内置模板手写;用户模板取正文首行非空文本)
|
||||
pub description: String,
|
||||
/// 是否为内置模板(前端据此提示「不可删除」)
|
||||
pub builtin: bool,
|
||||
/// 模板正文(含 front-matter)
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
/// 内置模板(编译进二进制)。
|
||||
const BUILTIN: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"空白笔记",
|
||||
"只有 front-matter 与一级标题,适合随手记",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: []\n---\n\n# {{title}}\n\n",
|
||||
),
|
||||
(
|
||||
"会议纪要",
|
||||
"议题 / 结论 / 待办三段式",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [会议]\n---\n\n# {{title}}\n\n- 时间:{{datetime}}\n- 参会:\n\n## 议题\n\n## 结论\n\n## 待办\n\n- [ ] \n",
|
||||
),
|
||||
(
|
||||
"日记",
|
||||
"按日期归档的日记骨架",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [日记]\n---\n\n# {{date}}\n\n## 今天做了什么\n\n## 明天要做什么\n\n- [ ] \n",
|
||||
),
|
||||
(
|
||||
"读书笔记",
|
||||
"书籍信息 + 摘录 + 思考",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [读书]\n---\n\n# {{title}}\n\n- 书名:\n- 作者:\n- 进度:\n\n## 摘录\n\n> \n\n## 我的思考\n\n",
|
||||
),
|
||||
];
|
||||
|
||||
/// 列出全部模板(用户模板优先,同名覆盖内置)。
|
||||
pub fn list(root: &Path) -> Vec<NoteTemplate> {
|
||||
let mut out: Vec<NoteTemplate> = Vec::new();
|
||||
|
||||
// 用户模板:`{库根}/templates/*.md`
|
||||
let dir = root.join("templates");
|
||||
if dir.is_dir() {
|
||||
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| {
|
||||
path.is_file()
|
||||
&& path
|
||||
.extension()
|
||||
.map(|e| e.eq_ignore_ascii_case("md"))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect();
|
||||
files.sort();
|
||||
for path in files {
|
||||
let name = path
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Ok(body) = std::fs::read_to_string(&path) else {
|
||||
continue;
|
||||
};
|
||||
out.push(NoteTemplate {
|
||||
id: format!("user:{name}"),
|
||||
description: first_meaningful_line(&body),
|
||||
name,
|
||||
builtin: false,
|
||||
body,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 内置模板:跳过已被用户模板同名的
|
||||
for (name, description, body) in BUILTIN {
|
||||
if out.iter().any(|item| item.name == *name) {
|
||||
continue;
|
||||
}
|
||||
out.push(NoteTemplate {
|
||||
id: format!("builtin:{name}"),
|
||||
name: name.to_string(),
|
||||
description: description.to_string(),
|
||||
builtin: true,
|
||||
body: body.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// 取模板 ID 对应的正文;找不到返回 `None`(调用方回退到默认模板)。
|
||||
pub fn body_of(root: &Path, id: &str) -> Option<String> {
|
||||
list(root).into_iter().find(|t| t.id == id).map(|t| t.body)
|
||||
}
|
||||
|
||||
/// 把模板正文渲染成一篇新笔记的内容。
|
||||
///
|
||||
/// `parent_dir` 是笔记所在的库内目录(用于 `{{date}}` 之类不受影响,但保留参数
|
||||
/// 以便将来加入「所在目录」变量)。
|
||||
pub fn render(body: &str, title: &str, _parent_dir: &str) -> String {
|
||||
let now = chrono::Local::now();
|
||||
body.replace("{{title}}", title)
|
||||
.replace("{{date}}", &now.format("%Y-%m-%d").to_string())
|
||||
.replace("{{time}}", &now.format("%H:%M").to_string())
|
||||
.replace("{{datetime}}", &now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
|
||||
}
|
||||
|
||||
/// 日记的默认文件名(`2026-09-30`),供「今日日记」入口用。
|
||||
pub fn daily_note_name() -> String {
|
||||
chrono::Local::now().format("%Y-%m-%d").to_string()
|
||||
}
|
||||
|
||||
/// 默认模板的 ID(新建笔记时未选模板就用它)。
|
||||
pub fn default_template_id() -> String {
|
||||
"builtin:空白笔记".to_string()
|
||||
}
|
||||
|
||||
/// 正文里第一行有意义的文本(用户模板的说明用)。
|
||||
fn first_meaningful_line(body: &str) -> String {
|
||||
for line in body.lines() {
|
||||
let text = line.trim();
|
||||
if text.is_empty() || text == "---" || text.starts_with('#') || text.starts_with("title:") {
|
||||
continue;
|
||||
}
|
||||
return text.chars().take(40).collect();
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// 为「新建笔记」渲染正文:`template_id` 为空或找不到时用默认模板。
|
||||
pub fn render_for_new_note(root: &Path, template_id: &str, title: &str, dir_rel: &str) -> String {
|
||||
let id = if template_id.trim().is_empty() {
|
||||
default_template_id()
|
||||
} else {
|
||||
template_id.to_string()
|
||||
};
|
||||
match body_of(root, &id) {
|
||||
Some(body) => render(&body, title, dir_rel),
|
||||
None => {
|
||||
// 兜底:内置空白模板(即使模板目录被清空也能新建)
|
||||
let fallback = BUILTIN
|
||||
.first()
|
||||
.map(|(_, _, body)| *body)
|
||||
.unwrap_or("---\ntitle: {{title}}\n---\n\n# {{title}}\n\n");
|
||||
render(fallback, title, dir_rel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保库里的 `templates/` 目录存在(用户想自定义模板时不用自己新建目录)。
|
||||
pub fn ensure_dir(root: &Path) -> Result<(), String> {
|
||||
std::fs::create_dir_all(root.join("templates")).map_err(|e| format!("创建模板目录失败: {e}"))
|
||||
}
|
||||
|
||||
/// 把内置模板写进库内 `templates/`(供「导出内置模板」按钮用;已存在的不覆盖)。
|
||||
pub fn export_builtin(root: &Path) -> Result<Vec<String>, String> {
|
||||
ensure_dir(root)?;
|
||||
let dir = root.join("templates");
|
||||
let mut written = Vec::new();
|
||||
for (name, _, body) in BUILTIN {
|
||||
let path = dir.join(format!("{name}.md"));
|
||||
if path.exists() {
|
||||
continue;
|
||||
}
|
||||
std::fs::write(&path, body).map_err(|e| format!("写入模板 {name} 失败: {e}"))?;
|
||||
written.push(name.to_string());
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// 模板文件在库内的相对路径(前端「编辑模板」用;内置模板返回 `None`)。
|
||||
pub fn relative_path(id: &str) -> Option<String> {
|
||||
id.strip_prefix("user:")
|
||||
.map(|name| format!("templates/{name}.md"))
|
||||
}
|
||||
|
||||
/// 校验模板名(新建模板时用)。
|
||||
pub fn validate_name(name: &str) -> Result<String, String> {
|
||||
library::validate_name(name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_root(tag: &str) -> std::path::PathBuf {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("thing-notes-tpl-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_templates_are_available_without_files() {
|
||||
let root = temp_root("builtin");
|
||||
let templates = list(&root);
|
||||
assert!(templates.len() >= 4, "{templates:?}");
|
||||
assert!(templates.iter().all(|t| t.builtin));
|
||||
assert!(templates.iter().any(|t| t.name == "日记"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_template_overrides_builtin_with_same_name() {
|
||||
let root = temp_root("override");
|
||||
ensure_dir(&root).unwrap();
|
||||
std::fs::write(root.join("templates/空白笔记.md"), "用户自己的模板 {{title}}").unwrap();
|
||||
let templates = list(&root);
|
||||
let blank = templates.iter().find(|t| t.name == "空白笔记").unwrap();
|
||||
assert!(!blank.builtin, "同名时用户模板应覆盖内置");
|
||||
assert!(blank.body.contains("用户自己的模板"));
|
||||
assert_eq!(
|
||||
templates.iter().filter(|t| t.name == "空白笔记").count(),
|
||||
1,
|
||||
"不该出现两份同名模板"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_substitutes_variables() {
|
||||
let out = render("---\ntitle: {{title}}\ncreated: {{datetime}}\n---\n\n# {{title}} {{date}}\n", "周会", "");
|
||||
assert!(out.contains("title: 周会"));
|
||||
assert!(out.contains("# 周会 "));
|
||||
assert!(!out.contains("{{"), "所有占位符都应被替换: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_for_new_note_falls_back_to_blank() {
|
||||
let root = temp_root("fallback");
|
||||
let out = render_for_new_note(&root, "user:不存在", "标题", "");
|
||||
assert!(out.contains("标题"));
|
||||
assert!(!out.contains("{{"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_builtin_does_not_overwrite() {
|
||||
let root = temp_root("export");
|
||||
ensure_dir(&root).unwrap();
|
||||
std::fs::write(root.join("templates/日记.md"), "我的日记模板").unwrap();
|
||||
let written = export_builtin(&root).unwrap();
|
||||
assert!(!written.contains(&"日记".to_string()), "{written:?}");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join("templates/日记.md")).unwrap(),
|
||||
"我的日记模板"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_path_only_for_user_templates() {
|
||||
assert_eq!(
|
||||
relative_path("user:会议纪要"),
|
||||
Some("templates/会议纪要.md".to_string())
|
||||
);
|
||||
assert_eq!(relative_path("builtin:日记"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_note_name_is_date_shaped() {
|
||||
let name = daily_note_name();
|
||||
assert_eq!(name.len(), 10, "{name}");
|
||||
assert_eq!(name.matches('-').count(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
//! 笔记模块的数据模型。
|
||||
//!
|
||||
//! 持久化位置:`{app_data_dir}/editor/settings.json`(与 ai / translate / terminal 同一范式)。
|
||||
//! 容器级 `#[serde(default)]`:新增字段对旧配置文件向后兼容(缺字段取
|
||||
//! `Default::default()` 的对应值,而不是让整份设置反序列化失败)。
|
||||
//!
|
||||
//! 笔记正文**不在这里**:它以 `.md` 文件为准(见 `library.rs`),
|
||||
//! 本结构只保存「库根 + 编辑器偏好」这类模块级设置。
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// 结构版本号。字段增减时递增,由 [`EditorSettings::heal`] 推进。
|
||||
pub const EDITOR_SETTINGS_VERSION: u32 = 5;
|
||||
|
||||
/// 最近文件 / 文件夹各自的保留上限(超出淘汰最旧)。
|
||||
pub const RECENT_LIMIT: usize = 20;
|
||||
|
||||
/// 同步方向。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SyncDirection {
|
||||
/// 双向同步(默认)
|
||||
Bidirectional,
|
||||
/// 只上传(本地覆盖远端)—— 等价于「推送到远端备份」
|
||||
Upload,
|
||||
/// 只下载(远端覆盖本地)—— 换机器恢复时用
|
||||
Download,
|
||||
}
|
||||
|
||||
impl Default for SyncDirection {
|
||||
fn default() -> Self {
|
||||
Self::Bidirectional
|
||||
}
|
||||
}
|
||||
|
||||
/// 两侧都改动时的冲突策略。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ConflictPolicy {
|
||||
/// 保留较新的(mtime 大的一方;无法判定时保守选本地)
|
||||
Newer,
|
||||
/// 本地覆盖远端
|
||||
LocalWins,
|
||||
/// 远端覆盖本地
|
||||
RemoteWins,
|
||||
/// 两侧都留(本地改名成 `*.sync-conflict-<时间>.md`,再把远端那份下载到原路径)
|
||||
KeepBoth,
|
||||
}
|
||||
|
||||
impl Default for ConflictPolicy {
|
||||
fn default() -> Self {
|
||||
// 默认「都留」:冲突时最保守的选择,绝不丢数据(规划 §7 R6)
|
||||
Self::KeepBoth
|
||||
}
|
||||
}
|
||||
|
||||
/// WebDAV 设置(密码**不在这里** —— 它进 keyring,见 `webdav/mod.rs`)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct WebdavSettings {
|
||||
/// 服务地址(`https://dav.jianguoyun.com/dav`)
|
||||
pub url: String,
|
||||
pub username: String,
|
||||
/// 远端根目录(相对 `url`;空串 = 直接用 `url` 指向的目录)
|
||||
pub remote_root: String,
|
||||
pub direction: SyncDirection,
|
||||
pub conflict: ConflictPolicy,
|
||||
/// 应用启动后自动同步一次
|
||||
pub auto_sync_on_launch: bool,
|
||||
/// 保留的 zip 快照份数(上传备份时轮转)
|
||||
pub backup_keep: u32,
|
||||
}
|
||||
|
||||
impl Default for WebdavSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
url: String::new(),
|
||||
username: String::new(),
|
||||
remote_root: "thing-notes".to_string(),
|
||||
direction: SyncDirection::Bidirectional,
|
||||
conflict: ConflictPolicy::KeepBoth,
|
||||
auto_sync_on_launch: false,
|
||||
backup_keep: 7,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WebdavSettings {
|
||||
/// 是否已经填了连接信息(决定设置页显示「未配置」还是「已配置」)。
|
||||
pub fn is_configured(&self) -> bool {
|
||||
!self.url.trim().is_empty() && !self.username.trim().is_empty()
|
||||
}
|
||||
|
||||
/// 填写是否足以发起请求。
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.url.trim().is_empty() {
|
||||
return Err("请先填写 WebDAV 地址".to_string());
|
||||
}
|
||||
if !self.url.starts_with("http://") && !self.url.starts_with("https://") {
|
||||
return Err("WebDAV 地址必须以 http:// 或 https:// 开头".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 同步进度(事件 `editor-sync-progress` 的负载)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncProgress {
|
||||
/// 已完成条数
|
||||
pub done: u32,
|
||||
/// 总条数
|
||||
pub total: u32,
|
||||
/// 当前处理的相对路径
|
||||
pub current: String,
|
||||
/// 动作类型(`upload` / `download` / …,见 `webdav::sync::SyncActionKind::as_str`)
|
||||
pub kind: String,
|
||||
/// 附加说明(如「正在打包快照」)
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// 一份远端备份快照。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BackupSnapshot {
|
||||
/// 远端文件名(`thing-notes-20260930-1530.zip`)
|
||||
pub name: String,
|
||||
pub size: u64,
|
||||
pub modified: u64,
|
||||
}
|
||||
|
||||
/// 备份结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BackupReport {
|
||||
/// 上传的快照名
|
||||
pub name: String,
|
||||
/// 快照字节数
|
||||
pub bytes: u64,
|
||||
/// 打包的笔记数
|
||||
pub files: u32,
|
||||
/// 因超出保留份数而被删除的旧快照
|
||||
pub pruned: Vec<String>,
|
||||
}
|
||||
|
||||
/// 导入结果。
|
||||
#[derive(Debug, Clone, Default, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ImportReport {
|
||||
/// 导入的笔记数
|
||||
pub imported: u32,
|
||||
/// 因重名而被改名的数量
|
||||
pub renamed: u32,
|
||||
/// 跳过的非 Markdown 文件数
|
||||
pub skipped: u32,
|
||||
/// 失败明细(最多若干条)
|
||||
pub failures: Vec<String>,
|
||||
}
|
||||
|
||||
/// 最近打开的一个文件 / 文件夹。
|
||||
///
|
||||
/// `exists` 在每次读取设置时刷新(不依赖前端探测),供 UI 灰显失效项。
|
||||
/// 与笔记库**解耦**:库可以换 / 删,历史不该跟着丢(规划 §3.5)。
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct RecentEntry {
|
||||
/// 绝对路径(文件或文件夹)
|
||||
pub path: String,
|
||||
/// 显示名(文件名 / 文件夹名)
|
||||
pub name: String,
|
||||
/// 最近打开时间(Unix 毫秒)
|
||||
pub opened_at: u64,
|
||||
/// 该路径当前是否仍存在(读取设置时刷新)
|
||||
pub exists: bool,
|
||||
}
|
||||
|
||||
/// 笔记 / 编辑器设置根结构。
|
||||
///
|
||||
/// 字段取值必须与前端 `src/modules/notes/editor/themes.ts` 的 key 保持一致,
|
||||
/// 否则用户选了主题却回落默认(静默失效,终端模块踩过这个坑)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct EditorSettings {
|
||||
/// 结构版本号
|
||||
pub version: u32,
|
||||
/// 自定义库根(`None` = 用默认 `{app_data_dir}/editor/library`)
|
||||
pub library_root: Option<String>,
|
||||
/// 编辑器配色方案 key(`"system"` / `"vscode-dark"` / `"vscode-light"` / …)
|
||||
pub editor_theme: String,
|
||||
/// 编辑器**窗口**是否跟随主应用主题(开:整体跟随应用;关:由 `editor_theme` 决定,
|
||||
/// 窗口外壳与编辑区保持同一深浅)
|
||||
pub follow_app_theme: bool,
|
||||
/// 编辑器字体族(空串 = 用内置等宽字体栈)
|
||||
pub font_family: String,
|
||||
/// 字号(px)
|
||||
pub font_size: u32,
|
||||
/// 行高倍数
|
||||
pub line_height: f64,
|
||||
/// 是否启用字体连字(ligatures)
|
||||
pub ligatures: bool,
|
||||
/// Tab 宽度(空格数)
|
||||
pub tab_size: u32,
|
||||
/// 是否启用「所见即所得」Live Preview(关闭则纯 Markdown 源码 + 高亮)
|
||||
pub live_preview: bool,
|
||||
/// 自动保存防抖(毫秒;0 = 关闭自动保存,仅手动 Ctrl+S)
|
||||
pub autosave_ms: u32,
|
||||
/// 默认视图:"wysiwyg" | "source"
|
||||
pub default_view: String,
|
||||
/// 是否显示行号
|
||||
pub show_line_numbers: bool,
|
||||
/// 是否显示大纲侧栏(P1)
|
||||
pub show_outline: bool,
|
||||
/// 是否启用代码自动补全 / 括号闭合(P1;大文件会强制关闭)
|
||||
pub autocomplete: bool,
|
||||
/// 单文件大小上限(MB)。超过则编辑器降级为「纯高亮 + 行号」,
|
||||
/// 关闭 Live Preview / 折叠 / 补全等重扩展(见 §7 R2)。
|
||||
pub max_file_size_mb: u32,
|
||||
/// 是否识别 `[[wikilink]]`(P1,仅影响高亮与后续反链)
|
||||
pub wikilink: bool,
|
||||
/// 多窗口是否复用同一文档的窗口(P1;关闭则每次新建窗口)
|
||||
pub reuse_window: bool,
|
||||
/// WebDAV 备份 / 同步设置(P2)
|
||||
pub webdav: WebdavSettings,
|
||||
/// 新建笔记时是否弹出模板选择(P2)
|
||||
pub show_template_picker: bool,
|
||||
/// 导出 HTML 时是否内联代码高亮样式(P2;关闭则用打印友好的纯黑白)
|
||||
pub export_highlight: bool,
|
||||
/// 全局快捷键:新建笔记(空串 = 不注册)。
|
||||
///
|
||||
/// 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译同一套),
|
||||
/// 触发时只发 `editor-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
|
||||
pub new_note_shortcut: String,
|
||||
/// 全局快捷键:打开编辑器窗口(空串 = 不注册)
|
||||
pub open_editor_shortcut: String,
|
||||
/// 最近打开的文件(与笔记库解耦;上限 [`RECENT_LIMIT`])
|
||||
pub recent_files: Vec<RecentEntry>,
|
||||
/// 最近打开的文件夹(与笔记库解耦;上限 [`RECENT_LIMIT`])
|
||||
pub recent_folders: Vec<RecentEntry>,
|
||||
}
|
||||
|
||||
impl Default for EditorSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: EDITOR_SETTINGS_VERSION,
|
||||
library_root: None,
|
||||
editor_theme: "system".to_string(),
|
||||
follow_app_theme: false,
|
||||
font_family: String::new(),
|
||||
font_size: 14,
|
||||
line_height: 1.7,
|
||||
ligatures: false,
|
||||
tab_size: 2,
|
||||
live_preview: true,
|
||||
// 自动保存默认关闭:800ms 一保存会让「保存按钮 / 标签 * 号 / 侧栏」跟着
|
||||
// 闪烁,干扰正常编辑。需要的人可在设置里显式开启(见 heal 的 v4 迁移)。
|
||||
autosave_ms: 0,
|
||||
default_view: "wysiwyg".to_string(),
|
||||
show_line_numbers: true,
|
||||
show_outline: true,
|
||||
autocomplete: true,
|
||||
max_file_size_mb: 5,
|
||||
wikilink: true,
|
||||
reuse_window: true,
|
||||
webdav: WebdavSettings::default(),
|
||||
show_template_picker: true,
|
||||
export_highlight: true,
|
||||
new_note_shortcut: String::new(),
|
||||
open_editor_shortcut: "Alt+E".to_string(),
|
||||
recent_files: Vec::new(),
|
||||
recent_folders: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EditorSettings {
|
||||
/// 自愈:把越界/非法取值夹回合法区间,推进版本号。
|
||||
/// 返回是否发生了变更(由调用方决定是否落盘)。
|
||||
pub fn heal(&mut self) -> bool {
|
||||
let mut changed = false;
|
||||
|
||||
let clamp_u32 = |value: &mut u32, min: u32, max: u32, changed: &mut bool| {
|
||||
let next = (*value).clamp(min, max);
|
||||
if next != *value {
|
||||
*value = next;
|
||||
*changed = true;
|
||||
}
|
||||
};
|
||||
clamp_u32(&mut self.font_size, 10, 32, &mut changed);
|
||||
clamp_u32(&mut self.tab_size, 1, 8, &mut changed);
|
||||
clamp_u32(&mut self.autosave_ms, 0, 10_000, &mut changed);
|
||||
// 上限 100MB:再大就不该用编辑器打开(也不该走 IPC 把全文搬进 WebView)
|
||||
clamp_u32(&mut self.max_file_size_mb, 1, 100, &mut changed);
|
||||
// 快照保留份数:至少 1 份(0 份等于「备份完就删」,显然是误配)
|
||||
clamp_u32(&mut self.webdav.backup_keep, 1, 100, &mut changed);
|
||||
|
||||
if !(1.0..=3.0).contains(&self.line_height) {
|
||||
self.line_height = 1.7;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if self.editor_theme.trim().is_empty() {
|
||||
self.editor_theme = "system".to_string();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if self.default_view != "wysiwyg" && self.default_view != "source" {
|
||||
self.default_view = "wysiwyg".to_string();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if let Some(root) = &self.library_root {
|
||||
if root.trim().is_empty() {
|
||||
self.library_root = None;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// v3:引入「打开编辑器」默认快捷键 Alt+E(用户已显式设过则不覆盖)
|
||||
if self.version < 3 && self.open_editor_shortcut.trim().is_empty() {
|
||||
self.open_editor_shortcut = "Alt+E".to_string();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// v4:自动保存默认从 800ms 改为关闭 —— 仍是 800 说明用户从未改过这个值
|
||||
//(旧默认),此时关闭它;用户显式设过的其他值一律保留。
|
||||
if self.version < 4 && self.autosave_ms == 800 {
|
||||
self.autosave_ms = 0;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// v5:`followAppTheme` 的语义从「配色方案取色基准」改为「编辑器窗口是否跟随主应用
|
||||
// 主题」,默认亦由「跟随」改为「不跟随」。仍是 true 说明用户从未改过这个值(旧默认),
|
||||
// 此时改为不跟随;用户显式关过(false)的保持 false,不做任何覆盖。
|
||||
if self.version < 5 && self.follow_app_theme {
|
||||
self.follow_app_theme = false;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if self.version < EDITOR_SETTINGS_VERSION {
|
||||
self.version = EDITOR_SETTINGS_VERSION;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// 最近记录上限:超出淘汰最旧(列表约定为新在前)
|
||||
if self.recent_files.len() > RECENT_LIMIT {
|
||||
self.recent_files.truncate(RECENT_LIMIT);
|
||||
changed = true;
|
||||
}
|
||||
if self.recent_folders.len() > RECENT_LIMIT {
|
||||
self.recent_folders.truncate(RECENT_LIMIT);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
/// 刷新最近记录的「是否存在」标记(读取设置时调用,供 UI 灰显失效项)。
|
||||
pub fn refresh_recent_exists(&mut self) {
|
||||
for entry in self
|
||||
.recent_files
|
||||
.iter_mut()
|
||||
.chain(self.recent_folders.iter_mut())
|
||||
{
|
||||
entry.exists = !entry.path.trim().is_empty() && std::path::Path::new(&entry.path).exists();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 库内一个条目(文件或目录)的扁平描述。
|
||||
///
|
||||
/// **刻意用扁平列表而不是树**:递归类型在 specta 的 `Type` 派生下容易生成
|
||||
/// 无穷展开的 TS 类型;扁平结构由前端组装成树,更稳也更简单。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LibraryEntry {
|
||||
/// 显示名(不含目录前缀)
|
||||
pub name: String,
|
||||
/// 相对库根的路径,统一用 `/` 分隔(如 `2026/09/meeting.md`)
|
||||
pub rel_path: String,
|
||||
/// 父目录的相对路径(库根为 `""`)
|
||||
pub parent_rel: String,
|
||||
/// 是否目录
|
||||
pub is_dir: bool,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 文件字节数(目录为 0)
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
/// 库状态概览(主模块页横幅与设置页用)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LibraryInfo {
|
||||
/// 当前生效的库根绝对路径
|
||||
pub root: String,
|
||||
/// 是否为用户自定义库根(false = 默认 `{app_data_dir}/editor/library`)
|
||||
pub is_custom: bool,
|
||||
/// `.md` 笔记数量(不含目录)
|
||||
pub note_count: u32,
|
||||
}
|
||||
|
||||
/// 单篇笔记的读取/写入结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteDoc {
|
||||
/// 相对库根的路径(`/` 分隔)
|
||||
pub rel_path: String,
|
||||
/// 显示名(含扩展名)
|
||||
pub name: String,
|
||||
/// 完整文件内容(含 front-matter)
|
||||
pub content: String,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
}
|
||||
@@ -0,0 +1,797 @@
|
||||
//! WebDAV 客户端:`PROPFIND` / `MKCOL` / `GET` / `PUT` / `DELETE` / `MOVE`。
|
||||
//!
|
||||
//! # 定位:备份 / 同步目标,不是工作区
|
||||
//!
|
||||
//! 这条边界是产品级的(规划 §3.6 已确认):笔记的真相永远在本地文件系统,
|
||||
//! WebDAV 只接收「本地 → 远端」的推送与「远端 → 本地」的拉取,**不做远端直连读写**
|
||||
//! (不把远端当工作目录)。这样即使远端服务商限流、掉线、或者把文件改坏,本地
|
||||
//! 那份始终是完整可用的。
|
||||
//!
|
||||
//! # XML 解析为什么用 quick-xml
|
||||
//!
|
||||
//! `PROPFIND` 的响应是 `<D:multistatus>` 里套一堆 `<D:response>`,命名空间前缀
|
||||
//! 由服务端随意指定(`D:` / `d:` / `lp1:` / 甚至没有前缀)。因此**不能按前缀匹配**,
|
||||
//! 只能按 local name 匹配。这里用 quick-xml 的事件流手写一小段状态机:遇到
|
||||
//! `response` 开始收集,遇到 `href` / `getlastmodified` / `getcontentlength` /
|
||||
//! `resourcetype` 各自记录,`response` 结束时产出一条 [`RemoteEntry`]。
|
||||
//! 手写而不是上 `serde` 反序列化,是因为各家 NAS(群晖、威联通、Alist)的字段
|
||||
//! 集合与顺序都不一致,宽容的事件流比严格的结构体映射稳。
|
||||
//!
|
||||
//! # 请求节流与退避
|
||||
//!
|
||||
//! 坚果云一类服务对请求频率有硬限制(超限直接 503)。这里的策略是:
|
||||
//! `REQ_INTERVAL_MS` 之内的**连续请求之间强制 sleep**,并且对 429/503 做指数退避
|
||||
//! 重试。同步一个几百篇的库会发几百个请求,不节流几乎必然被限流。
|
||||
|
||||
use std::io::Read;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use base64::Engine as _;
|
||||
use quick_xml::events::Event;
|
||||
use quick_xml::Reader;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// 连续请求之间的最小间隔(坚果云等服务的限流底线)。
|
||||
const REQ_INTERVAL_MS: u64 = 60;
|
||||
|
||||
/// 单次请求超时(连接 15s / 整体 180s)。
|
||||
///
|
||||
/// 整体超时给得比一般的 HTTP 调用长:`PROPFIND` 一个几千文件的目录、
|
||||
/// 或者上传一个几十 MB 的 zip 备份都可能耗时,短超时会表现为「同步随机失败」。
|
||||
const TIMEOUT: Duration = Duration::from_secs(180);
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// 退避重试:遇到 429/503 时的等待序列(毫秒)。
|
||||
const BACKOFF_MS: [u64; 4] = [500, 1500, 4000, 9000];
|
||||
|
||||
/// 远端一个文件/目录的条目。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RemoteEntry {
|
||||
/// 相对远端根的路径(统一 `/` 分隔,无前导斜杠)
|
||||
pub rel_path: String,
|
||||
/// 是否目录
|
||||
pub is_dir: bool,
|
||||
/// 字节数(目录为 0)
|
||||
pub size: u64,
|
||||
/// 最后修改时间(Unix 毫秒;服务端未提供时为 0)
|
||||
pub modified: u64,
|
||||
}
|
||||
|
||||
/// 连接与认证配置(密码从 keyring 单独取,不进这里)。
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct WebdavConfig {
|
||||
/// 服务地址(如 `https://dav.jianguoyun.com/dav`)
|
||||
pub url: String,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
/// 远端根目录(相对 `url`,空串 = 直接用 `url` 指向的目录)
|
||||
pub remote_root: String,
|
||||
}
|
||||
|
||||
impl WebdavConfig {
|
||||
/// 是否具备发起请求的最小条件。
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.url.trim().is_empty() {
|
||||
return Err("请先填写 WebDAV 地址".to_string());
|
||||
}
|
||||
if !self.url.starts_with("http://") && !self.url.starts_with("https://") {
|
||||
return Err("WebDAV 地址必须以 http:// 或 https:// 开头".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 拼接「远端根 + 相对路径」为完整 URL 路径(已做百分号编码)。
|
||||
fn url_for(&self, rel: &str) -> String {
|
||||
let base = self.url.trim_end_matches('/');
|
||||
let root = self.remote_root.trim().trim_matches('/');
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
if !root.is_empty() {
|
||||
for segment in root.split('/') {
|
||||
if !segment.is_empty() {
|
||||
parts.push(encode_segment(segment));
|
||||
}
|
||||
}
|
||||
}
|
||||
for segment in rel.replace('\\', "/").split('/') {
|
||||
if !segment.is_empty() {
|
||||
parts.push(encode_segment(segment));
|
||||
}
|
||||
}
|
||||
if parts.is_empty() {
|
||||
// 指向目录时必须带尾斜杠:部分服务端(IIS、nginx 的 dav 模块)在缺尾斜杠时
|
||||
// 会回 301,而 `PROPFIND` 遇到 301 有些实现不会自动跟(跟了也可能丢 Depth 头)
|
||||
format!("{base}/")
|
||||
} else {
|
||||
format!("{base}/{}", parts.join("/"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 父目录的相对路径(用于 `MKCOL` 逐级创建)。
|
||||
fn parent_of(rel: &str) -> String {
|
||||
match rel.rfind('/') {
|
||||
Some(index) => rel[..index].to_string(),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 把一个路径段做百分号编码(只放过 unreserved 字符)。
|
||||
///
|
||||
/// 手写而不用 `urlencoding`:本文件已经为 `quick-xml` 加了一个依赖,
|
||||
/// 再为「编码一个路径段」加第二个不划算;规则本身只有十几行。
|
||||
fn encode_segment(segment: &str) -> String {
|
||||
let mut out = String::with_capacity(segment.len());
|
||||
for byte in segment.as_bytes() {
|
||||
match byte {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
out.push(*byte as char)
|
||||
}
|
||||
other => out.push_str(&format!("%{other:02X}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 百分号解码(服务端回传的 `href` 是编码过的)。
|
||||
fn decode_segment(segment: &str) -> String {
|
||||
let bytes = segment.as_bytes();
|
||||
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
if bytes[index] == b'%' && index + 2 < bytes.len() {
|
||||
let hex = std::str::from_utf8(&bytes[index + 1..index + 3]).unwrap_or("");
|
||||
if let Ok(value) = u8::from_str_radix(hex, 16) {
|
||||
out.push(value);
|
||||
index += 3;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(bytes[index]);
|
||||
index += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// WebDAV 客户端(`blocking` 是刻意的:见 `lib.rs` 的依赖注释)。
|
||||
pub struct WebdavClient {
|
||||
http: reqwest::blocking::Client,
|
||||
config: WebdavConfig,
|
||||
/// 上次请求时间(节流用)
|
||||
last_request: Mutex<Option<Instant>>,
|
||||
}
|
||||
|
||||
impl WebdavClient {
|
||||
pub fn new(config: WebdavConfig) -> Result<Self, String> {
|
||||
config.validate()?;
|
||||
let http = reqwest::blocking::Client::builder()
|
||||
.timeout(TIMEOUT)
|
||||
.connect_timeout(CONNECT_TIMEOUT)
|
||||
// 跟随重定向:不少服务端在「目录缺尾斜杠」时回 301
|
||||
.redirect(reqwest::redirect::Policy::limited(5))
|
||||
.user_agent("Thing-Notes/1.0")
|
||||
.build()
|
||||
.map_err(|e| format!("创建 HTTP 客户端失败: {e}"))?;
|
||||
Ok(Self {
|
||||
http,
|
||||
config,
|
||||
last_request: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
/// 节流:保证两次请求之间至少间隔 [`REQ_INTERVAL_MS`]。
|
||||
fn throttle(&self) { let mut slot = match self.last_request.lock() {
|
||||
Ok(slot) => slot,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
if let Some(previous) = *slot {
|
||||
let elapsed = previous.elapsed();
|
||||
let min = Duration::from_millis(REQ_INTERVAL_MS);
|
||||
if elapsed < min {
|
||||
std::thread::sleep(min - elapsed);
|
||||
}
|
||||
}
|
||||
*slot = Some(Instant::now());
|
||||
}
|
||||
|
||||
/// 目录型 URL(`remote_root` 与每一层子目录都用它)。
|
||||
///
|
||||
/// `WebdavConfig::url_for("")` 只有在 `remote_root` 为空时才带尾斜杠;
|
||||
/// `remote_root` 非空时拼出来的是纯路径(如 `.../thing%20notes`),
|
||||
/// 而**目录请求必须带尾斜杠**(见 `url_for` 的注释)。
|
||||
fn dir_url(&self, rel: &str) -> String {
|
||||
let url = self.config.url_for(rel);
|
||||
if url.ends_with('/') {
|
||||
url
|
||||
} else {
|
||||
format!("{url}/")
|
||||
}
|
||||
}
|
||||
|
||||
/// 带 Basic 认证与节流的请求构造。
|
||||
fn request(&self, method: reqwest::Method, url: &str) -> reqwest::blocking::RequestBuilder {
|
||||
self.throttle();
|
||||
let mut builder = self.http.request(method, url);
|
||||
if !self.config.username.is_empty() || !self.config.password.is_empty() {
|
||||
let token = base64::engine::general_purpose::STANDARD
|
||||
.encode(format!("{}:{}", self.config.username, self.config.password));
|
||||
builder = builder.header("Authorization", format!("Basic {token}"));
|
||||
}
|
||||
builder
|
||||
}
|
||||
|
||||
/// 发请求并做退避重试(对 429/503 与网络错误重试)。
|
||||
fn send(
|
||||
&self,
|
||||
method: reqwest::Method,
|
||||
url: &str,
|
||||
body: Option<Vec<u8>>,
|
||||
content_type: Option<&str>,
|
||||
headers: &[(&str, &str)],
|
||||
) -> Result<reqwest::blocking::Response, String> {
|
||||
let mut attempt = 0usize;
|
||||
loop {
|
||||
let mut builder = self.request(method.clone(), url);
|
||||
for (name, value) in headers {
|
||||
builder = builder.header(*name, *value);
|
||||
}
|
||||
if let Some(content_type) = content_type {
|
||||
builder = builder.header("Content-Type", content_type);
|
||||
}
|
||||
if let Some(body) = &body {
|
||||
builder = builder.body(body.clone());
|
||||
}
|
||||
|
||||
let result = builder.send();
|
||||
match result {
|
||||
Ok(response) => {
|
||||
let status = response.status().as_u16();
|
||||
// 429(限流)与 503(服务不可用)是可重试的;其余 4xx 是请求本身的问题
|
||||
if (status == 429 || status == 503) && attempt < BACKOFF_MS.len() {
|
||||
let wait = BACKOFF_MS[attempt];
|
||||
crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!("WebDAV 返回 {status},{wait}ms 后重试(第 {} 次)", attempt + 1),
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(wait));
|
||||
attempt += 1;
|
||||
continue;
|
||||
}
|
||||
return Ok(response);
|
||||
}
|
||||
Err(e) => {
|
||||
if attempt < BACKOFF_MS.len() {
|
||||
let wait = BACKOFF_MS[attempt];
|
||||
crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!("WebDAV 请求失败({e}),{wait}ms 后重试"),
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(wait));
|
||||
attempt += 1;
|
||||
continue;
|
||||
}
|
||||
return Err(format!("WebDAV 请求失败: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 把响应状态翻译成「人能看懂的错误」。
|
||||
fn ensure_success(response: &reqwest::blocking::Response, what: &str) -> Result<(), String> {
|
||||
let status = response.status();
|
||||
if status.is_success() {
|
||||
return Ok(());
|
||||
}
|
||||
let code = status.as_u16();
|
||||
let hint = match code {
|
||||
401 => "(用户名或密码/应用密码不正确)",
|
||||
403 => "(账号无此目录权限)",
|
||||
404 => "(路径不存在)",
|
||||
405 => "(服务端不允许该操作,可能不是标准 WebDAV)",
|
||||
409 => "(父目录不存在)",
|
||||
507 => "(远端空间不足)",
|
||||
_ => "",
|
||||
};
|
||||
Err(format!("{what}失败:HTTP {code}{hint}"))
|
||||
}
|
||||
|
||||
/// 探测远端根目录是否存在(返回条目列表;不存在返回 `None`)。
|
||||
pub fn list(&self, rel: &str) -> Result<Option<Vec<RemoteEntry>>, String> {
|
||||
let url = self.dir_url(rel);
|
||||
let body = br#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<D:propfind xmlns:D="DAV:"><D:prop>
|
||||
<D:resourcetype/><D:getcontentlength/><D:getlastmodified/>
|
||||
</D:prop></D:propfind>"#
|
||||
.to_vec();
|
||||
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"PROPFIND").unwrap_or(reqwest::Method::GET),
|
||||
&url,
|
||||
Some(body),
|
||||
Some("application/xml; charset=utf-8"),
|
||||
&[("Depth", "1")],
|
||||
)?;
|
||||
|
||||
if response.status().as_u16() == 404 {
|
||||
return Ok(None);
|
||||
}
|
||||
Self::ensure_success(&response, "列目录")?;
|
||||
|
||||
let text = response
|
||||
.text()
|
||||
.map_err(|e| format!("读取 PROPFIND 响应失败: {e}"))?;
|
||||
let entries = parse_multistatus(&text, &self.config.url, &self.config.remote_root, rel)?;
|
||||
Ok(Some(entries))
|
||||
}
|
||||
|
||||
/// 确认远端根可用(不存在则创建)。
|
||||
///
|
||||
/// 自检的意义在于:把「地址写错 / 密码错 / 目录不存在」这三类问题在用户点下
|
||||
/// 「立即同步」**之前**就暴露出来,而不是让同步跑到一半报错。
|
||||
pub fn ensure_root(&self) -> Result<Vec<String>, String> {
|
||||
self.config.validate()?;
|
||||
let mut created: Vec<String> = Vec::new();
|
||||
|
||||
// 逐级创建 remote_root(服务端不会自动补父目录)
|
||||
let root = self.config.remote_root.trim().trim_matches('/').to_string();
|
||||
if !root.is_empty() {
|
||||
for next in Self::segments(&root) {
|
||||
let url = self.dir_url(&next);
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"MKCOL").unwrap_or(reqwest::Method::POST),
|
||||
&url,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
)?;
|
||||
let code = response.status().as_u16();
|
||||
// 201 = 建成;405 = 已存在(各家服务端口径不一,两者都算成功)
|
||||
if code == 201 {
|
||||
created.push(next);
|
||||
} else if code != 405 {
|
||||
Self::ensure_success(&response, &format!("创建远端目录 {next}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 最后列一次,确认真的可读
|
||||
match self.list("")? {
|
||||
Some(_) => Ok(created),
|
||||
None => Err("远端根目录不存在且无法创建".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 递归列出远端某目录下的全部文件(跳过 [`should_skip`] 命中的路径)。
|
||||
pub fn list_recursive(&self) -> Result<Vec<RemoteEntry>, String> {
|
||||
let mut out: Vec<RemoteEntry> = Vec::new();
|
||||
let mut queue: Vec<String> = vec![String::new()];
|
||||
// 深度上限:远端目录结构异常(成环的软链)时不至于无限翻页
|
||||
let mut depth = 0usize;
|
||||
|
||||
while let Some(dir) = queue.pop() {
|
||||
depth += 1;
|
||||
if depth > 4096 {
|
||||
crate::logger::log_warn("editor", "远端目录过多,提前结束遍历");
|
||||
break;
|
||||
}
|
||||
let Some(entries) = self.list(&dir)? else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries {
|
||||
if entry.rel_path.is_empty() || entry.rel_path == dir {
|
||||
continue;
|
||||
}
|
||||
if should_skip(&entry.rel_path) {
|
||||
continue;
|
||||
}
|
||||
if entry.is_dir {
|
||||
queue.push(entry.rel_path.clone());
|
||||
} else {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 创建目录(含父级)。
|
||||
pub fn mkdir_all(&self, rel: &str) -> Result<(), String> {
|
||||
for next in Self::segments(rel) {
|
||||
let url = self.dir_url(&next);
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"MKCOL").unwrap_or(reqwest::Method::POST),
|
||||
&url,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
)?;
|
||||
let code = response.status().as_u16();
|
||||
if code != 201 && code != 405 {
|
||||
Self::ensure_success(&response, &format!("创建远端目录 {next}"))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把 `a/b/c` 展开成 `["a", "a/b", "a/b/c"]`(逐级创建用)。
|
||||
fn segments(rel: &str) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
let mut prefix = String::new();
|
||||
for segment in rel.trim_matches('/').split('/') {
|
||||
if segment.is_empty() {
|
||||
continue;
|
||||
}
|
||||
prefix = if prefix.is_empty() {
|
||||
segment.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{segment}")
|
||||
};
|
||||
out.push(prefix.clone());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 读取远端文件内容。
|
||||
pub fn get(&self, rel: &str) -> Result<Vec<u8>, String> {
|
||||
let url = self.config.url_for(rel);
|
||||
let response = self.send(reqwest::Method::GET, &url, None, None, &[])?;
|
||||
Self::ensure_success(&response, &format!("下载 {rel}"))?;
|
||||
let mut out = Vec::new();
|
||||
response
|
||||
.take(512 * 1024 * 1024)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| format!("读取下载内容失败: {e}"))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 上传文件内容(必要时先建父目录)。
|
||||
pub fn put(&self, rel: &str, bytes: Vec<u8>) -> Result<(), String> {
|
||||
let parent = WebdavConfig::parent_of(rel);
|
||||
if !parent.is_empty() {
|
||||
self.mkdir_all(&parent)?;
|
||||
}
|
||||
let url = self.config.url_for(rel);
|
||||
let response = self.send(
|
||||
reqwest::Method::PUT,
|
||||
&url,
|
||||
Some(bytes),
|
||||
Some("application/octet-stream"),
|
||||
&[],
|
||||
)?;
|
||||
Self::ensure_success(&response, &format!("上传 {rel}"))
|
||||
}
|
||||
|
||||
/// 删除文件(404 视为成功 —— 目标已经不存在,结果一致)。
|
||||
pub fn delete(&self, rel: &str) -> Result<(), String> {
|
||||
let url = self.config.url_for(rel);
|
||||
let response = self.send(reqwest::Method::DELETE, &url, None, None, &[])?;
|
||||
if response.status().as_u16() == 404 {
|
||||
return Ok(());
|
||||
}
|
||||
Self::ensure_success(&response, &format!("删除远端 {rel}"))
|
||||
}
|
||||
|
||||
/// 移动 / 重命名(`MOVE`,覆盖写)。
|
||||
pub fn move_to(&self, from: &str, to: &str) -> Result<(), String> {
|
||||
let url = self.config.url_for(from);
|
||||
let parent = WebdavConfig::parent_of(to);
|
||||
if !parent.is_empty() {
|
||||
self.mkdir_all(&parent)?;
|
||||
}
|
||||
let destination = self.config.url_for(to);
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"MOVE").unwrap_or(reqwest::Method::POST),
|
||||
&url,
|
||||
None,
|
||||
None,
|
||||
&[("Destination", destination.as_str()), ("Overwrite", "T")],
|
||||
)?;
|
||||
Self::ensure_success(&response, &format!("移动 {from} → {to}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析 `multistatus` 响应。
|
||||
///
|
||||
/// 按 **local name** 匹配(忽略命名空间前缀),并把 `href` 归一化成「相对远端根的
|
||||
/// 路径」。`base_url` 与 `remote_root` 用于剥掉服务端回传的完整 URL 前缀。
|
||||
fn parse_multistatus(
|
||||
xml: &str,
|
||||
base_url: &str,
|
||||
remote_root: &str,
|
||||
listing_dir: &str,
|
||||
) -> Result<Vec<RemoteEntry>, String> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
reader.config_mut().trim_text(true);
|
||||
|
||||
let mut entries: Vec<RemoteEntry> = Vec::new();
|
||||
let mut in_response = false;
|
||||
let mut current_href = String::new();
|
||||
let mut current_is_dir = false;
|
||||
let mut current_size = 0u64;
|
||||
let mut current_modified = 0u64;
|
||||
// 当前正在读的字段(`href` 可能在 propstat 里出现多次,只取第一个)
|
||||
let mut field = String::new();
|
||||
|
||||
loop {
|
||||
match reader.read_event() {
|
||||
Ok(Event::Start(element)) => {
|
||||
let name = element.name();
|
||||
let local = local_name(name.as_ref());
|
||||
match local.as_str() {
|
||||
"response" => {
|
||||
in_response = true;
|
||||
current_href.clear();
|
||||
current_is_dir = false;
|
||||
current_size = 0;
|
||||
current_modified = 0;
|
||||
}
|
||||
"href" | "getcontentlength" | "getlastmodified" | "collection" => {
|
||||
field = local;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Event::Empty(element)) => {
|
||||
// `<D:collection/>` 是「这是目录」的标志
|
||||
let name = element.name();
|
||||
if local_name(name.as_ref()) == "collection" {
|
||||
current_is_dir = true;
|
||||
}
|
||||
}
|
||||
Ok(Event::Text(text)) => {
|
||||
// quick-xml 0.42 的 `BytesText` 直接 `Deref<Target = str>`(Reader 是
|
||||
// `from_str` 建的,输入本身就是 UTF-8,不需要再 decode/unescape)。
|
||||
// 这里拷成 owned String 是因为 `field` 的匹配在借用结束之后才用。
|
||||
let value: String = text.as_ref().to_string();
|
||||
match field.as_str() {
|
||||
"href" if current_href.is_empty() => current_href = value,
|
||||
"getcontentlength" => current_size = value.trim().parse().unwrap_or(0),
|
||||
"getlastmodified" => current_modified = parse_http_date(&value).unwrap_or(0),
|
||||
"collection" => current_is_dir = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Event::End(element)) => {
|
||||
let name = element.name();
|
||||
let local = local_name(name.as_ref());
|
||||
if local == "response" && in_response {
|
||||
in_response = false;
|
||||
let rel = normalize_href(¤t_href, base_url, remote_root, listing_dir);
|
||||
if let Some(rel) = rel {
|
||||
entries.push(RemoteEntry {
|
||||
rel_path: rel,
|
||||
is_dir: current_is_dir,
|
||||
size: if current_is_dir { 0 } else { current_size },
|
||||
modified: current_modified,
|
||||
});
|
||||
}
|
||||
}
|
||||
field.clear();
|
||||
}
|
||||
Ok(Event::Eof) => break,
|
||||
Err(e) => return Err(format!("解析 WebDAV 响应失败: {e}")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// 取 XML 元素的 local name(去掉 `D:` / `lp1:` 之类前缀)。
|
||||
///
|
||||
/// quick-xml 0.42 的 `QName::as_ref()` 返回 `&str`(更早的版本是 `&[u8]`)——
|
||||
/// 这也是本文件里唯一需要跟着版本走的细节。
|
||||
fn local_name(raw: &str) -> String {
|
||||
match raw.rsplit(':').next() {
|
||||
Some(name) => name.to_ascii_lowercase(),
|
||||
None => raw.to_ascii_lowercase(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 把服务端回传的 `href` 归一化成相对远端根的路径。
|
||||
///
|
||||
/// 服务端的三种形态都要吃下:
|
||||
/// 1. 完整 URL(`https://host/dav/root/a.md`)—— 剥掉 `base_url` 与 `remote_root`;
|
||||
/// 2. 绝对路径(`/dav/root/a.md`)—— 同上;
|
||||
/// 3. 相对路径(`a.md`)—— 拼到当前列出的目录之后再归一化。
|
||||
fn normalize_href(
|
||||
href: &str,
|
||||
base_url: &str,
|
||||
remote_root: &str,
|
||||
listing_dir: &str,
|
||||
) -> Option<String> {
|
||||
if href.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
// 去掉协议与主机
|
||||
let path = if let Some(rest) = href.split("://").nth(1) {
|
||||
match rest.find('/') {
|
||||
Some(index) => &rest[index..],
|
||||
None => "/",
|
||||
}
|
||||
} else {
|
||||
href
|
||||
};
|
||||
let decoded = decode_segment(path);
|
||||
let trimmed_base = base_url.trim_end_matches('/');
|
||||
// 剥掉 base 的路径部分(如 `/dav`)
|
||||
let base_path = if let Some(rest) = trimmed_base.split("://").nth(1) {
|
||||
match rest.find('/') {
|
||||
Some(index) => &rest[index..],
|
||||
None => "",
|
||||
}
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let mut rel = decoded.as_str();
|
||||
if !base_path.is_empty() {
|
||||
if let Some(rest) = rel.strip_prefix(base_path) {
|
||||
rel = rest;
|
||||
}
|
||||
}
|
||||
let root = remote_root.trim().trim_matches('/');
|
||||
if !root.is_empty() {
|
||||
let with_slash = format!("/{root}");
|
||||
if let Some(rest) = rel.strip_prefix(with_slash.as_str()) {
|
||||
rel = rest;
|
||||
} else if let Some(rest) = rel.strip_prefix(root) {
|
||||
rel = rest;
|
||||
}
|
||||
}
|
||||
let clean = rel.trim_matches('/').to_string();
|
||||
if clean.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// 相对 href:拼到 listing_dir 后面
|
||||
let full = if !path.starts_with('/') && !listing_dir.trim().is_empty() {
|
||||
format!("{}/{}", listing_dir.trim_matches('/'), clean)
|
||||
} else {
|
||||
clean
|
||||
};
|
||||
Some(full)
|
||||
}
|
||||
|
||||
/// 解析 HTTP 日期(RFC 1123,如 `Wed, 21 Oct 2015 07:28:00 GMT`)为 Unix 毫秒。
|
||||
///
|
||||
/// 用 `chrono::DateTime::parse_from_rfc2822`:RFC 2822 与 RFC 1123 的日期部分兼容,
|
||||
/// 而 chrono 正好提供这个解析器(不引入第二个时间库)。
|
||||
fn parse_http_date(value: &str) -> Option<u64> {
|
||||
let parsed = chrono::DateTime::parse_from_rfc2822(value.trim()).ok()?;
|
||||
Some(parsed.timestamp_millis().max(0) as u64)
|
||||
}
|
||||
|
||||
/// 该远端路径是否应当排除在同步之外。
|
||||
///
|
||||
/// `.editor/` 是本模块的私有目录(索引 + 同步状态),**必须排除**:把索引同步到
|
||||
/// 远端毫无意义,且它随每次搜索变化,会让每一次同步都变成全量传输。
|
||||
pub fn should_skip(rel: &str) -> bool {
|
||||
let normalized = rel.replace('\\', "/");
|
||||
normalized.split('/').any(|part| {
|
||||
part.starts_with('.') || part.eq_ignore_ascii_case("node_modules")
|
||||
})
|
||||
}
|
||||
|
||||
// ===== 测试 =====
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn url_join_and_encoding() {
|
||||
let config = WebdavConfig {
|
||||
url: "https://dav.example.com/dav/".to_string(),
|
||||
remote_root: "thing notes".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
config.url_for("a/b.md"),
|
||||
"https://dav.example.com/dav/thing%20notes/a/b.md"
|
||||
);
|
||||
// 文件路径不带尾斜杠
|
||||
assert_eq!(
|
||||
config.url_for("a.md"),
|
||||
"https://dav.example.com/dav/thing%20notes/a.md"
|
||||
);
|
||||
// 目录请求必须带尾斜杠(否则部分服务端 301,PROPFIND 会丢 Depth 头)
|
||||
let client = WebdavClient::new(config).unwrap();
|
||||
assert_eq!(
|
||||
client.dir_url(""),
|
||||
"https://dav.example.com/dav/thing%20notes/"
|
||||
);
|
||||
assert_eq!(
|
||||
client.dir_url("sub"),
|
||||
"https://dav.example.com/dav/thing%20notes/sub/"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_bad_url() {
|
||||
let mut config = WebdavConfig::default();
|
||||
assert!(config.validate().is_err());
|
||||
config.url = "dav.example.com".to_string();
|
||||
assert!(config.validate().is_err());
|
||||
config.url = "https://dav.example.com".to_string();
|
||||
assert!(config.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multistatus_parsing_tolerates_namespace_prefixes() {
|
||||
// 三家服务的常见形态:D: / d: / lp1: / 无前缀
|
||||
let xml = r#"<?xml version="1.0"?>
|
||||
<D:multistatus xmlns:D="DAV:">
|
||||
<D:response>
|
||||
<D:href>/dav/root/</D:href>
|
||||
<D:propstat><D:prop><D:resourcetype><D:collection/></D:resourcetype></D:prop></D:propstat>
|
||||
</D:response>
|
||||
<d:response xmlns:d="DAV:">
|
||||
<d:href>https://host/dav/root/notes/meeting.md</d:href>
|
||||
<d:propstat><d:prop>
|
||||
<d:resourcetype/>
|
||||
<d:getcontentlength>1234</d:getcontentlength>
|
||||
<d:getlastmodified>Wed, 21 Oct 2015 07:28:00 GMT</d:getlastmodified>
|
||||
</d:prop></d:propstat>
|
||||
</d:response>
|
||||
<response>
|
||||
<href>/dav/root/notes/%E4%B8%AD%E6%96%87.md</href>
|
||||
<propstat><prop><resourcetype/></prop></propstat>
|
||||
</response>
|
||||
</D:multistatus>"#;
|
||||
|
||||
let entries = parse_multistatus(xml, "https://host/dav", "root", "").unwrap();
|
||||
// 根目录自身被剥成空路径 → 不产出条目
|
||||
assert_eq!(entries.len(), 2, "{entries:?}");
|
||||
|
||||
let meeting = entries
|
||||
.iter()
|
||||
.find(|e| e.rel_path == "notes/meeting.md")
|
||||
.expect("应解析出 notes/meeting.md");
|
||||
assert!(!meeting.is_dir);
|
||||
assert_eq!(meeting.size, 1234);
|
||||
assert!(meeting.modified > 0, "应解析出 RFC1123 日期");
|
||||
|
||||
let chinese = entries
|
||||
.iter()
|
||||
.find(|e| e.rel_path == "notes/中文.md")
|
||||
.expect("百分号编码的 href 应被解码");
|
||||
assert!(!chinese.is_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_is_detected_as_directory() {
|
||||
let xml = r#"<multistatus xmlns="DAV:"><response>
|
||||
<href>/dav/root/sub</href>
|
||||
<propstat><prop><resourcetype><collection/></resourcetype></prop></propstat>
|
||||
</response></multistatus>"#;
|
||||
let entries = parse_multistatus(xml, "https://host/dav", "root", "").unwrap();
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert!(entries[0].is_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skip_rules_exclude_private_dir() {
|
||||
assert!(should_skip(".editor/editor.db"));
|
||||
assert!(should_skip("a/.hidden/b.md"));
|
||||
assert!(should_skip("node_modules/x.md"));
|
||||
assert!(!should_skip("notes/a.md"));
|
||||
assert!(!should_skip("a/b/c.md"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percent_encoding_roundtrip() {
|
||||
let encoded = encode_segment("中文 名字.md");
|
||||
assert_eq!(decode_segment(&encoded), "中文 名字.md");
|
||||
// 特殊字符(`?` / `#` / `/`)必须编码,否则会被服务端当查询串或路径分隔
|
||||
assert!(!encode_segment("a?b#c/d").contains('?'));
|
||||
assert!(!encode_segment("a?b#c/d").contains('#'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_date_parsing() {
|
||||
let ms = parse_http_date("Wed, 21 Oct 2015 07:28:00 GMT").unwrap();
|
||||
assert_eq!(ms, 1_445_412_480_000);
|
||||
assert!(parse_http_date("不是日期").is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//! WebDAV 子模块:客户端与会话层。
|
||||
//!
|
||||
//! ```text
|
||||
//! client.rs ── 协议层:PROPFIND / MKCOL / GET / PUT / DELETE / MOVE(quick-xml 解析)
|
||||
//! mod.rs ── 会话层:读设置 → 取 keyring 密码 → 建客户端(供命令层一步调用)
|
||||
//! sync.rs ── 引擎层:清单比对 / 冲突策略 / 执行与基线维护
|
||||
//! ```
|
||||
//!
|
||||
//! 备份(zip 快照)在 `super::backup`:它只用 `PUT`,与同步是两条独立的路径
|
||||
//! (规划 §3.6 的取舍:对「只是要个备份」的用户,快照比双向同步可靠得多)。
|
||||
|
||||
pub mod client;
|
||||
pub mod sync;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use crate::editor::types::WebdavSettings;
|
||||
use client::WebdavClient;
|
||||
|
||||
/// keyring 里的服务名(与 `secrets.rs` 的约定一致,服务名固定 `"Thing"`)。
|
||||
pub const KEYRING_PASSWORD: &str = "editor.webdav.password";
|
||||
|
||||
/// 连接自检结果(设置页展示)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WebdavTestResult {
|
||||
/// 是否连通
|
||||
pub ok: bool,
|
||||
/// 远端根目录中已有的条目数(自检时顺带列出)
|
||||
pub entries: u32,
|
||||
/// 本次自检自动创建的目录
|
||||
pub created: Vec<String>,
|
||||
/// 人话结论(失败时是原因)
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// 由设置构造客户端(密码从 keyring 取,**不落盘**)。
|
||||
///
|
||||
/// 密码走系统凭据管理器而不是 `settings.json`:设置文件是明文 JSON,用户可能把库
|
||||
/// 连同设置一起放到同步目录里(那就等于把密码公开了)。keyring 的键是
|
||||
/// [`KEYRING_PASSWORD`],服务名沿用项目统一的 `"Thing"`。
|
||||
pub fn client_from(settings: &WebdavSettings) -> Result<WebdavClient, String> {
|
||||
settings.validate()?;
|
||||
let password = crate::secrets::secret_read(KEYRING_PASSWORD)
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
WebdavClient::new(client::WebdavConfig {
|
||||
url: settings.url.trim().to_string(),
|
||||
username: settings.username.trim().to_string(),
|
||||
password,
|
||||
remote_root: settings.remote_root.trim().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 连接自检:验证地址/凭据,并按需逐级创建远端根目录。
|
||||
pub fn test_connection(settings: &WebdavSettings) -> Result<WebdavTestResult, String> {
|
||||
let client = client_from(settings)?;
|
||||
let created = client.ensure_root()?;
|
||||
let entries = client.list_recursive()?.len() as u32;
|
||||
Ok(WebdavTestResult {
|
||||
ok: true,
|
||||
entries,
|
||||
created,
|
||||
message: format!("连接正常,远端已有 {entries} 个文件"),
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+227
-9
@@ -3,13 +3,16 @@ use tauri::Manager;
|
||||
mod ai;
|
||||
mod clipboard;
|
||||
mod constants;
|
||||
mod diff;
|
||||
mod download_engine;
|
||||
mod drag_drop;
|
||||
mod dsh;
|
||||
mod logger;
|
||||
mod mihomo_manager;
|
||||
mod monitor_kernel;
|
||||
pub mod music;
|
||||
mod network_monitor;
|
||||
mod editor;
|
||||
mod osd_window;
|
||||
mod process_manager;
|
||||
mod quickpanel;
|
||||
@@ -17,7 +20,9 @@ mod screenshot;
|
||||
mod secrets;
|
||||
mod setup;
|
||||
mod shortcut;
|
||||
mod smarthome;
|
||||
mod snap_fix;
|
||||
mod taskbar_identity;
|
||||
mod terminal;
|
||||
mod translate;
|
||||
mod tray_menu;
|
||||
@@ -37,6 +42,26 @@ use download_engine::{
|
||||
use logger::{
|
||||
log_clear, log_info_state, log_list, log_message,
|
||||
};
|
||||
use editor::{
|
||||
editor_add_template, editor_authorize_file, editor_backlinks, editor_backup_now,
|
||||
editor_create_folder, editor_create_note, editor_daily_note, editor_delete_entry,
|
||||
editor_export_note, editor_export_snapshot_local, editor_export_zip, editor_get_settings,
|
||||
editor_import, editor_index_stats, editor_library_info, editor_link_graph, editor_list_backups,
|
||||
editor_list_notes, editor_list_templates, editor_open_file, editor_read_asset, editor_read_note,
|
||||
editor_read_template, editor_rebuild_index, editor_redecode_file, editor_rename_entry, editor_restore_backup,
|
||||
editor_save_note, editor_save_settings, editor_scan_library, editor_scratch_dir, editor_search_notes,
|
||||
editor_set_library_root, editor_set_webdav_password, editor_sync_index, editor_sync_now,
|
||||
editor_tags, editor_take_pending_file, editor_test_webdav, editor_webdav_status,
|
||||
editor_write_asset, editor_write_file,
|
||||
editor_read_dir, editor_create_file, editor_create_dir, editor_rename_path, editor_delete_path,
|
||||
editor_move_path, editor_search_in_path, editor_replace_in_path,
|
||||
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
|
||||
};
|
||||
use diff::{
|
||||
diff_compare_dirs, diff_get_settings, diff_path_kind, diff_read_file, diff_save_settings,
|
||||
diff_write_file,
|
||||
};
|
||||
use drag_drop::window_attach_drag_drop;
|
||||
use mihomo_manager::{
|
||||
proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy,
|
||||
proxy_close_connection, proxy_confirm_install, proxy_delete_profile, proxy_get_connections, proxy_get_proxies, proxy_get_settings, proxy_get_system_proxy,
|
||||
@@ -45,9 +70,9 @@ use mihomo_manager::{
|
||||
proxy_test_delay, proxy_update_profile, proxy_version, MihomoManager,
|
||||
};
|
||||
use monitor_kernel::{
|
||||
monitor_elevate_self, monitor_get_auto_start, monitor_get_elevate_on_launch,
|
||||
monitor_get_auto_start, monitor_get_elevate_on_start,
|
||||
monitor_get_hardware_config, monitor_get_snapshot, monitor_get_status, monitor_kernel_info,
|
||||
monitor_repair_pawnio, monitor_set_auto_start, monitor_set_elevate_on_launch,
|
||||
monitor_repair_pawnio, monitor_set_auto_start, monitor_set_elevate_on_start,
|
||||
monitor_set_hardware_config, monitor_start, monitor_start_elevated, monitor_status, monitor_stop,
|
||||
MonitorKernel,
|
||||
};
|
||||
@@ -121,11 +146,12 @@ use quickpanel::{
|
||||
quickpanel_get_special_locations, quickpanel_hide_popup, quickpanel_init_file_index,
|
||||
quickpanel_list_archives, quickpanel_list_dir, quickpanel_lock_screen, quickpanel_open_file,
|
||||
quickpanel_open_special, quickpanel_preview_rename, quickpanel_register_shortcut,
|
||||
quickpanel_reveal_in_explorer, quickpanel_run_custom_command, quickpanel_run_system_command,
|
||||
quickpanel_reveal_in_explorer, quickpanel_reveal_in_explorer_rename,
|
||||
quickpanel_run_custom_command, quickpanel_run_system_command,
|
||||
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
|
||||
quickpanel_show_window, quickpanel_unregister_shortcut, quickpanel_focus_main_window,
|
||||
};
|
||||
use tray_menu::{tray_menu_action, tray_menu_hide, tray_menu_ready};
|
||||
use tray_menu::{tray_menu_action, tray_menu_hide, tray_menu_ready, tray_music_control, tray_music_state};
|
||||
use terminal::commands::{
|
||||
terminal_attach_session, terminal_clear_known_hosts, terminal_clear_session,
|
||||
terminal_close_session, terminal_confirm_host_key, terminal_default_cwd, terminal_delete_host,
|
||||
@@ -169,6 +195,17 @@ use terminal::commands::{
|
||||
terminal_ai_engines, terminal_ai_suggest,
|
||||
};
|
||||
use terminal::TerminalManager;
|
||||
use taskbar_identity::window_set_taskbar_identity;
|
||||
use smarthome::{
|
||||
smarthome_activate_connection, smarthome_call_service, smarthome_check_link,
|
||||
smarthome_clear_token, smarthome_delete_connection, smarthome_delete_rule,
|
||||
smarthome_get_entity, smarthome_get_settings, smarthome_list_entities, smarthome_list_registry,
|
||||
smarthome_list_rules, smarthome_save_connection, smarthome_save_rule,
|
||||
smarthome_save_ui_settings, smarthome_set_endpoint_mode, smarthome_set_realtime_enabled,
|
||||
smarthome_set_rules_enabled, smarthome_set_token, smarthome_test_connection,
|
||||
smarthome_ws_start, smarthome_ws_status, smarthome_ws_stop,
|
||||
};
|
||||
use win32_util::window_focus_window;
|
||||
use translate::{
|
||||
translate_abort, translate_ai_engine_remove, translate_ai_params_save, translate_apply_shortcuts,
|
||||
translate_copy_text, translate_engine_delete, translate_engine_models, translate_engine_save,
|
||||
@@ -229,7 +266,8 @@ fn export_bindings() {
|
||||
quickpanel_show_window, quickpanel_lock_screen, quickpanel_init_file_index,
|
||||
quickpanel_build_file_index, quickpanel_search_files, quickpanel_file_index_stats,
|
||||
quickpanel_scan_apps, quickpanel_get_app_icon, quickpanel_clear_app_icon_cache,
|
||||
quickpanel_reveal_in_explorer, quickpanel_open_file, quickpanel_get_special_locations,
|
||||
quickpanel_reveal_in_explorer, quickpanel_reveal_in_explorer_rename,
|
||||
quickpanel_open_file, quickpanel_get_special_locations,
|
||||
quickpanel_open_special, quickpanel_delete_file, quickpanel_run_custom_command,
|
||||
quickpanel_run_system_command, quickpanel_list_archives, quickpanel_list_dir,
|
||||
quickpanel_batch_extract, quickpanel_preview_rename, quickpanel_apply_rename,
|
||||
@@ -324,6 +362,65 @@ fn export_bindings() {
|
||||
dsh_unregister_shortcut, dsh_start, dsh_stop, dsh_restart,
|
||||
dsh_ai_preview, dsh_ai_sync, dsh_log_tail, dsh_install_log, dsh_log_clear,
|
||||
dsh_open_dir,
|
||||
// editor(40)——与 `run()` 里那份保持一致,否则 bindings.ts 缺类型
|
||||
editor_get_settings, editor_save_settings, editor_library_info, editor_set_library_root,
|
||||
editor_scan_library, editor_read_note, editor_save_note, editor_create_note,
|
||||
editor_create_folder, editor_rename_entry, editor_delete_entry,
|
||||
editor_rebuild_index, editor_sync_index, editor_search_notes, editor_list_notes,
|
||||
editor_tags, editor_index_stats, editor_open_file, editor_write_file,
|
||||
editor_scratch_dir,
|
||||
editor_redecode_file,
|
||||
editor_write_asset, editor_authorize_file,
|
||||
editor_list_templates, editor_add_template, editor_read_template, editor_daily_note,
|
||||
editor_import, editor_export_note, editor_export_zip, editor_export_snapshot_local,
|
||||
editor_webdav_status, editor_set_webdav_password, editor_test_webdav,
|
||||
editor_sync_now, editor_backup_now, editor_list_backups, editor_restore_backup,
|
||||
editor_backlinks, editor_link_graph, editor_take_pending_file, editor_read_asset,
|
||||
// 本地目录树(P3-5)
|
||||
editor_read_dir, editor_create_file, editor_create_dir, editor_rename_path,
|
||||
editor_delete_path, editor_move_path,
|
||||
// 在路径中查找 / 替换(统一搜索器的「当前目录 / 笔记库」范围)
|
||||
editor_search_in_path, editor_replace_in_path,
|
||||
// 系统集成(P4-4)
|
||||
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
|
||||
// 编辑器窗口拖放补注入(Windows;wry 只在创建时扫一次子窗口,运行期创建的
|
||||
// 编辑器窗口需要事后补注入才有 drop target)
|
||||
window_attach_drag_drop,
|
||||
// 对比模块:单文件读取 / 写回(编码探测复用 editor::files)+ 目录对比(只读)
|
||||
diff_read_file,
|
||||
diff_write_file,
|
||||
diff_path_kind,
|
||||
diff_compare_dirs,
|
||||
diff_get_settings,
|
||||
diff_save_settings,
|
||||
// 智能家居(Home Assistant):连接 / 令牌 / 端点策略 / 测试 —— 与 run() 里那份保持一致,否则 bindings.ts 缺类型
|
||||
smarthome_get_settings,
|
||||
smarthome_save_connection,
|
||||
smarthome_set_token,
|
||||
smarthome_clear_token,
|
||||
smarthome_delete_connection,
|
||||
smarthome_activate_connection,
|
||||
smarthome_set_endpoint_mode,
|
||||
smarthome_test_connection,
|
||||
smarthome_check_link,
|
||||
smarthome_list_entities,
|
||||
smarthome_save_ui_settings,
|
||||
smarthome_call_service,
|
||||
smarthome_get_entity,
|
||||
// 智能家居 P4:实时推送 / 注册表(房间分组)/ 本地规则
|
||||
smarthome_set_realtime_enabled,
|
||||
smarthome_ws_start,
|
||||
smarthome_ws_stop,
|
||||
smarthome_ws_status,
|
||||
smarthome_list_registry,
|
||||
smarthome_list_rules,
|
||||
smarthome_save_rule,
|
||||
smarthome_delete_rule,
|
||||
smarthome_set_rules_enabled,
|
||||
// 子窗口任务栏身份(独立 AUMID + 组合图标)
|
||||
window_set_taskbar_identity,
|
||||
// 通用「显示 + 取消最小化 + 强制置前」(绕过 Windows 前台锁定)
|
||||
window_focus_window,
|
||||
])
|
||||
.export(Typescript::default(), "../src/lib/bindings.ts")
|
||||
.expect("failed to export bindings");
|
||||
@@ -343,6 +440,32 @@ pub fn run() {
|
||||
win32_util::set_app_user_model_id("thing.lfeng.me");
|
||||
|
||||
tauri::Builder::default()
|
||||
// 单实例必须是**第一个**注册的插件:它决定「第二个进程是退出还是把参数转交过来」,
|
||||
// 排在别的插件后面会让后面的插件在第二个进程里先跑一遍初始化(起两个托盘图标之类)。
|
||||
//
|
||||
// # 为什么需要它
|
||||
//
|
||||
// 「用 Thing 打开」的文件关联会让 Windows 用 `thing.exe <文件路径>` 启动本应用;
|
||||
// 应用已在运行时就会冒出第二个进程 —— 没有这个插件,用户双击一个 .md 只会得到
|
||||
// 一个(或两个)空窗口,而且第二个实例会和第一个抢同一个 sqlite 索引文件。
|
||||
// 有了它,第二个进程立即退出,命令行参数被转交给第一个实例的下面这个回调。
|
||||
.plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {
|
||||
// 主窗口可能藏在托盘里:先把已有窗口叫出来,再决定开哪个
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.unminimize();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
// argv[0] 是第二个实例自身的 exe 路径(插件传的是完整命令行),必须跳过 ——
|
||||
// 否则 `open_target_from_args` 会把 exe 当成「要打开的文件」返回。
|
||||
match crate::editor::open_target_from_args(argv.into_iter().skip(1)) {
|
||||
Some(target) => crate::editor::emit_open_target(app, &target),
|
||||
None => {
|
||||
// 没有文件参数(用户又点了一次快捷方式):只把主窗口叫到前面,别开新窗口
|
||||
crate::logger::log_info("editor", "第二个实例无文件参数,仅聚焦主窗口");
|
||||
}
|
||||
}
|
||||
}))
|
||||
.plugin(tauri_plugin_autostart::Builder::new().build())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
@@ -411,15 +534,14 @@ pub fn run() {
|
||||
monitor_status,
|
||||
monitor_start,
|
||||
monitor_start_elevated,
|
||||
monitor_elevate_self,
|
||||
monitor_stop,
|
||||
monitor_get_status,
|
||||
monitor_repair_pawnio,
|
||||
monitor_get_snapshot,
|
||||
monitor_get_elevate_on_launch,
|
||||
monitor_set_elevate_on_launch,
|
||||
monitor_get_auto_start,
|
||||
monitor_set_auto_start,
|
||||
monitor_get_elevate_on_start,
|
||||
monitor_set_elevate_on_start,
|
||||
monitor_get_hardware_config,
|
||||
monitor_set_hardware_config,
|
||||
music_env_status,
|
||||
@@ -553,6 +675,7 @@ pub fn run() {
|
||||
quickpanel_get_app_icon,
|
||||
quickpanel_clear_app_icon_cache,
|
||||
quickpanel_reveal_in_explorer,
|
||||
quickpanel_reveal_in_explorer_rename,
|
||||
quickpanel_open_file,
|
||||
quickpanel_delete_file,
|
||||
quickpanel_delete_files,
|
||||
@@ -569,6 +692,8 @@ pub fn run() {
|
||||
tray_menu_action,
|
||||
tray_menu_hide,
|
||||
tray_menu_ready,
|
||||
tray_music_state,
|
||||
tray_music_control,
|
||||
snap_fix::fix_snap_background,
|
||||
screenshot_capture_fullscreen,
|
||||
screenshot_get_fullscreen_bmp,
|
||||
@@ -762,7 +887,100 @@ pub fn run() {
|
||||
dsh_log_tail,
|
||||
dsh_install_log,
|
||||
dsh_log_clear,
|
||||
dsh_open_dir
|
||||
dsh_open_dir,
|
||||
// editor(39)
|
||||
editor_get_settings,
|
||||
editor_save_settings,
|
||||
editor_library_info,
|
||||
editor_set_library_root,
|
||||
editor_scan_library,
|
||||
editor_read_note,
|
||||
editor_save_note,
|
||||
editor_create_note,
|
||||
editor_create_folder,
|
||||
editor_rename_entry,
|
||||
editor_delete_entry,
|
||||
editor_rebuild_index,
|
||||
editor_sync_index,
|
||||
editor_search_notes,
|
||||
editor_list_notes,
|
||||
editor_tags,
|
||||
editor_index_stats,
|
||||
editor_open_file,
|
||||
editor_scratch_dir,
|
||||
editor_write_file,
|
||||
editor_redecode_file,
|
||||
editor_write_asset,
|
||||
editor_authorize_file,
|
||||
editor_list_templates,
|
||||
editor_add_template,
|
||||
editor_read_template,
|
||||
editor_daily_note,
|
||||
editor_import,
|
||||
editor_export_note,
|
||||
editor_export_zip,
|
||||
editor_export_snapshot_local,
|
||||
editor_webdav_status,
|
||||
editor_set_webdav_password,
|
||||
editor_test_webdav,
|
||||
editor_sync_now,
|
||||
editor_backup_now,
|
||||
editor_list_backups,
|
||||
editor_restore_backup,
|
||||
editor_backlinks,
|
||||
editor_link_graph,
|
||||
editor_take_pending_file,
|
||||
editor_read_asset,
|
||||
// 本地目录树(P3-5)
|
||||
editor_read_dir,
|
||||
editor_create_file,
|
||||
editor_create_dir,
|
||||
editor_rename_path,
|
||||
editor_delete_path,
|
||||
editor_move_path,
|
||||
editor_search_in_path,
|
||||
editor_replace_in_path,
|
||||
// 系统集成(P4-4)
|
||||
editor_context_menu_status,
|
||||
editor_register_context_menu,
|
||||
editor_unregister_context_menu,
|
||||
// 编辑器窗口拖放补注入
|
||||
window_attach_drag_drop,
|
||||
// 对比模块:单文件读取 / 写回 + 目录对比(只读)+ 设置
|
||||
diff_read_file,
|
||||
diff_write_file,
|
||||
diff_path_kind,
|
||||
diff_compare_dirs,
|
||||
diff_get_settings,
|
||||
diff_save_settings,
|
||||
// 智能家居(Home Assistant):连接 / 令牌 / 端点策略 / 测试
|
||||
smarthome_get_settings,
|
||||
smarthome_save_connection,
|
||||
smarthome_set_token,
|
||||
smarthome_clear_token,
|
||||
smarthome_delete_connection,
|
||||
smarthome_activate_connection,
|
||||
smarthome_set_endpoint_mode,
|
||||
smarthome_test_connection,
|
||||
smarthome_check_link,
|
||||
smarthome_list_entities,
|
||||
smarthome_save_ui_settings,
|
||||
smarthome_call_service,
|
||||
smarthome_get_entity,
|
||||
// 智能家居 P4:实时推送 / 注册表(房间分组)/ 本地规则
|
||||
smarthome_set_realtime_enabled,
|
||||
smarthome_ws_start,
|
||||
smarthome_ws_stop,
|
||||
smarthome_ws_status,
|
||||
smarthome_list_registry,
|
||||
smarthome_list_rules,
|
||||
smarthome_save_rule,
|
||||
smarthome_delete_rule,
|
||||
smarthome_set_rules_enabled,
|
||||
// 子窗口任务栏身份(独立 AUMID + 组合图标)
|
||||
window_set_taskbar_identity,
|
||||
// 通用「显示 + 取消最小化 + 强制置前」
|
||||
window_focus_window
|
||||
])
|
||||
.setup(setup::init)
|
||||
.on_window_event(|window, event| {
|
||||
|
||||
+49
-115
@@ -142,6 +142,10 @@ pub struct MonitorSettings {
|
||||
/// 应用启动时自动启动监控内核(默认 false)
|
||||
#[serde(default)]
|
||||
pub auto_start: bool,
|
||||
/// 启动内核时使用提权模式(通过 UAC 以管理员权限启动,Thing 自身保持普通权限)。
|
||||
/// 由"提权内核"操作写入,使提权状态在应用重启后(自动启动路径)得以保持。
|
||||
#[serde(default)]
|
||||
pub elevate_on_start: bool,
|
||||
}
|
||||
|
||||
/// 监控设置文件路径: {app_data_dir}/monitor/settings.json
|
||||
@@ -167,59 +171,6 @@ pub fn save_monitor_settings(app_data_dir: &std::path::Path, settings: &MonitorS
|
||||
fs::write(path, content).map_err(|e| format!("写入设置失败: {}", e))
|
||||
}
|
||||
|
||||
// ===================== 永久提权标志持久化 =====================
|
||||
|
||||
/// 永久提权标志文件路径: {app_data_dir}/monitor/elevate.json
|
||||
/// 内容: { "enabled": true }
|
||||
fn elevate_flag_path(app_data_dir: &std::path::Path) -> PathBuf {
|
||||
app_data_dir.join("monitor").join("elevate.json")
|
||||
}
|
||||
|
||||
/// 读取永久提权标志
|
||||
fn read_elevate_flag(flag_path: &std::path::Path) -> bool {
|
||||
match fs::read_to_string(flag_path) {
|
||||
Ok(content) => serde_json::from_str::<serde_json::Value>(&content)
|
||||
.ok()
|
||||
.and_then(|v| v.get("enabled").and_then(|e| e.as_bool()))
|
||||
.unwrap_or(false),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 写入永久提权标志
|
||||
fn write_elevate_flag(flag_path: &std::path::Path, enabled: bool) -> Result<(), String> {
|
||||
if let Some(parent) = flag_path.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {}", e))?;
|
||||
}
|
||||
let content = serde_json::json!({ "enabled": enabled }).to_string();
|
||||
fs::write(flag_path, content).map_err(|e| format!("写入提权标志失败: {}", e))
|
||||
}
|
||||
|
||||
/// 启动时检查永久提权标志,如果已设置且当前非管理员,则 ShellExecute "runas" 重启自身。
|
||||
/// 在 `setup` 早期调用(MonitorKernel 初始化之前)。
|
||||
/// 返回 true 表示已触发提权重启,调用方应立即退出当前进程。
|
||||
pub fn check_and_relaunch_if_needed(app_data_dir: &std::path::Path) -> bool {
|
||||
let flag_path = elevate_flag_path(app_data_dir);
|
||||
if !read_elevate_flag(&flag_path) {
|
||||
return false;
|
||||
}
|
||||
if is_thing_elevated() {
|
||||
return false; // 已是管理员,无需重启
|
||||
}
|
||||
let exe = match std::env::current_exe() {
|
||||
Ok(e) => e,
|
||||
Err(_) => return false,
|
||||
};
|
||||
crate::logger::log_info("monitor", "检测到永久提权标志,以管理员权限重启 Thing");
|
||||
match shell_execute_elevated(&exe.to_string_lossy(), "", None) {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
crate::logger::log_warn("monitor", &format!("永久提权重启失败(用户可能取消了 UAC): {}", e));
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ===================== 数据结构 =====================
|
||||
|
||||
/// Kernel /status 响应(与 ThingHK Contracts.cs KernelStatus 对应)
|
||||
@@ -322,16 +273,6 @@ impl MonitorKernel {
|
||||
self.elevated.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// 永久提权标志是否已启用(后续启动自动触发 UAC)
|
||||
pub fn elevate_on_launch(&self) -> bool {
|
||||
read_elevate_flag(&self.root.join("elevate.json"))
|
||||
}
|
||||
|
||||
/// 设置/清除永久提权标志
|
||||
pub fn set_elevate_on_launch(&self, enabled: bool) -> Result<(), String> {
|
||||
write_elevate_flag(&self.root.join("elevate.json"), enabled)
|
||||
}
|
||||
|
||||
/// 读取监控设置(auto_start 等)
|
||||
pub fn load_settings(&self) -> MonitorSettings {
|
||||
load_monitor_settings(&self.root.parent().unwrap_or(&self.root).to_path_buf())
|
||||
@@ -685,6 +626,10 @@ impl MonitorKernel {
|
||||
/// - 如果是提权 Kernel(isAdmin=true):直接接管,设置 elevated=true,跳过 ProcessManager 启动
|
||||
/// - 如果是普通权限 Kernel:调用 /shutdown 停止后重新启动
|
||||
///
|
||||
/// 提权偏好模式(Thing 普通、ThingHK 提权,elevateOnStart=true):
|
||||
/// - 端口无内核运行时,走 start_elevated(ShellExecuteW "runas" 弹 UAC),
|
||||
/// 使提权状态在应用重启后的自动启动路径上得以保持
|
||||
///
|
||||
/// 永久提权模式(Thing 自身是管理员):
|
||||
/// - ThingHK 通过 ProcessManager 启动,子进程继承管理员权限
|
||||
/// - 设置 elevated=true 表示 ThingHK 在管理员权限下运行
|
||||
@@ -734,6 +679,21 @@ impl MonitorKernel {
|
||||
}
|
||||
}
|
||||
|
||||
// 提权偏好:Thing 自身非管理员时,按偏好以管理员权限启动内核(弹 UAC)。
|
||||
// 偏好由 monitor_start_elevated 写入,使提权状态在应用重启后(自动启动)仍能保持。
|
||||
if !thing_elevated && self.load_settings().elevate_on_start {
|
||||
crate::logger::log_info("monitor", "按提权偏好启动 ThingHK 内核");
|
||||
self.start_elevated(app).await?;
|
||||
// 提权模式下内核不归 ProcessManager 管理,pid 不可查询
|
||||
return Ok(crate::process_manager::ProcessInfo {
|
||||
id: PROCESS_ID.into(),
|
||||
name: "ThingHK".into(),
|
||||
status: crate::process_manager::ProcessStatus::Running,
|
||||
pid: None,
|
||||
restart_count: 0,
|
||||
});
|
||||
}
|
||||
|
||||
let pm = app.state::<ProcessManager>();
|
||||
let params = self.prepare_for_start(app)?;
|
||||
let info = pm.start(params)?;
|
||||
@@ -824,6 +784,14 @@ impl MonitorKernel {
|
||||
}
|
||||
|
||||
self.elevated.store(true, Ordering::SeqCst);
|
||||
// 记住提权偏好:后续启动(含应用重启后的自动启动)沿用提权模式
|
||||
let mut settings = self.load_settings();
|
||||
if !settings.elevate_on_start {
|
||||
settings.elevate_on_start = true;
|
||||
if let Err(e) = self.save_settings(&settings) {
|
||||
crate::logger::log_warn("monitor", &format!("保存提权偏好失败: {}", e));
|
||||
}
|
||||
}
|
||||
crate::logger::log_info("monitor", "提权启动已发起,等待 Kernel ready");
|
||||
|
||||
// 5. 启动 SSE 订阅(提权模式不注册 register_auto_reconnect:
|
||||
@@ -961,40 +929,6 @@ pub async fn monitor_start_elevated(
|
||||
state.start_elevated(&app).await
|
||||
}
|
||||
|
||||
/// 永久提权:以管理员权限重启 Thing 自身,并持久化标志使后续启动自动提权。
|
||||
/// - 已是管理员:仅设置标志,不重启
|
||||
/// - 非管理员:设置标志 + ShellExecute "runas" 重启 + 退出当前进程
|
||||
#[tauri::command]
|
||||
pub async fn monitor_elevate_self(
|
||||
state: tauri::State<'_, MonitorKernel>,
|
||||
app: AppHandle,
|
||||
) -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// 持久化标志:后续启动时 setup 检测到此标志会自动 ShellExecute "runas"
|
||||
state.set_elevate_on_launch(true)?;
|
||||
|
||||
if is_thing_elevated() {
|
||||
// 已是管理员,只需设置标志,无需重启
|
||||
crate::logger::log_info("monitor", "Thing 已是管理员,仅设置永久提权标志");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let exe = std::env::current_exe().map_err(|e| format!("获取当前路径失败: {}", e))?;
|
||||
let exe_str = exe.to_string_lossy().to_string();
|
||||
crate::logger::log_info("monitor", "永久提权:以管理员权限重启 Thing");
|
||||
shell_execute_elevated(&exe_str, "", None)?;
|
||||
// 退出当前进程(非提权),新的提权进程会接管
|
||||
app.exit(0);
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = (state, app);
|
||||
Err("永久提权仅支持 Windows".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn monitor_stop(
|
||||
state: tauri::State<'_, MonitorKernel>,
|
||||
@@ -1069,24 +1003,6 @@ pub async fn monitor_get_snapshot(state: tauri::State<'_, MonitorKernel>) -> Res
|
||||
state.get_snapshot().await
|
||||
}
|
||||
|
||||
/// 查询永久提权标志是否已启用
|
||||
#[tauri::command]
|
||||
pub fn monitor_get_elevate_on_launch(
|
||||
state: tauri::State<'_, MonitorKernel>,
|
||||
) -> bool {
|
||||
state.elevate_on_launch()
|
||||
}
|
||||
|
||||
/// 设置/清除永久提权标志。
|
||||
/// 清除后,下次启动不再触发 UAC(当前会话权限不变)。
|
||||
#[tauri::command]
|
||||
pub fn monitor_set_elevate_on_launch(
|
||||
state: tauri::State<'_, MonitorKernel>,
|
||||
enabled: bool,
|
||||
) -> Result<(), String> {
|
||||
state.set_elevate_on_launch(enabled)
|
||||
}
|
||||
|
||||
/// 查询"应用启动时自动启动监控内核"是否已启用
|
||||
#[tauri::command]
|
||||
pub fn monitor_get_auto_start(
|
||||
@@ -1106,6 +1022,24 @@ pub fn monitor_set_auto_start(
|
||||
state.save_settings(&settings)
|
||||
}
|
||||
|
||||
/// 查询"内核启动时以管理员权限运行"(提权偏好)是否已启用
|
||||
#[tauri::command]
|
||||
pub fn monitor_get_elevate_on_start(state: tauri::State<'_, MonitorKernel>) -> bool {
|
||||
state.load_settings().elevate_on_start
|
||||
}
|
||||
|
||||
/// 设置提权偏好:启用后内核启动(含应用重启后的自动启动)将以管理员权限运行(弹 UAC)。
|
||||
/// 由"提权内核"操作自动开启;关闭后内核启动回到普通权限。
|
||||
#[tauri::command]
|
||||
pub fn monitor_set_elevate_on_start(
|
||||
state: tauri::State<'_, MonitorKernel>,
|
||||
enabled: bool,
|
||||
) -> Result<(), String> {
|
||||
let mut settings = state.load_settings();
|
||||
settings.elevate_on_start = enabled;
|
||||
state.save_settings(&settings)
|
||||
}
|
||||
|
||||
/// 查询硬件监控配置(透传 Kernel GET /config/hardware)。
|
||||
/// 返回当前配置 + 可用硬件/传感器类型清单,供前端 Dialog 渲染。
|
||||
#[tauri::command]
|
||||
|
||||
@@ -224,6 +224,15 @@ impl AudioEngine {
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前音量与静音位(0.0~1.0)。
|
||||
/// 供托盘菜单读取显示;跨曲目沿用同一组值(切歌不重置)。
|
||||
pub fn volume(&self) -> (f32, bool) {
|
||||
(
|
||||
f32::from_bits(self.volume.load(Ordering::Relaxed)),
|
||||
self.muted.load(Ordering::Relaxed),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn state(&self) -> AudioState {
|
||||
let Some(s) = self.current() else {
|
||||
return AudioState {
|
||||
|
||||
@@ -32,6 +32,9 @@ pub use fnconnect::{extract_fn_id, resolve_base_url};
|
||||
use conn::{generate_device_id, sha256_hex};
|
||||
use proxy::{ProxyCfg, ProxyShared};
|
||||
|
||||
/// 登录接口路径(同时用于失败留痕)。
|
||||
const LOGIN_PATH: &str = "/music/api/v1/user/password-login";
|
||||
|
||||
/// 一条飞牛音乐连接(持久化在 `MusicSettings`)。
|
||||
#[derive(Serialize, Deserialize, Clone, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -151,6 +154,33 @@ fn slot_client(slot: &Mutex<Option<ClientSlot>>, insecure: bool, streaming: bool
|
||||
g.as_ref().unwrap().client.clone()
|
||||
}
|
||||
|
||||
/// 服务端错误 → 画面上要展示的提示。
|
||||
///
|
||||
/// 飞牛音乐失败时常常只回一句笼统的 `msg`(如 `unknown error`),单看它判断不出
|
||||
/// 该重试、该重新登录,还是该去 NAS 上修服务;这里按官方错误码表补上结论与处理动作,
|
||||
/// 让提示本身就能指导操作。HTTP 状态码与错误码附在括号里,便于对日志。
|
||||
///
|
||||
/// 只有取不到 `data` 的失败才会走到这里,因此不需要区分调用方。
|
||||
fn error_text(status: StatusCode, code: i64, msg: &str) -> String {
|
||||
let head = match code {
|
||||
100001 => "飞牛 NAS 的音乐服务内部异常,可在 NAS 上重启「飞牛音乐」应用后重试",
|
||||
100002 => "请求与 NAS 端音乐服务版本不匹配",
|
||||
100003 | 100004 => "当前账号没有权限",
|
||||
100005 => "目标不存在(可能已被删除)",
|
||||
110002 => "NAS 端音乐应用尚未初始化",
|
||||
140001 => "NAS 正在重建搜索索引,请稍后再试",
|
||||
_ => {
|
||||
let m = msg.trim();
|
||||
if m.is_empty() {
|
||||
"飞牛音乐请求失败"
|
||||
} else {
|
||||
m
|
||||
}
|
||||
}
|
||||
};
|
||||
format!("{head}(HTTP {} / code {code})", status.as_u16())
|
||||
}
|
||||
|
||||
impl Feiniu {
|
||||
/// 设置缓存根目录({app_data}/music/cache),应用启动时调用一次。
|
||||
pub fn set_cache_root(&mut self, app_data_dir: &Path) {
|
||||
@@ -310,7 +340,7 @@ impl Feiniu {
|
||||
.relay;
|
||||
let mut rb = self
|
||||
.client(insecure)
|
||||
.post(format!("{base}/music/api/v1/user/password-login"))
|
||||
.post(format!("{base}{LOGIN_PATH}"))
|
||||
.json(&body);
|
||||
// 中继链路:登录请求也需带 mode=relay,否则网关 302 回登录页
|
||||
if let Some(cookie) = Self::auth_cookie("", relay) {
|
||||
@@ -328,20 +358,24 @@ impl Feiniu {
|
||||
format!("{kind}: {e}")
|
||||
})?;
|
||||
let status = resp.status();
|
||||
let b: Value = resp
|
||||
.json()
|
||||
.await
|
||||
.unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let raw = resp.text().await.unwrap_or_default();
|
||||
let b: Value = serde_json::from_str(&raw).unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let code = b["code"].as_i64().unwrap_or(i64::from(status.as_u16()));
|
||||
if code != 0 {
|
||||
let msg = b["msg"].as_str().unwrap_or("");
|
||||
// 服务端对部分失败只给一句笼统的 msg(如 `unknown error`),
|
||||
// 不带状态码/错误码/原始响应就无从定位,这里一次性留全。
|
||||
crate::logger::log_error(
|
||||
"feiniu",
|
||||
&format!(
|
||||
"POST {LOGIN_PATH} 失败: HTTP {status} code={code} body={}",
|
||||
raw.chars().take(400).collect::<String>()
|
||||
),
|
||||
);
|
||||
if code == 120001 {
|
||||
return Err("用户名或密码错误".into());
|
||||
}
|
||||
let msg = b["msg"]
|
||||
.as_str()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("HTTP {status}"));
|
||||
return Err(msg);
|
||||
return Err(error_text(status, code, msg));
|
||||
}
|
||||
let token = b["data"]["userToken"]
|
||||
.as_str()
|
||||
@@ -515,20 +549,30 @@ impl Feiniu {
|
||||
}
|
||||
let resp = rb.send().await.map_err(|e| format!("请求失败: {e}"))?;
|
||||
let status = resp.status();
|
||||
let body: Value = resp
|
||||
.json()
|
||||
.await
|
||||
.unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let raw = resp.text().await.unwrap_or_default();
|
||||
let body: Value =
|
||||
serde_json::from_str(&raw).unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let code = body["code"].as_i64().unwrap_or(i64::from(status.as_u16()));
|
||||
if code != 0 {
|
||||
if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
|
||||
let msg = body["msg"].as_str().unwrap_or("");
|
||||
// 服务端对部分失败只给一句笼统的 msg(如 `unknown error`),
|
||||
// 不带状态码/错误码/原始响应就无从定位,这里一次性留全。
|
||||
crate::logger::log_error(
|
||||
"feiniu",
|
||||
&format!(
|
||||
"GET {path} 失败: HTTP {status} code={code} body={}",
|
||||
raw.chars().take(400).collect::<String>()
|
||||
),
|
||||
);
|
||||
// HTTP 401/403 与 120001(Unauthorized)都表示「这把会话不能用了」,
|
||||
// 需重新登录——不该混进「NAS 服务异常」的提示里。
|
||||
if status == StatusCode::UNAUTHORIZED
|
||||
|| status == StatusCode::FORBIDDEN
|
||||
|| code == 120001
|
||||
{
|
||||
return Err("登录已过期,请重新登录".into());
|
||||
}
|
||||
let msg = body["msg"]
|
||||
.as_str()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("请求失败(HTTP {status})"));
|
||||
return Err(msg);
|
||||
return Err(error_text(status, code, msg));
|
||||
}
|
||||
Ok(body["data"].clone())
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ pub use remote::{
|
||||
|
||||
pub use smtc::{
|
||||
music_smtc_clear, music_smtc_update_metadata, music_smtc_update_playback_state,
|
||||
music_smtc_update_position, SmtcController,
|
||||
music_smtc_update_position, SmtcController, SMTC_BUTTON_EVENT,
|
||||
};
|
||||
|
||||
pub use commands::{
|
||||
|
||||
@@ -337,6 +337,147 @@ pub fn quickpanel_reveal_in_explorer(path: String) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 等 Explorer 完成「定位 + 选中」再送 F2 的等待时长。
|
||||
///
|
||||
/// 这是纯 UI 时序:定位调用只是把一个请求交给已在运行的 Explorer 进程,
|
||||
/// 它要等窗口到前台、切到目标目录、滚到条目并选中,然后才会响应 F2。
|
||||
/// 给得太短会把 F2 送到当时还在前台的那个窗口上(而不是 Explorer)。
|
||||
const RENAME_KEY_DELAY_MS: u64 = 450;
|
||||
|
||||
/// 在资源管理器中定位文件(选中)并**进入重命名编辑状态**。
|
||||
///
|
||||
/// # 为什么不用 `explorer.exe /select,`
|
||||
///
|
||||
/// 本仓原先的定位做法是 `ShellExecuteW("explorer.exe", "/select,\"path\"")`。
|
||||
/// 那条命令行在 Win10/11 上**经常新开一个窗口**而不是复用用户已经打开的那个
|
||||
/// (尤其目标文件夹已通过标签页 / 其他窗口打开时)—— 表现就是"点保存后又弹出
|
||||
/// 一个资源管理器打开了这个文件夹"。`SHOpenFolderAndSelectItems` 才是 shell 为此
|
||||
/// 提供的 API:复用已有窗口、滚到条目并选中,随后该窗口即为前台窗口。
|
||||
///
|
||||
/// 重命名仍然只能借 Explorer 自己的快捷键 F2 —— shell 没有"开始重命名"的 API。
|
||||
///
|
||||
/// `spawn_blocking`:命令里有 sleep;同时 shell 调用要求 **STA** 线程,而 async 命令
|
||||
/// 跑在 tokio 工作线程(MTA)上 —— 所以在工作线程里自己
|
||||
/// `CoInitializeEx(APARTMENTTHREADED)`(与 `quickpanel::explorer` 同一做法),
|
||||
/// 既不占 IPC 线程,也不依赖命令所在线程的既有套间模型。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn quickpanel_reveal_in_explorer_rename(path: String) -> Result<(), String> {
|
||||
tauri::async_runtime::spawn_blocking(move || -> Result<(), String> {
|
||||
select_in_explorer(&path)?;
|
||||
std::thread::sleep(std::time::Duration::from_millis(RENAME_KEY_DELAY_MS));
|
||||
send_rename_key();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("定位 / 重命名任务失败: {}", e))?
|
||||
}
|
||||
|
||||
/// 用 shell 的「打开文件夹并选中」定位文件(复用已有窗口,不新开一个)。
|
||||
#[cfg(windows)]
|
||||
fn select_in_explorer(path: &str) -> Result<(), String> {
|
||||
use std::ffi::OsStr;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows::core::PCWSTR;
|
||||
use windows::Win32::System::Com::{
|
||||
CoInitializeEx, CoTaskMemFree, CoUninitialize, COINIT_APARTMENTTHREADED,
|
||||
};
|
||||
use windows::Win32::UI::Shell::Common::ITEMIDLIST;
|
||||
use windows::Win32::UI::Shell::{SHOpenFolderAndSelectItems, SHParseDisplayName};
|
||||
|
||||
let normalized = path.replace('/', "\\");
|
||||
let dir = match normalized.rfind('\\') {
|
||||
Some(i) if i > 0 => &normalized[..i],
|
||||
_ => return Err("路径缺少目录部分".into()),
|
||||
};
|
||||
|
||||
let wide = |s: &str| -> Vec<u16> {
|
||||
OsStr::new(s).encode_wide().chain(std::iter::once(0)).collect()
|
||||
};
|
||||
let dir_w = wide(dir);
|
||||
let file_w = wide(&normalized);
|
||||
|
||||
// 首次 COM 初始化失败(例如线程已在 MTA)时,后续 shell 调用一般仍可用,忽略错误继续
|
||||
let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
|
||||
|
||||
let result = unsafe {
|
||||
let mut folder_pidl: *mut ITEMIDLIST = std::ptr::null_mut();
|
||||
let mut file_pidl: *mut ITEMIDLIST = std::ptr::null_mut();
|
||||
let attempt = (|| -> Result<(), String> {
|
||||
SHParseDisplayName(PCWSTR(dir_w.as_ptr()), None, &mut folder_pidl, 0, None)
|
||||
.map_err(|e| format!("解析目录失败: {}", e))?;
|
||||
SHParseDisplayName(PCWSTR(file_w.as_ptr()), None, &mut file_pidl, 0, None)
|
||||
.map_err(|e| format!("解析文件失败: {}", e))?;
|
||||
// `apidl` 要的是**相对父目录的子 PIDL**,正是绝对 PIDL 的最后一个 ITEMID
|
||||
let child = il_find_last_id(file_pidl);
|
||||
SHOpenFolderAndSelectItems(folder_pidl, Some(&[child]), 0)
|
||||
.map_err(|e| format!("定位文件失败: {}", e))
|
||||
})();
|
||||
if !folder_pidl.is_null() {
|
||||
CoTaskMemFree(Some(folder_pidl as *const core::ffi::c_void));
|
||||
}
|
||||
if !file_pidl.is_null() {
|
||||
CoTaskMemFree(Some(file_pidl as *const core::ffi::c_void));
|
||||
}
|
||||
attempt
|
||||
};
|
||||
|
||||
unsafe { CoUninitialize() };
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn select_in_explorer(_path: &str) -> Result<(), String> {
|
||||
Err("当前平台不支持".into())
|
||||
}
|
||||
|
||||
/// `ITEMIDLIST` 是一条「ITEMID 链」:每个 ITEMID 以 2 字节的 `cb` 开头,`cb == 0` 表示链结束。
|
||||
/// 返回最后一个 ITEMID 的指针(即相对父目录的子 PIDL)。
|
||||
///
|
||||
/// `ILFindLastID` 在 `shlobj_core.h` 里是**内联函数**,`windows` crate 不导出,所以这里自己走一遍
|
||||
/// (windows-sys 把它声明成了 shell32 导入,但本项目统一用 `windows` crate 做 shell/COM)。
|
||||
#[cfg(windows)]
|
||||
unsafe fn il_find_last_id(pidl: *const windows::Win32::UI::Shell::Common::ITEMIDLIST) -> *const windows::Win32::UI::Shell::Common::ITEMIDLIST {
|
||||
use windows::Win32::UI::Shell::Common::ITEMIDLIST;
|
||||
let mut p: *const ITEMIDLIST = pidl;
|
||||
loop {
|
||||
let next = p.cast::<u8>().add((*p).mkid.cb as usize).cast::<ITEMIDLIST>();
|
||||
if (*next).mkid.cb == 0 {
|
||||
return p;
|
||||
}
|
||||
p = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// 向前台窗口发一次 F2(Explorer 的重命名快捷键)。
|
||||
///
|
||||
/// 用 SendInput 而不是 PostMessage:F2 要经过 Explorer 的消息泵与输入法状态,
|
||||
/// 与 `clipboard::popup::simulate_paste` 同一套做法(也是同一条已知限制:
|
||||
/// 目标窗口若以管理员权限运行,非提权进程的 SendInput 会被 UIPI 挡掉)。
|
||||
#[cfg(windows)]
|
||||
fn send_rename_key() {
|
||||
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
|
||||
SendInput, INPUT, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_KEYUP, VK_F2,
|
||||
};
|
||||
|
||||
// 安全初始化为零值,避免未定义字段
|
||||
let mut inputs: [INPUT; 2] = unsafe { std::mem::zeroed() };
|
||||
|
||||
inputs[0].r#type = INPUT_KEYBOARD;
|
||||
inputs[0].Anonymous.ki = KEYBDINPUT { wVk: VK_F2, wScan: 0, dwFlags: 0, time: 0, dwExtraInfo: 0 };
|
||||
|
||||
inputs[1].r#type = INPUT_KEYBOARD;
|
||||
inputs[1].Anonymous.ki =
|
||||
KEYBDINPUT { wVk: VK_F2, wScan: 0, dwFlags: KEYEVENTF_KEYUP, time: 0, dwExtraInfo: 0 };
|
||||
|
||||
unsafe {
|
||||
SendInput(2, inputs.as_ptr(), std::mem::size_of::<INPUT>() as i32);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn send_rename_key() {}
|
||||
|
||||
/// 用系统默认程序打开文件/文件夹。
|
||||
/// - 目录:explorer.exe 直接打开(修复索引目录点击后未打开的问题)
|
||||
/// - 文件:ShellExecuteW open,无关联应用时自动 fallback 到「打开方式」对话框(verb: openas)
|
||||
|
||||
@@ -23,7 +23,8 @@ pub use commands::{
|
||||
quickpanel_get_app_icon, quickpanel_get_settings, quickpanel_get_special_locations,
|
||||
quickpanel_hide_popup, quickpanel_init_file_index, quickpanel_lock_screen,
|
||||
quickpanel_open_file, quickpanel_open_special, quickpanel_register_shortcut,
|
||||
quickpanel_reveal_in_explorer, quickpanel_run_custom_command, quickpanel_run_system_command,
|
||||
quickpanel_reveal_in_explorer, quickpanel_reveal_in_explorer_rename,
|
||||
quickpanel_run_custom_command, quickpanel_run_system_command,
|
||||
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
|
||||
quickpanel_show_window, quickpanel_unregister_shortcut,
|
||||
};
|
||||
|
||||
+41
-7
@@ -18,12 +18,15 @@ use crate::ai::AiManager;
|
||||
use crate::download_engine::{DownloadEngine, ExtensionServer};
|
||||
use crate::logger::LogManager;
|
||||
use crate::mihomo_manager::MihomoManager;
|
||||
use crate::monitor_kernel::{MonitorKernel, check_and_relaunch_if_needed};
|
||||
use crate::monitor_kernel::MonitorKernel;
|
||||
use crate::music::MusicManager;
|
||||
use crate::network_monitor::NetworkMonitor;
|
||||
use crate::editor::EditorManager;
|
||||
use crate::smarthome::HaManager;
|
||||
use crate::process_manager::{ProcessManager, start_monitoring_thread};
|
||||
use crate::terminal::TerminalManager;
|
||||
use crate::translate::TranslateManager;
|
||||
use crate::diff::DiffManager;
|
||||
|
||||
/// 应用启动初始化入口(setup 闭包调用)。
|
||||
/// 初始化顺序即依赖顺序:日志 → 数据目录 → 各管理器 → 托盘 → 进程监控 → 自动启动。
|
||||
@@ -44,12 +47,6 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
||||
.app_data_dir()
|
||||
.unwrap_or_else(|_| std::path::PathBuf::from("."));
|
||||
|
||||
// 永久提权检查:如果标志已设置且当前非管理员,以管理员权限重启自身并退出
|
||||
// 必须在所有模块初始化之前执行(此时无资源需要清理)
|
||||
if check_and_relaunch_if_needed(&app_data_dir) {
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
// ===== 代理模块:MihomoManager =====
|
||||
let mihomo = MihomoManager::new(app_data_dir.clone());
|
||||
app.manage(mihomo);
|
||||
@@ -83,6 +80,43 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let dsh = crate::dsh::DshManager::new(app_data_dir.clone());
|
||||
app.manage(dsh);
|
||||
|
||||
// ===== 笔记模块:EditorManager =====
|
||||
// 仅注册状态:库扫描与读写都在命令调用时按需触发,启动阶段只创建目录结构。
|
||||
let notes = EditorManager::new(app_data_dir.clone());
|
||||
let _ = notes.load_settings();
|
||||
// 按设置注册「新建笔记 / 打开编辑器」两个全局快捷键(失败只记日志,不阻断启动)
|
||||
notes.init_on_launch(app.handle());
|
||||
app.manage(notes);
|
||||
// 「用 Thing 打开」的**冷启动**路径:命令行里带了 .md 就记下来。
|
||||
// 不在这里 `emit` —— 此时 WebView 还没加载、前端还没注册监听,事件会丢掉。
|
||||
// 前端注册完监听后会主动调 `editor_take_pending_file` 取走(见 editor/args.rs)。
|
||||
if let Some(target) = crate::editor::open_target_from_args(std::env::args().skip(1)) {
|
||||
crate::logger::log_info("editor", &format!("命令行指定打开: {}", target.path().display()));
|
||||
crate::editor::remember_pending_target(target);
|
||||
}
|
||||
|
||||
// ===== 对比模块:DiffManager =====
|
||||
// 只承担设置的读写与「打开对比窗口」全局快捷键(默认 Alt+C)的注册;
|
||||
// 左右目标(比哪两个文件 / 目录)是前端会话状态,Rust 侧不需要知道。
|
||||
let diff = DiffManager::new(app_data_dir.clone());
|
||||
diff.init_on_launch(app.handle());
|
||||
app.manage(diff);
|
||||
|
||||
// ===== 智能家居模块:HaManager(Home Assistant 对接) =====
|
||||
// 仅注册状态:连接与令牌都在命令调用时按需读取,**启动阶段不发任何网络请求**。
|
||||
// 端点探测(局域网 900ms / 反代 5s)发生在首次需要发请求时,不占启动时间。
|
||||
let smarthome = HaManager::new(app_data_dir.clone());
|
||||
app.manage(smarthome);
|
||||
// P4:用户上次开着「实时推送」或「本地规则总开关」时,启动后恢复 WS 连接。
|
||||
// 放在后台任务里(不阻塞启动),且**只有用户显式开过才会连** —— 与"启动不发请求"一致。
|
||||
{
|
||||
let handle = app.handle().clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let manager = handle.state::<HaManager>();
|
||||
manager.sync_ws(&handle).await;
|
||||
});
|
||||
}
|
||||
|
||||
// ===== 翻译模块:TranslateManager =====
|
||||
// 仅注册状态:设置与密钥都在命令调用时按需读取,启动阶段不发任何网络请求
|
||||
// (模型可用性校验因此改为懒校验:首次翻译失败时解释原因 + 设置页手动拉取模型列表)。
|
||||
|
||||
@@ -0,0 +1,549 @@
|
||||
//! 本地轻量规则引擎(P4)。
|
||||
//!
|
||||
//! 三段式(触发 / 条件 / 动作)线性规则,**不做嵌套树** —— 这是"简单自动化"的边界所在
|
||||
//! (plan §5.4-B)。求值在 Rust 侧:WS 事件一到就匹配,不依赖前端页面是否打开。
|
||||
//!
|
||||
//! **必须显式告知用户的前提**(D2 已拍板):本地规则只在 Thing 运行时生效。
|
||||
//! 应用退出、电脑关机后就不再触发;要 7×24 可靠就得把规则建在 HA 里。UI 有常驻警示条。
|
||||
//!
|
||||
//! 三条护栏(plan §5.4-B 明确要求,一条都不能省):
|
||||
//! 1. **冷却时间**:`cooldownSec` 内的重复触发直接丢弃;
|
||||
//! 2. **动作失败不中断**:某个动作 4xx/5xx 时记 `lastError` 并继续下一个,
|
||||
//! 否则一条失败会吞掉后续所有动作;
|
||||
//! 3. **循环保护**:规则动作引起的状态变化可能再次触发同一规则(A 开 B、B 关 A),
|
||||
//! 冷却不足以阻断时用"突发计数"兜底(同规则 10s 内最多 5 次)。
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use chrono::{Datelike, Local, Timelike};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tauri_plugin_notification::NotificationExt;
|
||||
use tokio::sync::watch;
|
||||
|
||||
use super::client;
|
||||
use super::types::{
|
||||
EndpointKind, EntitySummary, Rule, RuleAction, RuleCondition, RuleFiredEvent, RuleRecord,
|
||||
RuleTrigger, RulesFile, RULES_VERSION,
|
||||
};
|
||||
use crate::constants::events;
|
||||
|
||||
/// 内存里保留的运行记录条数。
|
||||
pub const MAX_RECORDS: usize = 50;
|
||||
/// 单个 `delay` 动作的上限(秒)。
|
||||
///
|
||||
/// 防的是"睡 1 小时"这种怪规则:本地规则只在 Thing 运行时生效,
|
||||
/// 一条要睡一小时的动作在应用重启后就永远跑不完了。
|
||||
pub const MAX_DELAY_SEC: u32 = 600;
|
||||
/// 突发护栏窗口与上限(循环保护,护栏 3)。
|
||||
const BURST_WINDOW: Duration = Duration::from_secs(10);
|
||||
const BURST_MAX: usize = 5;
|
||||
/// 触发统计落盘的最小间隔(秒)—— 去抖,见 `maybe_persist`。
|
||||
const PERSIST_MIN_INTERVAL_SECS: u64 = 3;
|
||||
/// `for`(持续 N 秒)触发器的巡检间隔(毫秒)。
|
||||
const SWEEP_INTERVAL_MS: u64 = 500;
|
||||
|
||||
/// 规则求值 / 执行所需的环境(`Clone` 以便丢进后台任务)。
|
||||
#[derive(Clone)]
|
||||
pub struct RuleEnv {
|
||||
pub app: AppHandle,
|
||||
/// REST 端点:动作里的服务调用走 REST(与 P2 的控制同一条路径,不另造一套)
|
||||
pub base_url: String,
|
||||
pub token: String,
|
||||
pub insecure: bool,
|
||||
pub kind: EndpointKind,
|
||||
pub rules: Arc<Mutex<RulesFile>>,
|
||||
pub records: Arc<Mutex<VecDeque<RuleRecord>>>,
|
||||
/// 当前实体摘要(`entity_id` → 摘要),条件判断读它
|
||||
pub summaries: Arc<Mutex<HashMap<String, EntitySummary>>>,
|
||||
/// 最近触发时刻(内存态,只服务突发护栏)
|
||||
pub recent: Arc<Mutex<VecDeque<(String, Instant)>>>,
|
||||
/// `for`(持续 N 秒)触发器的槽位表:`rule_id` → 到点时刻。
|
||||
///
|
||||
/// 用槽位表而不是"每次事件起一个 sleep 任务":1Hz 的实体配 `for=300`
|
||||
/// 会常驻几百个任务,而且那些任务不受连接切换影响(会用旧端点执行动作)。
|
||||
pub pending: Arc<Mutex<HashMap<String, Instant>>>,
|
||||
/// 触发统计上次落盘时刻(去抖用,见 `maybe_persist`)
|
||||
pub last_persist: Arc<Mutex<Instant>>,
|
||||
/// `automations.json` 路径
|
||||
pub rules_path: std::path::PathBuf,
|
||||
}
|
||||
|
||||
// ============================== 文件读写 ==============================
|
||||
|
||||
/// 读取规则文件(不存在 / 损坏时退化为默认值,**不报错**:规则是可选功能,
|
||||
/// 不该因为它坏了导致模块打不开)。
|
||||
pub fn load(path: &Path) -> RulesFile {
|
||||
let mut file: RulesFile = std::fs::read_to_string(path)
|
||||
.ok()
|
||||
.and_then(|t| serde_json::from_str(&t).ok())
|
||||
.unwrap_or_default();
|
||||
if file.version != RULES_VERSION {
|
||||
file.version = RULES_VERSION;
|
||||
}
|
||||
file
|
||||
}
|
||||
|
||||
/// 写入规则文件(调用方负责放到 `spawn_blocking` 里)。
|
||||
pub fn save(path: &Path, file: &RulesFile) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(file).map_err(|e| format!("序列化规则失败:{e}"))?;
|
||||
std::fs::write(path, json).map_err(|e| format!("写入规则文件失败:{e}"))
|
||||
}
|
||||
|
||||
/// 保存前的校验(**留在这里而不是组件里**:规则模型的知识只有一份)。
|
||||
pub fn validate(rule: &Rule) -> Result<(), String> {
|
||||
if rule.name.trim().is_empty() {
|
||||
return Err("请填写规则名称".to_string());
|
||||
}
|
||||
if rule.trigger.entity_id.trim().is_empty() {
|
||||
return Err("请选择触发实体".to_string());
|
||||
}
|
||||
if rule.actions.is_empty() {
|
||||
return Err("至少需要一个动作".to_string());
|
||||
}
|
||||
for action in &rule.actions {
|
||||
match action.kind.as_str() {
|
||||
"service" => {
|
||||
if action.domain.trim().is_empty()
|
||||
|| action.service.trim().is_empty()
|
||||
|| action.entity_id.trim().is_empty()
|
||||
{
|
||||
return Err("动作里的 domain / 服务 / 实体都不能为空".to_string());
|
||||
}
|
||||
}
|
||||
"delay" => {
|
||||
if action.seconds == 0 {
|
||||
return Err("延时的秒数必须大于 0".to_string());
|
||||
}
|
||||
if action.seconds > MAX_DELAY_SEC {
|
||||
return Err(format!("延时最长 {MAX_DELAY_SEC} 秒"));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ============================== 求值 ==============================
|
||||
|
||||
/// 触发条件是否成立(`old` 为 `None` 表示"首次见到该实体"或"延时复查")。
|
||||
pub fn trigger_matches(
|
||||
trigger: &RuleTrigger,
|
||||
old: Option<&EntitySummary>,
|
||||
new: &EntitySummary,
|
||||
) -> bool {
|
||||
if trigger.entity_id.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if !trigger.to.is_empty() && !trigger.to.contains(&new.state) {
|
||||
return false;
|
||||
}
|
||||
if !trigger.from.is_empty() {
|
||||
match old {
|
||||
Some(o) if trigger.from.contains(&o.state) => {}
|
||||
// from 非空但拿不到旧状态:不判定为命中(宁可漏一次,也不要误触)
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
if !trigger.numeric_op.is_empty() {
|
||||
let (Some(value), Some(threshold)) = (new.numeric, trigger.numeric_value) else {
|
||||
return false;
|
||||
};
|
||||
let ok = match trigger.numeric_op.as_str() {
|
||||
">" => value > threshold,
|
||||
">=" => value >= threshold,
|
||||
"<" => value < threshold,
|
||||
"<=" => value <= threshold,
|
||||
"==" => (value - threshold).abs() < f64::EPSILON,
|
||||
"!=" => (value - threshold).abs() >= f64::EPSILON,
|
||||
_ => true,
|
||||
};
|
||||
if !ok {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// 实体状态变化时的入口(由 `ws.rs` 的聚合任务调用,**必须是同步的**:
|
||||
/// 它跑在 WS 读循环里,耗时工作都丢给后台任务)。
|
||||
pub fn on_entity_changed(
|
||||
env: &RuleEnv,
|
||||
entity_id: &str,
|
||||
old: Option<&EntitySummary>,
|
||||
new: &EntitySummary,
|
||||
) {
|
||||
let candidates: Vec<(String, RuleTrigger)> = {
|
||||
let Ok(file) = env.rules.lock() else {
|
||||
return;
|
||||
};
|
||||
if !file.enabled {
|
||||
return;
|
||||
}
|
||||
file.rules
|
||||
.iter()
|
||||
.filter(|r| r.enabled && r.trigger.entity_id == entity_id)
|
||||
.map(|r| (r.id.clone(), r.trigger.clone()))
|
||||
.collect()
|
||||
};
|
||||
|
||||
for (rule_id, trigger) in candidates {
|
||||
if trigger.for_sec == 0 {
|
||||
if !trigger_matches(&trigger, old, new) {
|
||||
continue;
|
||||
}
|
||||
let env = env.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
fire(&env, &rule_id).await;
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// 持续 N 秒:只维护"首次满足的时刻",到点由巡检任务(`spawn_sweeper`)复查;
|
||||
// 状态一旦离开满足态就把槽位撤掉。**不重置**已存在的槽位 —— 那才是
|
||||
// "持续 N 秒满足"的语义(每次事件都重置会变成"静默 N 秒才触发")。
|
||||
let matches = trigger_matches(&trigger, old, new);
|
||||
if let Ok(mut pending) = env.pending.lock() {
|
||||
if matches {
|
||||
pending
|
||||
.entry(rule_id)
|
||||
.or_insert_with(|| Instant::now() + Duration::from_secs(trigger.for_sec as u64));
|
||||
} else {
|
||||
pending.remove(&rule_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `for` 触发器的巡检任务:每 `SWEEP_INTERVAL_MS` 看一次槽位表,到点的复查后执行。
|
||||
///
|
||||
/// **与 WS 连接同生命周期**(收到 stop 就退出):连接换了/停了,就不会有旧定时器
|
||||
/// 残留下来用旧端点、旧令牌继续执行动作。
|
||||
pub fn spawn_sweeper(env: &RuleEnv, mut stop: watch::Receiver<bool>) {
|
||||
let env = env.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(SWEEP_INTERVAL_MS));
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = stop.changed() => break,
|
||||
_ = tick.tick() => sweep_pending(&env),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn sweep_pending(env: &RuleEnv) {
|
||||
let due: Vec<String> = match env.pending.lock() {
|
||||
Ok(mut pending) => {
|
||||
let now = Instant::now();
|
||||
let ready: Vec<String> = pending
|
||||
.iter()
|
||||
.filter(|entry| *entry.1 <= now)
|
||||
.map(|entry| entry.0.clone())
|
||||
.collect();
|
||||
for id in &ready {
|
||||
pending.remove(id);
|
||||
}
|
||||
ready
|
||||
}
|
||||
Err(_) => return,
|
||||
};
|
||||
|
||||
for rule_id in due {
|
||||
let (trigger, entity_id) = match env.rules.lock() {
|
||||
Ok(file) if file.enabled => {
|
||||
match file.rules.iter().find(|r| r.id == rule_id && r.enabled) {
|
||||
Some(r) => (r.trigger.clone(), r.trigger.entity_id.clone()),
|
||||
None => continue,
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
// 复查:到点时**当前**状态仍需满足触发条件(去抖的真正含义)
|
||||
let current = env
|
||||
.summaries
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|g| g.get(&entity_id).cloned());
|
||||
let Some(current) = current else {
|
||||
continue;
|
||||
};
|
||||
if !trigger_matches(&trigger, None, ¤t) {
|
||||
continue;
|
||||
}
|
||||
let env = env.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
fire(&env, &rule_id).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 原子认领一次触发权:**在同一把锁里**判冷却并写下占位时间。
|
||||
///
|
||||
/// 为什么必须"认领"而不是"先读后写":`fire` 里的动作是 async(服务调用可能几秒),
|
||||
/// 同一聚合窗口内的两条事件会各自起一个 `fire`,两个都读到同一份旧 `last_fired_at`
|
||||
/// → 都通过冷却 → **同一条规则被重复执行**。占位把判定与写入收进一个临界区后,
|
||||
/// 后到的那次会读到新时间戳并被冷却挡掉。
|
||||
///
|
||||
/// 返回 `(规则快照, 认领时刻)`。
|
||||
fn claim(env: &RuleEnv, rule_id: &str) -> Option<(Rule, i64)> {
|
||||
let mut file = env.rules.lock().ok()?;
|
||||
if !file.enabled {
|
||||
return None;
|
||||
}
|
||||
let idx = file.rules.iter().position(|r| r.id == rule_id)?;
|
||||
if !file.rules[idx].enabled {
|
||||
return None;
|
||||
}
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let (cooldown, last) = (file.rules[idx].cooldown_sec, file.rules[idx].last_fired_at);
|
||||
if cooldown > 0 && last > 0 && now - last < cooldown as i64 {
|
||||
return None;
|
||||
}
|
||||
file.rules[idx].last_fired_at = now;
|
||||
Some((file.rules[idx].clone(), now))
|
||||
}
|
||||
|
||||
/// 执行一条规则(认领 → 突发护栏 → 条件 → 动作)。
|
||||
async fn fire(env: &RuleEnv, rule_id: &str) {
|
||||
let Some((rule, now)) = claim(env, rule_id) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// 护栏 3:突发计数(冷却不足以阻断的 A→B→A 互触)
|
||||
if !burst_allow(env, &rule.id) {
|
||||
crate::logger::log_warn(
|
||||
"smarthome",
|
||||
&format!(
|
||||
"规则「{}」在 {} 秒内触发超过 {} 次,已跳过(循环保护)",
|
||||
rule.name,
|
||||
BURST_WINDOW.as_secs(),
|
||||
BURST_MAX
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if !conditions_ok(env, &rule) {
|
||||
// 触发器确实命中了,是条件没放行:本次不执行、不计次数,
|
||||
// 但冷却槽已被占用(没有动作就不该反复重试)
|
||||
maybe_persist(env);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut failures: Vec<String> = Vec::new();
|
||||
for action in &rule.actions {
|
||||
// 护栏 2:单个动作失败**不中断**后续动作
|
||||
if let Err(e) = run_action(env, action).await {
|
||||
failures.push(e);
|
||||
}
|
||||
}
|
||||
let ok = failures.is_empty();
|
||||
let detail = if ok {
|
||||
format!("已执行 {} 个动作", rule.actions.len())
|
||||
} else {
|
||||
failures.join(";")
|
||||
};
|
||||
|
||||
if let Ok(mut file) = env.rules.lock() {
|
||||
if let Some(slot) = file.rules.iter_mut().find(|r| r.id == rule_id) {
|
||||
if ok {
|
||||
slot.fire_count = slot.fire_count.saturating_add(1);
|
||||
}
|
||||
slot.last_error = if ok { String::new() } else { detail.clone() };
|
||||
}
|
||||
}
|
||||
maybe_persist(env);
|
||||
|
||||
crate::logger::log_info(
|
||||
"smarthome",
|
||||
&format!("本地规则「{}」触发:{}", rule.name, detail),
|
||||
);
|
||||
push_record(
|
||||
env,
|
||||
RuleRecord {
|
||||
rule_id: rule.id.clone(),
|
||||
rule_name: rule.name.clone(),
|
||||
at: now,
|
||||
ok,
|
||||
detail,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// 触发统计的落盘去抖:内存立即更新,磁盘最多每 `PERSIST_MIN_INTERVAL_SECS` 写一次。
|
||||
///
|
||||
/// 规则很容易被传感器刷得勤(功率反复跳),每触发一次就整份序列化 + 写盘是纯浪费;
|
||||
/// 统计字段(`lastFiredAt` / `fireCount` / `lastError`)晚几秒落盘不影响任何判断。
|
||||
/// 命令层的**显式**保存(存规则 / 删规则 / 总开关)仍立即写盘 —— 那是用户动作。
|
||||
fn maybe_persist(env: &RuleEnv) {
|
||||
let due = match env.last_persist.lock() {
|
||||
Ok(mut at) => {
|
||||
if at.elapsed() >= Duration::from_secs(PERSIST_MIN_INTERVAL_SECS) {
|
||||
*at = Instant::now();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
Err(_) => true,
|
||||
};
|
||||
if !due {
|
||||
return;
|
||||
}
|
||||
let Ok(file) = env.rules.lock().map(|g| g.clone()) else {
|
||||
return;
|
||||
};
|
||||
let path = env.rules_path.clone();
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
if let Err(e) = save(&path, &file) {
|
||||
crate::logger::log_warn("smarthome", &format!("保存规则触发统计失败:{e}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 执行单个动作。
|
||||
async fn run_action(env: &RuleEnv, action: &RuleAction) -> Result<(), String> {
|
||||
match action.kind.as_str() {
|
||||
"delay" => {
|
||||
let secs = action.seconds.min(MAX_DELAY_SEC) as u64;
|
||||
if secs > 0 {
|
||||
tokio::time::sleep(Duration::from_secs(secs)).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"notify" => {
|
||||
let title = if action.title.trim().is_empty() {
|
||||
"Thing 智能家居".to_string()
|
||||
} else {
|
||||
action.title.clone()
|
||||
};
|
||||
env.app
|
||||
.notification()
|
||||
.builder()
|
||||
.title(title)
|
||||
.body(action.message.clone())
|
||||
.show()
|
||||
.map_err(|e| format!("系统通知发送失败:{e}"))
|
||||
}
|
||||
// 默认按 service 处理(前端只给这三种 kind)
|
||||
_ => {
|
||||
if action.domain.trim().is_empty()
|
||||
|| action.service.trim().is_empty()
|
||||
|| action.entity_id.trim().is_empty()
|
||||
{
|
||||
return Err("动作缺少 domain / 服务 / 实体".to_string());
|
||||
}
|
||||
client::call_service(
|
||||
&env.base_url,
|
||||
&env.token,
|
||||
env.insecure,
|
||||
env.kind,
|
||||
&action.domain,
|
||||
&action.service,
|
||||
&action.entity_id,
|
||||
&action.params,
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|f| format!("{}:{}", action.entity_id, f.message))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 条件全部 AND(plan §5.4-B)。
|
||||
fn conditions_ok(env: &RuleEnv, rule: &Rule) -> bool {
|
||||
rule.conditions.iter().all(|c| match c.kind.as_str() {
|
||||
"time" => time_ok(c),
|
||||
_ => state_ok(env, c),
|
||||
})
|
||||
}
|
||||
|
||||
fn state_ok(env: &RuleEnv, condition: &RuleCondition) -> bool {
|
||||
if condition.entity_id.is_empty() || condition.state.is_empty() {
|
||||
return true;
|
||||
}
|
||||
env.summaries
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|g| g.get(&condition.entity_id).map(|e| e.state == condition.state))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 时间窗口条件:`weekdays`(1=周一 … 7=周日,空 = 每天)+ `HH:MM` 区间。
|
||||
/// 跨零点(`to < from`)视为跨天窗口,例如 `23:00 – 06:00`。
|
||||
fn time_ok(condition: &RuleCondition) -> bool {
|
||||
if condition.from_time.is_empty() || condition.to_time.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let (Some((fh, fm)), Some((th, tm))) = (
|
||||
parse_hhmm(&condition.from_time),
|
||||
parse_hhmm(&condition.to_time),
|
||||
) else {
|
||||
return true;
|
||||
};
|
||||
let now = Local::now();
|
||||
if !condition.weekdays.is_empty() {
|
||||
let weekday = now.weekday().number_from_monday();
|
||||
if !condition.weekdays.contains(&weekday) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let current = now.hour() * 60 + now.minute();
|
||||
let from = fh * 60 + fm;
|
||||
let to = th * 60 + tm;
|
||||
if from <= to {
|
||||
current >= from && current <= to
|
||||
} else {
|
||||
current >= from || current <= to
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_hhmm(text: &str) -> Option<(u32, u32)> {
|
||||
let (h, m) = text.trim().split_once(':')?;
|
||||
let hour: u32 = h.trim().parse().ok()?;
|
||||
let minute: u32 = m.trim().parse().ok()?;
|
||||
if hour > 23 || minute > 59 {
|
||||
return None;
|
||||
}
|
||||
Some((hour, minute))
|
||||
}
|
||||
|
||||
/// 突发护栏:同规则在窗口内的触发次数上限。
|
||||
///
|
||||
/// 顺带把过期记录从队首清掉(队列按时间推进,天然有序)。
|
||||
fn burst_allow(env: &RuleEnv, rule_id: &str) -> bool {
|
||||
let Ok(mut g) = env.recent.lock() else {
|
||||
return true;
|
||||
};
|
||||
let cutoff = Instant::now() - BURST_WINDOW;
|
||||
while g.front().map(|(_, at)| *at < cutoff).unwrap_or(false) {
|
||||
g.pop_front();
|
||||
}
|
||||
if g.iter().filter(|(id, _)| id == rule_id).count() >= BURST_MAX {
|
||||
return false;
|
||||
}
|
||||
g.push_back((rule_id.to_string(), Instant::now()));
|
||||
true
|
||||
}
|
||||
|
||||
/// 记一条运行记录(内存环形)+ 推事件给前端。
|
||||
fn push_record(env: &RuleEnv, record: RuleRecord) {
|
||||
if let Ok(mut g) = env.records.lock() {
|
||||
g.push_front(record.clone());
|
||||
while g.len() > MAX_RECORDS {
|
||||
g.pop_back();
|
||||
}
|
||||
}
|
||||
let _ = env.app.emit(
|
||||
events::SMARTHOME_RULE_FIRED,
|
||||
RuleFiredEvent {
|
||||
rule_id: record.rule_id,
|
||||
rule_name: record.rule_name,
|
||||
at: record.at,
|
||||
ok: record.ok,
|
||||
detail: record.detail,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,735 @@
|
||||
//! Home Assistant HTTP 客户端与**端点选择**。
|
||||
//!
|
||||
//! P0 只用到两件事:探测(`GET /api/` + `GET /api/config`)与端点选择
|
||||
//! (`auto` / `local` / `remote` 三档)。设备数据与控制命令在 P1/P2 才接上来,
|
||||
//! 但它们**必须复用这里的 `resolve_endpoint`**,否则在外面的每次请求都会先等
|
||||
//! 局域网超时。
|
||||
//!
|
||||
//! 超时策略见 `SMART_HOME_MODULE_PLAN.md` §3.7:局域网探测必须短(在外会必然耗满),
|
||||
//! 反代探测可以宽松(Cloudflare Tunnel 的 RTT 常在 100–400ms)。
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::smarthome::types::{
|
||||
EndpointKind, EndpointMode, EndpointProbe, EntitySummary, HaConnection, ServiceParams,
|
||||
};
|
||||
|
||||
/// 局域网探测超时(**必须短**)。
|
||||
///
|
||||
/// 在家里局域网必然 <10ms 命中;在外面,这个地址会因为 ARP / 路由不可达而
|
||||
/// **必然耗满超时**。它直接决定"出门后每次冷探测有多卡"。
|
||||
pub const LOCAL_PROBE_TIMEOUT_MS: u64 = 900;
|
||||
/// 反代探测超时(Cloudflare Tunnel 首包可能较慢,给足余量)。
|
||||
pub const REMOTE_PROBE_TIMEOUT_MS: u64 = 5000;
|
||||
/// 强制模式(`local` / `remote`)下的超时:此时失败就是"真的连不上",
|
||||
/// 不该因为 900ms 这种"用于探测缺失"的短超时把可用链路判死。
|
||||
pub const FORCED_PROBE_TIMEOUT_MS: u64 = 5000;
|
||||
/// 「测试连接」在单个地址上的总超时(要跑两个请求,给比探测更宽的预算)。
|
||||
pub const TEST_LOCAL_TIMEOUT_MS: u64 = 8000;
|
||||
pub const TEST_REMOTE_TIMEOUT_MS: u64 = 20000;
|
||||
|
||||
/// 普通数据请求的超时:局域网 8s / 反代 30s。
|
||||
///
|
||||
/// 反代上 `/api/states` 是几百 KB(gzip 后几十 KB),这里给的是"能成功但慢"的余量,
|
||||
/// 不是"期望 30s" —— 实际体验主要由 §3.7 的链路选择与 gzip 决定。
|
||||
pub const REQUEST_TIMEOUT_LOCAL_MS: u64 = 8000;
|
||||
pub const REQUEST_TIMEOUT_REMOTE_MS: u64 = 30000;
|
||||
|
||||
/// 按链路取数据请求超时。
|
||||
pub fn request_timeout(kind: EndpointKind) -> u64 {
|
||||
match kind {
|
||||
EndpointKind::Local => REQUEST_TIMEOUT_LOCAL_MS,
|
||||
EndpointKind::Remote => REQUEST_TIMEOUT_REMOTE_MS,
|
||||
}
|
||||
}
|
||||
|
||||
/// 一次 HTTP 交互失败的分类结果(探测与数据/控制请求共用)。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProbeFailure {
|
||||
/// auth | network | notFound | badRequest | server | other
|
||||
pub kind: &'static str,
|
||||
pub message: String,
|
||||
/// 是否属于"令牌本身无效"。
|
||||
///
|
||||
/// 这类失败**必须立刻放弃换端点重试**:同一个令牌在所有地址上都无效,
|
||||
/// 继续试反代只会让用户多等一个超时,并把真正的原因(令牌失效)淹没在
|
||||
/// "都无法连接"里。
|
||||
pub fatal_auth: bool,
|
||||
}
|
||||
|
||||
impl ProbeFailure {
|
||||
fn auth(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind: "auth",
|
||||
message: message.into(),
|
||||
fatal_auth: true,
|
||||
}
|
||||
}
|
||||
fn network(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind: "network",
|
||||
message: message.into(),
|
||||
fatal_auth: false,
|
||||
}
|
||||
}
|
||||
fn server(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind: "server",
|
||||
message: message.into(),
|
||||
fatal_auth: false,
|
||||
}
|
||||
}
|
||||
/// 实体 / 服务不存在(设备被移除、集成重载)
|
||||
fn not_found(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind: "notFound",
|
||||
message: message.into(),
|
||||
fatal_auth: false,
|
||||
}
|
||||
}
|
||||
/// 参数不被该服务接受(如给不支持色温的灯传 `color_temp_kelvin`)
|
||||
fn bad_request(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind: "badRequest",
|
||||
message: message.into(),
|
||||
fatal_auth: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 端点选择结果。
|
||||
pub struct ResolvedEndpoint {
|
||||
pub url: String,
|
||||
pub kind: EndpointKind,
|
||||
pub latency_ms: u64,
|
||||
}
|
||||
|
||||
/// 端点选择失败:带分类,前端据此决定是"重填令牌"还是"重试/切换地址"(§3.6)。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ResolveFailure {
|
||||
/// auth | network | config
|
||||
pub kind: &'static str,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl ResolveFailure {
|
||||
fn new(kind: &'static str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 地址规范化:补协议(局域网默认 `http`、反代默认 `https`)、去掉结尾斜杠。
|
||||
pub fn normalize_url(input: &str, prefer_https: bool) -> String {
|
||||
let mut u = input.trim().to_string();
|
||||
if u.is_empty() {
|
||||
return u;
|
||||
}
|
||||
let lower = u.to_lowercase();
|
||||
if !lower.starts_with("http://") && !lower.starts_with("https://") {
|
||||
u = if prefer_https {
|
||||
format!("https://{u}")
|
||||
} else {
|
||||
format!("http://{u}")
|
||||
};
|
||||
}
|
||||
while u.ends_with('/') {
|
||||
u.pop();
|
||||
}
|
||||
u
|
||||
}
|
||||
|
||||
/// REST 端点 → WebSocket 端点:`http` → `ws`、`https` → `wss`,路径固定 `/api/websocket`。
|
||||
///
|
||||
/// **复用同一份端点选择结果**(plan §3.7-a 最后一条):WS 一旦连上就固定在所选端点,
|
||||
/// 不允许同一屏数据来自两条链路(否则"更新于 x 秒前"的时间戳会来自不同链路)。
|
||||
pub fn ws_url(base: &str) -> Result<String, String> {
|
||||
let mut u = url::Url::parse(base).map_err(|e| format!("HA 地址不合法:{e}"))?;
|
||||
let ok = match u.scheme() {
|
||||
"https" => u.set_scheme("wss").is_ok(),
|
||||
"http" => u.set_scheme("ws").is_ok(),
|
||||
"ws" | "wss" => true,
|
||||
other => return Err(format!("不支持用 {other} 建立 WebSocket 连接")),
|
||||
};
|
||||
if !ok {
|
||||
return Err("无法把该地址转换成 WebSocket 协议".to_string());
|
||||
}
|
||||
u.set_path("/api/websocket");
|
||||
u.set_query(None);
|
||||
Ok(u.to_string())
|
||||
}
|
||||
|
||||
/// 校验地址合法性(保存时做,**不要在请求时才失败**——那时错误信息已经离用户输入很远了)。
|
||||
pub fn validate_url(url: &str, label: &str) -> Result<(), String> {
|
||||
if url.trim().is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let parsed = url::Url::parse(url).map_err(|e| format!("{label}不是合法的地址:{e}"))?;
|
||||
if parsed.host_str().unwrap_or("").is_empty() {
|
||||
return Err(format!("{label}缺少主机名"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_client(insecure: bool, timeout_ms: u64) -> Result<reqwest::Client, String> {
|
||||
reqwest::Client::builder()
|
||||
// 自签证书:与飞牛连接同款开关。局域网 IP 的 HA 通常是 http,用不到它;
|
||||
// 反代若用 IP 直连 + 自签证书才需要。
|
||||
.danger_accept_invalid_certs(insecure)
|
||||
.timeout(std::time::Duration::from_millis(timeout_ms))
|
||||
// 压缩交给 reqwest 自动协商(Cargo.toml 已开 `gzip` feature):
|
||||
// 反代链路上 `/api/states` 是几百 KB JSON,不压缩就是白送 5–10 倍流量。
|
||||
.build()
|
||||
.map_err(|e| format!("构建 HTTP 客户端失败:{e}"))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ApiRoot {
|
||||
#[serde(default)]
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct HaConfig {
|
||||
#[serde(default)]
|
||||
version: String,
|
||||
#[serde(default)]
|
||||
location_name: String,
|
||||
#[serde(default)]
|
||||
unit_system: UnitSystem,
|
||||
}
|
||||
|
||||
/// HA 的系统单位制(`/api/config`)。只有温度是本模块需要的 ——
|
||||
/// climate 的 `temperature` / `min_temp` / `max_temp` 都按它给值。
|
||||
#[derive(Deserialize, Default)]
|
||||
struct UnitSystem {
|
||||
#[serde(default)]
|
||||
temperature: String,
|
||||
}
|
||||
|
||||
fn describe_request_error(e: &reqwest::Error) -> String {
|
||||
if e.is_timeout() {
|
||||
"连接超时".to_string()
|
||||
} else if e.is_connect() {
|
||||
"无法建立连接".to_string()
|
||||
} else {
|
||||
format!("请求失败:{e}")
|
||||
}
|
||||
}
|
||||
|
||||
/// 轻量可达性检查:`GET /api/`(地址可达 + 令牌有效 + **确实是 HA 的 API**)。
|
||||
/// 返回耗时(毫秒)。
|
||||
///
|
||||
/// 为什么要校验响应体而不仅是状态码:反代前面若挂了访问网关(如 Cloudflare Access),
|
||||
/// 未携带 Service Token 时会被重定向到一个 **200 的 HTML 登录页** —— 只看状态码会把它
|
||||
/// 判成"链路正常",随后的真实请求才会莫名其妙地失败(§2.2-6)。
|
||||
async fn check_reachable(
|
||||
base: &str,
|
||||
token: &str,
|
||||
insecure: bool,
|
||||
timeout_ms: u64,
|
||||
) -> Result<u64, ProbeFailure> {
|
||||
let client = build_client(insecure, timeout_ms).map_err(ProbeFailure::network)?;
|
||||
let started = Instant::now();
|
||||
let resp = client
|
||||
.get(format!("{base}/api/"))
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ProbeFailure::network(describe_request_error(&e)))?;
|
||||
|
||||
let status = resp.status();
|
||||
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||
return Err(ProbeFailure::auth("访问令牌无效或已被吊销"));
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(ProbeFailure::server(format!("HTTP {}", status.as_u16())));
|
||||
}
|
||||
let root = resp.json::<ApiRoot>().await.map_err(|_| {
|
||||
ProbeFailure::server("响应不是 Home Assistant 的 API(可能被反向代理或访问网关拦截)")
|
||||
})?;
|
||||
if root.message.is_empty() {
|
||||
return Err(ProbeFailure::server("Home Assistant 返回了空响应"));
|
||||
}
|
||||
Ok(started.elapsed().as_millis() as u64)
|
||||
}
|
||||
|
||||
/// 探测单个地址(「测试连接」用):`GET /api/` + `GET /api/config`。
|
||||
///
|
||||
/// 不拉 `/api/states` 统计实体数:那是几百 KB 的响应,在反代链路上会把
|
||||
/// "测试连接"从 1 秒拖到 3 秒以上,而实体列表在 P1 本来就会拉一次。
|
||||
pub async fn probe_url(
|
||||
url: &str,
|
||||
token: &str,
|
||||
insecure: bool,
|
||||
kind: EndpointKind,
|
||||
) -> EndpointProbe {
|
||||
let timeout_ms = match kind {
|
||||
EndpointKind::Local => TEST_LOCAL_TIMEOUT_MS,
|
||||
EndpointKind::Remote => TEST_REMOTE_TIMEOUT_MS,
|
||||
};
|
||||
let mut failure: Option<ProbeFailure> = None;
|
||||
let started = Instant::now();
|
||||
|
||||
let mut ha_version = String::new();
|
||||
let mut location_name = String::new();
|
||||
let mut temperature_unit = String::new();
|
||||
let mut ok = false;
|
||||
|
||||
match check_reachable(url, token, insecure, timeout_ms).await {
|
||||
Ok(_) => match fetch_config(url, token, insecure, timeout_ms).await {
|
||||
Ok(cfg) => {
|
||||
ha_version = cfg.version;
|
||||
location_name = cfg.location_name;
|
||||
temperature_unit = cfg.unit_system.temperature;
|
||||
ok = true;
|
||||
}
|
||||
Err(e) => failure = Some(e),
|
||||
},
|
||||
Err(e) => failure = Some(e),
|
||||
}
|
||||
|
||||
EndpointProbe {
|
||||
url: url.to_string(),
|
||||
kind,
|
||||
ok,
|
||||
ha_version,
|
||||
location_name,
|
||||
temperature_unit,
|
||||
elapsed_ms: started.elapsed().as_millis() as u64,
|
||||
error: failure.as_ref().map(|f| f.message.clone()),
|
||||
error_kind: failure.as_ref().map(|f| f.kind.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn fetch_config(
|
||||
base: &str,
|
||||
token: &str,
|
||||
insecure: bool,
|
||||
timeout_ms: u64,
|
||||
) -> Result<HaConfig, ProbeFailure> {
|
||||
let client = build_client(insecure, timeout_ms).map_err(ProbeFailure::network)?;
|
||||
let resp = client
|
||||
.get(format!("{base}/api/config"))
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ProbeFailure::network(describe_request_error(&e)))?;
|
||||
let status = resp.status();
|
||||
if !status.is_success() {
|
||||
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||
return Err(ProbeFailure::auth("访问令牌无效或已被吊销"));
|
||||
}
|
||||
return Err(ProbeFailure::server(format!("HTTP {}", status.as_u16())));
|
||||
}
|
||||
resp.json::<HaConfig>()
|
||||
.await
|
||||
.map_err(|e| ProbeFailure::server(format!("响应解析失败:{e}")))
|
||||
}
|
||||
|
||||
/// 逐个地址探测(顺序:局域网 → 反代),供「测试连接」使用。
|
||||
pub async fn probe_all(
|
||||
local_url: &str,
|
||||
remote_url: &str,
|
||||
token: &str,
|
||||
insecure: bool,
|
||||
) -> Vec<EndpointProbe> {
|
||||
let mut out = Vec::new();
|
||||
if !local_url.trim().is_empty() {
|
||||
out.push(probe_url(local_url.trim(), token, insecure, EndpointKind::Local).await);
|
||||
}
|
||||
if !remote_url.trim().is_empty() {
|
||||
out.push(probe_url(remote_url.trim(), token, insecure, EndpointKind::Remote).await);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 候选端点列表:(地址, 类型, 探测超时),按尝试顺序排列。
|
||||
fn candidates(conn: &HaConnection) -> Result<Vec<(&str, EndpointKind, u64)>, ResolveFailure> {
|
||||
let local = conn.local_candidate();
|
||||
let remote = conn.remote_candidate();
|
||||
match conn.endpoint_mode {
|
||||
EndpointMode::Local => match local {
|
||||
Some((u, _)) => Ok(vec![(u, EndpointKind::Local, FORCED_PROBE_TIMEOUT_MS)]),
|
||||
None => Err(ResolveFailure::new(
|
||||
"config",
|
||||
"当前连接未配置局域网地址(端点策略为「仅局域网」)",
|
||||
)),
|
||||
},
|
||||
EndpointMode::Remote => match remote {
|
||||
Some((u, _)) => Ok(vec![(u, EndpointKind::Remote, FORCED_PROBE_TIMEOUT_MS)]),
|
||||
None => Err(ResolveFailure::new(
|
||||
"config",
|
||||
"当前连接未配置反代地址(端点策略为「仅反代」)",
|
||||
)),
|
||||
},
|
||||
EndpointMode::Auto => {
|
||||
let mut v = Vec::new();
|
||||
// 局域网优先:回家时能自动切回,代价是出门后每轮冷探测多花 900ms
|
||||
// (见 types::EndpointMode 的注释,这里刻意**不**把 lastOkUrl 排在最前)。
|
||||
if let Some((u, k)) = local {
|
||||
v.push((u, k, LOCAL_PROBE_TIMEOUT_MS));
|
||||
}
|
||||
if let Some((u, k)) = remote {
|
||||
v.push((u, k, REMOTE_PROBE_TIMEOUT_MS));
|
||||
}
|
||||
if v.is_empty() {
|
||||
return Err(ResolveFailure::new("config", "该连接没有配置任何地址"));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 按 `endpoint_mode` 顺序探测,返回第一个可用端点。
|
||||
///
|
||||
/// 失败时的错误信息**包含每个地址的尝试结果** —— 用户需要知道"是局域网不可达、
|
||||
/// 还是反代也挂了",一个笼统的"连接失败"无法排障。
|
||||
pub async fn resolve_endpoint(
|
||||
conn: &HaConnection,
|
||||
token: &str,
|
||||
) -> Result<ResolvedEndpoint, ResolveFailure> {
|
||||
let list = candidates(conn)?;
|
||||
let mut failures: Vec<String> = Vec::new();
|
||||
|
||||
for (url, kind, timeout_ms) in list {
|
||||
match check_reachable(url, token, conn.insecure, timeout_ms).await {
|
||||
Ok(latency_ms) => {
|
||||
return Ok(ResolvedEndpoint {
|
||||
url: url.to_string(),
|
||||
kind,
|
||||
latency_ms,
|
||||
});
|
||||
}
|
||||
Err(f) => {
|
||||
// 令牌无效:换任何地址都是同一个结果,立即停止
|
||||
if f.fatal_auth {
|
||||
return Err(ResolveFailure::new("auth", f.message));
|
||||
}
|
||||
failures.push(format!("{}:{}", kind_label(kind), f.message));
|
||||
crate::logger::log_warn(
|
||||
"smarthome",
|
||||
&format!("端点探测失败({} {}):{}", kind_label(kind), url, f.message),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(ResolveFailure::new(
|
||||
"network",
|
||||
format!("所有地址均不可达 —— {}", failures.join(";")),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn kind_label(kind: EndpointKind) -> &'static str {
|
||||
match kind {
|
||||
EndpointKind::Local => "局域网",
|
||||
EndpointKind::Remote => "反代",
|
||||
}
|
||||
}
|
||||
|
||||
/// 取 HA 元信息(版本 / 实例名 / 温度单位)。
|
||||
///
|
||||
/// 「检测链路」与"首次拉实体时还不知道实例信息"两个场景会用到它 ——
|
||||
/// 只是一个很小的 `/api/config` 请求,因此不塞进每次数据拉取里。
|
||||
pub async fn fetch_meta(
|
||||
base: &str,
|
||||
token: &str,
|
||||
insecure: bool,
|
||||
kind: EndpointKind,
|
||||
) -> Result<(String, String, String), ProbeFailure> {
|
||||
let cfg = fetch_config(base, token, insecure, request_timeout(kind)).await?;
|
||||
Ok((cfg.version, cfg.location_name, cfg.unit_system.temperature))
|
||||
}
|
||||
|
||||
// ============ 实体状态(P1) ============
|
||||
|
||||
/// HA 的原始状态对象(`/api/states` 的元素,也是 WS 里 `subscribe_entities` 的形态)。
|
||||
///
|
||||
/// P4 起 `ws.rs` 也要用:WS 的增量是**差量更新**,必须先把 attributes 合并回一份
|
||||
/// 完整的原始对象,再转 `EntitySummary` —— 所以这里不再是 P1 的私有实现细节。
|
||||
#[derive(Deserialize, Default, Clone)]
|
||||
pub struct RawState {
|
||||
#[serde(default)]
|
||||
pub entity_id: String,
|
||||
#[serde(default)]
|
||||
pub state: String,
|
||||
/// **故意不建结构体**:attributes 的字段集合随 domain 差异极大
|
||||
/// (灯 / 窗帘 / 气候 / 媒体播放器各不相同),按需白名单取用才稳。
|
||||
#[serde(default)]
|
||||
pub attributes: serde_json::Value,
|
||||
#[serde(default)]
|
||||
pub last_changed: String,
|
||||
}
|
||||
|
||||
/// 拉取全量实体状态并转成精简结构。
|
||||
///
|
||||
/// 调用方必须先 `resolve_endpoint` 拿到可用的 `base` 与 `kind` —— 这里不做链路选择。
|
||||
pub async fn fetch_entities(
|
||||
base: &str,
|
||||
token: &str,
|
||||
insecure: bool,
|
||||
kind: EndpointKind,
|
||||
) -> Result<Vec<EntitySummary>, ProbeFailure> {
|
||||
let client = build_client(insecure, request_timeout(kind)).map_err(ProbeFailure::network)?;
|
||||
let resp = client
|
||||
.get(format!("{base}/api/states"))
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ProbeFailure::network(describe_request_error(&e)))?;
|
||||
|
||||
let status = resp.status();
|
||||
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||
return Err(ProbeFailure::auth("访问令牌无效或已被吊销"));
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(ProbeFailure::server(format!("HTTP {}", status.as_u16())));
|
||||
}
|
||||
let raw = resp
|
||||
.json::<Vec<RawState>>()
|
||||
.await
|
||||
.map_err(|e| ProbeFailure::server(format!("状态响应解析失败:{e}")))?;
|
||||
Ok(raw.into_iter().map(to_summary).collect())
|
||||
}
|
||||
|
||||
fn attr_str(attrs: &serde_json::Value, key: &str) -> String {
|
||||
attrs
|
||||
.get(key)
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn attr_f64(attrs: &serde_json::Value, key: &str) -> Option<f64> {
|
||||
attrs.get(key).and_then(|v| v.as_f64())
|
||||
}
|
||||
|
||||
/// 0–255 的整数属性(亮度)。上界夹紧,避免异常集成给出超范围值反倒转换失败。
|
||||
fn attr_u8(attrs: &serde_json::Value, key: &str) -> Option<u8> {
|
||||
attrs
|
||||
.get(key)
|
||||
.and_then(|v| v.as_u64())
|
||||
.map(|n| n.min(255) as u8)
|
||||
}
|
||||
|
||||
/// 0–100 的整数属性(窗帘位置 / 风扇档位)。
|
||||
fn attr_pct(attrs: &serde_json::Value, key: &str) -> Option<u8> {
|
||||
attrs
|
||||
.get(key)
|
||||
.and_then(|v| v.as_u64())
|
||||
.map(|n| n.min(100) as u8)
|
||||
}
|
||||
|
||||
fn attr_u32(attrs: &serde_json::Value, key: &str) -> Option<u32> {
|
||||
attrs.get(key).and_then(|v| v.as_u64()).map(|n| n as u32)
|
||||
}
|
||||
|
||||
/// 字符串数组属性(`supported_color_modes` / `hvac_modes`)
|
||||
fn attr_str_list(attrs: &serde_json::Value, key: &str) -> Vec<String> {
|
||||
attrs
|
||||
.get(key)
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.as_str().map(|s| s.to_string()))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// HA 状态对象 → 精简结构。控制类命令(服务响应里带回的变化实体)也复用它,
|
||||
/// P4 的 WS 增量合并后同样走这里。
|
||||
pub fn to_summary(raw: RawState) -> EntitySummary {
|
||||
let attrs = &raw.attributes;
|
||||
let domain = raw
|
||||
.entity_id
|
||||
.split('.')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let name = {
|
||||
let n = attr_str(attrs, "friendly_name");
|
||||
if n.is_empty() {
|
||||
raw.entity_id.clone()
|
||||
} else {
|
||||
n
|
||||
}
|
||||
};
|
||||
// sensor 的读数在 state 里(字符串形式的数字):能解析就顺手给前端一个数值
|
||||
let numeric = raw.state.parse::<f64>().ok();
|
||||
EntitySummary {
|
||||
entity_id: raw.entity_id,
|
||||
domain,
|
||||
name,
|
||||
state: raw.state,
|
||||
numeric,
|
||||
unit: attr_str(attrs, "unit_of_measurement"),
|
||||
device_class: attr_str(attrs, "device_class"),
|
||||
brightness: attr_u8(attrs, "brightness"),
|
||||
// 窗帘:HA 官方集成给 `current_position`,个别集成给 `position`,两个都认
|
||||
position: attr_pct(attrs, "current_position").or_else(|| attr_pct(attrs, "position")),
|
||||
target_temp: attr_f64(attrs, "temperature"),
|
||||
min_temp: attr_f64(attrs, "min_temp"),
|
||||
max_temp: attr_f64(attrs, "max_temp"),
|
||||
current_temp: attr_f64(attrs, "current_temperature"),
|
||||
last_changed: raw.last_changed,
|
||||
last_triggered: attr_str(attrs, "last_triggered"),
|
||||
supported_features: attr_u32(attrs, "supported_features").unwrap_or(0),
|
||||
supported_color_modes: attr_str_list(attrs, "supported_color_modes"),
|
||||
min_color_temp_kelvin: attr_u32(attrs, "min_color_temp_kelvin"),
|
||||
max_color_temp_kelvin: attr_u32(attrs, "max_color_temp_kelvin"),
|
||||
color_temp_kelvin: attr_u32(attrs, "color_temp_kelvin"),
|
||||
hvac_modes: attr_str_list(attrs, "hvac_modes"),
|
||||
target_temp_step: attr_f64(attrs, "target_temp_step"),
|
||||
volume_level: attr_f64(attrs, "volume_level"),
|
||||
percentage: attr_pct(attrs, "percentage"),
|
||||
min: attr_f64(attrs, "min"),
|
||||
max: attr_f64(attrs, "max"),
|
||||
step: attr_f64(attrs, "step"),
|
||||
options: attr_str_list(attrs, "options"),
|
||||
}
|
||||
}
|
||||
|
||||
// ============ 设备控制(P2) ============
|
||||
|
||||
/// 调用服务(控制设备)。
|
||||
///
|
||||
/// 返回 HA 在响应体里带回的**已变化实体**新状态(`200` 响应就是这些状态对象,
|
||||
/// 与 `/api/states` 同构)。解析失败时返回空列表而**不是报错**:命令本身已经成功,
|
||||
/// 状态只是"还没反映出来",不该因此告诉用户"控制失败"。
|
||||
pub async fn call_service(
|
||||
base: &str,
|
||||
token: &str,
|
||||
insecure: bool,
|
||||
kind: EndpointKind,
|
||||
domain: &str,
|
||||
service: &str,
|
||||
entity_id: &str,
|
||||
params: &ServiceParams,
|
||||
) -> Result<Vec<EntitySummary>, ProbeFailure> {
|
||||
let client = build_client(insecure, request_timeout(kind)).map_err(ProbeFailure::network)?;
|
||||
|
||||
let mut body = serde_json::Map::new();
|
||||
body.insert(
|
||||
"entity_id".to_string(),
|
||||
serde_json::Value::String(entity_id.to_string()),
|
||||
);
|
||||
// 只带真正有值的参数:HA 各服务对 `null` 的处理并不统一
|
||||
if let Some(v) = params.brightness_pct {
|
||||
body.insert("brightness_pct".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = params.color_temp_kelvin {
|
||||
body.insert("color_temp_kelvin".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = params.position {
|
||||
body.insert("position".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = params.temperature {
|
||||
body.insert("temperature".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = ¶ms.hvac_mode {
|
||||
body.insert("hvac_mode".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = params.percentage {
|
||||
body.insert("percentage".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = params.volume_level {
|
||||
body.insert("volume_level".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = params.value {
|
||||
body.insert("value".into(), json!(v));
|
||||
}
|
||||
if let Some(v) = ¶ms.option {
|
||||
body.insert("option".into(), json!(v));
|
||||
}
|
||||
|
||||
let resp = client
|
||||
.post(format!("{base}/api/services/{domain}/{service}"))
|
||||
.bearer_auth(token)
|
||||
.json(&serde_json::Value::Object(body))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ProbeFailure::network(describe_request_error(&e)))?;
|
||||
|
||||
let status = resp.status();
|
||||
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||
return Err(ProbeFailure::auth("访问令牌无效或已被吊销"));
|
||||
}
|
||||
if status.as_u16() == 404 {
|
||||
return Err(ProbeFailure::not_found("实体或服务不存在(设备可能已被移除)"));
|
||||
}
|
||||
if status.as_u16() == 400 {
|
||||
// HA 对参数不支持会返回可读的中文/英文 message,原样带给用户最有用
|
||||
let text = resp.text().await.unwrap_or_default();
|
||||
return Err(ProbeFailure::bad_request(extract_message(&text)));
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(ProbeFailure::server(format!("HTTP {}", status.as_u16())));
|
||||
}
|
||||
Ok(resp
|
||||
.json::<Vec<RawState>>()
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(to_summary)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 取单个实体状态(控制后的校正用)。
|
||||
///
|
||||
/// 只在校正窗口到期时才调用 —— 它不是常规路径,所以单独一个命令而不是重拉全量。
|
||||
pub async fn fetch_entity(
|
||||
base: &str,
|
||||
token: &str,
|
||||
insecure: bool,
|
||||
kind: EndpointKind,
|
||||
entity_id: &str,
|
||||
) -> Result<EntitySummary, ProbeFailure> {
|
||||
let client = build_client(insecure, request_timeout(kind)).map_err(ProbeFailure::network)?;
|
||||
let resp = client
|
||||
.get(format!("{base}/api/states/{entity_id}"))
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ProbeFailure::network(describe_request_error(&e)))?;
|
||||
|
||||
let status = resp.status();
|
||||
if status.as_u16() == 401 || status.as_u16() == 403 {
|
||||
return Err(ProbeFailure::auth("访问令牌无效或已被吊销"));
|
||||
}
|
||||
if status.as_u16() == 404 {
|
||||
return Err(ProbeFailure::not_found("该实体已不存在"));
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(ProbeFailure::server(format!("HTTP {}", status.as_u16())));
|
||||
}
|
||||
let raw = resp
|
||||
.json::<RawState>()
|
||||
.await
|
||||
.map_err(|e| ProbeFailure::server(format!("实体响应解析失败:{e}")))?;
|
||||
Ok(to_summary(raw))
|
||||
}
|
||||
|
||||
/// 从 HA 的错误响应里抠出可读的 `message`(响应不是 JSON 时退化为原文截断)。
|
||||
fn extract_message(text: &str) -> String {
|
||||
let parsed = serde_json::from_str::<serde_json::Value>(text)
|
||||
.ok()
|
||||
.and_then(|v| v.get("message").and_then(|m| m.as_str()).map(|s| s.to_string()));
|
||||
match parsed {
|
||||
Some(m) if !m.is_empty() => m,
|
||||
_ => {
|
||||
let short: String = text.chars().take(200).collect();
|
||||
if short.is_empty() {
|
||||
"该服务不接受这些参数".to_string()
|
||||
} else {
|
||||
short
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,734 @@
|
||||
//! 智能家居模块的 Tauri 命令。
|
||||
//!
|
||||
//! 约定(同项目其它模块):命令名以模块前缀开头,错误用 `Result<_, String>`;
|
||||
//! **没有任何命令会向前端返回明文令牌** —— 只有 `tokenMasked` 与 `hasToken`。
|
||||
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tauri::{AppHandle, State};
|
||||
|
||||
use super::client;
|
||||
use super::types::{
|
||||
EndpointMode, EndpointProbe, EntityListResult, EntitySummary, HaApiError, HaConnection,
|
||||
HaConnectionInput, HaSaveConnectionResult, HaSettingsView, HaUiSettings, LinkInfo,
|
||||
RegistryResult, Rule, RuleListResult, RulesFile, ServiceCallResult, ServiceParams, WsStatus,
|
||||
};
|
||||
use super::{automation, registry, HaManager, InstanceMeta};
|
||||
|
||||
/// 读取模块设置视图(连接列表 + 偏好;令牌只有掩码)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn smarthome_get_settings(state: State<'_, HaManager>) -> Result<HaSettingsView, String> {
|
||||
Ok(state.settings_view())
|
||||
}
|
||||
|
||||
/// 新建或更新一条连接(令牌**不在**此命令里,见 `smarthome_set_token`)。
|
||||
///
|
||||
/// 地址可能刚被改动,已建立的实时连接仍粘在旧端点上 → 重连一次(P4)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_save_connection(
|
||||
app: AppHandle,
|
||||
state: State<'_, HaManager>,
|
||||
input: HaConnectionInput,
|
||||
) -> Result<HaSaveConnectionResult, String> {
|
||||
let name = input.name.trim().to_string();
|
||||
if name.is_empty() {
|
||||
return Err("请填写名称".to_string());
|
||||
}
|
||||
// 局域网默认补 http(HA 的默认端口 8123 无 TLS);反代默认补 https
|
||||
let local_url = client::normalize_url(&input.local_url, false);
|
||||
let remote_url = client::normalize_url(&input.remote_url, true);
|
||||
if local_url.is_empty() && remote_url.is_empty() {
|
||||
return Err("请至少填写一个地址(局域网或反代)".to_string());
|
||||
}
|
||||
// 保存时就校验地址:等到请求时才失败,错误信息已经离用户输入很远了
|
||||
client::validate_url(&local_url, "局域网地址")?;
|
||||
client::validate_url(&remote_url, "反代地址")?;
|
||||
|
||||
let mut settings = state.load_settings();
|
||||
let mut conn = HaConnection {
|
||||
id: input.id.trim().to_string(),
|
||||
name,
|
||||
local_url,
|
||||
remote_url,
|
||||
endpoint_mode: input.endpoint_mode,
|
||||
insecure: input.insecure,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// 只配了一个地址时把策略收敛到对应模式:不必让用户理解 auto 的含义
|
||||
if conn.endpoint_mode == EndpointMode::Auto {
|
||||
match (conn.local_url.is_empty(), conn.remote_url.is_empty()) {
|
||||
(true, false) => conn.endpoint_mode = EndpointMode::Remote,
|
||||
(false, true) => conn.endpoint_mode = EndpointMode::Local,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// 强制模式与地址必须自洽:否则要到"检测链路"时才报"未配置该地址",错误离用户输入太远
|
||||
if conn.endpoint_mode == EndpointMode::Local && conn.local_url.is_empty() {
|
||||
return Err("端点策略选了「仅局域网」,但没填局域网地址".to_string());
|
||||
}
|
||||
if conn.endpoint_mode == EndpointMode::Remote && conn.remote_url.is_empty() {
|
||||
return Err("端点策略选了「仅反代」,但没填反代地址".to_string());
|
||||
}
|
||||
|
||||
if conn.id.is_empty() {
|
||||
conn.id = new_conn_id();
|
||||
}
|
||||
|
||||
// 运行期信息(上次成功 / HA 版本 / 实例名)不随编辑清空
|
||||
if let Some(existing) = settings.connection(&conn.id) {
|
||||
conn.last_ok_url = existing.last_ok_url.clone();
|
||||
conn.last_ok_at = existing.last_ok_at;
|
||||
conn.ha_version = existing.ha_version.clone();
|
||||
conn.location_name = existing.location_name.clone();
|
||||
}
|
||||
|
||||
let id = conn.id.clone();
|
||||
let is_new = !settings.connections.iter().any(|c| c.id == id);
|
||||
match settings.connections.iter_mut().find(|c| c.id == id) {
|
||||
Some(slot) => *slot = conn,
|
||||
None => settings.connections.push(conn),
|
||||
}
|
||||
if settings.active_id.is_empty() {
|
||||
settings.active_id = id.clone();
|
||||
}
|
||||
// 首次保存连接时**默认打开实时连接**:按设备 / 按房间浏览、状态实时更新、
|
||||
// 本地规则触发都依赖 WebSocket,默认关闭会让第一次打开模块的人看到一个
|
||||
// "什么都点不了"的设备页。用户仍可在设置页显式关掉。
|
||||
if is_new && !settings.realtime.enabled {
|
||||
settings.realtime.enabled = true;
|
||||
settings.realtime.last_connected_at = chrono::Utc::now().timestamp();
|
||||
}
|
||||
state.save_settings(settings)?;
|
||||
// 地址可能刚被改动:缓存里的端点可能已经不适用了
|
||||
state.clear_endpoint_cache();
|
||||
restart_ws(&app, &state).await;
|
||||
Ok(HaSaveConnectionResult {
|
||||
id,
|
||||
settings: state.settings_view(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 写入长期访问令牌(进系统凭据管理器,**不落 settings.json**)。
|
||||
///
|
||||
/// 令牌换了,已经建立的实时连接用的还是旧令牌 → 重连一次。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_set_token(
|
||||
app: AppHandle,
|
||||
state: State<'_, HaManager>,
|
||||
conn_id: String,
|
||||
token: String,
|
||||
) -> Result<HaSettingsView, String> {
|
||||
if state.load_settings().connection(&conn_id).is_none() {
|
||||
return Err("该连接不存在".to_string());
|
||||
}
|
||||
let t = token.trim();
|
||||
if t.is_empty() {
|
||||
return Err("请填写访问令牌".to_string());
|
||||
}
|
||||
state.set_token(&conn_id, t)?;
|
||||
restart_ws(&app, &state).await;
|
||||
Ok(state.settings_view())
|
||||
}
|
||||
|
||||
/// 清除令牌(连接本身保留)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_clear_token(
|
||||
app: AppHandle,
|
||||
state: State<'_, HaManager>,
|
||||
conn_id: String,
|
||||
) -> Result<HaSettingsView, String> {
|
||||
state.clear_token(&conn_id)?;
|
||||
restart_ws(&app, &state).await;
|
||||
Ok(state.settings_view())
|
||||
}
|
||||
|
||||
/// 删除一条连接(连带清除它的令牌)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_delete_connection(
|
||||
app: AppHandle,
|
||||
state: State<'_, HaManager>,
|
||||
conn_id: String,
|
||||
) -> Result<HaSettingsView, String> {
|
||||
let mut settings = state.load_settings();
|
||||
settings.connections.retain(|c| c.id != conn_id);
|
||||
if settings.active_id == conn_id {
|
||||
settings.active_id = settings
|
||||
.connections
|
||||
.first()
|
||||
.map(|c| c.id.clone())
|
||||
.unwrap_or_default();
|
||||
}
|
||||
state.save_settings(settings)?;
|
||||
// 凭据库里那条令牌也要清掉:连接都删了,留着它是纯粹的残留
|
||||
if let Err(e) = state.clear_token(&conn_id) {
|
||||
crate::logger::log_warn("smarthome", &format!("删除连接时清理令牌失败:{e}"));
|
||||
}
|
||||
state.clear_endpoint_cache();
|
||||
state.clear_entities_cache();
|
||||
state.clear_registry_cache();
|
||||
restart_ws(&app, &state).await;
|
||||
Ok(state.settings_view())
|
||||
}
|
||||
|
||||
/// 切换激活连接。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_activate_connection(
|
||||
app: AppHandle,
|
||||
state: State<'_, HaManager>,
|
||||
conn_id: String,
|
||||
) -> Result<HaSettingsView, String> {
|
||||
let mut settings = state.load_settings();
|
||||
if settings.connection(&conn_id).is_none() {
|
||||
return Err("该连接不存在".to_string());
|
||||
}
|
||||
settings.active_id = conn_id;
|
||||
state.save_settings(settings)?;
|
||||
state.clear_endpoint_cache();
|
||||
// 房间 / 实体都属于"上一条连接",切连接必须一并作废
|
||||
state.clear_entities_cache();
|
||||
state.clear_registry_cache();
|
||||
restart_ws(&app, &state).await;
|
||||
Ok(state.settings_view())
|
||||
}
|
||||
|
||||
/// 修改端点选择策略(auto / local / remote)。
|
||||
///
|
||||
/// 策略变了,实时连接也应当按新策略重新选端点 → 重连一次。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_set_endpoint_mode(
|
||||
app: AppHandle,
|
||||
state: State<'_, HaManager>,
|
||||
conn_id: String,
|
||||
mode: EndpointMode,
|
||||
) -> Result<HaSettingsView, String> {
|
||||
let mut settings = state.load_settings();
|
||||
let conn = settings
|
||||
.connections
|
||||
.iter_mut()
|
||||
.find(|c| c.id == conn_id)
|
||||
.ok_or_else(|| "该连接不存在".to_string())?;
|
||||
conn.endpoint_mode = mode;
|
||||
state.save_settings(settings)?;
|
||||
state.clear_endpoint_cache();
|
||||
restart_ws(&app, &state).await;
|
||||
Ok(state.settings_view())
|
||||
}
|
||||
|
||||
/// 测试连接:**逐个地址**探测,每个地址各给一条结果。
|
||||
///
|
||||
/// `token` 留空时回落到该连接已存的令牌(编辑连接时不必重输)。
|
||||
/// 草案也能直接测(不必先保存)——`input.id` 为空只是没有回落令牌可用。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_test_connection(
|
||||
state: State<'_, HaManager>,
|
||||
input: HaConnectionInput,
|
||||
token: String,
|
||||
) -> Result<Vec<EndpointProbe>, String> {
|
||||
let stored = if input.id.trim().is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
state.token(input.id.trim())
|
||||
};
|
||||
let token = if token.trim().is_empty() {
|
||||
stored
|
||||
} else {
|
||||
token.trim().to_string()
|
||||
};
|
||||
if token.is_empty() {
|
||||
return Err("请填写访问令牌".to_string());
|
||||
}
|
||||
|
||||
let local_url = client::normalize_url(&input.local_url, false);
|
||||
let remote_url = client::normalize_url(&input.remote_url, true);
|
||||
if local_url.is_empty() && remote_url.is_empty() {
|
||||
return Err("请至少填写一个地址(局域网或反代)".to_string());
|
||||
}
|
||||
client::validate_url(&local_url, "局域网地址")?;
|
||||
client::validate_url(&remote_url, "反代地址")?;
|
||||
|
||||
let probes = client::probe_all(&local_url, &remote_url, &token, input.insecure).await;
|
||||
|
||||
// 测的是已保存的连接,且有一条成功 → 记下"上次成功"(含版本 / 实例名 / 温度单位)
|
||||
let conn_id = input.id.trim();
|
||||
if !conn_id.is_empty() {
|
||||
if let Some(ok) = probes.iter().find(|p| p.ok) {
|
||||
let meta = InstanceMeta {
|
||||
ha_version: ok.ha_version.clone(),
|
||||
location_name: ok.location_name.clone(),
|
||||
temperature_unit: ok.temperature_unit.clone(),
|
||||
};
|
||||
if let Err(e) = state.mark_ok(conn_id, &ok.url, &meta) {
|
||||
crate::logger::log_warn("smarthome", &format!("记录上次成功失败:{e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(probes)
|
||||
}
|
||||
|
||||
/// 检测当前链路:按端点策略**强制新探测**一次,返回实际使用的地址与耗时。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_check_link(
|
||||
state: State<'_, HaManager>,
|
||||
conn_id: String,
|
||||
) -> Result<LinkInfo, String> {
|
||||
let conn = state
|
||||
.load_settings()
|
||||
.connection(&conn_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| "该连接不存在".to_string())?;
|
||||
match state.resolve_fresh(&conn).await {
|
||||
Ok((url, kind, latency_ms)) => {
|
||||
// 顺带取一次实例信息(版本 / 名称 / 温度单位):只有「检测链路」这个显式动作需要它,
|
||||
// 取到就记进设置,设置页与设备页因此不必再单独请求 /api/config。
|
||||
let meta = {
|
||||
let token = state.token(&conn_id);
|
||||
match client::fetch_meta(&url, &token, conn.insecure, kind).await {
|
||||
Ok((version, location, unit)) => InstanceMeta {
|
||||
ha_version: version,
|
||||
location_name: location,
|
||||
temperature_unit: unit,
|
||||
},
|
||||
Err(e) => {
|
||||
crate::logger::log_warn(
|
||||
"smarthome",
|
||||
&format!("读取 HA 实例信息失败(不影响链路判定):{}", e.message),
|
||||
);
|
||||
InstanceMeta::default()
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Err(e) = state.mark_ok(&conn_id, &url, &meta) {
|
||||
crate::logger::log_warn("smarthome", &format!("记录上次成功失败:{e}"));
|
||||
}
|
||||
Ok(LinkInfo {
|
||||
url: Some(url),
|
||||
kind: Some(kind),
|
||||
ok: true,
|
||||
latency_ms,
|
||||
error: None,
|
||||
error_kind: None,
|
||||
})
|
||||
}
|
||||
Err(e) => Ok(LinkInfo {
|
||||
url: None,
|
||||
kind: None,
|
||||
ok: false,
|
||||
latency_ms: 0,
|
||||
error: Some(e.message),
|
||||
error_kind: Some(e.kind.to_string()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// 拉取实体列表(精简视图)。
|
||||
///
|
||||
/// `force = false` 且内存缓存未过期(60s)时直接返回缓存 —— 在反代链路上,
|
||||
/// 每次切回设备页都重新拉几百 KB 是明显的浪费(§5.2)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_list_entities(
|
||||
state: State<'_, HaManager>,
|
||||
conn_id: String,
|
||||
force: bool,
|
||||
) -> Result<EntityListResult, HaApiError> {
|
||||
let conn = state
|
||||
.load_settings()
|
||||
.connection(&conn_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| HaApiError::new("config", "该连接不存在"))?;
|
||||
|
||||
if !force {
|
||||
if let Some((entities, fetched_at)) = state.cached_entities(&conn_id) {
|
||||
return Ok(EntityListResult {
|
||||
entities,
|
||||
fetched_at,
|
||||
from_cache: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let (url, kind, _latency) = state.resolve(&conn).await.map_err(to_api_error)?;
|
||||
let token = state.token(&conn_id);
|
||||
|
||||
// 首次进入还不知道实例信息?顺带取一次 `/api/config`。
|
||||
// 温度单位必须从实例读(`°F` 的实例上写死 `°C` 会显示成"77°C"),
|
||||
// 而它只在"还不知道"时才需要这一跳;之后 `ha_version` 有了就不再请求。
|
||||
if conn.ha_version.is_empty() {
|
||||
match client::fetch_meta(&url, &token, conn.insecure, kind).await {
|
||||
Ok((version, location, unit)) => {
|
||||
let meta = InstanceMeta {
|
||||
ha_version: version,
|
||||
location_name: location,
|
||||
temperature_unit: unit,
|
||||
};
|
||||
if let Err(e) = state.mark_ok(&conn_id, &url, &meta) {
|
||||
crate::logger::log_warn("smarthome", &format!("记录实例信息失败:{e}"));
|
||||
}
|
||||
}
|
||||
Err(e) => crate::logger::log_warn(
|
||||
"smarthome",
|
||||
&format!("读取实例信息失败(不影响设备列表):{}", e.message),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
match client::fetch_entities(&url, &token, conn.insecure, kind).await {
|
||||
Ok(entities) => {
|
||||
let fetched_at = chrono::Utc::now().timestamp();
|
||||
state.store_entities(&conn_id, entities.clone());
|
||||
if let Err(e) = state.mark_ok(&conn_id, &url, &InstanceMeta::default()) {
|
||||
crate::logger::log_warn("smarthome", &format!("记录上次成功失败:{e}"));
|
||||
}
|
||||
Ok(EntityListResult {
|
||||
entities,
|
||||
fetched_at,
|
||||
from_cache: false,
|
||||
})
|
||||
}
|
||||
Err(f) => {
|
||||
// 端点可能已经不可用(出门 / 断网 / 隧道挂了):清掉,让下次请求重新探测
|
||||
state.clear_endpoint_cache();
|
||||
if f.fatal_auth {
|
||||
// 令牌失效时旧数据不再可信,留着会让下次把它误当成"还能用"
|
||||
state.clear_entities_cache();
|
||||
}
|
||||
Err(HaApiError::new(f.kind, f.message))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 保存界面偏好(自动刷新间隔 / 收藏等)。
|
||||
///
|
||||
/// 整体覆盖写入:偏好字段少且同屏修改,没必要为每个开关单开一条命令
|
||||
/// (多命令各自的字段同步反倒容易漏)。
|
||||
///
|
||||
/// 注意:**实时推送开关不在 `ui` 里**(它在 `settings.realtime`),
|
||||
/// 因此这里不碰实时连接;收藏 / 自动刷新这类改动不该引起重连。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn smarthome_save_ui_settings(
|
||||
state: State<'_, HaManager>,
|
||||
ui: HaUiSettings,
|
||||
) -> Result<HaSettingsView, String> {
|
||||
let mut settings = state.load_settings();
|
||||
settings.ui = ui;
|
||||
// heal 里会把非法的 autoRefreshSec 收敛回 0
|
||||
state.save_settings(settings)?;
|
||||
Ok(state.settings_view())
|
||||
}
|
||||
|
||||
/// 开关实时推送(WebSocket)。
|
||||
///
|
||||
/// 打开 = 建立 WS(设备状态不再依赖手动刷新);关闭 = 断开。
|
||||
/// **本地规则也依赖它**:只要规则总开关开着,关掉推送 Rust 侧仍会保持连接
|
||||
/// (见 `HaManager::sync_ws`)—— 规则没连接永远不会触发。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_set_realtime_enabled(
|
||||
app: AppHandle,
|
||||
state: State<'_, HaManager>,
|
||||
enabled: bool,
|
||||
) -> Result<HaSettingsView, String> {
|
||||
let mut settings = state.load_settings();
|
||||
if settings.realtime.enabled == enabled {
|
||||
return Ok(state.settings_view());
|
||||
}
|
||||
settings.realtime.enabled = enabled;
|
||||
if enabled {
|
||||
settings.realtime.last_connected_at = chrono::Utc::now().timestamp();
|
||||
}
|
||||
state.save_settings(settings)?;
|
||||
// 用 `sync_ws` 而不是 `restart_ws`:关掉推送但本地规则总开关还开着时,
|
||||
// 连接本来就该保留 —— `sync_ws` 会据此保持不动,不会做无谓的重连。
|
||||
state.sync_ws(&app).await;
|
||||
Ok(state.settings_view())
|
||||
}
|
||||
|
||||
/// `client::ResolveFailure` → 命令层错误(保留分类)。
|
||||
fn to_api_error(e: client::ResolveFailure) -> HaApiError {
|
||||
HaApiError::new(e.kind, e.message)
|
||||
}
|
||||
|
||||
/// 调用设备服务(控制)。
|
||||
///
|
||||
/// 前端流程(§5.3):乐观更新 → 本命令 → **若响应带回新状态就直接采用**(省一次往返),
|
||||
/// 否则在分级窗口后调 `smarthome_get_entity` 校正。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_call_service(
|
||||
state: State<'_, HaManager>,
|
||||
conn_id: String,
|
||||
domain: String,
|
||||
service: String,
|
||||
entity_id: String,
|
||||
params: ServiceParams,
|
||||
) -> Result<ServiceCallResult, HaApiError> {
|
||||
let conn = state
|
||||
.load_settings()
|
||||
.connection(&conn_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| HaApiError::new("config", "该连接不存在"))?;
|
||||
let domain = domain.trim().to_string();
|
||||
let service = service.trim().to_string();
|
||||
let entity_id = entity_id.trim().to_string();
|
||||
if domain.is_empty() || service.is_empty() || entity_id.is_empty() {
|
||||
return Err(HaApiError::new(
|
||||
"badRequest",
|
||||
"domain / service / entity_id 都不能为空",
|
||||
));
|
||||
}
|
||||
|
||||
let (url, kind, _latency) = state.resolve(&conn).await.map_err(to_api_error)?;
|
||||
let token = state.token(&conn_id);
|
||||
match client::call_service(
|
||||
&url, &token, conn.insecure, kind, &domain, &service, &entity_id, ¶ms,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(entities) => {
|
||||
// 缓存要与 UI 保持一致:带回新状态就并进去,没带回就整份作废
|
||||
// (否则"开灯 → 切页 → 切回来"会看到控制前的旧状态)
|
||||
if entities.is_empty() {
|
||||
state.clear_entities_cache();
|
||||
} else {
|
||||
state.merge_entities(&conn_id, &entities);
|
||||
}
|
||||
if let Err(e) = state.mark_ok(&conn_id, &url, &InstanceMeta::default()) {
|
||||
crate::logger::log_warn("smarthome", &format!("记录上次成功失败:{e}"));
|
||||
}
|
||||
Ok(ServiceCallResult { entities })
|
||||
}
|
||||
Err(f) => {
|
||||
state.clear_endpoint_cache();
|
||||
if f.fatal_auth {
|
||||
state.clear_entities_cache();
|
||||
}
|
||||
Err(HaApiError::new(f.kind, f.message))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 取单个实体状态(控制后的校正用,不是常规路径)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_get_entity(
|
||||
state: State<'_, HaManager>,
|
||||
conn_id: String,
|
||||
entity_id: String,
|
||||
) -> Result<EntitySummary, HaApiError> {
|
||||
let conn = state
|
||||
.load_settings()
|
||||
.connection(&conn_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| HaApiError::new("config", "该连接不存在"))?;
|
||||
let (url, kind, _latency) = state.resolve(&conn).await.map_err(to_api_error)?;
|
||||
let token = state.token(&conn_id);
|
||||
match client::fetch_entity(&url, &token, conn.insecure, kind, entity_id.trim()).await {
|
||||
Ok(e) => {
|
||||
state.merge_entities(&conn_id, std::slice::from_ref(&e));
|
||||
Ok(e)
|
||||
}
|
||||
Err(f) => {
|
||||
if !f.fatal_auth {
|
||||
state.clear_endpoint_cache();
|
||||
}
|
||||
Err(HaApiError::new(f.kind, f.message))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 新建连接 id(不依赖 uuid crate,同 music 的 `new_conn_id` 做法)。
|
||||
fn new_conn_id() -> String {
|
||||
let n = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0);
|
||||
format!("h{n:x}")
|
||||
}
|
||||
|
||||
/// 新建规则 id。
|
||||
fn new_rule_id() -> String {
|
||||
let n = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0);
|
||||
format!("r{n:x}")
|
||||
}
|
||||
|
||||
/// 端点 / 令牌 / 连接发生变化后:先停当前的实时连接,再按需重连。
|
||||
///
|
||||
/// 必须"先停再起"而不是直接 `sync_ws`:`sync_ws` 对**同一个**连接是幂等的(不动它),
|
||||
/// 而这里恰恰要重连 —— 换了令牌或换了链路却继续粘在旧连接上是最坏的结果
|
||||
/// (UI 显示着新配置,实际走的是老链路)。
|
||||
async fn restart_ws(app: &AppHandle, state: &State<'_, HaManager>) {
|
||||
state.stop_ws();
|
||||
state.sync_ws(app).await;
|
||||
}
|
||||
|
||||
/// 落盘规则文件并更新内存。
|
||||
///
|
||||
/// 同步磁盘 IO 丢到阻塞线程池(编辑器模块的教训:在异步线程里直接读写文件
|
||||
/// 会占住 IPC 线程)。
|
||||
async fn persist_rules(state: &State<'_, HaManager>, file: RulesFile) -> Result<(), String> {
|
||||
let path = state.rules_path();
|
||||
let snapshot = file.clone();
|
||||
tauri::async_runtime::spawn_blocking(move || automation::save(&path, &snapshot))
|
||||
.await
|
||||
.map_err(|e| format!("保存规则失败:{e}"))??;
|
||||
state.set_rules_memory(file);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ============================== P4:实时连接命令 ==============================
|
||||
|
||||
/// 启动实时连接(显式动作)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_ws_start(
|
||||
app: AppHandle,
|
||||
state: State<'_, HaManager>,
|
||||
conn_id: String,
|
||||
) -> Result<WsStatus, String> {
|
||||
let conn = state
|
||||
.load_settings()
|
||||
.connection(&conn_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| "该连接不存在".to_string())?;
|
||||
state.start_ws(&app, &conn).await
|
||||
}
|
||||
|
||||
/// 停止实时连接(**不改持久化开关**:设置页的开关走 `smarthome_set_realtime_enabled`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn smarthome_ws_stop(state: State<'_, HaManager>) -> WsStatus {
|
||||
state.stop_ws();
|
||||
state.ws_status()
|
||||
}
|
||||
|
||||
/// 当前实时连接状态(诊断用)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn smarthome_ws_status(state: State<'_, HaManager>) -> WsStatus {
|
||||
state.ws_status()
|
||||
}
|
||||
|
||||
// ============================== P4:注册表(房间分组) ==============================
|
||||
|
||||
/// 拉取区域 / 设备 / 实体注册表,返回 `entity_id → area_id`(三级回退已算好)。
|
||||
///
|
||||
/// **需要实时连接**:注册表只能通过 WebSocket 查(plan §0.4),因此这里显式依赖
|
||||
/// `smarthome_ws_start` 已经连上;没连上就给出可操作的错误文案(不是笼统的"失败")。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_list_registry(
|
||||
state: State<'_, HaManager>,
|
||||
conn_id: String,
|
||||
force: bool,
|
||||
) -> Result<RegistryResult, HaApiError> {
|
||||
if let Some(cached) = state.cached_registry(&conn_id, force) {
|
||||
return Ok(cached);
|
||||
}
|
||||
let Some(handle) = state.ws_handle() else {
|
||||
return Err(HaApiError::new(
|
||||
"ws",
|
||||
"房间分组需要实时连接:请在设置页开启「实时推送」",
|
||||
));
|
||||
};
|
||||
if handle.conn_id != conn_id {
|
||||
return Err(HaApiError::new(
|
||||
"ws",
|
||||
"实时连接属于另一条连接,请先切换回该连接",
|
||||
));
|
||||
}
|
||||
let registry = registry::fetch(&handle)
|
||||
.await
|
||||
.map_err(|e| HaApiError::new("ws", e))?;
|
||||
state.store_registry(&conn_id, registry.clone());
|
||||
Ok(registry)
|
||||
}
|
||||
|
||||
// ============================== P4:本地规则命令 ==============================
|
||||
|
||||
/// 规则列表(含总开关与最近运行记录)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn smarthome_list_rules(state: State<'_, HaManager>) -> RuleListResult {
|
||||
state.rules_result()
|
||||
}
|
||||
|
||||
/// 新建或更新一条规则。
|
||||
///
|
||||
/// **动作的合法性只在 Rust 侧判定一次**(`automation::validate`):前端可以少校验,
|
||||
/// 但"能不能真的执行"这套规则必须只有一份。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_save_rule(
|
||||
app: AppHandle,
|
||||
state: State<'_, HaManager>,
|
||||
rule: Rule,
|
||||
) -> Result<RuleListResult, String> {
|
||||
let mut rule = rule;
|
||||
automation::validate(&rule)?;
|
||||
if rule.id.trim().is_empty() {
|
||||
rule.id = new_rule_id();
|
||||
} else {
|
||||
rule.id = rule.id.trim().to_string();
|
||||
}
|
||||
|
||||
let mut file = state.rules_file();
|
||||
// 编辑既有规则时保留运行统计(前端提交的是"规则定义",统计属于运行期数据)
|
||||
if let Some(existing) = file.rules.iter().find(|r| r.id == rule.id) {
|
||||
rule.last_fired_at = existing.last_fired_at;
|
||||
rule.fire_count = existing.fire_count;
|
||||
rule.last_error = existing.last_error.clone();
|
||||
}
|
||||
match file.rules.iter_mut().find(|r| r.id == rule.id) {
|
||||
Some(slot) => *slot = rule,
|
||||
None => file.rules.push(rule),
|
||||
}
|
||||
persist_rules(&state, file).await?;
|
||||
// 规则总开关开着就需要实时连接(事件驱动),幂等对齐一次
|
||||
state.sync_ws(&app).await;
|
||||
Ok(state.rules_result())
|
||||
}
|
||||
|
||||
/// 删除一条规则。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_delete_rule(
|
||||
app: AppHandle,
|
||||
state: State<'_, HaManager>,
|
||||
rule_id: String,
|
||||
) -> Result<RuleListResult, String> {
|
||||
let mut file = state.rules_file();
|
||||
file.rules.retain(|r| r.id != rule_id);
|
||||
persist_rules(&state, file).await?;
|
||||
state.sync_ws(&app).await;
|
||||
Ok(state.rules_result())
|
||||
}
|
||||
|
||||
/// 规则总开关(关掉后所有规则都不求值,规则本身保留)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn smarthome_set_rules_enabled(
|
||||
app: AppHandle,
|
||||
state: State<'_, HaManager>,
|
||||
enabled: bool,
|
||||
) -> Result<RuleListResult, String> {
|
||||
let mut file = state.rules_file();
|
||||
file.enabled = enabled;
|
||||
persist_rules(&state, file).await?;
|
||||
// 打开总开关意味着"现在就要开始跑规则":它依赖 WS,因此强制对齐(必要时建连)
|
||||
state.sync_ws(&app).await;
|
||||
Ok(state.rules_result())
|
||||
}
|
||||
@@ -0,0 +1,582 @@
|
||||
//! 智能家居模块(Home Assistant):状态容器、设置持久化、会话内端点缓存。
|
||||
//!
|
||||
//! 分工:`types` 数据模型(specta 导出)· `client` HTTP 客户端与端点选择 · `commands` Tauri 命令。
|
||||
//!
|
||||
//! 目录布局(`{app_data_dir}/smarthome/`):
|
||||
//! - `settings.json` 模块设置(版本号 + 自愈)
|
||||
//!
|
||||
//! 凭据:长期访问令牌存**系统凭据管理器**,键 `smarthome-token-<connId>`,
|
||||
//! **不落 settings.json**(见 `crate::secrets` 的模块注释)。
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tauri::AppHandle;
|
||||
|
||||
use types::{
|
||||
EndpointKind, EntitySummary, HaConnection, HaConnectionView, HaSettings, HaSettingsView,
|
||||
RegistryResult, RuleListResult, RuleRecord, RulesFile, WsStatus, SECRET_PREFIX,
|
||||
};
|
||||
|
||||
pub mod automation;
|
||||
pub mod client;
|
||||
pub mod commands;
|
||||
pub mod registry;
|
||||
pub mod types;
|
||||
pub mod ws;
|
||||
|
||||
// 命令在 lib.rs 里按模块路径导入(`smarthome::smarthome_xxx`),因此在这里 re-export
|
||||
pub use commands::{
|
||||
smarthome_activate_connection, smarthome_call_service, smarthome_check_link,
|
||||
smarthome_clear_token, smarthome_delete_connection, smarthome_delete_rule,
|
||||
smarthome_get_entity, smarthome_get_settings, smarthome_list_entities, smarthome_list_registry,
|
||||
smarthome_list_rules, smarthome_save_connection, smarthome_save_rule,
|
||||
smarthome_save_ui_settings, smarthome_set_endpoint_mode, smarthome_set_realtime_enabled,
|
||||
smarthome_set_rules_enabled, smarthome_set_token, smarthome_test_connection,
|
||||
smarthome_ws_start, smarthome_ws_status, smarthome_ws_stop,
|
||||
};
|
||||
|
||||
/// 会话内端点缓存 TTL。
|
||||
///
|
||||
/// - 缓存在**局域网**上给 60s:短一点,好尽快发现"出门了"(失败也会立即重探)。
|
||||
/// - 缓存在**反代**上给 300s:此时唯一的提升空间是"回家切回局域网",
|
||||
/// 为它每分钟白花 900ms 去探局域网不值得。
|
||||
const CACHE_TTL_LOCAL: Duration = Duration::from_secs(60);
|
||||
const CACHE_TTL_REMOTE: Duration = Duration::from_secs(300);
|
||||
|
||||
/// 会话内端点缓存条目(**不落盘**:它表达的是"这次跑在哪个网络环境",
|
||||
/// 下次启动的网络环境可能完全不同,落盘只会让人先走错一次)。
|
||||
struct CachedEndpoint {
|
||||
conn_id: String,
|
||||
url: String,
|
||||
kind: EndpointKind,
|
||||
latency_ms: u64,
|
||||
at: Instant,
|
||||
}
|
||||
|
||||
/// 实体列表内存缓存(**不落盘**)。
|
||||
///
|
||||
/// 理由同 §3.7-c:智能家居里"显示灯已关、实际还亮着"的误导比"多等一秒"糟得多,
|
||||
/// 所以不把可能过期的状态持久化。这里只是省掉"切走再切回设备页就重拉一次全量"
|
||||
/// 的那次请求(在反代链路上那是几百 KB)。
|
||||
struct EntityCache {
|
||||
conn_id: String,
|
||||
entities: Vec<EntitySummary>,
|
||||
fetched_at: i64,
|
||||
}
|
||||
|
||||
/// 实体缓存 TTL(秒)—— 约束的是"多久之内不重新拉全量"。
|
||||
const ENTITY_CACHE_TTL_SECS: i64 = 60;
|
||||
|
||||
/// 注册表缓存 TTL(秒)。
|
||||
///
|
||||
/// 房间归属变化极少(用户在 HA 里改名 / 挪设备才会变),给 5 分钟足够;
|
||||
/// 而且每次查注册表在反代上是 3 个来回(约 2s),不该每次进设备页都查一遍。
|
||||
const REGISTRY_CACHE_TTL_SECS: i64 = 300;
|
||||
|
||||
/// 一次成功通信里学到的实例信息(版本 / 实例名 / 温度单位)。
|
||||
///
|
||||
/// 数据请求(拉实体、调服务)只带空的那份 —— 它们不请求 `/api/config`,
|
||||
/// 因此 `mark_ok` 里**空值不覆盖旧值**,免得把已经记住的元信息抹掉。
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct InstanceMeta {
|
||||
pub ha_version: String,
|
||||
pub location_name: String,
|
||||
pub temperature_unit: String,
|
||||
}
|
||||
|
||||
/// 智能家居模块管理器(Tauri State)。
|
||||
pub struct HaManager {
|
||||
/// 模块目录 `{app_data_dir}/smarthome`
|
||||
module_dir: PathBuf,
|
||||
/// 设置(内存为真相;写盘即同步)
|
||||
settings: Mutex<HaSettings>,
|
||||
/// 端点选择缓存
|
||||
endpoint_cache: Mutex<Option<CachedEndpoint>>,
|
||||
/// 实体列表缓存
|
||||
entity_cache: Mutex<Option<EntityCache>>,
|
||||
// ---------- P4 ----------
|
||||
/// 运行中的 WebSocket 连接(生命周期归属应用,Tab 切走不关)
|
||||
ws: Mutex<Option<ws::WsHandle>>,
|
||||
/// 最近一次 WS 启动失败原因(没有运行中的连接时用于诊断)
|
||||
ws_error: Mutex<String>,
|
||||
/// 本地规则(内存为真相;与 WS 任务共享同一份 Arc)
|
||||
rules: Arc<Mutex<RulesFile>>,
|
||||
/// 规则运行记录(内存环形,最多 `automation::MAX_RECORDS` 条)
|
||||
records: Arc<Mutex<VecDeque<RuleRecord>>>,
|
||||
/// 规则突发护栏用的最近触发时刻(与 WS 任务共享)
|
||||
recent: Arc<Mutex<VecDeque<(String, Instant)>>>,
|
||||
/// 注册表缓存(房间分组,不落盘)。**带 connId**:房间归属是每条连接各自的,
|
||||
/// 切了实例还返回上一实例的房间,用户会看到"房间名全对不上、筛选后一片空白"。
|
||||
registry_cache: Mutex<Option<(String, RegistryResult)>>,
|
||||
}
|
||||
|
||||
impl HaManager {
|
||||
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||
let module_dir = app_data_dir.join("smarthome");
|
||||
if let Err(e) = std::fs::create_dir_all(&module_dir) {
|
||||
crate::logger::log_warn("smarthome", &format!("创建模块目录失败:{e}"));
|
||||
}
|
||||
let mut settings: HaSettings = std::fs::read_to_string(module_dir.join("settings.json"))
|
||||
.ok()
|
||||
.and_then(|t| serde_json::from_str(&t).ok())
|
||||
.unwrap_or_default();
|
||||
if settings.heal() {
|
||||
// 首次启动(version = 0)也走这里:落一份带版本号的默认设置
|
||||
let _ = write_settings_file(&module_dir, &settings);
|
||||
}
|
||||
// 规则文件:**启动阶段不建文件**(还没人用过本地规则时不必产生空文件)
|
||||
let rules = automation::load(&module_dir.join("automations.json"));
|
||||
Self {
|
||||
module_dir,
|
||||
settings: Mutex::new(settings),
|
||||
endpoint_cache: Mutex::new(None),
|
||||
entity_cache: Mutex::new(None),
|
||||
ws: Mutex::new(None),
|
||||
ws_error: Mutex::new(String::new()),
|
||||
rules: Arc::new(Mutex::new(rules)),
|
||||
records: Arc::new(Mutex::new(VecDeque::new())),
|
||||
recent: Arc::new(Mutex::new(VecDeque::new())),
|
||||
registry_cache: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 设置 ----------
|
||||
|
||||
pub fn load_settings(&self) -> HaSettings {
|
||||
match self.settings.lock() {
|
||||
Ok(s) => s.clone(),
|
||||
Err(e) => {
|
||||
crate::logger::log_error("smarthome", &format!("设置锁中毒:{e}"));
|
||||
HaSettings::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save_settings(&self, mut next: HaSettings) -> Result<(), String> {
|
||||
next.heal();
|
||||
write_settings_file(&self.module_dir, &next)?;
|
||||
if let Ok(mut s) = self.settings.lock() {
|
||||
*s = next;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------- 令牌(系统凭据管理器) ----------
|
||||
|
||||
fn token_key(conn_id: &str) -> String {
|
||||
format!("{SECRET_PREFIX}{conn_id}")
|
||||
}
|
||||
|
||||
/// 读取明文令牌,失败/未配置一律退化为空串(调用方无需区分两者)。
|
||||
pub fn token(&self, conn_id: &str) -> String {
|
||||
crate::secrets::read_or_empty(&Self::token_key(conn_id))
|
||||
}
|
||||
|
||||
pub fn set_token(&self, conn_id: &str, token: &str) -> Result<(), String> {
|
||||
crate::secrets::secret_write(&Self::token_key(conn_id), token)
|
||||
}
|
||||
|
||||
pub fn clear_token(&self, conn_id: &str) -> Result<(), String> {
|
||||
crate::secrets::secret_delete(&Self::token_key(conn_id))
|
||||
}
|
||||
|
||||
// ---------- 视图 ----------
|
||||
|
||||
pub fn connection_view(&self, conn: &HaConnection) -> HaConnectionView {
|
||||
let token = self.token(&conn.id);
|
||||
let cached = self.cached_endpoint(&conn.id);
|
||||
HaConnectionView {
|
||||
id: conn.id.clone(),
|
||||
name: conn.name.clone(),
|
||||
local_url: conn.local_url.clone(),
|
||||
remote_url: conn.remote_url.clone(),
|
||||
endpoint_mode: conn.endpoint_mode,
|
||||
insecure: conn.insecure,
|
||||
has_token: !token.is_empty(),
|
||||
token_masked: crate::secrets::mask(&token),
|
||||
last_ok_url: conn.last_ok_url.clone(),
|
||||
last_ok_at: conn.last_ok_at,
|
||||
ha_version: conn.ha_version.clone(),
|
||||
location_name: conn.location_name.clone(),
|
||||
temperature_unit: conn.temperature_unit.clone(),
|
||||
endpoint_url: cached.as_ref().map(|c| c.0.clone()),
|
||||
endpoint_kind: cached.as_ref().map(|c| c.1),
|
||||
endpoint_latency_ms: cached.as_ref().map(|c| c.2),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn settings_view(&self) -> HaSettingsView {
|
||||
let s = self.load_settings();
|
||||
HaSettingsView {
|
||||
version: s.version,
|
||||
active_id: s.active_id.clone(),
|
||||
connections: s
|
||||
.connections
|
||||
.iter()
|
||||
.map(|c| self.connection_view(c))
|
||||
.collect(),
|
||||
ui: s.ui.clone(),
|
||||
realtime: s.realtime.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 端点缓存 ----------
|
||||
|
||||
pub fn cached_endpoint(&self, conn_id: &str) -> Option<(String, EndpointKind, u64)> {
|
||||
let guard = self.endpoint_cache.lock().ok()?;
|
||||
let c = guard.as_ref()?;
|
||||
if c.conn_id != conn_id {
|
||||
return None;
|
||||
}
|
||||
let ttl = if c.kind == EndpointKind::Local {
|
||||
CACHE_TTL_LOCAL
|
||||
} else {
|
||||
CACHE_TTL_REMOTE
|
||||
};
|
||||
if c.at.elapsed() > ttl {
|
||||
return None;
|
||||
}
|
||||
Some((c.url.clone(), c.kind, c.latency_ms))
|
||||
}
|
||||
|
||||
fn store_endpoint(&self, conn_id: &str, url: &str, kind: EndpointKind, latency_ms: u64) {
|
||||
if let Ok(mut c) = self.endpoint_cache.lock() {
|
||||
*c = Some(CachedEndpoint {
|
||||
conn_id: conn_id.to_string(),
|
||||
url: url.to_string(),
|
||||
kind,
|
||||
latency_ms,
|
||||
at: Instant::now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 失效端点缓存。触发点:地址被改动、请求失败、用户手动重探。
|
||||
pub fn clear_endpoint_cache(&self) {
|
||||
if let Ok(mut c) = self.endpoint_cache.lock() {
|
||||
*c = None;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 实体缓存 ----------
|
||||
|
||||
/// 读取**未过期**的实体缓存(过期视为未命中)。
|
||||
pub fn cached_entities(&self, conn_id: &str) -> Option<(Vec<EntitySummary>, i64)> {
|
||||
let guard = self.entity_cache.lock().ok()?;
|
||||
let c = guard.as_ref()?;
|
||||
if c.conn_id != conn_id {
|
||||
return None;
|
||||
}
|
||||
if chrono::Utc::now().timestamp() - c.fetched_at > ENTITY_CACHE_TTL_SECS {
|
||||
return None;
|
||||
}
|
||||
Some((c.entities.clone(), c.fetched_at))
|
||||
}
|
||||
|
||||
pub fn store_entities(&self, conn_id: &str, entities: Vec<EntitySummary>) {
|
||||
if let Ok(mut c) = self.entity_cache.lock() {
|
||||
*c = Some(EntityCache {
|
||||
conn_id: conn_id.to_string(),
|
||||
entities,
|
||||
fetched_at: chrono::Utc::now().timestamp(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 清空实体缓存。触发点:令牌失效(旧数据不再可信)、删除连接。
|
||||
pub fn clear_entities_cache(&self) {
|
||||
if let Ok(mut c) = self.entity_cache.lock() {
|
||||
*c = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// 把控制命令带回的新状态并进缓存。
|
||||
///
|
||||
/// 必须做,否则会出现这种误导:开灯 → 切到设置页 → 切回设备页(60s 内命中缓存)
|
||||
/// → 又显示"灯是关的"。响应没带回状态时(部分云端集成)调用方应改为清缓存。
|
||||
pub fn merge_entities(&self, conn_id: &str, changed: &[EntitySummary]) {
|
||||
if changed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Ok(mut guard) = self.entity_cache.lock() else {
|
||||
return;
|
||||
};
|
||||
let Some(cache) = guard.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if cache.conn_id != conn_id {
|
||||
return;
|
||||
}
|
||||
for e in changed {
|
||||
match cache.entities.iter_mut().find(|x| x.entity_id == e.entity_id) {
|
||||
Some(slot) => *slot = e.clone(),
|
||||
None => cache.entities.push(e.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析当前端点(命中会话缓存则不再探测)。
|
||||
///
|
||||
/// 数据请求走这里;**失败时必须调用 `clear_endpoint_cache()`**,
|
||||
/// 否则会一直粘在一个已经不可用的端点上。
|
||||
pub async fn resolve(
|
||||
&self,
|
||||
conn: &HaConnection,
|
||||
) -> Result<(String, EndpointKind, u64), client::ResolveFailure> {
|
||||
if let Some(hit) = self.cached_endpoint(&conn.id) {
|
||||
return Ok(hit);
|
||||
}
|
||||
self.resolve_fresh(conn).await
|
||||
}
|
||||
|
||||
/// 强制重新探测(「检测链路」按钮、以及缓存未命中时)。
|
||||
pub async fn resolve_fresh(
|
||||
&self,
|
||||
conn: &HaConnection,
|
||||
) -> Result<(String, EndpointKind, u64), client::ResolveFailure> {
|
||||
let token = self.token(&conn.id);
|
||||
if token.is_empty() {
|
||||
return Err(client::ResolveFailure {
|
||||
kind: "auth",
|
||||
message: "尚未配置访问令牌".to_string(),
|
||||
});
|
||||
}
|
||||
let r = client::resolve_endpoint(conn, &token).await?;
|
||||
self.store_endpoint(&conn.id, &r.url, r.kind, r.latency_ms);
|
||||
Ok((r.url, r.kind, r.latency_ms))
|
||||
}
|
||||
|
||||
/// 记录一次成功通信的结果(供设置页展示"上次成功 / HA 版本 / 实例名 / 温度单位")。
|
||||
pub fn mark_ok(
|
||||
&self,
|
||||
conn_id: &str,
|
||||
url: &str,
|
||||
meta: &InstanceMeta,
|
||||
) -> Result<(), String> {
|
||||
let mut s = self.load_settings();
|
||||
let Some(conn) = s.connections.iter_mut().find(|c| c.id == conn_id) else {
|
||||
return Ok(());
|
||||
};
|
||||
conn.last_ok_url = url.to_string();
|
||||
conn.last_ok_at = chrono::Utc::now().timestamp();
|
||||
// 空值不覆盖:数据请求带的是空 meta,不能因此把已记住的版本 / 单位抹掉
|
||||
if !meta.ha_version.is_empty() {
|
||||
conn.ha_version = meta.ha_version.clone();
|
||||
}
|
||||
if !meta.location_name.is_empty() {
|
||||
conn.location_name = meta.location_name.clone();
|
||||
}
|
||||
if !meta.temperature_unit.is_empty() {
|
||||
conn.temperature_unit = meta.temperature_unit.clone();
|
||||
}
|
||||
self.save_settings(s)
|
||||
}
|
||||
|
||||
// ---------- 本地规则(P4) ----------
|
||||
|
||||
pub fn rules_path(&self) -> PathBuf {
|
||||
self.module_dir.join("automations.json")
|
||||
}
|
||||
|
||||
/// 当前规则文件快照。
|
||||
pub fn rules_file(&self) -> RulesFile {
|
||||
match self.rules.lock() {
|
||||
Ok(g) => g.clone(),
|
||||
Err(e) => {
|
||||
crate::logger::log_error("smarthome", &format!("规则锁中毒:{e}"));
|
||||
RulesFile::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 规则列表视图(含总开关与最近运行记录)。
|
||||
pub fn rules_result(&self) -> RuleListResult {
|
||||
let file = self.rules_file();
|
||||
let records = self
|
||||
.records
|
||||
.lock()
|
||||
.map(|g| g.iter().cloned().collect())
|
||||
.unwrap_or_default();
|
||||
RuleListResult {
|
||||
enabled: file.enabled,
|
||||
rules: file.rules,
|
||||
records,
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新内存里的规则(写盘由调用方在 `spawn_blocking` 里做)。
|
||||
pub fn set_rules_memory(&self, file: RulesFile) {
|
||||
if let Ok(mut g) = self.rules.lock() {
|
||||
*g = file;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 实时连接(P4) ----------
|
||||
|
||||
pub fn ws_handle(&self) -> Option<ws::WsHandle> {
|
||||
self.ws.lock().ok().and_then(|g| g.as_ref().cloned())
|
||||
}
|
||||
|
||||
fn set_ws_error(&self, message: &str) {
|
||||
if let Ok(mut g) = self.ws_error.lock() {
|
||||
*g = message.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前实时连接状态(没有运行中的连接时,用最近一次失败原因作诊断信息)。
|
||||
pub fn ws_status(&self) -> WsStatus {
|
||||
if let Some(handle) = self.ws_handle() {
|
||||
return handle.status();
|
||||
}
|
||||
let detail = self.ws_error.lock().map(|g| g.clone()).unwrap_or_default();
|
||||
let conn_id = self.load_settings().active_id;
|
||||
let mut status = WsStatus::new(
|
||||
&conn_id,
|
||||
if detail.is_empty() { "idle" } else { "disconnected" },
|
||||
);
|
||||
status.detail = detail;
|
||||
status
|
||||
}
|
||||
|
||||
/// 停止实时连接(幂等)。
|
||||
pub fn stop_ws(&self) {
|
||||
let taken = self.ws.lock().ok().and_then(|mut g| g.take());
|
||||
if let Some(handle) = taken {
|
||||
handle.stop();
|
||||
}
|
||||
self.set_ws_error("");
|
||||
}
|
||||
|
||||
/// 启动实时连接:复用 P0 的端点选择(`resolve`),把所选端点换成 `ws(s)://`。
|
||||
///
|
||||
/// **一旦连上就固定在该端点**(plan §3.7-a):不允许同一屏数据来自两条链路。
|
||||
/// 幂等:同一条连接已经连着 / 正在连时直接返回它的状态,不重复建连。
|
||||
pub async fn start_ws(
|
||||
&self,
|
||||
app: &AppHandle,
|
||||
conn: &HaConnection,
|
||||
) -> Result<WsStatus, String> {
|
||||
if let Some(handle) = self.ws_handle() {
|
||||
if handle.conn_id == conn.id {
|
||||
let status = handle.status();
|
||||
if status.state == "connected" || status.state == "connecting" {
|
||||
return Ok(status);
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = self.start_ws_fresh(app, conn).await;
|
||||
if let Err(e) = &result {
|
||||
self.set_ws_error(e);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn start_ws_fresh(
|
||||
&self,
|
||||
app: &AppHandle,
|
||||
conn: &HaConnection,
|
||||
) -> Result<WsStatus, String> {
|
||||
// 已有句柄但连接不可用(断线 / 鉴权失败):先彻底停掉,避免留下第二个任务
|
||||
self.stop_ws();
|
||||
let token = self.token(&conn.id);
|
||||
if token.is_empty() {
|
||||
return Err("尚未配置访问令牌".to_string());
|
||||
}
|
||||
let (url, kind, _latency) = self.resolve(conn).await.map_err(|e| e.message)?;
|
||||
let ws_url = client::ws_url(&url)?;
|
||||
let cfg = ws::WsTaskConfig {
|
||||
conn_id: conn.id.clone(),
|
||||
app: app.clone(),
|
||||
base_url: url,
|
||||
ws_url,
|
||||
token,
|
||||
insecure: conn.insecure,
|
||||
kind,
|
||||
rules: self.rules.clone(),
|
||||
records: self.records.clone(),
|
||||
recent: self.recent.clone(),
|
||||
rules_path: self.rules_path(),
|
||||
};
|
||||
let handle = ws::spawn(cfg);
|
||||
if let Ok(mut g) = self.ws.lock() {
|
||||
*g = Some(handle);
|
||||
}
|
||||
self.set_ws_error("");
|
||||
Ok(self.ws_status())
|
||||
}
|
||||
|
||||
/// 按"该不该有实时连接"对齐运行状态(幂等)。
|
||||
///
|
||||
/// 触发条件:**实时推送开关开着**,或**本地规则总开关开着** ——
|
||||
/// 后者是硬依赖:规则靠 WS 事件驱动,没有实时连接它永远不会触发。
|
||||
/// 调用点:启动时、保存界面偏好 / 连接 / 规则之后。
|
||||
pub async fn sync_ws(&self, app: &AppHandle) {
|
||||
let settings = self.load_settings();
|
||||
let want = settings.realtime.enabled || self.rules_file().enabled;
|
||||
let conn = settings.connection(&settings.active_id).cloned();
|
||||
|
||||
if !want {
|
||||
self.stop_ws();
|
||||
return;
|
||||
}
|
||||
let Some(conn) = conn else {
|
||||
self.stop_ws();
|
||||
self.set_ws_error("没有可用的连接(请先在设置页配置 Home Assistant)");
|
||||
return;
|
||||
};
|
||||
// 已经连着同一个连接:不动它(避免切个设置页就重连一次)。
|
||||
// 但 **authFailed 例外**:那种句柄是"永久放弃重连"的状态(§3.3 要求不刷日志),
|
||||
// 若用户刚补了新令牌,这里必须给它一次重新尝试的机会。
|
||||
if let Some(handle) = self.ws_handle() {
|
||||
if handle.conn_id == conn.id && handle.status().state != "authFailed" {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.stop_ws();
|
||||
if let Err(e) = self.start_ws(app, &conn).await {
|
||||
crate::logger::log_warn("smarthome", &format!("启动实时连接失败:{e}"));
|
||||
self.set_ws_error(&e);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 注册表(房间分组,P4) ----------
|
||||
|
||||
/// 命中缓存的前提:**是同一个连接**且未超过 TTL。
|
||||
pub fn cached_registry(&self, conn_id: &str, force: bool) -> Option<RegistryResult> {
|
||||
if force {
|
||||
return None;
|
||||
}
|
||||
let guard = self.registry_cache.lock().ok()?;
|
||||
let (cached_conn, cached) = guard.as_ref()?;
|
||||
if cached_conn != conn_id {
|
||||
return None;
|
||||
}
|
||||
if chrono::Utc::now().timestamp() - cached.fetched_at > REGISTRY_CACHE_TTL_SECS {
|
||||
return None;
|
||||
}
|
||||
Some(cached.clone())
|
||||
}
|
||||
|
||||
pub fn store_registry(&self, conn_id: &str, registry: RegistryResult) {
|
||||
if let Ok(mut g) = self.registry_cache.lock() {
|
||||
*g = Some((conn_id.to_string(), registry));
|
||||
}
|
||||
}
|
||||
|
||||
/// 失效注册表缓存。触发点:切换/删除连接(房间归属跟着连接走)。
|
||||
pub fn clear_registry_cache(&self) {
|
||||
if let Ok(mut g) = self.registry_cache.lock() {
|
||||
*g = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_settings_file(module_dir: &Path, settings: &HaSettings) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(settings)
|
||||
.map_err(|e| format!("序列化智能家居设置失败:{e}"))?;
|
||||
std::fs::write(module_dir.join("settings.json"), json)
|
||||
.map_err(|e| format!("写入智能家居设置失败:{e}"))
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
//! 区域 / 设备 / 实体注册表查询(P4)。
|
||||
//!
|
||||
//! **房间分组的唯一来源**:纯 REST 拿不到 area(plan §0.4),注册表只能走 WebSocket 的
|
||||
//! `config/area_registry/list` 等命令。
|
||||
//!
|
||||
//! **真机修正(§9.5-1)**:目标实例上实体级 `area_id` **全空**(606 条 0 条),
|
||||
//! 房间归属在**设备**上(36 设备 / 27 有 area)。照原计划只读实体的 `area_id`
|
||||
//! 会得到"一间房都没有",因此这里必须做三级回退:
|
||||
//! `entity.area_id` → `device.area_id` → 归入「未分配房间」(前端负责这一档)。
|
||||
//! 这个"未分配"分组是**必需的**而不是兜底:那台实例上 9 个设备确实没有房间。
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use super::types::{EntityRegistryEntry, HaArea, HaDevice, RegistryResult};
|
||||
use super::ws::WsHandle;
|
||||
|
||||
/// 拉取三张注册表并算出 `entity_id → area_id` 映射 + 设备聚合所需的实体注册表。
|
||||
pub async fn fetch(ws: &WsHandle) -> Result<RegistryResult, String> {
|
||||
let timeout = super::ws::request_timeout();
|
||||
let areas = ws
|
||||
.request(json!({ "type": "config/area_registry/list" }), timeout)
|
||||
.await?;
|
||||
let devices = ws
|
||||
.request(json!({ "type": "config/device_registry/list" }), timeout)
|
||||
.await?;
|
||||
let entities = ws
|
||||
.request(json!({ "type": "config/entity_registry/list" }), timeout)
|
||||
.await?;
|
||||
|
||||
let area_list: Vec<HaArea> = items(&areas)
|
||||
.iter()
|
||||
.map(|a| HaArea {
|
||||
area_id: text(a, "area_id"),
|
||||
name: text(a, "name"),
|
||||
})
|
||||
.filter(|a| !a.area_id.is_empty())
|
||||
.collect();
|
||||
|
||||
let device_list: Vec<HaDevice> = items(&devices)
|
||||
.iter()
|
||||
.map(|d| HaDevice {
|
||||
id: text(d, "id"),
|
||||
name: text(d, "name"),
|
||||
name_by_user: text(d, "name_by_user"),
|
||||
area_id: text(d, "area_id"),
|
||||
manufacturer: text(d, "manufacturer"),
|
||||
model: text(d, "model"),
|
||||
})
|
||||
.filter(|d| !d.id.is_empty())
|
||||
.collect();
|
||||
|
||||
// 设备级房间(真机上房间归属实际就在这一层)
|
||||
let device_area: HashMap<&str, &str> = device_list
|
||||
.iter()
|
||||
.filter(|d| !d.area_id.is_empty())
|
||||
.map(|d| (d.id.as_str(), d.area_id.as_str()))
|
||||
.collect();
|
||||
|
||||
let mut entity_areas: HashMap<String, String> = HashMap::new();
|
||||
let mut entity_registry: Vec<EntityRegistryEntry> = Vec::new();
|
||||
for e in items(&entities) {
|
||||
let entity_id = text(e, "entity_id");
|
||||
if entity_id.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let device_id = text(e, "device_id");
|
||||
let direct = text(e, "area_id");
|
||||
let area = if !direct.is_empty() {
|
||||
direct
|
||||
} else {
|
||||
device_area
|
||||
.get(device_id.as_str())
|
||||
.map(|a| a.to_string())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
// 三级都拿不到 → 不进表;前端把它归入「未分配房间」
|
||||
if !area.is_empty() {
|
||||
entity_areas.insert(entity_id.clone(), area);
|
||||
}
|
||||
entity_registry.push(EntityRegistryEntry {
|
||||
entity_id,
|
||||
device_id,
|
||||
name: text(e, "name"),
|
||||
original_name: text(e, "original_name"),
|
||||
entity_category: text(e, "entity_category"),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(RegistryResult {
|
||||
areas: area_list,
|
||||
devices: device_list,
|
||||
entity_areas,
|
||||
entity_registry,
|
||||
fetched_at: chrono::Utc::now().timestamp(),
|
||||
})
|
||||
}
|
||||
|
||||
fn items(v: &Value) -> &[Value] {
|
||||
v.as_array().map(|a| a.as_slice()).unwrap_or(&[])
|
||||
}
|
||||
|
||||
fn text(v: &Value, key: &str) -> String {
|
||||
v.get(key)
|
||||
.and_then(|x| x.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
}
|
||||
@@ -0,0 +1,699 @@
|
||||
//! 智能家居(Home Assistant)模块的数据模型。
|
||||
//!
|
||||
//! 全部走 specta 导出到 `src/lib/bindings.ts`,字段 camelCase。
|
||||
//!
|
||||
//! 持久化:`{app_data_dir}/smarthome/settings.json`(范式同 dsh / editor / terminal)。
|
||||
//! **长期访问令牌不在这里** —— 它只进系统凭据管理器(`crate::secrets`),
|
||||
//! 键名 `smarthome-token-<connId>`;前端拿到的永远是掩码。
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// 设置结构版本号(自愈用;**只补增量、不清空**,避免误删用户配置)。
|
||||
pub const SETTINGS_VERSION: u32 = 1;
|
||||
|
||||
/// 凭据键前缀:`smarthome-token-<connId>`。
|
||||
pub const SECRET_PREFIX: &str = "smarthome-token-";
|
||||
|
||||
/// 允许的自动刷新间隔(秒),0 = 关闭。远端(反代)链路下强制为 0,见 §3.7-b。
|
||||
pub const AUTO_REFRESH_OPTIONS: [u32; 4] = [0, 5, 10, 30];
|
||||
|
||||
/// 端点(链路)类型。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum EndpointKind {
|
||||
/// 局域网直连
|
||||
Local,
|
||||
/// 反代(Cloudflare Tunnel 等)
|
||||
Remote,
|
||||
}
|
||||
|
||||
/// 端点选择策略。
|
||||
///
|
||||
/// 探测顺序与超时见 `client.rs` 的常量;`auto` 是「先短超时试局域网、失败再试反代」,
|
||||
/// 而不是「优先上次成功的端点」—— 后者会把人困在反代上:回家后反代仍然可用,
|
||||
/// 就永远不会切回局域网(§3.7-a)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum EndpointMode {
|
||||
/// 自动(局域网优先,反代兜底)
|
||||
#[default]
|
||||
Auto,
|
||||
/// 强制局域网
|
||||
Local,
|
||||
/// 强制反代
|
||||
Remote,
|
||||
}
|
||||
|
||||
/// 一条 Home Assistant 连接。
|
||||
///
|
||||
/// 支持**两个地址**:局域网直连(在家、快)+ 反代(在外面、慢但可达)。
|
||||
/// 两者至少填一个;只填一个时 `endpoint_mode` 退化为对应模式。
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct HaConnection {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// 局域网地址,如 `http://192.168.1.10:8123`(可空)
|
||||
pub local_url: String,
|
||||
/// 反代地址,如 `https://ha.example.com`(可空)
|
||||
pub remote_url: String,
|
||||
/// 端点选择策略
|
||||
pub endpoint_mode: EndpointMode,
|
||||
/// 忽略 HTTPS 证书校验(自签证书时勾选)
|
||||
pub insecure: bool,
|
||||
/// 上次成功的地址(**仅用于展示**;不参与探测排序,理由见 `EndpointMode` 注释)
|
||||
pub last_ok_url: String,
|
||||
/// 上次成功时间(unix 秒,0 = 从未)
|
||||
pub last_ok_at: i64,
|
||||
/// HA 版本(`GET /api/config` 的 `version`)
|
||||
pub ha_version: String,
|
||||
/// HA 实例名(`GET /api/config` 的 `location_name`)
|
||||
pub location_name: String,
|
||||
/// 温度单位(`GET /api/config` 的 `unit_system.temperature`,如 `°C` / `°F`)。
|
||||
///
|
||||
/// **必须从实例读**:HA 的 `climate.temperature` / `min_temp` / `max_temp` 都按
|
||||
/// 系统单位制给值,写死 `°C` 在美制实例上会显示成"77°C"。
|
||||
pub temperature_unit: String,
|
||||
}
|
||||
|
||||
impl HaConnection {
|
||||
/// 局域网候选(空串表示未配置)。
|
||||
pub fn local_candidate(&self) -> Option<(&str, EndpointKind)> {
|
||||
let u = self.local_url.trim();
|
||||
if u.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some((u, EndpointKind::Local))
|
||||
}
|
||||
}
|
||||
|
||||
/// 反代候选(空串表示未配置)。
|
||||
pub fn remote_candidate(&self) -> Option<(&str, EndpointKind)> {
|
||||
let u = self.remote_url.trim();
|
||||
if u.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some((u, EndpointKind::Remote))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 界面与行为偏好。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct HaUiSettings {
|
||||
/// 自动刷新间隔(秒),0 = 关闭
|
||||
pub auto_refresh_sec: u32,
|
||||
/// 不展示的 domain(如 `sensor` 太多时可隐藏)
|
||||
pub hidden_domains: Vec<String>,
|
||||
/// 不展示的具体实体
|
||||
pub hidden_entity_ids: Vec<String>,
|
||||
/// 收藏(置顶)
|
||||
pub favorite_entity_ids: Vec<String>,
|
||||
/// 危险操作(解锁 / 开门 / 全开)二次确认
|
||||
pub confirm_dangerous: bool,
|
||||
}
|
||||
|
||||
impl Default for HaUiSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
auto_refresh_sec: 0,
|
||||
hidden_domains: Vec::new(),
|
||||
hidden_entity_ids: Vec::new(),
|
||||
favorite_entity_ids: Vec::new(),
|
||||
// 默认开启:这是有实际后果的操作(开锁 / 开门),宁可多一次确认
|
||||
confirm_dangerous: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 实时推送配置(P4 才真正使用;P0 只落字段,避免以后升级设置结构)。
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct HaRealtimeSettings {
|
||||
/// 是否启用 WebSocket 实时推送
|
||||
pub enabled: bool,
|
||||
/// 上次连接成功时间(unix 秒,0 = 从未)
|
||||
pub last_connected_at: i64,
|
||||
}
|
||||
|
||||
/// 模块设置(`{app_data}/smarthome/settings.json`)。
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct HaSettings {
|
||||
pub version: u32,
|
||||
/// 激活连接 id(空 = 未选择)
|
||||
pub active_id: String,
|
||||
pub connections: Vec<HaConnection>,
|
||||
pub ui: HaUiSettings,
|
||||
pub realtime: HaRealtimeSettings,
|
||||
}
|
||||
|
||||
impl HaSettings {
|
||||
/// 自愈:补版本号、校正激活连接、收敛非法的自动刷新间隔。返回「是否发生过修改」。
|
||||
pub fn heal(&mut self) -> bool {
|
||||
let mut changed = false;
|
||||
if self.version != SETTINGS_VERSION {
|
||||
self.version = SETTINGS_VERSION;
|
||||
changed = true;
|
||||
}
|
||||
// 激活连接指向一个已不存在的 id(删连接后旧快照回写等):回落到第一条
|
||||
let active_ok = self.connections.iter().any(|c| c.id == self.active_id);
|
||||
if !active_ok {
|
||||
let next = self.connections.first().map(|c| c.id.clone()).unwrap_or_default();
|
||||
if next != self.active_id {
|
||||
self.active_id = next;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !AUTO_REFRESH_OPTIONS.contains(&self.ui.auto_refresh_sec) {
|
||||
self.ui.auto_refresh_sec = 0;
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub fn connection(&self, id: &str) -> Option<&HaConnection> {
|
||||
self.connections.iter().find(|c| c.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
/// 前端提交的连接草案(新建或编辑)。令牌**不在此结构里**,走独立命令写入凭据库。
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct HaConnectionInput {
|
||||
/// 空 = 新建
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub local_url: String,
|
||||
pub remote_url: String,
|
||||
pub endpoint_mode: EndpointMode,
|
||||
pub insecure: bool,
|
||||
}
|
||||
|
||||
/// 发给前端的连接视图:**不含明文令牌**,只有掩码与"是否已配置"。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HaConnectionView {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub local_url: String,
|
||||
pub remote_url: String,
|
||||
pub endpoint_mode: EndpointMode,
|
||||
pub insecure: bool,
|
||||
pub has_token: bool,
|
||||
/// 掩码(`secrets::mask`):长度不足 8 时整串打码,绝不泄露完整明文
|
||||
pub token_masked: String,
|
||||
pub last_ok_url: String,
|
||||
pub last_ok_at: i64,
|
||||
pub ha_version: String,
|
||||
pub location_name: String,
|
||||
/// 温度单位(`°C` / `°F`)—— climate 的温度显示必须用它
|
||||
pub temperature_unit: String,
|
||||
/// 本次会话实际使用的端点(未探测过为 null)
|
||||
pub endpoint_url: Option<String>,
|
||||
pub endpoint_kind: Option<EndpointKind>,
|
||||
/// 该端点最近一次实测耗时(毫秒)
|
||||
pub endpoint_latency_ms: Option<u64>,
|
||||
}
|
||||
|
||||
/// 模块设置视图。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HaSettingsView {
|
||||
pub version: u32,
|
||||
pub active_id: String,
|
||||
pub connections: Vec<HaConnectionView>,
|
||||
pub ui: HaUiSettings,
|
||||
pub realtime: HaRealtimeSettings,
|
||||
}
|
||||
|
||||
/// 保存连接的结果:**回传 id**(新建时前端要靠它接着写令牌,按名称/地址反查不可靠),
|
||||
/// 外加刷新后的整份视图。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HaSaveConnectionResult {
|
||||
pub id: String,
|
||||
pub settings: HaSettingsView,
|
||||
}
|
||||
|
||||
/// 单个地址的探测结果(「测试连接」逐地址返回)。
|
||||
///
|
||||
/// 逐地址给结果而不是一个笼统的成功/失败:用户在外面测时,局域网失败是**预期内**的,
|
||||
/// 只有把两条链路的结果分开呈现,这个信息才有用(§5.1)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EndpointProbe {
|
||||
pub url: String,
|
||||
pub kind: EndpointKind,
|
||||
pub ok: bool,
|
||||
pub ha_version: String,
|
||||
pub location_name: String,
|
||||
/// 实例的温度单位(见 `HaConnection::temperature_unit`)
|
||||
pub temperature_unit: String,
|
||||
/// 耗时(毫秒):既是诊断信息,也是"反代比局域网慢多少"的直觉来源
|
||||
pub elapsed_ms: u64,
|
||||
/// 失败原因(中文可读)
|
||||
pub error: Option<String>,
|
||||
/// 失败分类:auth | network | server | other(前端据此决定是否提示"重填令牌")
|
||||
pub error_kind: Option<String>,
|
||||
}
|
||||
|
||||
/// 当前链路信息(诊断区)。
|
||||
///
|
||||
/// 失败时 `url` / `kind` 也可能为空 —— 例如 `auto` 模式下两个地址都不可达,
|
||||
/// 这时没有"当前链路"可言,只能把失败原因(包含每个地址的尝试结果)交给前端展示。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LinkInfo {
|
||||
pub url: Option<String>,
|
||||
pub kind: Option<EndpointKind>,
|
||||
pub ok: bool,
|
||||
/// 成功时:该端点实测耗时(毫秒)。失败时为 0
|
||||
pub latency_ms: u64,
|
||||
/// 失败原因(含各候选地址的尝试结果)
|
||||
pub error: Option<String>,
|
||||
/// 失败分类:auth | network | config(前端据此决定提示"重填令牌"还是"重试")
|
||||
pub error_kind: Option<String>,
|
||||
}
|
||||
|
||||
/// 实体摘要(发给前端的**精简结构**)。
|
||||
///
|
||||
/// 只带前端**要显示**的字段。完整 `attributes` 因 domain 而异(灯有
|
||||
/// `supported_color_modes`、窗帘有 `current_position`、气候有 `hvac_modes`…),
|
||||
/// 几百个实体整份过 IPC 会让序列化与前端响应式都明显变重(§6.1)。
|
||||
///
|
||||
/// 「是否可控 / 分组 / 图标 / 状态文案」这类**表现层语义由前端 `format.ts` 决定**,
|
||||
/// 不在这里算 —— Rust 侧只负责"协议 → 数据的忠实搬运"。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EntitySummary {
|
||||
pub entity_id: String,
|
||||
/// `entity_id` 的前半段(light / switch / sensor…)
|
||||
pub domain: String,
|
||||
/// `friendly_name`,缺失时回落 `entity_id`
|
||||
pub name: String,
|
||||
/// 原始状态字符串:`on` / `off` / `24.5` / `unavailable` / `unknown` …
|
||||
pub state: String,
|
||||
/// `state` 可解析为数字时的数值(sensor 这类读数就在 `state` 里)
|
||||
pub numeric: Option<f64>,
|
||||
/// `unit_of_measurement`
|
||||
pub unit: String,
|
||||
/// `device_class`(binary_sensor / sensor 的语义细分)
|
||||
pub device_class: String,
|
||||
/// 灯亮度 0–255
|
||||
pub brightness: Option<u8>,
|
||||
/// 窗帘当前位置 0–100
|
||||
pub position: Option<u8>,
|
||||
/// 空调目标温度
|
||||
pub target_temp: Option<f64>,
|
||||
/// 空调可设的上下限(**单位随系统单位制**,如美制是 61–86 °F)。
|
||||
/// 控件必须用它,不能自己写死 5–35 —— 美制下 77 会被钳成 35(真机踩到过)。
|
||||
pub min_temp: Option<f64>,
|
||||
pub max_temp: Option<f64>,
|
||||
/// 空调当前温度(室温)
|
||||
pub current_temp: Option<f64>,
|
||||
/// 最后变化时间(HA 的 ISO8601 串,前端格式化成相对时间)
|
||||
pub last_changed: String,
|
||||
/// `attributes.last_triggered` —— 自动化 / 脚本的"上次触发时间"(空 = 从未触发)。
|
||||
/// P3 的自动化列表要靠它回答"这条规则最近到底跑没跑"。
|
||||
pub last_triggered: String,
|
||||
// ---- 以下为 P2 控制所需的能力位与参数(同一次拉取里拿到,不必为控制再请求一次)----
|
||||
/// HA 的 `supported_features` 位掩码。**语义按 domain 不同**(窗帘 OPEN/CLOSE/…、
|
||||
/// 气候 TARGET_TEMPERATURE/…),因此这里原样透传,由前端按 domain 解释。
|
||||
pub supported_features: u32,
|
||||
/// 灯的 `supported_color_modes`(`onoff` / `brightness` / `color_temp` / `hs` …)。
|
||||
/// 判断"能不能调亮度 / 色温"必须用它,而不是 `supported_features` 的旧位约定。
|
||||
pub supported_color_modes: Vec<String>,
|
||||
/// 色温可调范围(灯)
|
||||
pub min_color_temp_kelvin: Option<u32>,
|
||||
pub max_color_temp_kelvin: Option<u32>,
|
||||
/// 当前色温(灯)。**必须有**:没有它,色温滑杆只能猜一个初始位置,
|
||||
/// 那就成了一个会骗人的控件。
|
||||
pub color_temp_kelvin: Option<u32>,
|
||||
/// 空调可选模式(cool / heat / off / auto …)
|
||||
pub hvac_modes: Vec<String>,
|
||||
/// 空调温度步进(0.5 / 1)
|
||||
pub target_temp_step: Option<f64>,
|
||||
/// 媒体播放器音量 0.0–1.0
|
||||
pub volume_level: Option<f64>,
|
||||
/// 风扇档位 0–100
|
||||
pub percentage: Option<u8>,
|
||||
// ---- 通用域(`number` / `select` / `button`):这三类能覆盖最多"能控但没控件"的实体 ----
|
||||
/// `number` 实体的可设上下限与步长(各集成差异极大:0–100 音量、10–90 变焦、步长 180 的翻转角)
|
||||
pub min: Option<f64>,
|
||||
pub max: Option<f64>,
|
||||
pub step: Option<f64>,
|
||||
/// `select` 实体的可选项
|
||||
pub options: Vec<String>,
|
||||
}
|
||||
|
||||
/// 服务调用的可选参数。
|
||||
///
|
||||
/// **用固定字段而不是 `serde_json::Value`**:specta 无法为 `Value` 生成类型
|
||||
/// (见 lib.rs 的豁免清单);而且固定字段顺带把"能传什么参数"限死了,
|
||||
/// 前端不可能把任意键塞进 HA 的 `service_data`。
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct ServiceParams {
|
||||
/// 灯亮度百分比 0–100(HA 侧换算成 `brightness`)
|
||||
pub brightness_pct: Option<u8>,
|
||||
/// 色温(开尔文)
|
||||
pub color_temp_kelvin: Option<u32>,
|
||||
/// 窗帘位置 0–100
|
||||
pub position: Option<u8>,
|
||||
/// 空调目标温度
|
||||
pub temperature: Option<f64>,
|
||||
/// 空调模式(`cool` / `heat` / `off` …)
|
||||
pub hvac_mode: Option<String>,
|
||||
/// 风扇档位 0–100
|
||||
pub percentage: Option<u8>,
|
||||
/// 媒体音量 0.0–1.0
|
||||
pub volume_level: Option<f64>,
|
||||
/// `number.set_value` 的目标值
|
||||
pub value: Option<f64>,
|
||||
/// `select.select_option` 的目标项
|
||||
pub option: Option<String>,
|
||||
}
|
||||
|
||||
/// 服务调用结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ServiceCallResult {
|
||||
/// HA 在 `200` 响应体里带回的**已变化实体**新状态(已转成精简结构)。
|
||||
///
|
||||
/// **可能为空**:部分集成(尤其走云端的设备)是"发完就返回",状态要稍后才反映。
|
||||
/// 前端据此决定"直接采用服务端结果"还是"等分级窗口后重拉一次"(§9.3)。
|
||||
pub entities: Vec<EntitySummary>,
|
||||
}
|
||||
|
||||
/// 实体列表结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EntityListResult {
|
||||
pub entities: Vec<EntitySummary>,
|
||||
/// 抓取时间(unix 秒)。"更新于 x 秒前"必须用它 —— 那是**服务端数据的时刻**,
|
||||
/// 而不是前端收到响应的时刻。
|
||||
pub fetched_at: i64,
|
||||
/// true = 命中内存缓存,未重新请求
|
||||
pub from_cache: bool,
|
||||
}
|
||||
|
||||
// ============================== P4:实时推送 ==============================
|
||||
|
||||
/// WebSocket 连接状态(`smarthome_ws_status` 的返回,也是 `smarthome-connection-status` 的载荷)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WsStatus {
|
||||
pub conn_id: String,
|
||||
/// idle | connecting | connected | authFailed | disconnected
|
||||
pub state: String,
|
||||
/// 失败原因 / 补充说明(正常时为空)
|
||||
pub detail: String,
|
||||
/// 本次连上的时间(unix 秒,0 = 未连上)
|
||||
pub connected_at: i64,
|
||||
/// 最近一次收到服务端消息的时间(unix 秒)—— 半开连接靠它判断
|
||||
pub last_event_at: i64,
|
||||
/// 已订阅到的实体数(`subscribe_entities` 首帧后写入)
|
||||
pub entity_count: u32,
|
||||
}
|
||||
|
||||
impl WsStatus {
|
||||
pub fn new(conn_id: &str, state: &str) -> Self {
|
||||
Self {
|
||||
conn_id: conn_id.to_string(),
|
||||
state: state.to_string(),
|
||||
detail: String::new(),
|
||||
connected_at: 0,
|
||||
last_event_at: 0,
|
||||
entity_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// 状态变化时重置"连上时间 / 事件时间"(只有 connected 才重新计时)。
|
||||
pub fn set(&mut self, state: &str, detail: impl Into<String>) {
|
||||
self.state = state.to_string();
|
||||
self.detail = detail.into();
|
||||
}
|
||||
}
|
||||
|
||||
/// `smarthome-state-batch` 事件的载荷。
|
||||
///
|
||||
/// **200ms 聚合后**才发(plan §6.5):一次全屋状态变化(HA 重启恢复、场景切换)
|
||||
/// 会造成数十条消息,逐条 IPC 会把 WebView 卡住。窗口内的多次变更按 `entity_id`
|
||||
/// 合并,只发最终值。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StateBatch {
|
||||
pub conn_id: String,
|
||||
/// 本次窗口内新出现的实体(含首次订阅的全量快照)
|
||||
pub added: Vec<EntitySummary>,
|
||||
/// 本次窗口内发生变化的实体(只带最终值)
|
||||
pub changed: Vec<EntitySummary>,
|
||||
/// 本次窗口内被移除的实体 id
|
||||
pub removed: Vec<String>,
|
||||
}
|
||||
|
||||
/// 规则列表结果(含总开关与最近运行记录)。
|
||||
///
|
||||
/// 计划 §6.2 只列了 `Rule[]`,这里把「总开关 + 最近记录」并进同一个返回:
|
||||
/// 自动化页进来就要用这三样,拆成三条命令只是多两次往返。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuleListResult {
|
||||
/// 规则总开关(关掉后所有规则都不求值)
|
||||
pub enabled: bool,
|
||||
pub rules: Vec<Rule>,
|
||||
/// 最近运行记录(新的在前,最多 `automation::MAX_RECORDS` 条;仅本次运行期内有)
|
||||
pub records: Vec<RuleRecord>,
|
||||
}
|
||||
|
||||
// ============================== P4:注册表(房间分组) ==============================
|
||||
|
||||
/// 区域(房间)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HaArea {
|
||||
pub area_id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// 设备(设备聚合与详情页头部所需的最小字段集合)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HaDevice {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// 用户在 HA 里改过的名字(为空时用 `name`)
|
||||
pub name_by_user: String,
|
||||
/// 空 = 未分配房间
|
||||
pub area_id: String,
|
||||
/// 厂商 / 型号(详情页头部显示,便于认出是哪台设备)
|
||||
pub manufacturer: String,
|
||||
pub model: String,
|
||||
}
|
||||
|
||||
/// 实体注册表条目(**设备聚合的唯一来源**:REST 的 `/api/states` 里没有 device_id)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EntityRegistryEntry {
|
||||
pub entity_id: String,
|
||||
/// 空 = 未归组到设备(真机上是 `person` / `todo` 这类)
|
||||
pub device_id: String,
|
||||
/// 注册表里的名字(小米集成上**大量为空**,因此只作兜底)
|
||||
pub name: String,
|
||||
/// 集成给的原始名字
|
||||
pub original_name: String,
|
||||
/// `""` | `config` | `diagnostic` —— HA 官方标记的"高级 / 配置"类实体。
|
||||
///
|
||||
/// 真机上只有 30/606 条有值,所以它只是"三级"的**判据之一**,不是全部。
|
||||
pub entity_category: String,
|
||||
}
|
||||
|
||||
/// 注册表查询结果(房间分组 + 设备聚合的唯一来源)。
|
||||
///
|
||||
/// **真机修正(§9.5-1)**:目标实例上实体级 `area_id` 全空,房间归属在设备上,
|
||||
/// 因此 `entity_areas` 已按「实体 → 设备 → 区域」三级回退算好;仍未解析到的不进表
|
||||
/// (前端把它归入「未分配房间」,这是必需的分组而不是兜底)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RegistryResult {
|
||||
pub areas: Vec<HaArea>,
|
||||
pub devices: Vec<HaDevice>,
|
||||
/// `entity_id` → `area_id`
|
||||
pub entity_areas: HashMap<String, String>,
|
||||
/// 实体注册表(`entity_id` → 设备 / 名字 / 分类)
|
||||
pub entity_registry: Vec<EntityRegistryEntry>,
|
||||
/// 抓取时间(unix 秒)
|
||||
pub fetched_at: i64,
|
||||
}
|
||||
|
||||
// ============================== P4:本地规则 ==============================
|
||||
|
||||
/// 规则触发段(线性三段式的第一段)。
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct RuleTrigger {
|
||||
pub entity_id: String,
|
||||
/// 命中这些状态才触发(空 = 任意变化)
|
||||
pub to: Vec<String>,
|
||||
/// 仅当从这些状态变化而来(空 = 不限)
|
||||
pub from: Vec<String>,
|
||||
/// 持续 N 秒仍然满足才触发(0 = 立即;用于去抖)
|
||||
pub for_sec: u32,
|
||||
/// 数值比较运算符(空 = 不做数值判断;否则 `>` `>=` `<` `<=` `==` `!=`)
|
||||
pub numeric_op: String,
|
||||
/// 数值比较的阈值
|
||||
pub numeric_value: Option<f64>,
|
||||
}
|
||||
|
||||
/// 规则条件段(全部 AND)。
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct RuleCondition {
|
||||
/// state | time
|
||||
pub kind: String,
|
||||
/// `state` 条件:实体 id
|
||||
pub entity_id: String,
|
||||
/// `state` 条件:要求的状态
|
||||
pub state: String,
|
||||
/// `time` 条件:起始 `HH:MM`
|
||||
pub from_time: String,
|
||||
/// `time` 条件:结束 `HH:MM`(跨零点时 `to < from` 视为跨天)
|
||||
pub to_time: String,
|
||||
/// `time` 条件:星期(1=周一 … 7=周日;空 = 每天)
|
||||
pub weekdays: Vec<u32>,
|
||||
}
|
||||
|
||||
/// 规则动作段(顺序执行)。
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct RuleAction {
|
||||
/// service | delay | notify
|
||||
pub kind: String,
|
||||
/// `service`:domain / service / 目标实体
|
||||
pub domain: String,
|
||||
pub service: String,
|
||||
pub entity_id: String,
|
||||
pub params: ServiceParams,
|
||||
/// `delay`:秒(上限见 `automation::MAX_DELAY_SEC`)
|
||||
pub seconds: u32,
|
||||
/// `notify`:标题与正文
|
||||
pub title: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// 一条本地规则。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct Rule {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub enabled: bool,
|
||||
pub trigger: RuleTrigger,
|
||||
pub conditions: Vec<RuleCondition>,
|
||||
pub actions: Vec<RuleAction>,
|
||||
/// 冷却秒数:窗口内的重复触发直接丢弃(护栏 1)
|
||||
pub cooldown_sec: u32,
|
||||
/// 上次触发时间(unix 秒,0 = 从未)
|
||||
pub last_fired_at: i64,
|
||||
/// 累计触发次数
|
||||
pub fire_count: u32,
|
||||
/// 上次失败原因(空 = 上次正常)
|
||||
pub last_error: String,
|
||||
}
|
||||
|
||||
impl Default for Rule {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: String::new(),
|
||||
name: String::new(),
|
||||
enabled: true,
|
||||
trigger: RuleTrigger::default(),
|
||||
conditions: Vec::new(),
|
||||
actions: Vec::new(),
|
||||
// 默认 30s:小米设备的状态抖动(如功率传感器反复跳)很容易把规则刷爆
|
||||
cooldown_sec: 30,
|
||||
last_fired_at: 0,
|
||||
fire_count: 0,
|
||||
last_error: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 规则运行记录(内存里保留最近 `automation::MAX_RECORDS` 条)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuleRecord {
|
||||
pub rule_id: String,
|
||||
pub rule_name: String,
|
||||
pub at: i64,
|
||||
pub ok: bool,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
/// `smarthome-rule-fired` 事件的载荷(与 `RuleRecord` 同构,但字段名对齐计划 §6.3)。
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuleFiredEvent {
|
||||
pub rule_id: String,
|
||||
pub rule_name: String,
|
||||
pub at: i64,
|
||||
pub ok: bool,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
/// 规则文件(`{app_data}/smarthome/automations.json`)。
|
||||
///
|
||||
/// `enabled` 是**总开关**:关掉后所有规则都不求值(但规则本身保留)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct RulesFile {
|
||||
pub version: u32,
|
||||
pub enabled: bool,
|
||||
pub rules: Vec<Rule>,
|
||||
}
|
||||
|
||||
impl Default for RulesFile {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: RULES_VERSION,
|
||||
enabled: false,
|
||||
rules: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 规则文件版本号(自愈用)。
|
||||
pub const RULES_VERSION: u32 = 1;
|
||||
|
||||
/// 命令层错误:带分类。
|
||||
///
|
||||
/// 前端据此区分"重填令牌"(`auth`,重试无意义)与"重试 / 检查地址"
|
||||
/// (`network` / `config`)—— **分类判定留在 Rust 侧**,不让前端靠匹配错误文案猜(§3.6)。
|
||||
/// 这是本项目第一个不用 `String` 作错误类型的命令模块;理由见 §9.1。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HaApiError {
|
||||
/// auth | network | config | server | other
|
||||
pub kind: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl HaApiError {
|
||||
pub fn new(kind: &str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind: kind.to_string(),
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for HaApiError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,768 @@
|
||||
//! Home Assistant WebSocket 实时客户端(P4)。
|
||||
//!
|
||||
//! 职责(plan §3.3 / §6.1):握手鉴权 → `subscribe_entities` → 增量合并 → 200ms 聚合后
|
||||
//! 发 `smarthome-state-batch`;顺带把状态变化喂给本地规则引擎(`automation`)。
|
||||
//! 还提供「请求 / 应答」通道,供 `registry` 拉区域 / 实体 / 设备注册表。
|
||||
//!
|
||||
//! 生命周期归属**应用**而非页面:连接由 Rust 侧持有(后台任务),模块 Tab 切走不关连接;
|
||||
//! 只有用户显式关掉实时、规则总开关关闭、或应用退出才断(plan §3.3 第一条)。
|
||||
//!
|
||||
//! 真机实测前提(§9.5):
|
||||
//! - 握手 `auth_required` → `auth` → `auth_ok`,HA 2026.10.1;
|
||||
//! - `subscribe_entities` 首帧是**一条大消息**(577 实体 / 152 KB / 2.23s),
|
||||
//! 之后 30 秒仅 2 个增量事件 —— 这就是"实时优于轮询"的量化依据;
|
||||
//! - `ping/pong` 往返 617ms(反代),心跳与聚合窗口按它设计;
|
||||
//! - **`c`(changed)里的 attributes 可能是差量**(`{"+": {...}, "-": [...]}`),
|
||||
//! 因此必须维护一份原始 attributes 再合并,然后重新推导 `EntitySummary`,
|
||||
//! 不能整份替换(整份替换会在下一次事件把未变化的字段抹掉)。
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde_json::{json, Map, Value};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
use super::automation::{self, RuleEnv};
|
||||
use super::client::{self, RawState};
|
||||
use super::types::{EntitySummary, StateBatch, WsStatus};
|
||||
use crate::constants::events;
|
||||
|
||||
/// 心跳间隔(秒)。
|
||||
///
|
||||
/// 反代链路上的 `ping/pong` 实测 **617ms**(§9.5),25s 足够保活,也给 Cloudflare
|
||||
/// 约 100s 的空闲超时留足余量。**必须主动发**:不能只依赖 TCP keepalive,
|
||||
/// 路由器 / NAT 把连接悄悄丢掉时 TCP 是不会有反应的。
|
||||
const PING_SECS: u64 = 25;
|
||||
/// 超过这么久没收到任何入站消息 → 判定半开连接,主动断开重连。
|
||||
const STALE_SECS: u64 = PING_SECS * 3;
|
||||
/// 聚合窗口(毫秒)—— **硬要求**(plan §6.5):一次全屋变化会有数十条消息。
|
||||
const AGG_MS: u64 = 200;
|
||||
/// 重连退避上限(秒)。
|
||||
const MAX_BACKOFF_SECS: u64 = 30;
|
||||
/// 握手 / 鉴权等待超时(秒)。反代上首帧可能慢,给足。
|
||||
const HANDSHAKE_TIMEOUT_SECS: u64 = 20;
|
||||
/// 连上后至少活这么久才认为"这次连接是成功的",从而把退避重置回 1s
|
||||
/// (否则"连上即断"会退化成 1s 一次的重连风暴)。
|
||||
const STABLE_CONNECT_SECS: u64 = 5;
|
||||
/// 实时命令(注册表查询)的等待超时(秒)。
|
||||
const REQUEST_TIMEOUT_SECS: u64 = 20;
|
||||
|
||||
/// 应答等待表:`id` → 一次性回执。
|
||||
type Pending = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value, String>>>>>;
|
||||
|
||||
/// 客户端连接的具体类型(`MaybeTlsStream` 在开了 `rustls-tls-webpki-roots` 后
|
||||
/// 会带上 TLS 分支,因此必须用具名别名而不是泛型参数)。
|
||||
type WsStream = tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
|
||||
|
||||
/// 传给后台任务的配置。
|
||||
pub struct WsTaskConfig {
|
||||
pub conn_id: String,
|
||||
pub app: AppHandle,
|
||||
/// REST 端点(规则动作走 REST 下发;不重造一份"WS 版 call_service")
|
||||
pub base_url: String,
|
||||
/// WebSocket 端点(由 `client::ws_url` 从 REST 端点推出来)
|
||||
pub ws_url: String,
|
||||
pub token: String,
|
||||
pub insecure: bool,
|
||||
pub kind: super::types::EndpointKind,
|
||||
pub rules: Arc<Mutex<super::types::RulesFile>>,
|
||||
pub records: Arc<Mutex<std::collections::VecDeque<super::types::RuleRecord>>>,
|
||||
pub recent: Arc<Mutex<std::collections::VecDeque<(String, Instant)>>>,
|
||||
pub rules_path: std::path::PathBuf,
|
||||
}
|
||||
|
||||
/// 运行中的 WS 连接的句柄(克隆是廉价的:内部全是 Arc / channel)。
|
||||
#[derive(Clone)]
|
||||
pub struct WsHandle {
|
||||
pub conn_id: String,
|
||||
out: mpsc::UnboundedSender<String>,
|
||||
pending: Pending,
|
||||
next_id: Arc<AtomicU64>,
|
||||
stop: watch::Sender<bool>,
|
||||
status: Arc<Mutex<WsStatus>>,
|
||||
}
|
||||
|
||||
impl WsHandle {
|
||||
/// 当前状态快照。
|
||||
pub fn status(&self) -> WsStatus {
|
||||
match self.status.lock() {
|
||||
Ok(g) => g.clone(),
|
||||
Err(e) => {
|
||||
crate::logger::log_error("smarthome", &format!("WS 状态锁中毒:{e}"));
|
||||
WsStatus::new(&self.conn_id, "disconnected")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 请求停止(任务会在下一个 select 轮次退出)。
|
||||
pub fn stop(&self) {
|
||||
let _ = self.stop.send(true);
|
||||
}
|
||||
|
||||
/// 发一条实时命令并等应答(注册表查询用它)。
|
||||
///
|
||||
/// 超时后要把等待表里的条目删掉 —— 否则应答迟到时会往一个已丢弃的 oneshot
|
||||
/// 里写(无害但会泄漏一条记录)。
|
||||
pub async fn request(&self, mut payload: Value, timeout: Duration) -> Result<Value, String> {
|
||||
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
|
||||
match payload.as_object_mut() {
|
||||
Some(o) => {
|
||||
o.insert("id".to_string(), json!(id));
|
||||
}
|
||||
None => return Err("内部错误:实时命令载荷不是对象".to_string()),
|
||||
}
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Ok(mut g) = self.pending.lock() {
|
||||
g.insert(id, tx);
|
||||
}
|
||||
self.out
|
||||
.send(payload.to_string())
|
||||
.map_err(|_| "实时连接已断开".to_string())?;
|
||||
match tokio::time::timeout(timeout, rx).await {
|
||||
Ok(Ok(v)) => v,
|
||||
Ok(Err(_)) => Err("实时连接已断开".to_string()),
|
||||
Err(_) => {
|
||||
if let Ok(mut g) = self.pending.lock() {
|
||||
g.remove(&id);
|
||||
}
|
||||
Err("Home Assistant 未在预期时间内应答".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 启动一条实时连接,返回句柄(**不阻塞**:连接建立与重连都在后台任务里)。
|
||||
pub fn spawn(cfg: WsTaskConfig) -> WsHandle {
|
||||
let status = Arc::new(Mutex::new(WsStatus::new(&cfg.conn_id, "connecting")));
|
||||
let (out_tx, out_rx) = mpsc::unbounded_channel::<String>();
|
||||
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
|
||||
let next_id = Arc::new(AtomicU64::new(1));
|
||||
let (stop_tx, stop_rx) = watch::channel(false);
|
||||
let summaries: Arc<Mutex<HashMap<String, EntitySummary>>> = Arc::new(Mutex::new(HashMap::new()));
|
||||
|
||||
let rule_env = RuleEnv {
|
||||
app: cfg.app.clone(),
|
||||
base_url: cfg.base_url.clone(),
|
||||
token: cfg.token.clone(),
|
||||
insecure: cfg.insecure,
|
||||
kind: cfg.kind,
|
||||
rules: cfg.rules.clone(),
|
||||
records: cfg.records.clone(),
|
||||
recent: cfg.recent.clone(),
|
||||
pending: Arc::new(Mutex::new(HashMap::new())),
|
||||
last_persist: Arc::new(Mutex::new(Instant::now())),
|
||||
rules_path: cfg.rules_path.clone(),
|
||||
summaries: summaries.clone(),
|
||||
};
|
||||
let session = Session {
|
||||
cfg,
|
||||
pending: pending.clone(),
|
||||
next_id: next_id.clone(),
|
||||
status: status.clone(),
|
||||
summaries,
|
||||
rule_env,
|
||||
raw: HashMap::new(),
|
||||
added: HashSet::new(),
|
||||
changed: HashSet::new(),
|
||||
removed: HashSet::new(),
|
||||
};
|
||||
// `for`(持续 N 秒)触发器的巡检任务:与连接同生共死(stop 信号一响就退出),
|
||||
// 因此不会有"连接已经换了、旧定时器还在跑旧端点"的残留(见自动化模块注释)
|
||||
automation::spawn_sweeper(&session.rule_env, stop_rx.clone());
|
||||
let handle = WsHandle {
|
||||
conn_id: session.cfg.conn_id.clone(),
|
||||
out: out_tx,
|
||||
pending,
|
||||
next_id,
|
||||
stop: stop_tx,
|
||||
status,
|
||||
};
|
||||
tauri::async_runtime::spawn(run(session, out_rx, stop_rx));
|
||||
handle
|
||||
}
|
||||
|
||||
// ============================== 任务主体 ==============================
|
||||
|
||||
/// 任务内部状态。
|
||||
struct Session {
|
||||
cfg: WsTaskConfig,
|
||||
pending: Pending,
|
||||
next_id: Arc<AtomicU64>,
|
||||
status: Arc<Mutex<WsStatus>>,
|
||||
/// 原始实体状态(**差量合并的基准**,见文件头注释)
|
||||
raw: HashMap<String, RawEntity>,
|
||||
/// 当前摘要(与规则引擎共享同一份 Arc,条件判断直接读它)
|
||||
summaries: Arc<Mutex<HashMap<String, EntitySummary>>>,
|
||||
rule_env: RuleEnv,
|
||||
added: HashSet<String>,
|
||||
changed: HashSet<String>,
|
||||
removed: HashSet<String>,
|
||||
}
|
||||
|
||||
/// 合并基准:一份完整的原始状态。
|
||||
struct RawEntity {
|
||||
state: String,
|
||||
attrs: Map<String, Value>,
|
||||
last_changed: String,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// 更新状态并推给前端(同状态同原因不重复推)。
|
||||
fn push_status(&mut self, state: &str, detail: impl Into<String>) {
|
||||
let detail = detail.into();
|
||||
let Ok(mut g) = self.status.lock() else {
|
||||
return;
|
||||
};
|
||||
if g.state == state && g.detail == detail {
|
||||
return;
|
||||
}
|
||||
g.set(state, detail);
|
||||
if state == "connected" {
|
||||
g.connected_at = now_secs();
|
||||
} else if state == "idle" || state == "disconnected" || state == "authFailed" {
|
||||
// 断开/停止后"连上时间"不再有效,别让它在那儿假装还连着
|
||||
g.connected_at = 0;
|
||||
}
|
||||
let payload = g.clone();
|
||||
drop(g);
|
||||
let _ = self
|
||||
.cfg
|
||||
.app
|
||||
.emit(events::SMARTHOME_CONNECTION_STATUS, payload);
|
||||
}
|
||||
|
||||
/// 记一次"收到服务端消息"的时刻(诊断用,不推事件:状态本身没变)。
|
||||
fn note_event(&mut self) {
|
||||
if let Ok(mut g) = self.status.lock() {
|
||||
g.last_event_at = now_secs();
|
||||
}
|
||||
}
|
||||
|
||||
/// 断线后清空本地状态:增量已经丢了,重连时 `subscribe_entities` 会给全量快照。
|
||||
fn reset_state(&mut self) {
|
||||
self.raw.clear();
|
||||
if let Ok(mut g) = self.summaries.lock() {
|
||||
g.clear();
|
||||
}
|
||||
self.added.clear();
|
||||
self.changed.clear();
|
||||
self.removed.clear();
|
||||
}
|
||||
|
||||
/// 分配一个自增 id 并直接发送(不等应答:订阅与心跳的结果不参与流程)。
|
||||
async fn send_fire_and_forget(
|
||||
&mut self,
|
||||
write: &mut futures_util::stream::SplitSink<WsStream, Message>,
|
||||
mut payload: Value,
|
||||
) {
|
||||
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
|
||||
if let Some(o) = payload.as_object_mut() {
|
||||
o.insert("id".to_string(), json!(id));
|
||||
}
|
||||
if let Err(e) = write.send(Message::Text(payload.to_string())).await {
|
||||
crate::logger::log_warn("smarthome", &format!("发送实时命令失败:{e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 收到一条文本消息:先路由应答,再处理事件。
|
||||
fn on_text(&mut self, text: &str) {
|
||||
let v: Value = match serde_json::from_str(text) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
crate::logger::log_warn("smarthome", &format!("忽略无法解析的实时消息:{e}"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// 1) 应答路由(订阅 / 心跳 / 注册表查询都带 id)
|
||||
if let Some(id) = v.get("id").and_then(|x| x.as_u64()) {
|
||||
let ty = v.get("type").and_then(|x| x.as_str()).unwrap_or("");
|
||||
if ty == "result" || ty == "pong" {
|
||||
let sender = self.pending.lock().ok().and_then(|mut g| g.remove(&id));
|
||||
if let Some(tx) = sender {
|
||||
let outcome = if ty == "pong" {
|
||||
Ok(Value::Null)
|
||||
} else if v.get("success").and_then(|x| x.as_bool()).unwrap_or(false) {
|
||||
Ok(v.get("result").cloned().unwrap_or(Value::Null))
|
||||
} else {
|
||||
Err(error_message(&v))
|
||||
};
|
||||
let _ = tx.send(outcome);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 事件(只订阅了 subscribe_entities)
|
||||
if v.get("type").and_then(|x| x.as_str()) == Some("event") {
|
||||
if let Some(ev) = v.get("event") {
|
||||
self.apply_event(ev);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `subscribe_entities` 的事件:`a` 新增全量 / `c` 变化(可能是差量)/ `r` 移除。
|
||||
fn apply_event(&mut self, ev: &Value) {
|
||||
if let Some(map) = ev.get("a").and_then(|x| x.as_object()) {
|
||||
let first = self.summaries.lock().map(|g| g.is_empty()).unwrap_or(false);
|
||||
if first && !map.is_empty() {
|
||||
// 首帧是一条大消息:记下实际大小(plan §2.2-3 要求把它记进日志)
|
||||
crate::logger::log_info(
|
||||
"smarthome",
|
||||
&format!("实时订阅首帧:{} 个实体(约 {} KB)", map.len(), approx_kb(ev)),
|
||||
);
|
||||
}
|
||||
for (entity_id, obj) in map {
|
||||
self.upsert_full(entity_id, obj);
|
||||
}
|
||||
}
|
||||
if let Some(map) = ev.get("c").and_then(|x| x.as_object()) {
|
||||
for (entity_id, obj) in map {
|
||||
self.apply_change(entity_id, obj);
|
||||
}
|
||||
}
|
||||
if let Some(list) = ev.get("r").and_then(|x| x.as_array()) {
|
||||
for item in list {
|
||||
if let Some(id) = item.as_str() {
|
||||
self.remove_entity(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 全量状态(`a` 段,或变化数据里带了完整状态时)。
|
||||
fn upsert_full(&mut self, entity_id: &str, obj: &Value) {
|
||||
let raw = RawEntity {
|
||||
state: obj
|
||||
.get("s")
|
||||
.and_then(|x| x.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
attrs: obj
|
||||
.get("a")
|
||||
.and_then(|x| x.as_object())
|
||||
.cloned()
|
||||
.unwrap_or_default(),
|
||||
last_changed: last_changed_of(obj),
|
||||
};
|
||||
self.commit(entity_id, raw);
|
||||
}
|
||||
|
||||
/// 差量变化(`c` 段):**先合并回原始对象再推导摘要**,绝不整份替换。
|
||||
fn apply_change(&mut self, entity_id: &str, obj: &Value) {
|
||||
match self.raw.get_mut(entity_id) {
|
||||
Some(stored) => {
|
||||
if let Some(s) = obj.get("s").and_then(|x| x.as_str()) {
|
||||
stored.state = s.to_string();
|
||||
}
|
||||
if let Some(a) = obj.get("a").and_then(|x| x.as_object()) {
|
||||
// 差量形态:`+` 是要补的键、`-` 是要删的键;其余键按普通属性合并
|
||||
if let Some(plus) = a.get("+").and_then(|x| x.as_object()) {
|
||||
for (k, v) in plus {
|
||||
stored.attrs.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
if let Some(minus) = a.get("-").and_then(|x| x.as_array()) {
|
||||
for k in minus {
|
||||
if let Some(k) = k.as_str() {
|
||||
stored.attrs.remove(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (k, v) in a {
|
||||
if k == "+" || k == "-" {
|
||||
continue;
|
||||
}
|
||||
stored.attrs.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
let lc = last_changed_of(obj);
|
||||
if !lc.is_empty() {
|
||||
stored.last_changed = lc;
|
||||
}
|
||||
let raw = RawEntity {
|
||||
state: stored.state.clone(),
|
||||
attrs: stored.attrs.clone(),
|
||||
last_changed: stored.last_changed.clone(),
|
||||
};
|
||||
self.commit(entity_id, raw);
|
||||
}
|
||||
None => {
|
||||
// 没见过这个实体(订阅之后才出现的实体理论上会先走 `a`):
|
||||
// 用这条变化消息构造一份(属性可能不全),下一次全量会补齐
|
||||
self.upsert_full(entity_id, obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_entity(&mut self, entity_id: &str) {
|
||||
self.raw.remove(entity_id);
|
||||
if let Ok(mut g) = self.summaries.lock() {
|
||||
g.remove(entity_id);
|
||||
}
|
||||
self.added.remove(entity_id);
|
||||
self.changed.remove(entity_id);
|
||||
self.removed.insert(entity_id.to_string());
|
||||
}
|
||||
|
||||
/// 落一份新状态:算摘要、标记批次、喂规则引擎。
|
||||
fn commit(&mut self, entity_id: &str, raw: RawEntity) {
|
||||
let summary = summary_of(entity_id, &raw);
|
||||
let previous = self
|
||||
.summaries
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut g| g.insert(entity_id.to_string(), summary.clone()));
|
||||
self.raw.insert(entity_id.to_string(), raw);
|
||||
self.removed.remove(entity_id);
|
||||
match previous {
|
||||
Some(prev) => {
|
||||
self.changed.insert(entity_id.to_string());
|
||||
if prev.state != summary.state || prev.numeric != summary.numeric {
|
||||
automation::on_entity_changed(&self.rule_env, entity_id, Some(&prev), &summary);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// **首次见到不触发规则。**
|
||||
// `subscribe_entities` 的首帧就是全量快照,重连后也会重放一遍 ——
|
||||
// 把快照当成"状态变化"会让只配了「变化为 on」的边沿触发规则在每次
|
||||
// 连接/重连时凭空执行一次(门开着 → 每次都重新锁门)。
|
||||
// 订阅之后**新出现**的实体同样走这条路径,代价是"实体一出现就触发"
|
||||
// 这种玩法不支持 —— 那本来也不是"状态变化"。
|
||||
self.added.insert(entity_id.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 聚合窗口到点:把窗口内累计的变化合并成一批发出去。
|
||||
fn flush(&mut self) {
|
||||
if self.added.is_empty() && self.changed.is_empty() && self.removed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let removed: Vec<String> = self.removed.drain().collect();
|
||||
let removed_set: HashSet<String> = removed.iter().cloned().collect();
|
||||
|
||||
let mut added = Vec::new();
|
||||
let mut changed = Vec::new();
|
||||
// 一次锁住摘要表把两批都取出来:首帧是 577 个实体,逐个 lock/clone 没必要
|
||||
match self.summaries.lock() {
|
||||
Ok(summaries) => {
|
||||
for id in self.added.drain() {
|
||||
if removed_set.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(s) = summaries.get(&id) {
|
||||
added.push(s.clone());
|
||||
}
|
||||
}
|
||||
for id in self.changed.drain() {
|
||||
if removed_set.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(s) = summaries.get(&id) {
|
||||
changed.push(s.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
crate::logger::log_error("smarthome", &format!("实体摘要锁中毒:{e}"));
|
||||
self.added.clear();
|
||||
self.changed.clear();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 实体数变了要**推一次状态**:否则设置页的「实时连接」永远显示
|
||||
// "已连接(0 个实体实时同步)」—— 那个数字只存在 Rust 内存里没人看得到
|
||||
let payload = match self.status.lock() {
|
||||
Ok(mut g) => {
|
||||
let total = self.summaries.lock().map(|m| m.len()).unwrap_or(0) as u32;
|
||||
if g.entity_count != total {
|
||||
g.entity_count = total;
|
||||
Some(g.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Err(_) => None,
|
||||
};
|
||||
if let Some(payload) = payload {
|
||||
let _ = self
|
||||
.cfg
|
||||
.app
|
||||
.emit(events::SMARTHOME_CONNECTION_STATUS, payload);
|
||||
}
|
||||
|
||||
let _ = self.cfg.app.emit(
|
||||
events::SMARTHOME_STATE_BATCH,
|
||||
StateBatch {
|
||||
conn_id: self.cfg.conn_id.clone(),
|
||||
added,
|
||||
changed,
|
||||
removed,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum Outcome {
|
||||
/// 用户主动停止
|
||||
Stopped,
|
||||
/// 令牌无效:**停止重连**(继续试只会刷爆日志,见 plan §3.3)
|
||||
AuthFailed(String),
|
||||
/// 链路断开:指数退避后重连
|
||||
Lost(String),
|
||||
}
|
||||
|
||||
async fn run(
|
||||
mut session: Session,
|
||||
mut rx: mpsc::UnboundedReceiver<String>,
|
||||
mut stop_rx: watch::Receiver<bool>,
|
||||
) {
|
||||
let mut backoff = Duration::from_secs(1);
|
||||
loop {
|
||||
if *stop_rx.borrow() {
|
||||
session.push_status("idle", "");
|
||||
return;
|
||||
}
|
||||
session.push_status("connecting", "");
|
||||
match connect_and_run(&mut session, &mut rx, &mut stop_rx, &mut backoff).await {
|
||||
Outcome::Stopped => {
|
||||
session.push_status("idle", "");
|
||||
return;
|
||||
}
|
||||
Outcome::AuthFailed(msg) => {
|
||||
crate::logger::log_error("smarthome", &format!("实时连接鉴权失败:{msg}"));
|
||||
session.push_status("authFailed", msg);
|
||||
return;
|
||||
}
|
||||
Outcome::Lost(msg) => {
|
||||
crate::logger::log_warn("smarthome", &format!("实时连接断开:{msg}"));
|
||||
session.push_status("disconnected", msg);
|
||||
session.reset_state();
|
||||
tokio::select! {
|
||||
_ = stop_rx.changed() => {}
|
||||
_ = tokio::time::sleep(backoff) => {}
|
||||
}
|
||||
backoff = std::cmp::min(backoff * 2, Duration::from_secs(MAX_BACKOFF_SECS));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_and_run(
|
||||
session: &mut Session,
|
||||
rx: &mut mpsc::UnboundedReceiver<String>,
|
||||
stop_rx: &mut watch::Receiver<bool>,
|
||||
backoff: &mut Duration,
|
||||
) -> Outcome {
|
||||
let started = Instant::now();
|
||||
let mut stream: WsStream = match tokio_tungstenite::connect_async(session.cfg.ws_url.as_str())
|
||||
.await
|
||||
{
|
||||
Ok((s, _resp)) => s,
|
||||
Err(e) => return Outcome::Lost(format!("建立 WebSocket 失败:{e}")),
|
||||
};
|
||||
|
||||
// ---- 握手:等 auth_required ----
|
||||
let hello = match timeout_json(
|
||||
wait_for_type(&mut stream, "auth_required"),
|
||||
HANDSHAKE_TIMEOUT_SECS,
|
||||
"等待 Home Assistant 握手",
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(v)) => v,
|
||||
Ok(Err(e)) | Err(e) => return Outcome::Lost(e),
|
||||
};
|
||||
if hello.get("type").and_then(|x| x.as_str()) != Some("auth_required") {
|
||||
return Outcome::Lost("握手消息类型异常".to_string());
|
||||
}
|
||||
|
||||
// ---- 鉴权 ----
|
||||
let auth = json!({ "type": "auth", "access_token": session.cfg.token });
|
||||
if let Err(e) = stream.send(Message::Text(auth.to_string())).await {
|
||||
return Outcome::Lost(format!("发送鉴权消息失败:{e}"));
|
||||
}
|
||||
let result = match timeout_json(
|
||||
wait_for_any(&mut stream, &["auth_ok", "auth_invalid"]),
|
||||
HANDSHAKE_TIMEOUT_SECS,
|
||||
"等待鉴权结果",
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(v)) => v,
|
||||
Ok(Err(e)) | Err(e) => return Outcome::Lost(e),
|
||||
};
|
||||
match result.get("type").and_then(|x| x.as_str()) {
|
||||
Some("auth_ok") => {}
|
||||
Some("auth_invalid") => {
|
||||
return Outcome::AuthFailed(error_message(&result));
|
||||
}
|
||||
_ => return Outcome::Lost("鉴权应答类型异常".to_string()),
|
||||
}
|
||||
|
||||
session.push_status("connected", "");
|
||||
crate::logger::log_info("smarthome", "实时连接已建立(WebSocket 已鉴权)");
|
||||
|
||||
// ---- 拆分读写两半,进入主循环 ----
|
||||
let (mut write, mut read) = stream.split();
|
||||
|
||||
// 订阅全实体(省略 entity_ids = 全量;首帧就是完整快照)
|
||||
session
|
||||
.send_fire_and_forget(&mut write, json!({ "type": "subscribe_entities" }))
|
||||
.await;
|
||||
|
||||
let mut ping_at = tokio::time::Instant::now() + Duration::from_secs(PING_SECS);
|
||||
let mut flush_at = tokio::time::Instant::now() + Duration::from_millis(AGG_MS);
|
||||
let mut last_rx = tokio::time::Instant::now();
|
||||
|
||||
let outcome = loop {
|
||||
tokio::select! {
|
||||
_ = stop_rx.changed() => break Outcome::Stopped,
|
||||
out = rx.recv() => match out {
|
||||
Some(text) => {
|
||||
if let Err(e) = write.send(Message::Text(text)).await {
|
||||
break Outcome::Lost(format!("发送实时命令失败:{e}"));
|
||||
}
|
||||
}
|
||||
None => break Outcome::Stopped,
|
||||
},
|
||||
msg = read.next() => match msg {
|
||||
Some(Ok(Message::Text(text))) => {
|
||||
last_rx = tokio::time::Instant::now();
|
||||
session.note_event();
|
||||
session.on_text(&text);
|
||||
}
|
||||
Some(Ok(Message::Binary(_))) => {}
|
||||
Some(Ok(Message::Ping(payload))) => {
|
||||
// 协议级 ping 必须回 pong,否则服务端会判为死连接
|
||||
let _ = write.send(Message::Pong(payload)).await;
|
||||
}
|
||||
Some(Ok(Message::Close(_))) => break Outcome::Lost("服务端关闭了连接".to_string()),
|
||||
Some(Ok(_)) => {}
|
||||
Some(Err(e)) => break Outcome::Lost(format!("WebSocket 读取失败:{e}")),
|
||||
None => break Outcome::Lost("WebSocket 已断开".to_string()),
|
||||
},
|
||||
_ = tokio::time::sleep_until(ping_at) => {
|
||||
ping_at += Duration::from_secs(PING_SECS);
|
||||
session.send_fire_and_forget(&mut write, json!({ "type": "ping" })).await;
|
||||
if last_rx.elapsed() > Duration::from_secs(STALE_SECS) {
|
||||
break Outcome::Lost(format!(
|
||||
"{} 秒未收到任何消息(连接可能已被中间设备半开)",
|
||||
STALE_SECS
|
||||
));
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep_until(flush_at) => {
|
||||
flush_at += Duration::from_millis(AGG_MS);
|
||||
session.flush();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 连上后稳定存活过一段时间才算"这次连接是成功的":否则"连上即断"会变成
|
||||
// 1s 一次的重连风暴(真机上半开连接就是这种表现)
|
||||
if started.elapsed() >= Duration::from_secs(STABLE_CONNECT_SECS) {
|
||||
*backoff = Duration::from_secs(1);
|
||||
}
|
||||
outcome
|
||||
}
|
||||
|
||||
// ============================== 小工具 ==============================
|
||||
|
||||
fn now_secs() -> i64 {
|
||||
chrono::Utc::now().timestamp()
|
||||
}
|
||||
|
||||
/// 事件 / 应答里的可读错误信息。
|
||||
fn error_message(v: &Value) -> String {
|
||||
v.get("error")
|
||||
.and_then(|e| e.get("message"))
|
||||
.and_then(|m| m.as_str())
|
||||
.or_else(|| v.get("message").and_then(|m| m.as_str()))
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| "Home Assistant 拒绝了这条实时命令".to_string())
|
||||
}
|
||||
|
||||
/// 粗略估算一条消息的 KB 数(只用于日志,不值得精确序列化)。
|
||||
fn approx_kb(v: &Value) -> usize {
|
||||
v.to_string().len() / 1024
|
||||
}
|
||||
|
||||
/// 紧凑状态里的时间戳。
|
||||
///
|
||||
/// HA 的紧凑形态是 `c` = `last_changed`、`lc` = `last_updated`;
|
||||
/// 个别版本在变化帧里只带 `lc`,所以这里按 `c` → `lc` → `lu` 兜底取用。
|
||||
/// 两者都是时间戳,最坏情况是"x 分钟前"差一点,不影响状态本身。
|
||||
fn last_changed_of(obj: &Value) -> String {
|
||||
for key in ["c", "lc", "lu"] {
|
||||
if let Some(s) = obj.get(key).and_then(|x| x.as_str()) {
|
||||
if !s.is_empty() {
|
||||
return s.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// 原始状态 → 精简摘要(与 REST 路径共用同一份推导逻辑,见 `client::to_summary`)。
|
||||
fn summary_of(entity_id: &str, raw: &RawEntity) -> EntitySummary {
|
||||
client::to_summary(RawState {
|
||||
entity_id: entity_id.to_string(),
|
||||
state: raw.state.clone(),
|
||||
attributes: Value::Object(raw.attrs.clone()),
|
||||
last_changed: raw.last_changed.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 带超时的等待(把两个 Result 层级压平成一个)。
|
||||
async fn timeout_json(
|
||||
fut: impl std::future::Future<Output = Result<Value, String>>,
|
||||
secs: u64,
|
||||
what: &str,
|
||||
) -> Result<Result<Value, String>, String> {
|
||||
match tokio::time::timeout(Duration::from_secs(secs), fut).await {
|
||||
Ok(r) => Ok(r),
|
||||
Err(_) => Err(format!("{what}超时")),
|
||||
}
|
||||
}
|
||||
|
||||
/// 读到指定 `type` 的消息为止(其余消息按协议回 pong / 跳过)。
|
||||
async fn wait_for_type(stream: &mut WsStream, want: &str) -> Result<Value, String> {
|
||||
wait_for_any(stream, &[want]).await
|
||||
}
|
||||
|
||||
async fn wait_for_any(stream: &mut WsStream, want: &[&str]) -> Result<Value, String> {
|
||||
loop {
|
||||
match stream.next().await {
|
||||
Some(Ok(Message::Text(text))) => {
|
||||
let Ok(v) = serde_json::from_str::<Value>(&text) else {
|
||||
continue;
|
||||
};
|
||||
let ty = v.get("type").and_then(|x| x.as_str()).unwrap_or("");
|
||||
if want.contains(&ty) {
|
||||
return Ok(v);
|
||||
}
|
||||
}
|
||||
Some(Ok(Message::Ping(payload))) => {
|
||||
let _ = stream.send(Message::Pong(payload)).await;
|
||||
}
|
||||
Some(Ok(Message::Close(_))) | None => {
|
||||
return Err("连接被服务端关闭".to_string());
|
||||
}
|
||||
Some(Err(e)) => return Err(format!("WebSocket 读取失败:{e}")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 供 `commands` 复用的等待超时。
|
||||
pub fn request_timeout() -> Duration {
|
||||
Duration::from_secs(REQUEST_TIMEOUT_SECS)
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! 子窗口的「任务栏身份」:窗口级 AppUserModelID + 自定义窗口图标。
|
||||
//!
|
||||
//! # 为什么需要它
|
||||
//!
|
||||
//! 应用启动时用 [`crate::win32_util::set_app_user_model_id`] 设置了**进程级** AUMID
|
||||
//! (`thing.lfeng.me`,与安装包写进开始菜单快捷方式的标识一致),好处是系统托盘/媒体面板
|
||||
//! 能认出本应用;代价是 Windows 任务栏按 AUMID 分组 —— 编辑器、终端等**子窗口全都和主窗口
|
||||
//! 合并成一个按钮、共用主程序图标**,最小化后根本分不清谁是谁。
|
||||
//!
|
||||
//! 本模块给子窗口做两件事:
|
||||
//!
|
||||
//! 1. **窗口级 AUMID**(`PKEY_AppUserModel_ID`,见 `win32_util::set_window_app_user_model_id`):
|
||||
//! 覆盖进程级值 → 该窗口独立成组 → 任务栏多出一个自己的按钮;
|
||||
//! 2. **自定义窗口图标**:底图是该窗口类型的功能图形(现在是「文档」代表编辑器),右下角
|
||||
//! 叠加**主程序图标**,一眼能看出「这是 Thing 的哪个子窗口」。
|
||||
//!
|
||||
//! # 时机
|
||||
//!
|
||||
//! 必须在窗口**首次 `show()` 之前**调用:任务栏按钮在窗口显示时创建并按 AUMID 分组。
|
||||
//! 编辑器窗口正是「隐藏创建 → 前端应用完主题再 show」,中间这段窗口期刚好可以设置。
|
||||
//! 前端调用点见 `EditorWindow.vue`。
|
||||
|
||||
use tauri::Manager;
|
||||
|
||||
use crate::logger;
|
||||
|
||||
/// 主程序 AUMID(与开始菜单快捷方式 / Tauri identifier 一致);子窗口在其后缀派生。
|
||||
const APP_AUMID: &str = "thing.lfeng.me";
|
||||
/// 主程序图标 PNG(随二进制打包,保证与安装包图标一致)
|
||||
const APP_ICON_PNG: &[u8] = include_bytes!("../icons/128x128.png");
|
||||
|
||||
/// 输出图标边长(任务栏会自行缩放到 16/32/48…,用大图更清晰)
|
||||
const ICON_SIZE: u32 = 256;
|
||||
/// 右下角主程序图标的边长
|
||||
const BADGE_SIZE: u32 = 100;
|
||||
|
||||
/// 支持的窗口类型(同时作为 AUMID 后缀与图形选择键)。
|
||||
/// 新增一类子窗口时:在此登记 + 在 [`draw_glyph`] / [`glyph_accent`] 加一个分支。
|
||||
const SUPPORTED_KINDS: &[&str] = &["editor", "terminal", "files", "download", "dsh", "diff"];
|
||||
|
||||
/// 设置某个窗口的任务栏身份(独立 AUMID + 组合图标)。
|
||||
///
|
||||
/// 由窗口自身在 `show()` 之前调用(`label` 传自己的窗口 label)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn window_set_taskbar_identity(
|
||||
app: tauri::AppHandle,
|
||||
label: String,
|
||||
kind: String,
|
||||
) -> Result<(), String> {
|
||||
let Some(window) = app.get_webview_window(&label) else {
|
||||
return Err(format!("窗口不存在: {label}"));
|
||||
};
|
||||
if !SUPPORTED_KINDS.contains(&kind.as_str()) {
|
||||
return Err(format!("不支持的窗口类型: {kind}"));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let hwnd = window.hwnd().map_err(|e| format!("取窗口句柄失败: {e}"))?;
|
||||
let aumid = format!("{APP_AUMID}.{kind}");
|
||||
crate::win32_util::set_window_app_user_model_id(hwnd.0 as isize, &aumid)?;
|
||||
}
|
||||
|
||||
let icon = compose_icon(&kind)?;
|
||||
window.set_icon(icon).map_err(|e| format!("设置窗口图标失败: {e}"))?;
|
||||
|
||||
logger::log_info("window", &format!("任务栏身份已设置: {label} kind={kind}"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 组合图标:功能图形铺底(圆角色块),右下角叠加主程序图标。
|
||||
fn compose_icon(kind: &str) -> Result<tauri::image::Image<'static>, String> {
|
||||
use image::{Rgba, RgbaImage};
|
||||
|
||||
let accent = glyph_accent(kind);
|
||||
let pad = 10;
|
||||
let radius = 56;
|
||||
|
||||
// 底:圆角色块(透明度即「可见区域」,最后据此裁剪,避免角标溢出圆角)
|
||||
let mut base = RgbaImage::from_pixel(ICON_SIZE, ICON_SIZE, Rgba([0, 0, 0, 0]));
|
||||
fill_rounded_rect(&mut base, pad, pad, ICON_SIZE - pad, ICON_SIZE - pad, radius, accent);
|
||||
|
||||
// 上层:功能图形 + 角标(先画在独立图层,最后按底色裁剪合成)
|
||||
let mut layer = RgbaImage::from_pixel(ICON_SIZE, ICON_SIZE, Rgba([0, 0, 0, 0]));
|
||||
draw_glyph(&mut layer, kind, accent);
|
||||
|
||||
let badge_from = ICON_SIZE - BADGE_SIZE - 14;
|
||||
fill_rounded_rect(
|
||||
&mut layer,
|
||||
badge_from.saturating_sub(6),
|
||||
badge_from.saturating_sub(6),
|
||||
badge_from + BADGE_SIZE + 6,
|
||||
badge_from + BADGE_SIZE + 6,
|
||||
24,
|
||||
Rgba([255, 255, 255, 255]),
|
||||
);
|
||||
let app_icon = image::load_from_memory(APP_ICON_PNG)
|
||||
.map_err(|e| format!("解码主程序图标失败: {e}"))?
|
||||
.to_rgba8();
|
||||
let badge = image::imageops::resize(
|
||||
&app_icon,
|
||||
BADGE_SIZE,
|
||||
BADGE_SIZE,
|
||||
image::imageops::FilterType::Lanczos3,
|
||||
);
|
||||
image::imageops::overlay(&mut layer, &badge, badge_from as i64, badge_from as i64);
|
||||
|
||||
// 合成:底色不透明处才写入图层内容
|
||||
let mut out = base.clone();
|
||||
for (x, y, px) in layer.enumerate_pixels() {
|
||||
if px.0[3] > 0 && base.get_pixel(x, y).0[3] > 0 {
|
||||
blend_pixel(&mut out, x, y, *px);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(tauri::image::Image::new_owned(out.into_raw(), ICON_SIZE, ICON_SIZE))
|
||||
}
|
||||
|
||||
/// 各窗口类型的主色(圆角色块底色)。
|
||||
fn glyph_accent(kind: &str) -> image::Rgba<u8> {
|
||||
match kind {
|
||||
// 终端:深板岩
|
||||
"terminal" => image::Rgba([15, 23, 42, 255]),
|
||||
// 文件管理:琥珀
|
||||
"files" => image::Rgba([245, 158, 11, 255]),
|
||||
// 下载:天蓝
|
||||
"download" => image::Rgba([14, 165, 233, 255]),
|
||||
// dsh:紫罗兰
|
||||
"dsh" => image::Rgba([124, 58, 237, 255]),
|
||||
// 对比:青碧(与下载的「天蓝」在缩略尺寸下仍可区分)
|
||||
"diff" => image::Rgba([13, 148, 136, 255]),
|
||||
// 编辑器(默认):靛蓝
|
||||
_ => image::Rgba([79, 70, 229, 255]),
|
||||
}
|
||||
}
|
||||
|
||||
/// 画各窗口类型的功能图形(画在透明图层上,颜色自定)。
|
||||
fn draw_glyph(img: &mut image::RgbaImage, kind: &str, accent: image::Rgba<u8>) {
|
||||
use image::Rgba;
|
||||
let white = Rgba([255, 255, 255, 255]);
|
||||
match kind {
|
||||
"terminal" => {
|
||||
// 窗口主体 + 绿色标题栏 + 两行绿色提示符
|
||||
let green = Rgba([34, 197, 94, 255]);
|
||||
fill_rounded_rect(img, 58, 58, 198, 198, 20, white);
|
||||
fill_rounded_rect(img, 58, 58, 198, 96, 20, green);
|
||||
fill_rounded_rect(img, 58, 84, 198, 96, 0, green);
|
||||
fill_rounded_rect(img, 84, 122, 176, 136, 7, green);
|
||||
fill_rounded_rect(img, 84, 152, 146, 166, 7, green);
|
||||
}
|
||||
"files" => {
|
||||
// 文件夹:左上标签 + 主体
|
||||
fill_rounded_rect(img, 66, 62, 132, 96, 12, white);
|
||||
fill_rounded_rect(img, 58, 84, 198, 198, 20, white);
|
||||
}
|
||||
"download" => {
|
||||
// 向下箭头 + 托盘
|
||||
fill_rounded_rect(img, 114, 56, 142, 132, 14, white);
|
||||
fill_triangle(img, (128.0, 178.0), (82.0, 124.0), (174.0, 124.0), white);
|
||||
fill_rounded_rect(img, 64, 150, 84, 198, 10, white);
|
||||
fill_rounded_rect(img, 172, 150, 192, 198, 10, white);
|
||||
fill_rounded_rect(img, 64, 178, 192, 198, 10, white);
|
||||
}
|
||||
"dsh" => {
|
||||
// 嵌套方框:外壳 / 内层 / 核心 —— 「harness」容器
|
||||
fill_rounded_rect(img, 58, 58, 198, 198, 26, white);
|
||||
fill_rounded_rect(img, 84, 84, 172, 172, 18, accent);
|
||||
fill_rounded_rect(img, 106, 106, 150, 150, 10, white);
|
||||
}
|
||||
"diff" => {
|
||||
// 双栏:左右两块面板,中间留出底色的缝隙 —— 一眼读出「两边对照」
|
||||
fill_rounded_rect(img, 56, 62, 122, 194, 16, white);
|
||||
fill_rounded_rect(img, 134, 62, 200, 194, 16, white);
|
||||
}
|
||||
_ => {
|
||||
// 编辑器:白色纸张 + 主色文字行(最后一行短一点,更像正文)
|
||||
fill_rounded_rect(img, 70, 44, 186, 214, 16, white);
|
||||
let rows = [(92u32, 168u32), (120, 168), (148, 168), (176, 142)];
|
||||
for (y, right) in rows {
|
||||
fill_rounded_rect(img, 94, y, right, y + 12, 6, accent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 填充三角形(下载箭头的箭头部分;边缘符号法判定内外)。
|
||||
fn fill_triangle(
|
||||
img: &mut image::RgbaImage,
|
||||
a: (f32, f32),
|
||||
b: (f32, f32),
|
||||
c: (f32, f32),
|
||||
color: image::Rgba<u8>,
|
||||
) {
|
||||
let min_x = a.0.min(b.0).min(c.0).floor().max(0.0) as u32;
|
||||
let max_x = a.0.max(b.0).max(c.0).ceil().min(img.width() as f32) as u32;
|
||||
let min_y = a.1.min(b.1).min(c.1).floor().max(0.0) as u32;
|
||||
let max_y = a.1.max(b.1).max(c.1).ceil().min(img.height() as f32) as u32;
|
||||
let edge = |p: (f32, f32), q: (f32, f32), r: (f32, f32)| {
|
||||
(q.0 - p.0) * (r.1 - p.1) - (q.1 - p.1) * (r.0 - p.0)
|
||||
};
|
||||
for y in min_y..max_y {
|
||||
for x in min_x..max_x {
|
||||
let p = (x as f32 + 0.5, y as f32 + 0.5);
|
||||
let (d1, d2, d3) = (edge(a, b, p), edge(b, c, p), edge(c, a, p));
|
||||
let has_neg = d1 < 0.0 || d2 < 0.0 || d3 < 0.0;
|
||||
let has_pos = d1 > 0.0 || d2 > 0.0 || d3 > 0.0;
|
||||
if !(has_neg && has_pos) {
|
||||
blend_pixel(img, x, y, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 填充圆角矩形(硬边;任务栏缩放到小尺寸后看不出锯齿)。
|
||||
fn fill_rounded_rect(
|
||||
img: &mut image::RgbaImage,
|
||||
x0: u32,
|
||||
y0: u32,
|
||||
x1: u32,
|
||||
y1: u32,
|
||||
radius: u32,
|
||||
color: image::Rgba<u8>,
|
||||
) {
|
||||
if color.0[3] == 0 || x1 <= x0 || y1 <= y0 {
|
||||
return;
|
||||
}
|
||||
let (fx0, fy0, fx1, fy1) = (x0 as f32, y0 as f32, x1 as f32, y1 as f32);
|
||||
let r = (radius as f32).min((fx1 - fx0) / 2.0).min((fy1 - fy0) / 2.0);
|
||||
for y in y0..y1 {
|
||||
let fy = y as f32 + 0.5;
|
||||
for x in x0..x1 {
|
||||
let fx = x as f32 + 0.5;
|
||||
let dx = if fx < fx0 + r {
|
||||
fx0 + r - fx
|
||||
} else if fx > fx1 - r {
|
||||
fx - (fx1 - r)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let dy = if fy < fy0 + r {
|
||||
fy0 + r - fy
|
||||
} else if fy > fy1 - r {
|
||||
fy - (fy1 - r)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
if dx * dx + dy * dy <= r * r {
|
||||
blend_pixel(img, x, y, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 把 `src` 以 alpha 混合写到 `img` 的 (x, y)(不做边界外的处理)。
|
||||
fn blend_pixel(img: &mut image::RgbaImage, x: u32, y: u32, src: image::Rgba<u8>) {
|
||||
if x >= img.width() || y >= img.height() {
|
||||
return;
|
||||
}
|
||||
let sa = src.0[3] as u32;
|
||||
if sa == 0 {
|
||||
return;
|
||||
}
|
||||
if sa == 255 {
|
||||
img.put_pixel(x, y, src);
|
||||
return;
|
||||
}
|
||||
let dst = img.get_pixel(x, y).0;
|
||||
let inv = 255 - sa;
|
||||
let mix = |s: u8, d: u8| ((s as u32 * sa + d as u32 * inv) / 255) as u8;
|
||||
img.put_pixel(
|
||||
x,
|
||||
y,
|
||||
image::Rgba([
|
||||
mix(src.0[0], dst[0]),
|
||||
mix(src.0[1], dst[1]),
|
||||
mix(src.0[2], dst[2]),
|
||||
(sa + dst[3] as u32 * inv / 255) as u8,
|
||||
]),
|
||||
);
|
||||
}
|
||||
+139
-8
@@ -27,6 +27,7 @@ static LAST_MENU_LAYOUT: Mutex<Option<(f64, f64, f64, f64, f64)>> = Mutex::new(N
|
||||
use crate::win32_util::{get_work_area, get_monitor_bounds_at_point, get_dpi_for_point};
|
||||
use crate::mihomo_manager::{MihomoManager, is_pseudo_node};
|
||||
use crate::monitor_kernel::MonitorKernel;
|
||||
use crate::music::{AudioEngine, SmtcMetaCache, SMTC_BUTTON_EVENT};
|
||||
use crate::process_manager::{ProcessManager, ProcessStatus};
|
||||
|
||||
/// 托盘菜单窗口标签
|
||||
@@ -53,6 +54,56 @@ pub struct TrayMenuState {
|
||||
pub proxy_current: Option<String>,
|
||||
}
|
||||
|
||||
/// 托盘音乐控制条状态。
|
||||
///
|
||||
/// 曲目信息取自 [`SmtcMetaCache`](前端推给 SMTC 的元数据回填),
|
||||
/// 播放态取自 [`AudioEngine`]:两者都在 Rust 侧,托盘菜单只需一次拉取。
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MusicState {
|
||||
pub playing: bool,
|
||||
pub title: String,
|
||||
pub artist: String,
|
||||
/// 当前音量(0.0~1.0)
|
||||
pub volume: f32,
|
||||
pub muted: bool,
|
||||
}
|
||||
|
||||
/// 托盘调音量 / 静音后广播给主窗口前端的权威值(前端据此更新 ref 并落盘)。
|
||||
///
|
||||
/// 为什么不走 [`SMTC_BUTTON_EVENT`]:那条通道是「无负载字符串动作」,音量要带数值。
|
||||
pub const TRAY_MUSIC_VOLUME_EVENT: &str = "tray-music-volume";
|
||||
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TrayVolumeState {
|
||||
pub volume: f32,
|
||||
pub muted: bool,
|
||||
}
|
||||
|
||||
fn get_music_state(app: &AppHandle) -> MusicState {
|
||||
let playing = app
|
||||
.try_state::<AudioEngine>()
|
||||
.map(|e| e.state().playing)
|
||||
.unwrap_or(false);
|
||||
// 音量/静音取自引擎:托盘拖动滑块直接改的就是它,这里读到的是真实生效值
|
||||
let (volume, muted) = app
|
||||
.try_state::<AudioEngine>()
|
||||
.map(|e| e.volume())
|
||||
.unwrap_or((1.0, false));
|
||||
let (title, artist) = app
|
||||
.try_state::<SmtcMetaCache>()
|
||||
.and_then(|c| c.0.lock().ok().map(|g| (g.title.clone(), g.artist.clone())))
|
||||
.unwrap_or_default();
|
||||
MusicState {
|
||||
playing,
|
||||
title,
|
||||
artist,
|
||||
volume,
|
||||
muted,
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 状态查询 =====
|
||||
|
||||
fn is_proxy_running(app: &AppHandle) -> bool {
|
||||
@@ -420,14 +471,18 @@ pub async fn tray_menu_action(
|
||||
send_notification(&app, "Kernel 重启失败", &e);
|
||||
}
|
||||
}
|
||||
"download_new" => {
|
||||
focus_main_window(&app);
|
||||
let _ = app.emit(crate::constants::events::TRAY_NEW_DOWNLOAD, ());
|
||||
"terminal" => {
|
||||
// 新建终端选择窗口由前端创建(label 需命中 terminal-window-* 授权)
|
||||
let _ = app.emit(crate::constants::events::TRAY_OPEN_TERMINAL, ());
|
||||
hide_tray_menu(&app);
|
||||
}
|
||||
"settings" => {
|
||||
focus_main_window(&app);
|
||||
let _ = app.emit(crate::constants::events::TRAY_OPEN_SETTINGS, ());
|
||||
"dsh" => {
|
||||
// 未启动时前端会先开进度窗口并同步拉起服务
|
||||
let _ = app.emit(crate::constants::events::TRAY_OPEN_DSH, ());
|
||||
hide_tray_menu(&app);
|
||||
}
|
||||
"editor" => {
|
||||
let _ = app.emit(crate::constants::events::TRAY_OPEN_EDITOR, ());
|
||||
hide_tray_menu(&app);
|
||||
}
|
||||
"quit" => {
|
||||
@@ -463,6 +518,63 @@ pub async fn tray_menu_hide(app: AppHandle) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 读取音乐控制条状态(托盘菜单显示时 / 可见期间轮询)。
|
||||
#[tauri::command]
|
||||
pub fn tray_music_state(app: AppHandle) -> MusicState {
|
||||
get_music_state(&app)
|
||||
}
|
||||
|
||||
/// 托盘音乐控制条动作。
|
||||
///
|
||||
/// 播放语义(队列、洗牌、单曲循环等)都在前端,托盘只负责转发:
|
||||
/// - 播放/暂停/上下首/切换播放顺序 → [`SMTC_BUTTON_EVENT`] 转给主窗口前端(`feiniuStore`)执行;
|
||||
/// - 音量与静音**直接改 Rust 侧引擎**(拖动滑块要即时出声,不能等一轮事件往返),
|
||||
/// 改完把权威值经 [`TRAY_MUSIC_VOLUME_EVENT`] 广播给前端,由它更新 ref 并落盘。
|
||||
///
|
||||
/// `action`:`toggle` | `play` | `pause` | `next` | `prev` | `toggle-mode` | `volume` | `toggle-mute`。
|
||||
/// `level`:仅 `volume` 需要(0.0~1.0)。
|
||||
#[tauri::command]
|
||||
pub fn tray_music_control(
|
||||
app: AppHandle,
|
||||
action: String,
|
||||
level: Option<f32>,
|
||||
) -> Result<(), String> {
|
||||
if action == "volume" || action == "toggle-mute" {
|
||||
let engine = app.try_state::<AudioEngine>().ok_or("播放引擎未初始化")?;
|
||||
let (cur, muted) = engine.volume();
|
||||
if action == "volume" {
|
||||
let v = level.ok_or("volume 动作缺少 level")?.clamp(0.0, 1.0);
|
||||
// 调到非零即解除静音(与手机遥控的音量语义一致)
|
||||
engine.set_volume(v, if v > 0.0 { false } else { muted });
|
||||
} else {
|
||||
engine.set_volume(cur, !muted);
|
||||
}
|
||||
let (volume, muted) = engine.volume();
|
||||
return app
|
||||
.emit(TRAY_MUSIC_VOLUME_EVENT, TrayVolumeState { volume, muted })
|
||||
.map_err(|e| e.to_string());
|
||||
}
|
||||
|
||||
let name = match action.as_str() {
|
||||
"play" => "play",
|
||||
"pause" => "pause",
|
||||
// 无当前会话时按下「播放/暂停」应重新起播,故按引擎真实态决定
|
||||
"toggle" => {
|
||||
if get_music_state(&app).playing {
|
||||
"pause"
|
||||
} else {
|
||||
"play"
|
||||
}
|
||||
}
|
||||
"next" => "next",
|
||||
"prev" => "prev",
|
||||
// 播放顺序(列表循环 / 单曲循环 / 随机)由前端维护,这里只转发
|
||||
"toggle-mode" => "toggle-mode",
|
||||
other => return Err(format!("未知的音乐控制动作: {other}")),
|
||||
};
|
||||
app.emit(SMTC_BUTTON_EVENT, name).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 前端测量内容高度后调用:调整窗口大小、精确定位、然后显示。
|
||||
/// 这样窗口从一开始就是正确尺寸和位置,不会出现间隙。
|
||||
#[tauri::command]
|
||||
@@ -475,8 +587,11 @@ pub async fn tray_menu_ready(content_height: f64, app: AppHandle) -> Result<(),
|
||||
layout.unwrap_or((0.0, 1040.0, 0.0, 1080.0, 1.0))
|
||||
};
|
||||
|
||||
// 将内容高度限制在合理范围内(前端上报为逻辑像素)
|
||||
let h = content_height.max(100.0).min(520.0);
|
||||
// 可用高度:光标所在位置到屏幕顶部的空间(菜单底部对齐光标向上展开)。
|
||||
// 不再用固定上限,内容多时窗口按内容完整撑开;仅当内容超过可用空间时才收窄
|
||||
// (此时前端 .tray-menu-scroll 退化为滚动)。
|
||||
let avail_logical = (cursor_y - scr_top).max(0.0) / scale;
|
||||
let h = content_height.max(100.0).min(avail_logical.max(100.0));
|
||||
|
||||
// 调整窗口尺寸(物理像素,与物理坐标定位保持一致,避免混合 DPI 换算偏移)
|
||||
let win_w_px = MENU_W * scale;
|
||||
@@ -502,6 +617,22 @@ pub async fn tray_menu_ready(content_height: f64, app: AppHandle) -> Result<(),
|
||||
let mut t = LAST_SHOW_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*t = Some(Instant::now());
|
||||
}
|
||||
|
||||
// 位置与尺寸先交给一次原生 SetWindowPos 落位:窗口隐藏时,上面的 set_size/set_position
|
||||
// 不保证在紧随其后的 show 之前生效,首次弹出会沿用预创建时的旧高度——表现为
|
||||
// 「第一次高度不对、收起后再开正常」。原生调用同步返回,窗口已处于目标位置与尺寸。
|
||||
// 显示仍走 Tauri 的 show():它才会做 tao 的可见性/激活/Z 序处理(直接 SWP_SHOWWINDOW
|
||||
// 会让菜单掉到任务栏后面,且窗口拿不到焦点,失焦自动关闭随之失效)。
|
||||
#[cfg(windows)]
|
||||
if let Ok(hwnd) = win.hwnd() {
|
||||
crate::win32_util::set_bounds(
|
||||
hwnd.0 as isize,
|
||||
x as i32,
|
||||
y as i32,
|
||||
win_w_px as i32,
|
||||
win_h_px as i32,
|
||||
);
|
||||
}
|
||||
let _ = win.show();
|
||||
let _ = win.set_focus();
|
||||
|
||||
|
||||
@@ -21,6 +21,41 @@ pub fn set_app_user_model_id(app_id: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 给**单个窗口**设置 AppUserModelID(窗口级 AUMID),使其在任务栏**独立成组**。
|
||||
///
|
||||
/// 进程级 AUMID(见 [`set_app_user_model_id`])会让整个应用的所有窗口合并成一个任务栏
|
||||
/// 按钮;子窗口想要自己的按钮与图标,就用窗口级 AUMID 覆盖它 —— 任务栏按窗口的
|
||||
/// `PKEY_AppUserModel_ID` 决定分组,不同值即不同按钮。
|
||||
///
|
||||
/// **必须在窗口首次 `show()` 之前调用**:任务栏按钮在窗口显示时创建并按 AUMID 分组,
|
||||
/// 显示之后再改往往要 hide/show 才重新生效。
|
||||
///
|
||||
/// 本函数由 Tauri 同步命令调用(跑在主线程,COM 已由 WebView2 初始化为 STA),
|
||||
/// 因此不再自行 `CoInitializeEx`。
|
||||
#[cfg(windows)]
|
||||
pub fn set_window_app_user_model_id(hwnd: isize, app_id: &str) -> Result<(), String> {
|
||||
use windows62::Win32::Foundation::HWND;
|
||||
use windows62::Win32::Storage::EnhancedStorage::PKEY_AppUserModel_ID;
|
||||
use windows62::Win32::System::Com::StructuredStorage::PROPVARIANT;
|
||||
use windows62::Win32::UI::Shell::PropertiesSystem::{IPropertyStore, SHGetPropertyStoreForWindow};
|
||||
|
||||
// SAFETY: hwnd 来自当前进程的真实窗口,且在调用期间保持有效;PROPVARIANT 由 &str 构造。
|
||||
unsafe {
|
||||
let store: IPropertyStore = SHGetPropertyStoreForWindow(HWND(hwnd as *mut core::ffi::c_void))
|
||||
.map_err(|e| format!("SHGetPropertyStoreForWindow 失败: {e}"))?;
|
||||
let value: PROPVARIANT = app_id.into();
|
||||
store
|
||||
.SetValue(&PKEY_AppUserModel_ID, &value)
|
||||
.map_err(|e| format!("写入 PKEY_AppUserModel_ID 失败: {e}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn set_window_app_user_model_id(_hwnd: isize, _app_id: &str) -> Result<(), String> {
|
||||
Err("窗口级 AUMID 仅支持 Windows".into())
|
||||
}
|
||||
|
||||
/// 获取鼠标位置(屏幕坐标,物理像素)
|
||||
#[cfg(windows)]
|
||||
pub fn get_cursor_pos() -> Option<(i32, i32)> {
|
||||
@@ -141,6 +176,33 @@ pub fn force_foreground(hwnd: isize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 显示 + 取消最小化 + 强制置前(按窗口 label 定位)。
|
||||
///
|
||||
/// 前端 `setFocus()` 在 Windows 上同样受前台锁定限制(本进程不拥有前台时被忽略),
|
||||
/// 表现就是「窗口明明开着却唤不到前面」。这里统一走原生
|
||||
/// [`force_foreground`](SetForegroundWindow + BringWindowToTop),与下载窗口 /
|
||||
/// 快速面板 / 托盘同一套做法。
|
||||
///
|
||||
/// 窗口不存在时**不报错**(已关闭 = 目标已达成),让调用方少写一层判空。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn window_focus_window(app: tauri::AppHandle, label: String) -> Result<(), String> {
|
||||
use tauri::Manager;
|
||||
|
||||
let Some(window) = app.get_webview_window(&label) else {
|
||||
return Ok(());
|
||||
};
|
||||
window.show().map_err(|e| e.to_string())?;
|
||||
window.unminimize().map_err(|e| e.to_string())?;
|
||||
match window.hwnd() {
|
||||
Ok(hwnd) => force_foreground(hwnd.0 as isize),
|
||||
Err(_) => {
|
||||
window.set_focus().ok();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 应用 WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW 扩展样式到指定窗口。
|
||||
/// 用于预览窗等不抢焦点的悬浮窗:窗口可接收鼠标交互但不激活、不进 Alt-Tab。
|
||||
#[cfg(windows)]
|
||||
@@ -233,6 +295,45 @@ pub fn hide_window(hwnd: isize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 一次调用原子地设置窗口位置与**客户区**尺寸(物理像素),不改变可见性与 Z 序。
|
||||
///
|
||||
/// `w`/`h` 是客户区(内容区)尺寸,不是外框尺寸——调用方量的是内容高度,这里负责换算:
|
||||
/// `SetWindowPos` 的宽高按**外框**算,而无边框 + 阴影的窗口外侧还有一段 DWM 阴影边距,
|
||||
/// 直接把它当外框传会把客户区压小、内容底下被裁掉。换算方式与 tao 的 `set_inner_size`
|
||||
/// 一致:用 `GetWindowRect - GetClientRect` 得到这段隐藏偏移后补上去。
|
||||
///
|
||||
/// 存在的理由:窗口处于隐藏态时,Tauri 的 `set_size`/`set_position` 不保证在紧随其后的
|
||||
/// `show` 之前落到窗口上——托盘菜单首次弹出因此沿用预创建时的旧高度,收起后再开才正常。
|
||||
/// `SetWindowPos` 是同步调用,返回时窗口已在目标位置与尺寸上;先由它落位、再走 Tauri 的
|
||||
/// `show()`,首次显示即为最终尺寸且无中间帧。
|
||||
///
|
||||
/// 注意**不要**在这里加 `SWP_SHOWWINDOW`:那会绕开 tao 的可见性/激活处理,
|
||||
/// 窗口既不置顶(掉到任务栏后面)也拿不到焦点(继而不能靠失焦自动关闭)。
|
||||
#[cfg(windows)]
|
||||
pub fn set_bounds(hwnd: isize, x: i32, y: i32, w: i32, h: i32) {
|
||||
use windows_sys::Win32::Foundation::RECT;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||
GetClientRect, GetWindowRect, SetWindowPos, SWP_NOACTIVATE, SWP_NOZORDER,
|
||||
};
|
||||
unsafe {
|
||||
let (mut wr, mut cr): (RECT, RECT) = (std::mem::zeroed(), std::mem::zeroed());
|
||||
if GetWindowRect(hwnd, &mut wr) == 0 || GetClientRect(hwnd, &mut cr) == 0 {
|
||||
return;
|
||||
}
|
||||
let frame_w = (wr.right - wr.left) - (cr.right - cr.left);
|
||||
let frame_h = (wr.bottom - wr.top) - (cr.bottom - cr.top);
|
||||
SetWindowPos(
|
||||
hwnd,
|
||||
0,
|
||||
x,
|
||||
y,
|
||||
w + frame_w,
|
||||
h + frame_h,
|
||||
SWP_NOACTIVATE | SWP_NOZORDER,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 系统自上次用户输入(鼠标/键盘)以来的空闲时长(毫秒)。
|
||||
/// 用于闲时执行耗时后台任务(如文件索引构建),避免与应用运行/用户操作抢 IO。
|
||||
/// GetLastInputInfo 的 dwTime 与 GetTickCount 同为系统启动后毫秒数,用 wrapping 减法防回绕。
|
||||
@@ -288,5 +389,8 @@ pub fn show_no_activate(_hwnd: isize) {}
|
||||
#[cfg(not(windows))]
|
||||
pub fn hide_window(_hwnd: isize) {}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn set_bounds(_hwnd: isize, _x: i32, _y: i32, _w: i32, _h: i32) {}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn get_idle_time_ms() -> u64 { 0 }
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "thing",
|
||||
"version": "26.9.4",
|
||||
"version": "26.10.1",
|
||||
"identifier": "thing.lfeng.me",
|
||||
"build": {
|
||||
"beforeDevCommand": "bun run dev",
|
||||
@@ -38,7 +38,18 @@
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"resources": ["binaries/*", "resources/thing-extension/**/*"],
|
||||
"fileAssociations": [
|
||||
{
|
||||
"ext": ["md", "markdown", "mdx"],
|
||||
"name": "Markdown 文档",
|
||||
"description": "用 Thing 编辑器打开 Markdown 文档",
|
||||
"role": "Editor"
|
||||
}
|
||||
],
|
||||
"windows": {
|
||||
"wix": {
|
||||
"language": "zh-CN"
|
||||
},
|
||||
"nsis": {
|
||||
"compression": "lzma"
|
||||
}
|
||||
|
||||
+51
-14
@@ -14,10 +14,14 @@ import { useScreenshotStore } from '@/stores/screenshotStore'
|
||||
import { useQuickPanelStore } from '@/stores/quickpanelStore'
|
||||
import { useMonitorStore } from '@/stores/monitorStore'
|
||||
import { useProcessStore } from '@/stores/processStore'
|
||||
import { useDshStore } from '@/stores/dshStore'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import { moduleRegistry } from '@/modules/registry'
|
||||
import type { ModuleMeta } from '@/types/module'
|
||||
import { pendingNewDownload } from '@/lib/trayEvents'
|
||||
import { openTerminalPickerWindow } from '@/modules/terminal/openWindow'
|
||||
import { openEditorWindow } from '@/modules/editor/openWindow'
|
||||
import { openDiffWindow } from '@/modules/diff/openWindow'
|
||||
import { EVENTS, STORAGE_KEYS, WINDOWS } from '@/lib/constants'
|
||||
import { commands } from '@/lib/bindings'
|
||||
|
||||
@@ -27,6 +31,8 @@ const screenshotStore = useScreenshotStore()
|
||||
const quickpanelStore = useQuickPanelStore()
|
||||
const monitorStore = useMonitorStore()
|
||||
const processStore = useProcessStore()
|
||||
const dshStore = useDshStore()
|
||||
const editorStore = useEditorStore()
|
||||
|
||||
/** 侧边栏 / 标题栏需要的模块信息(id + name + icon) */
|
||||
interface NavModule {
|
||||
@@ -244,15 +250,51 @@ onMounted(async () => {
|
||||
|
||||
// 监听托盘菜单事件
|
||||
// tray:toggle-osd 由 monitorStore.initOsd() 注册的监听处理(与监控模块生命周期解耦)
|
||||
// 托盘「终端」:开「新建终端选择窗口」(与快捷键同一条路径,全程不打扰主窗口)
|
||||
trayUnlisteners.push(
|
||||
await listen(EVENTS.trayNewDownload, () => {
|
||||
// 设置标志位,DownloaderModule 挂载后消费
|
||||
pendingNewDownload.value = true
|
||||
// 切换到下载模块(如果未启用则切换到设置)
|
||||
const enabledIds = appStore.enabledModules.map(m => m.id)
|
||||
if (enabledIds.includes('downloader') || moduleRegistry.getConfig('downloader')?.builtin) {
|
||||
handleModuleChange('downloader')
|
||||
}
|
||||
await listen(EVENTS.trayOpenTerminal, () => {
|
||||
void openTerminalPickerWindow().catch(e =>
|
||||
console.error('[tray] 打开终端窗口失败:', e)
|
||||
)
|
||||
})
|
||||
)
|
||||
// 托盘「编辑器」:开编辑器独立窗口
|
||||
trayUnlisteners.push(
|
||||
await listen(EVENTS.trayOpenEditor, () => {
|
||||
void openEditorWindow().catch(e => console.error('[tray] 打开编辑器窗口失败:', e))
|
||||
})
|
||||
)
|
||||
// 全局快捷键 Alt+E:打开 / 唤出编辑器窗口。
|
||||
//
|
||||
// **必须挂在应用级**(而非编辑器模块页里):快捷键要在任意模块下都能用 —— 挂在模块页
|
||||
// 只有当编辑器页已挂载时才有效,于是「刚启动应用、还没进过编辑器页」时按 Alt+E 毫无反应
|
||||
// (同 main.ts 里 dsh 快捷键的取舍:模块卸载不能把快捷键带走)。
|
||||
trayUnlisteners.push(
|
||||
await listen(EVENTS.editorOpenEditor, () => {
|
||||
void openEditorWindow().catch(e => console.error('[shortcut] 打开编辑器窗口失败:', e))
|
||||
})
|
||||
)
|
||||
// 全局快捷键 Alt+C:打开 / 唤出对比窗口(默认值,见 Rust `DiffSettings::default`)。
|
||||
// 同样必须挂在应用级:快捷键要在任意模块下都能用,挂在对比模块页里会导致
|
||||
// 「刚启动、还没进过对比页」时按了没反应(同上面 Alt+E 的取舍)。
|
||||
trayUnlisteners.push(
|
||||
await listen(EVENTS.diffOpenWindow, () => {
|
||||
void openDiffWindow().catch(e => console.error('[shortcut] 打开对比窗口失败:', e))
|
||||
})
|
||||
)
|
||||
// 全局快捷键 Ctrl+Shift+N:新建笔记。
|
||||
// 对话框在编辑器模块页 → 先置挂起请求、再切到该页(模块挂载时消费,见 EditorModule);
|
||||
// 同理不能放进模块页里监听,否则没进过编辑器页时按了没反应。
|
||||
trayUnlisteners.push(
|
||||
await listen(EVENTS.editorNewNote, () => {
|
||||
editorStore.requestNewNote()
|
||||
handleModuleChange('editor')
|
||||
})
|
||||
)
|
||||
// 托盘「dsh」:就绪则直接开界面,否则先开启动进度窗口并同步拉起服务
|
||||
trayUnlisteners.push(
|
||||
await listen(EVENTS.trayOpenDsh, () => {
|
||||
void dshStore.openFromTray().catch(e => console.error('[tray] 打开 dsh 失败:', e))
|
||||
})
|
||||
)
|
||||
// 浏览器扩展新增下载:为该任务创建一个专属的一次性下载窗口(不打断主界面)。
|
||||
@@ -263,11 +305,6 @@ onMounted(async () => {
|
||||
void openDownloadWindow(e.payload.id)
|
||||
})
|
||||
)
|
||||
trayUnlisteners.push(
|
||||
await listen(EVENTS.trayOpenSettings, () => {
|
||||
handleModuleChange('settings')
|
||||
})
|
||||
)
|
||||
// 截图导出监听(应用级常驻,确保任何来源的截图都记录到历史)
|
||||
screenshotStore.initExportListener().catch(e => console.error('[screenshot] 导出监听初始化失败:', e))
|
||||
// 滚动截图完成 → 进编辑器(应用级常驻)
|
||||
|
||||
@@ -24,50 +24,65 @@ const displayModules = computed(() => {
|
||||
class="w-17 shrink-0 flex flex-col items-center py-4 border-r border-border transition-[background-color,border-color] duration-300"
|
||||
:style="{ backgroundColor: 'var(--effect-bg)', backdropFilter: 'var(--effect-blur)' }"
|
||||
>
|
||||
<div class="flex flex-col gap-1">
|
||||
<div v-for="module in displayModules" :key="module.id">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
:variant="activeModule === module.id ? 'default' : 'ghost'"
|
||||
size="icon"
|
||||
class="size-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
||||
:class="{
|
||||
'bg-primary text-primary-foreground shadow-md': activeModule === module.id,
|
||||
'hover:bg-secondary/50': activeModule !== module.id
|
||||
}"
|
||||
@click="activeModule !== module.id && emit('change', module.id)"
|
||||
>
|
||||
<component :is="getModuleIcon(module.icon)" class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right" class="w-fit">
|
||||
<p>{{ module.name }}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<!-- 模块列表:超出侧边栏高度时可滚动(隐藏滚动条),避免把底部的「常规设置」挤出视口 -->
|
||||
<div class="sidebar-scroll w-full flex-1 min-h-0 overflow-y-auto">
|
||||
<div class="flex flex-col items-center gap-1">
|
||||
<div v-for="module in displayModules" :key="module.id">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
:variant="activeModule === module.id ? 'default' : 'ghost'"
|
||||
size="icon"
|
||||
class="size-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
||||
:class="{
|
||||
'bg-primary text-primary-foreground shadow-md': activeModule === module.id,
|
||||
'hover:bg-secondary/50': activeModule !== module.id
|
||||
}"
|
||||
@click="activeModule !== module.id && emit('change', module.id)"
|
||||
>
|
||||
<component :is="getModuleIcon(module.icon)" class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right" class="w-fit">
|
||||
<p>{{ module.name }}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1"></div>
|
||||
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
:variant="activeModule === 'settings' ? 'default' : 'ghost'"
|
||||
size="icon"
|
||||
class="size-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
||||
:class="{
|
||||
'bg-primary text-primary-foreground shadow-md': activeModule === 'settings',
|
||||
'hover:bg-secondary/50': activeModule !== 'settings'
|
||||
}"
|
||||
@click="activeModule !== 'settings' && emit('change', 'settings')"
|
||||
>
|
||||
<Settings class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right" class="w-fit">
|
||||
<p>常规设置</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<!-- 常规设置:固定在底部,不参与滚动 -->
|
||||
<div class="shrink-0 pt-1">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
:variant="activeModule === 'settings' ? 'default' : 'ghost'"
|
||||
size="icon"
|
||||
class="size-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
||||
:class="{
|
||||
'bg-primary text-primary-foreground shadow-md': activeModule === 'settings',
|
||||
'hover:bg-secondary/50': activeModule !== 'settings'
|
||||
}"
|
||||
@click="activeModule !== 'settings' && emit('change', 'settings')"
|
||||
>
|
||||
<Settings class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right" class="w-fit">
|
||||
<p>常规设置</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 模块列表滚动条隐藏(Firefox + Chromium),滚动仍可用 */
|
||||
.sidebar-scroll {
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.sidebar-scroll::-webkit-scrollbar {
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
</style>
|
||||
+1462
File diff suppressed because it is too large.
Load diff
+47
-2
@@ -27,6 +27,18 @@ export const WINDOWS = {
|
||||
* 时,webview 仍可正常加载与交互,只是拿不到 IPC)。
|
||||
*/
|
||||
dshWeb: 'dsh-web',
|
||||
/** 编辑器独立窗口前缀,实际 label = `${editorWindow}-<n>`(可多开) */
|
||||
editorWindow: 'editor-window',
|
||||
/**
|
||||
* dsh「启动进度」独立窗口(单例)。
|
||||
* 服务就绪后由主窗口打开真正的 {@link dshWeb} 窗口并关闭它。
|
||||
*/
|
||||
dshWindow: 'dsh-window',
|
||||
/**
|
||||
* 对比工具独立窗口(单例)。双栏差异视图 + 目录三态树,
|
||||
* 与编辑器窗口同一范式(隐藏创建 → 应用主题 → 设置任务栏身份 → show)。
|
||||
*/
|
||||
diffWindow: 'diff-window',
|
||||
} as const
|
||||
|
||||
/** Tauri 事件名(前端 emit / listen 与 Rust constants::events 对应) */
|
||||
@@ -35,8 +47,12 @@ export const EVENTS = {
|
||||
trayMenuShow: 'tray-menu-show',
|
||||
trayMenuStateUpdated: 'tray-menu-state-updated',
|
||||
trayToggleOsd: 'tray:toggle-osd',
|
||||
trayNewDownload: 'tray:new-download',
|
||||
trayOpenSettings: 'tray:open-settings',
|
||||
/** 托盘「终端」:打开新建终端选择窗口 */
|
||||
trayOpenTerminal: 'tray:open-terminal',
|
||||
/** 托盘「dsh」:打开 dsh 独立窗口(未启动时先显示启动进度) */
|
||||
trayOpenDsh: 'tray:open-dsh',
|
||||
/** 托盘「编辑器」:打开编辑器独立窗口 */
|
||||
trayOpenEditor: 'tray:open-editor',
|
||||
// 剪贴板
|
||||
clipboardChanged: 'clipboard-changed',
|
||||
clipboardPopupShow: 'clipboard-popup-show',
|
||||
@@ -147,6 +163,35 @@ export const EVENTS = {
|
||||
dshServerState: 'dsh-server-state',
|
||||
/** 全局快捷键按下:打开 dsh 独立窗口(无负载) */
|
||||
dshOpenWindow: 'dsh-open-window',
|
||||
/** 笔记:设置已保存(无负载)。各窗口据此重读设置,实现跨窗口同步 */
|
||||
editorSettings: 'editor-settings',
|
||||
/** 笔记:库内容已变更(新建/保存/重命名/删除/切换库根,无负载) */
|
||||
editorLibraryChanged: 'editor-library-changed',
|
||||
/** 笔记:库内文件在应用外被改动(负载见 src/types/editor.ts 的 NoteFileEvent) */
|
||||
editorFileChanged: 'editor-file-changed',
|
||||
/** 笔记:WebDAV 同步进度(负载见 src/types/editor.ts 的 SyncProgress) */
|
||||
editorSyncProgress: 'editor-sync-progress',
|
||||
/** 笔记:全局快捷键「新建笔记」被按下(无负载;主窗口据此打开新建对话框) */
|
||||
editorNewNote: 'editor-new-note',
|
||||
/** 笔记:全局快捷键「打开编辑器」被按下(无负载) */
|
||||
editorOpenEditor: 'editor-open-editor',
|
||||
/** 笔记:需要打开一个磁盘文件(负载 `{ path }`;来自文件关联 / 命令行) */
|
||||
editorOpenFile: 'editor-open-file',
|
||||
/** 编辑器:需要打开一个文件夹(负载 `{ path }`;来自资源管理器右键) */
|
||||
editorOpenFolder: 'editor-open-folder',
|
||||
/**
|
||||
* 编辑器:在**既有**编辑器窗口里加一个标签(负载见 `EditorOpenTabPayload`)。
|
||||
* 纯前端事件(Rust 不参与):主窗口在发现有编辑器窗口时用 `emitTo` 定向发给它,
|
||||
* 于是「系统右键 / 主界面打开历史文件」不会再多开一个窗口。
|
||||
*/
|
||||
editorOpenTab: 'editor-open-tab',
|
||||
// 对比:全局快捷键按下「打开对比窗口」(无负载;窗口由前端创建,见 modules/diff/openWindow.ts)
|
||||
diffOpenWindow: 'diff-open-window',
|
||||
/**
|
||||
* 对比:目录扫描进度(负载见 src/modules/diff/types.ts 的 DiffScanProgress)。
|
||||
* 进度在 Rust 侧按时间节流发送;前端按 `scanId` 过滤(事件是全局的)。
|
||||
*/
|
||||
diffScanProgress: 'diff-scan-progress',
|
||||
} as const
|
||||
|
||||
/** localStorage 存储键 */
|
||||
|
||||
+9
-2
@@ -43,18 +43,25 @@ const standaloneWindowApps: Array<[hash: string, label: string, loader: () => Pr
|
||||
['#terminal-window', '终端独立窗口', () => import('./modules/terminal/TerminalWindow.vue')],
|
||||
['#new-terminal-window', '新建终端窗口', () => import('./modules/terminal/NewTerminalWindow.vue')],
|
||||
['#file-window', '文件管理器窗口', () => import('./modules/terminal/FileWindow.vue')],
|
||||
['#editor-window', '编辑器窗口', () => import('./modules/editor/EditorWindow.vue')],
|
||||
['#diff-window', '对比窗口', () => import('./modules/diff/DiffWindow.vue')],
|
||||
['#dsh-window', 'dsh 启动窗口', () => import('./modules/dsh/DshWindow.vue')],
|
||||
]
|
||||
|
||||
const winHash = window.location.hash
|
||||
|
||||
// #screenshot-overlay 带窗口号参数(多屏)、#download-window 带 ?task= 参数,
|
||||
// #terminal-window 带 /{session_id} 路径参数,均按前缀匹配;其余精确匹配
|
||||
// #terminal-window 带 /{session_id} 路径参数、#editor-window 带 ?file=(库内笔记)
|
||||
// 或 ?path=(库外文件)参数、#diff-window 带 ?path=(P2 起的目标文件)参数,
|
||||
// 均按前缀匹配;其余精确匹配
|
||||
const matched = standaloneWindowApps.find(([hash]) => {
|
||||
if (
|
||||
hash === '#screenshot-overlay' ||
|
||||
hash === '#screenshot-scroll' ||
|
||||
hash === '#download-window' ||
|
||||
hash === '#terminal-window'
|
||||
hash === '#terminal-window' ||
|
||||
hash === '#editor-window' ||
|
||||
hash === '#diff-window'
|
||||
)
|
||||
return winHash.startsWith(hash)
|
||||
return winHash === hash
|
||||
|
||||
@@ -89,7 +89,7 @@ watch(selectedId, () => {
|
||||
p-5 属于**滚动内容**(模块根在主滚动区内部),因此卡片阴影四周都有余量,
|
||||
不再需要任何负外边距补偿。
|
||||
|
||||
工具自身需要限高的地方(正则结果、diff 输出等)仍保留各自的 `max-h-*` 内滚动
|
||||
工具自身需要限高的地方(正则结果等)仍保留各自的 `max-h-*` 内滚动
|
||||
盒子 —— 那是「一块有边界的输出区」,与页面级滚动不是一回事。
|
||||
-->
|
||||
<div class="min-h-full p-5 flex flex-col">
|
||||
|
||||
@@ -14,7 +14,7 @@ export const moduleConfig: ModuleConfig = {
|
||||
id: 'devtools',
|
||||
name: '开发者工具',
|
||||
icon: 'devtools',
|
||||
description: 'JSON / Base64 / 时间戳 / 正则 / 颜色 / Cron / 密码等 20 个常用开发工具',
|
||||
description: 'JSON / Base64 / 时间戳 / 正则 / 颜色 / Cron / 密码等 19 个常用开发工具',
|
||||
category: 'tool',
|
||||
defaultEnabled: true,
|
||||
loader: () => import('./DevToolsModule.vue'),
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import ResultArea from '../components/ResultArea.vue'
|
||||
|
||||
const oldText = ref('')
|
||||
const newText = ref('')
|
||||
|
||||
type Op = 'equal' | 'del' | 'add'
|
||||
interface DiffLine {
|
||||
op: Op
|
||||
oldLine: string
|
||||
line: string
|
||||
newLine: string
|
||||
}
|
||||
|
||||
// LCS DP 为 O(n·m),行数过大会卡死 UI;超过上限停止计算并提示
|
||||
const MAX_LINES = 3000
|
||||
|
||||
// 先裁剪公共前缀/后缀,LCS 只算中间差异部分(典型场景提速明显)
|
||||
function diffLines(a: string[], b: string[]): DiffLine[] {
|
||||
const out: DiffLine[] = []
|
||||
let start = 0
|
||||
while (start < a.length && start < b.length && a[start] === b[start]) {
|
||||
out.push({ op: 'equal', oldLine: a[start], line: a[start], newLine: b[start] })
|
||||
start++
|
||||
}
|
||||
let endA = a.length, endB = b.length
|
||||
while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
|
||||
endA--
|
||||
endB--
|
||||
}
|
||||
const mid = lcsDiff(a.slice(start, endA), b.slice(start, endB))
|
||||
// 后缀公共部分:a[endA..] 与 b[endB..] 逐行配对
|
||||
const suffix: DiffLine[] = []
|
||||
for (let i = a.length - 1; i >= endA; i--) {
|
||||
const j = endB + (i - endA)
|
||||
suffix.unshift({ op: 'equal', oldLine: a[i], line: a[i], newLine: b[j] })
|
||||
}
|
||||
return [...out, ...mid, ...suffix]
|
||||
}
|
||||
|
||||
function lcsDiff(a: string[], b: string[]): DiffLine[] {
|
||||
const n = a.length
|
||||
const m = b.length
|
||||
if (n === 0) return b.map(line => ({ op: 'add' as const, oldLine: '', line, newLine: '' }))
|
||||
if (m === 0) return a.map(line => ({ op: 'del' as const, oldLine: line, line, newLine: '' }))
|
||||
// LCS DP
|
||||
const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0))
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
for (let j = m - 1; j >= 0; j--) {
|
||||
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1])
|
||||
}
|
||||
}
|
||||
const out: DiffLine[] = []
|
||||
let i = 0
|
||||
let j = 0
|
||||
while (i < n && j < m) {
|
||||
if (a[i] === b[j]) {
|
||||
out.push({ op: 'equal', oldLine: a[i], line: a[i], newLine: b[j] })
|
||||
i++
|
||||
j++
|
||||
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
|
||||
out.push({ op: 'del', oldLine: a[i], line: a[i], newLine: '' })
|
||||
i++
|
||||
} else {
|
||||
out.push({ op: 'add', oldLine: '', line: b[j], newLine: b[j] })
|
||||
j++
|
||||
}
|
||||
}
|
||||
while (i < n) {
|
||||
out.push({ op: 'del', oldLine: a[i], line: a[i], newLine: '' })
|
||||
i++
|
||||
}
|
||||
while (j < m) {
|
||||
out.push({ op: 'add', oldLine: '', line: b[j], newLine: b[j] })
|
||||
j++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const tooLarge = computed(() =>
|
||||
oldText.value.split('\n').length > MAX_LINES || newText.value.split('\n').length > MAX_LINES
|
||||
)
|
||||
|
||||
const lines = computed(() => {
|
||||
if (tooLarge.value) return []
|
||||
return diffLines(oldText.value.split('\n'), newText.value.split('\n'))
|
||||
})
|
||||
|
||||
const stats = computed(() => {
|
||||
let adds = 0
|
||||
let dels = 0
|
||||
for (const l of lines.value) {
|
||||
if (l.op === 'add') adds++
|
||||
else if (l.op === 'del') dels++
|
||||
}
|
||||
return { adds, dels }
|
||||
})
|
||||
|
||||
const unifiedText = computed(() => {
|
||||
if (lines.value.length === 0) return ''
|
||||
return lines.value
|
||||
.map(l => (l.op === 'add' ? '+' : l.op === 'del' ? '-' : ' ') + l.line)
|
||||
.join('\n')
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs text-danger">旧文本(删除 {{ stats.dels }} 行)</Label>
|
||||
<Textarea v-model="oldText" placeholder="旧文本..." class="min-h-[140px] font-mono text-xs resize-y" />
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs text-success">新文本(新增 {{ stats.adds }} 行)</Label>
|
||||
<Textarea v-model="newText" placeholder="新文本..." class="min-h-[140px] font-mono text-xs resize-y" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs">差异预览</Label>
|
||||
<div class="rounded-md border border-border max-h-64 overflow-auto font-mono text-xs leading-relaxed">
|
||||
<div v-if="tooLarge" class="p-3 text-destructive">文本超过 {{ MAX_LINES }} 行,差异计算已停止(LCS 算法复杂度 O(n·m)),请缩减输入。</div>
|
||||
<div v-else-if="lines.length === 0 || (oldText === '' && newText === '')" class="p-3 text-muted-foreground">输入两边文本查看差异。</div>
|
||||
<div
|
||||
v-for="(l, i) in lines"
|
||||
:key="i"
|
||||
class="flex whitespace-pre px-2 py-0.5"
|
||||
:class="{
|
||||
'bg-danger-soft text-danger-text': l.op === 'del',
|
||||
'bg-success-soft text-success-text': l.op === 'add',
|
||||
'text-muted-foreground': l.op === 'equal'
|
||||
}"
|
||||
>
|
||||
<span class="w-5 shrink-0 select-none">{{ l.op === 'add' ? '+' : l.op === 'del' ? '-' : ' ' }}</span>
|
||||
<span class="break-all">{{ l.line }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ResultArea :text="unifiedText" label="统一格式(可复制)" placeholder="unified diff" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -2,7 +2,7 @@ import type { Component } from 'vue'
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
import {
|
||||
FileJson, Binary, Link, Clock, MoveHorizontal, Fingerprint,
|
||||
Wand2, KeyRound, CaseSensitive, Hash, Code, GitCompare, Shield,
|
||||
Wand2, KeyRound, CaseSensitive, Hash, Code, Shield,
|
||||
Palette, Lock, CalendarClock, Network, Sigma, Replace, Globe
|
||||
} from '@lucide/vue'
|
||||
import { registerTool, type DevTool } from '../registry'
|
||||
@@ -69,11 +69,6 @@ export const TOOLS_META: Array<Omit<DevTool, 'component' | 'icon'>> = [
|
||||
description: '在线测试正则表达式,实时匹配、分组查看与替换预览',
|
||||
keywords: ['正则', 'regex', '匹配', 'test', 're', '替换']
|
||||
},
|
||||
{
|
||||
id: 'diff', name: '文本对比', category: 'text',
|
||||
description: '两段文本逐行差异对比',
|
||||
keywords: ['对比', '差异', 'diff', '比较', 'compare']
|
||||
},
|
||||
{
|
||||
id: 'eol', name: '行尾符转换', category: 'text',
|
||||
description: 'CRLF / LF / CR 行尾符统一',
|
||||
@@ -125,7 +120,6 @@ const TOOL_ICONS: Record<string, Component> = {
|
||||
escape: Code,
|
||||
case: CaseSensitive,
|
||||
regex: Wand2,
|
||||
diff: GitCompare,
|
||||
eol: MoveHorizontal,
|
||||
replace: Replace,
|
||||
charcount: Sigma,
|
||||
@@ -149,7 +143,6 @@ const TOOL_COMPONENTS: Record<string, () => Promise<{ default: Component }>> = {
|
||||
escape: () => import('./EscapeTools.vue'),
|
||||
case: () => import('./CaseTools.vue'),
|
||||
regex: () => import('./RegexTools.vue'),
|
||||
diff: () => import('./DiffTools.vue'),
|
||||
eol: () => import('./EolTools.vue'),
|
||||
replace: () => import('./ReplaceTools.vue'),
|
||||
charcount: () => import('./CharCountTools.vue'),
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 对比工具主模块页(主窗口内)。
|
||||
*
|
||||
* 真正的对比发生在独立窗口(`openWindow.ts`),本页只负责入口、进度说明与设置 ——
|
||||
* 与编辑器模块「主模块页做设置与入口、编辑发生在独立窗口」同一分工。
|
||||
*
|
||||
* 设置项少(只有一个快捷键 + 两个目录对比默认值),因此直接从 Rust 读写,不再单独建
|
||||
* store:`diff_get_settings` / `diff_save_settings` 一次往返就够,且保存后后端会就地
|
||||
* 重注册快捷键,「改完立刻生效」不需要前端额外做什么。
|
||||
*/
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { Diff, FileText, FolderTree, Rows2 } from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { SettingGroup, SettingRow } from '@/components/common'
|
||||
import { diffClient } from './diffClient'
|
||||
import { openDiffWindow } from './openWindow'
|
||||
import type { DiffSettings } from './types'
|
||||
|
||||
/** 三种对比能力。 */
|
||||
const LEVELS = [
|
||||
{
|
||||
id: 'text',
|
||||
name: '文本对比',
|
||||
icon: Rows2,
|
||||
description: '两段文本并排对照,块级高亮差异,可上下跳转',
|
||||
available: true
|
||||
},
|
||||
{
|
||||
id: 'file',
|
||||
name: '文件对比',
|
||||
icon: FileText,
|
||||
description: '两个磁盘文件并排对照,自动探测编码(GBK / Shift_JIS / UTF-8…),支持拖入与单侧写回',
|
||||
available: true
|
||||
},
|
||||
{
|
||||
id: 'folder',
|
||||
name: '文件夹对比',
|
||||
icon: FolderTree,
|
||||
description: '左右两棵结构树,递归比对:仅左侧有 / 仅右侧有 / 内容不同(只读,不做写回)',
|
||||
available: true
|
||||
}
|
||||
]
|
||||
|
||||
const settings = ref<DiffSettings | null>(null)
|
||||
|
||||
async function openDiff(): Promise<void> {
|
||||
try {
|
||||
await openDiffWindow()
|
||||
} catch (e) {
|
||||
toast.error(`打开对比窗口失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 提交一处设置改动(后端保存后会就地重注册快捷键)。 */
|
||||
async function commit(patch: Partial<DiffSettings>): Promise<void> {
|
||||
const current = settings.value
|
||||
if (!current) return
|
||||
try {
|
||||
settings.value = await diffClient.saveSettings({ ...current, ...patch })
|
||||
} catch (e) {
|
||||
toast.error(`保存失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
settings.value = await diffClient.getSettings()
|
||||
} catch (e) {
|
||||
toast.error(`读取设置失败:${String(e)}`)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-full p-5">
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- 状态与入口 -->
|
||||
<Card class="!py-0 !gap-0">
|
||||
<CardContent class="flex flex-wrap items-center gap-x-6 gap-y-3 px-4 py-4">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<span class="flex items-center gap-1.5 text-[13px] text-fg-secondary">
|
||||
<span class="size-2 rounded-full bg-success" />三层均已可用
|
||||
</span>
|
||||
<span class="text-[13px] text-fg-secondary">文本 · 文件 · 文件夹对比</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">当前范围</span>
|
||||
<span class="truncate text-[13px] text-fg-secondary">
|
||||
目录对比为只读(不做写回 / 同步)
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="ml-auto flex flex-wrap gap-2">
|
||||
<Button size="sm" @click="openDiff">
|
||||
<Diff class="size-3.5" />打开对比窗口
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 三种对比层级 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardContent class="flex flex-col divide-y divide-divider !px-4">
|
||||
<div
|
||||
v-for="level in LEVELS"
|
||||
:key="level.id"
|
||||
class="flex items-center gap-4 py-3 first:pt-0 last:pb-0"
|
||||
>
|
||||
<div
|
||||
class="flex size-8 shrink-0 items-center justify-center rounded-lg bg-primary-soft text-primary-soft-text"
|
||||
>
|
||||
<component :is="level.icon" class="size-4" />
|
||||
</div>
|
||||
<div class="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span class="text-[13px] text-foreground">{{ level.name }}</span>
|
||||
<span class="truncate text-xs text-muted-foreground">{{ level.description }}</span>
|
||||
</div>
|
||||
<span class="shrink-0 rounded-sm bg-success-soft px-1.5 py-0.5 text-[10px] text-success-text">
|
||||
可用
|
||||
</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 设置(改动即时生效,无保存按钮) -->
|
||||
<SettingGroup
|
||||
v-if="settings"
|
||||
title="对比窗口"
|
||||
description="快捷键与目录对比的默认行为;改动即时生效,无需保存"
|
||||
>
|
||||
<SettingRow
|
||||
label="打开对比窗口"
|
||||
description="全局快捷键,任意模块下都可用;留空则不注册"
|
||||
control-width="wide"
|
||||
>
|
||||
<Input
|
||||
:model-value="settings.openDiffShortcut"
|
||||
placeholder="Alt+C"
|
||||
spellcheck="false"
|
||||
@change="(e: Event) => commit({ openDiffShortcut: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="目录对比默认比对内容"
|
||||
description="大小相同但时间戳不同时,读文件内容逐字节比对(更准,也更慢)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="settings.compareContent"
|
||||
@update:model-value="v => commit({ compareContent: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="目录对比默认跳过构建目录"
|
||||
description="跳过 node_modules / .git / target 等目录,避免把无关目录也扫一遍"
|
||||
>
|
||||
<Switch
|
||||
:model-value="settings.skipBuildDirs"
|
||||
@update:model-value="v => commit({ skipBuildDirs: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</SettingGroup>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,981 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 目录对比视图(**只读**):左右两棵结构树。
|
||||
*
|
||||
* # 为什么是两棵树,而不是一棵并集树
|
||||
*
|
||||
* 第一版是一棵「三态并集树」(每行用一种颜色标 仅左 / 仅右 / 不同)。但对比工具的心智
|
||||
* 模型是「左边是一个目录、右边是另一个目录」—— 参考 Beyond Compare:两边各自一棵树、
|
||||
* 各自一列大小与修改时间,人一眼就能看出「这个文件只在右边有」。因此这里**两个结构树
|
||||
* 渲染同一份并集行**(行数、顺序完全一致,共用折叠状态),只是每一侧的单元格只显示该侧
|
||||
* 真实存在的文件(另一侧缺失时显示为「—」并把名字压暗)。
|
||||
*
|
||||
* 共用一份行列表还有两个好处:左右永远不错行;将来做「滚动联动」时不需要额外对齐逻辑。
|
||||
*
|
||||
* # 会话状态是「共享可变模型」
|
||||
*
|
||||
* 状态由 `DiffWindow` 持有(一个选项卡一份),本组件直接读写传入的 `session` —— 理由见
|
||||
* `types.ts` 的 `DirSessionState` 注释(8 个字段几乎都双向改,拆成 props/emits 会得到
|
||||
* 十几个定义,而它们本来就是同一个东西)。
|
||||
*
|
||||
* # 点击任意一侧的文件 → 新开一个文件对比选项卡
|
||||
*
|
||||
* 这符合 Beyond Compare 的用法:在目录级先定位「哪个文件不一样」,再下钻到内容级。
|
||||
* 只在一侧存在的文件也可以开(另一侧为空,整篇都是新增/删除)。
|
||||
*/
|
||||
import { computed, markRaw, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { ChevronDown, ChevronRight, FolderOpen, Loader2, RefreshCw } from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { EVENTS } from '@/lib/constants'
|
||||
import { diffClient } from '../diffClient'
|
||||
import type {
|
||||
DiffScanProgress,
|
||||
DiffSide,
|
||||
DirDiffEntry,
|
||||
DirFilterId,
|
||||
DirSessionState
|
||||
} from '../types'
|
||||
|
||||
/**
|
||||
* 会话状态:用 `v-model:session` 而不是普通 prop。
|
||||
*
|
||||
* 本组件要**直接改**会话字段(根路径、过滤、折叠、扫描结果…),而 Vue 的
|
||||
* `vue/no-mutating-props` 明确禁止改 prop。`defineModel` 拿到的是本地 model 引用
|
||||
* (与父组件共享同一个响应式对象),改它的**字段**是合法且惯用的做法 —— 父组件那边
|
||||
* 用 getter-only 的 computed 提供句柄即可(子组件从不整体替换会话,只改字段)。
|
||||
*/
|
||||
const session = defineModel<DirSessionState>('session', { required: true })
|
||||
const emit = defineEmits<{
|
||||
/** 点击某一侧的文件 → 由 DiffWindow 新开一个文件对比选项卡 */
|
||||
'open-file': [payload: { side: DiffSide; entry: DirDiffEntry }]
|
||||
}>()
|
||||
|
||||
const SIDES: readonly DiffSide[] = ['a', 'b']
|
||||
|
||||
/**
|
||||
* 默认跳过的目录名(**唯一事实来源在这里**)。
|
||||
*
|
||||
* 与 `editor` 模块的默认跳过清单保持一致:同一台机器上「哪些目录不值得看」是同一个
|
||||
* 判断,两个功能给出不同的默认值会让人困惑。后端只接收这份清单并按它执行。
|
||||
*/
|
||||
const DEFAULT_SKIP_DIRS =
|
||||
'debug|.vs|.git|.svn|.hg|.idea|.vscode|node_modules|target|dist|build|out|.cache|__pycache__|.venv|venv|vendor|.next|coverage|.tmp-build'
|
||||
.split('|')
|
||||
|
||||
const FILTERS: Array<{ id: DirFilterId; label: string }> = [
|
||||
{ id: 'diff', label: '仅差异' },
|
||||
{ id: 'all', label: '全部' },
|
||||
{ id: 'left-only', label: '仅左侧' },
|
||||
{ id: 'right-only', label: '仅右侧' }
|
||||
]
|
||||
|
||||
const ready = computed(() => !!session.value.leftRoot && !!session.value.rightRoot)
|
||||
|
||||
function rootOf(side: DiffSide): string {
|
||||
return side === 'a' ? session.value.leftRoot : session.value.rightRoot
|
||||
}
|
||||
|
||||
/** 输入框回车 / 失焦即生效(失焦只有值变了才写,避免无意义的重扫)。 */
|
||||
function onRootInput(side: DiffSide, event: Event): void {
|
||||
const value = (event.target as HTMLInputElement).value
|
||||
if (value === rootOf(side)) return
|
||||
setRoot(side, value)
|
||||
}
|
||||
|
||||
/**
|
||||
* 输入框回车。
|
||||
*
|
||||
* 值有改动时**什么都不做**:回车随后会触发 `change`,由它提交并(两侧就绪时)扫描。
|
||||
* 若这里也顺手扫一次,就会先用**旧**根路径白扫一遍(`keydown` 早于 `change`,此刻
|
||||
* 会话里的根还是旧值),表现为「按回车闪一下旧结果再换成新的」。
|
||||
* 值没改时回车 = 重新扫描(这是用户按回车的常见意图)。
|
||||
*/
|
||||
function onRootEnter(side: DiffSide, event: KeyboardEvent): void {
|
||||
const value = (event.target as HTMLInputElement).value
|
||||
if (value !== rootOf(side)) return
|
||||
void compare()
|
||||
}
|
||||
|
||||
/** 图标按钮:系统对话框选目录。 */
|
||||
async function browse(side: DiffSide): Promise<void> {
|
||||
try {
|
||||
const selected = await open({ directory: true, multiple: false, title: '选择要对比的文件夹' })
|
||||
if (typeof selected !== 'string') return
|
||||
setRoot(side, selected)
|
||||
} catch (e) {
|
||||
toast.error(`选择文件夹失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 设定某一侧的根;两侧都就绪时自动开始扫描。 */
|
||||
function setRoot(side: DiffSide, path: string): void {
|
||||
if (side === 'a') session.value.leftRoot = path
|
||||
else session.value.rightRoot = path
|
||||
if (ready.value) void compare()
|
||||
}
|
||||
|
||||
/**
|
||||
* 拖入一个路径:目录直接作为该侧根;文件则取其**所在目录**
|
||||
* (拖一个文件进来想比的是它所在的目录结构,而不是报错)。
|
||||
*/
|
||||
async function loadDropped(side: DiffSide, path: string): Promise<void> {
|
||||
let target = path
|
||||
try {
|
||||
if ((await diffClient.pathKind(path)) === 'file') target = parentDir(path)
|
||||
} catch {
|
||||
/* 探测失败就按原路径试,让 compare 给出明确错误 */
|
||||
}
|
||||
setRoot(side, target)
|
||||
}
|
||||
|
||||
/** 取父目录(同时兼容 `\` 与 `/`)。 */
|
||||
function parentDir(path: string): string {
|
||||
const trimmed = path.replace(/[\\/]+$/, '')
|
||||
const index = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'))
|
||||
return index > 0 ? trimmed.slice(0, index) : trimmed
|
||||
}
|
||||
|
||||
/** 本轮扫描的序号(进度事件按它过滤,见 `compare`)。 */
|
||||
let scanSeq = 0
|
||||
/** 当前扫描的进度(`null` = 还没收到第一帧,界面显示「扫描中…」)。 */
|
||||
const scanProgress = ref<DiffScanProgress | null>(null)
|
||||
let unlistenProgress: UnlistenFn | null = null
|
||||
|
||||
/** 进度文案(`null` = 还没收到进度帧)。 */
|
||||
const progressText = computed(() => {
|
||||
const p = scanProgress.value
|
||||
if (!p) return null
|
||||
const label = p.phase === 'compare' ? '正在核对内容' : '已遍历'
|
||||
return p.total ? `${label} ${p.done} / ${p.total}` : `${label} ${p.done} 项`
|
||||
})
|
||||
|
||||
async function compare(): Promise<void> {
|
||||
if (!ready.value) return
|
||||
session.value.scanning = true
|
||||
// 每轮扫描一个新的 id:进度事件是**全局**的(Rust 侧不区分选项卡),用一个自增 id
|
||||
// 把别人的进度过滤掉 —— 否则切到另一个正在扫的目录选项卡时会看到对不上的计数。
|
||||
const id = ++scanSeq
|
||||
scanProgress.value = null
|
||||
try {
|
||||
const report = await diffClient.compareDirs(
|
||||
id,
|
||||
session.value.leftRoot,
|
||||
session.value.rightRoot,
|
||||
session.value.skipBuild ? DEFAULT_SKIP_DIRS : [],
|
||||
session.value.compareContent
|
||||
)
|
||||
// markRaw:条目可达数千,让它进响应式系统会逐条生成 Proxy(纯开销)
|
||||
session.value.report = markRaw(report)
|
||||
session.value.collapsed = new Set()
|
||||
} catch (e) {
|
||||
session.value.report = null
|
||||
toast.error(`目录对比失败:${String(e)}`)
|
||||
} finally {
|
||||
session.value.scanning = false
|
||||
scanProgress.value = null
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 树 =====
|
||||
interface TreeNode {
|
||||
relPath: string
|
||||
name: string
|
||||
depth: number
|
||||
isDir: boolean
|
||||
entry: DirDiffEntry | null
|
||||
children: TreeNode[]
|
||||
/** 自身或子树里是否有「值得显示」的条目 */
|
||||
significant: boolean
|
||||
}
|
||||
|
||||
function matches(entry: DirDiffEntry): boolean {
|
||||
switch (session.value.filter) {
|
||||
case 'all':
|
||||
return true
|
||||
case 'diff':
|
||||
return entry.status === 'different' || entry.status === 'type-mismatch'
|
||||
case 'left-only':
|
||||
return entry.status === 'left-only'
|
||||
case 'right-only':
|
||||
return entry.status === 'right-only'
|
||||
}
|
||||
}
|
||||
|
||||
/** 由扁平条目组装成树(缺失的中间目录会被补齐,避免因截断 / 跳过而丢上下文)。 */
|
||||
function buildTree(entries: DirDiffEntry[]): TreeNode {
|
||||
const root: TreeNode = {
|
||||
relPath: '',
|
||||
name: '',
|
||||
depth: 0,
|
||||
isDir: true,
|
||||
entry: null,
|
||||
children: [],
|
||||
significant: false
|
||||
}
|
||||
const map = new Map<string, TreeNode>([['', root]])
|
||||
|
||||
const ensure = (relPath: string): TreeNode => {
|
||||
const existing = map.get(relPath)
|
||||
if (existing) return existing
|
||||
const cut = relPath.lastIndexOf('/')
|
||||
const name = cut < 0 ? relPath : relPath.slice(cut + 1)
|
||||
const parent = ensure(cut < 0 ? '' : relPath.slice(0, cut))
|
||||
const node: TreeNode = {
|
||||
relPath,
|
||||
name,
|
||||
depth: parent.depth + 1,
|
||||
isDir: false,
|
||||
entry: null,
|
||||
children: [],
|
||||
significant: false
|
||||
}
|
||||
parent.children.push(node)
|
||||
map.set(relPath, node)
|
||||
return node
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
const node = ensure(entry.relPath)
|
||||
node.entry = entry
|
||||
node.isDir = entry.isDir
|
||||
}
|
||||
|
||||
// 目录在前、同级按名字排序(与资源管理器的观感一致)
|
||||
for (const node of map.values()) {
|
||||
node.children.sort((a, b) => {
|
||||
if (a.isDir !== b.isDir) return a.isDir ? -1 : 1
|
||||
return a.name.localeCompare(b.name)
|
||||
})
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
/** 自底向上标注「这一支有没有值得显示的东西」。 */
|
||||
function markSignificant(node: TreeNode): boolean {
|
||||
let childSignificant = false
|
||||
for (const child of node.children) {
|
||||
// 注意顺序:先递归再取返回值,不能短路(短路会让后面的分支不被标注)
|
||||
if (markSignificant(child)) childSignificant = true
|
||||
}
|
||||
node.significant = childSignificant || (node.entry ? matches(node.entry) : false)
|
||||
return node.significant
|
||||
}
|
||||
|
||||
/** 由扁平条目组装成的树(只随扫描结果变化;过滤条件不影响它的结构)。 */
|
||||
const builtTree = computed<TreeNode>(() => {
|
||||
const current = session.value.report
|
||||
return buildTree(current ? current.entries : [])
|
||||
})
|
||||
|
||||
/**
|
||||
* 带「值得显示」标注的树。
|
||||
*
|
||||
* 与 `builtTree` 拆开,是为了**不让过滤条件的变化触发整棵树的重新组装**:`buildTree` 是
|
||||
* O(条目数) 的分配 + 排序,而 `markSignificant` 只是在既有节点上重算一个布尔量。原来两步
|
||||
* 挤在同一个 computed 里,点一下「仅差异 / 仅左侧」就要把全部节点重新建一遍。
|
||||
*/
|
||||
const tree = computed<TreeNode>(() => {
|
||||
const root = builtTree.value
|
||||
markSignificant(root)
|
||||
return root
|
||||
})
|
||||
|
||||
/** 展平成可渲染的行(跳过被剪掉的与折叠的)。左右两个结构树共用这份行。 */
|
||||
const rows = computed<Array<{ node: TreeNode; depth: number }>>(() => {
|
||||
const out: Array<{ node: TreeNode; depth: number }> = []
|
||||
const collapsed = session.value.collapsed
|
||||
const walk = (node: TreeNode): void => {
|
||||
for (const child of node.children) {
|
||||
if (!child.significant) continue
|
||||
out.push({ node: child, depth: child.depth })
|
||||
if (child.isDir && !collapsed.has(child.relPath)) walk(child)
|
||||
}
|
||||
}
|
||||
walk(tree.value)
|
||||
return out
|
||||
})
|
||||
|
||||
function toggleDir(relPath: string): void {
|
||||
const next = new Set(session.value.collapsed)
|
||||
if (next.has(relPath)) next.delete(relPath)
|
||||
else next.add(relPath)
|
||||
session.value.collapsed = next
|
||||
}
|
||||
|
||||
/** 展开 / 折叠全部目录。 */
|
||||
function setAllCollapsed(value: boolean): void {
|
||||
if (!value) {
|
||||
session.value.collapsed = new Set()
|
||||
return
|
||||
}
|
||||
const keys = new Set<string>()
|
||||
const walk = (node: TreeNode): void => {
|
||||
for (const child of node.children) {
|
||||
if (child.isDir && child.children.length) keys.add(child.relPath)
|
||||
walk(child)
|
||||
}
|
||||
}
|
||||
walk(tree.value)
|
||||
session.value.collapsed = keys
|
||||
}
|
||||
|
||||
// ===== 汇总 =====
|
||||
const summary = computed(() => {
|
||||
const counts = { different: 0, leftOnly: 0, rightOnly: 0, identical: 0, mismatch: 0 }
|
||||
for (const entry of session.value.report?.entries ?? []) {
|
||||
if (entry.isDir) {
|
||||
if (entry.status === 'type-mismatch') counts.mismatch++
|
||||
continue
|
||||
}
|
||||
if (entry.status === 'different') counts.different++
|
||||
else if (entry.status === 'left-only') counts.leftOnly++
|
||||
else if (entry.status === 'right-only') counts.rightOnly++
|
||||
else if (entry.status === 'identical') counts.identical++
|
||||
}
|
||||
return counts
|
||||
})
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
function formatTime(ms: number): string {
|
||||
if (!ms) return ''
|
||||
const d = new Date(ms)
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
|
||||
/** 该侧是否存在于这个条目(不存在的一侧显示为「—」并把名字压暗)。 */
|
||||
function existsOn(entry: DirDiffEntry, side: DiffSide): boolean {
|
||||
return side === 'a' ? !!entry.leftPath : !!entry.rightPath
|
||||
}
|
||||
|
||||
function sizeOn(entry: DirDiffEntry, side: DiffSide): number {
|
||||
return side === 'a' ? entry.leftSize : entry.rightSize
|
||||
}
|
||||
|
||||
function timeOn(entry: DirDiffEntry, side: DiffSide): number {
|
||||
return side === 'a' ? entry.leftModified : entry.rightModified
|
||||
}
|
||||
|
||||
/** 状态点颜色(两侧都用同一套语义,便于一眼对上)。 */
|
||||
function dotClass(status: DirDiffEntry['status']): string {
|
||||
switch (status) {
|
||||
case 'different':
|
||||
return 'bg-danger'
|
||||
case 'left-only':
|
||||
return 'bg-warning'
|
||||
case 'right-only':
|
||||
return 'bg-info'
|
||||
case 'type-mismatch':
|
||||
return 'bg-danger'
|
||||
default:
|
||||
return 'bg-fg-disabled'
|
||||
}
|
||||
}
|
||||
|
||||
/** 行点击:目录折叠,文件开新选项卡(任一侧都可点)。 */
|
||||
function onRowClick(node: TreeNode): void {
|
||||
if (node.isDir) {
|
||||
toggleDir(node.relPath)
|
||||
return
|
||||
}
|
||||
const entry = node.entry
|
||||
if (!entry) return
|
||||
emit('open-file', { side: existsOn(entry, 'a') ? 'a' : 'b', entry })
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件名颜色:**有差异**的文件用红、一致的文件用前景色(浅色主题下即黑色);
|
||||
* 该侧不存在时一律压暗(那是「—」占位,不该与真实名字同色调)。
|
||||
*
|
||||
* 目录保持前景色:目录的差异由前面的状态点与另一侧的「—」表达,把整棵树的目录都染红
|
||||
* 反而让真正要看的那几个文件淹没在噪声里。
|
||||
*/
|
||||
function nameClass(node: TreeNode, side: DiffSide): string {
|
||||
if (!node.entry || !existsOn(node.entry, side)) return 'text-fg-disabled'
|
||||
if (node.isDir) return 'text-foreground'
|
||||
return node.entry.status === 'identical' ? 'text-foreground' : 'text-danger-text'
|
||||
}
|
||||
|
||||
/**
|
||||
* 该条目的「不同」是**按时间戳**判定的,而非内容逐字节比对。
|
||||
*
|
||||
* 后端只在「大小相同、时间戳不同」时才读内容核对,且有预算(单文件体积 / 条数上限);
|
||||
* 预算用尽或文件过大时结论仍记为 `different`,但 `contentCompared` 为 false —— 界面上
|
||||
* 必须与「已确认不同」区分,否则等于把猜测当结论。
|
||||
*
|
||||
* 判据要连 `leftSize === rightSize` 一起看:**大小不同**时后端也把 `contentCompared`
|
||||
* 记为 false(它根本不需要读内容 —— 大小都不同,内容不可能相同),那是确定结论,
|
||||
* 拿 `!contentCompared` 单独当判据会给几乎每个差异文件都挂上「未核实」。
|
||||
*/
|
||||
function unverified(entry: DirDiffEntry | null): boolean {
|
||||
return (
|
||||
!!entry &&
|
||||
entry.status === 'different' &&
|
||||
!entry.contentCompared &&
|
||||
entry.leftSize === entry.rightSize
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 目录行是否隐藏「大小 / 已修改」两列(合并成一个占位)。
|
||||
*
|
||||
* 目录的这两个属性不是可用于对比的信号:大小(`meta.len()` 在 Windows 上取决于文件系统,
|
||||
* 后端已统一置 0)没有意义;mtime 只是「有子项被增删改」的副产物,几乎每次都和另一侧不同,
|
||||
* 拿它当差异线索会误导。因此目录行把这两列并成一格。
|
||||
*
|
||||
* 例外是 `type-mismatch`(同名但一侧是文件):那是有意义的差异,按原来的两列渲染。
|
||||
*/
|
||||
function quietMeta(node: TreeNode): boolean {
|
||||
return node.isDir && node.entry?.status !== 'type-mismatch'
|
||||
}
|
||||
|
||||
// ===== 左右两棵树滚动联动 =====
|
||||
//
|
||||
// 两侧渲染的是**同一份行**(行数、顺序完全一致,只有单元格内容不同),因此行高一致、
|
||||
// 内容高度一致 —— 一个像素级的镜像就够了。
|
||||
//
|
||||
// 不用「布尔锁 + 延迟释放」那种写法:scroll 事件是异步派发的,锁的释放时机很难对齐,
|
||||
// 漏放会让联动卡死、错放会让两侧互相推着抖动。这里改成**比较目标位置**:谁在滚动就把
|
||||
// 另一侧对齐到同一位置;后者随后触发的 scroll 事件会发现「对方已经和我一样」,自然不再
|
||||
// 回推 —— 无需在两次事件之间维护任何时序状态。
|
||||
const treeRootRef = ref<HTMLElement | null>(null)
|
||||
let viewports: [HTMLElement, HTMLElement] | null = null
|
||||
|
||||
/** 把 `to` 对齐到 `from`;差值 ≤1px 视为已对齐(避免像素取整引起的抖动)。 */
|
||||
function mirrorScroll(from: HTMLElement, to: HTMLElement): void {
|
||||
if (Math.abs(to.scrollTop - from.scrollTop) <= 1) return
|
||||
to.scrollTop = from.scrollTop
|
||||
}
|
||||
|
||||
// ===== 行虚拟化 =====
|
||||
//
|
||||
// 上限 8000 条 × 两侧 = 最多约 6 万个 DOM 节点,一次性铺出来会让首次渲染与滚动都卡。
|
||||
// 这里只渲染视口内的行(上下各留 OVERSCAN 行),用上下两个撑高的空 div 占住剩余空间,
|
||||
// 于是滚动条长度与滚动位置与「全部渲染」完全一致(两者之和恒等于 行数 × 行高)。
|
||||
//
|
||||
// 两侧**共用同一份窗口**:滚动已被联动对齐、行数又完全一致,因此一个 scrollTop 对
|
||||
// 两边都成立 —— 不需要按侧各算一份(那还会引入两侧窗口错位的一类新 bug)。
|
||||
|
||||
/**
|
||||
* 行高(px)。
|
||||
*
|
||||
* 必须与模板里行的高度严格相等(那里同一个 `:style` 里就写了 `height`)。用像素而不是
|
||||
* `h-6.5` 这类 rem 类:虚拟化的偏移量必须精确等于真实行高,绑在显式常量上比「依赖根字号
|
||||
* 恰好 16px(6.5 × 0.25rem = 26px)」可靠。
|
||||
*/
|
||||
const ROW_HEIGHT = 26
|
||||
/** 视口上下各多渲染的行数(滚动时不至于露白)。 */
|
||||
const OVERSCAN = 8
|
||||
|
||||
/** 两侧共用的滚动位置(联动使两侧恒等,虚拟化只需一份)。 */
|
||||
const scrollTop = ref(0)
|
||||
/** 视口高度(两侧等宽等高,取其中一个即可)。 */
|
||||
const viewportHeight = ref(0)
|
||||
let viewportObserver: ResizeObserver | null = null
|
||||
|
||||
/** 当前要渲染的行区间 `[first, last)`。 */
|
||||
const rowRange = computed(() => {
|
||||
const total = rows.value.length
|
||||
const first = Math.max(0, Math.floor(scrollTop.value / ROW_HEIGHT) - OVERSCAN)
|
||||
const last = Math.max(
|
||||
first,
|
||||
Math.min(total, Math.ceil((scrollTop.value + viewportHeight.value) / ROW_HEIGHT) + OVERSCAN)
|
||||
)
|
||||
return { first, last }
|
||||
})
|
||||
/** 视口内(含上下缓冲)的行,并带上它在**全量 rows** 里的下标(键盘导航与 ARIA 要用真下标)。 */
|
||||
const visibleRows = computed(() =>
|
||||
rows.value
|
||||
.slice(rowRange.value.first, rowRange.value.last)
|
||||
.map((row, i) => ({ row, index: rowRange.value.first + i }))
|
||||
)
|
||||
/** 可见行上方的占位高度。 */
|
||||
const padTop = computed(() => rowRange.value.first * ROW_HEIGHT)
|
||||
/** 可见行下方的占位高度。 */
|
||||
const padBottom = computed(() =>
|
||||
Math.max(0, (rows.value.length - rowRange.value.last) * ROW_HEIGHT)
|
||||
)
|
||||
|
||||
// ===== 整行 hover =====
|
||||
//
|
||||
// 两侧渲染的是同一份行,却是**两个独立的滚动容器** —— 只在鼠标所在的那一侧加 CSS `hover:`
|
||||
// 会让高亮只覆盖半行。这里改记一个**行下标**,两侧按同一个下标上色,看起来就是一整行。
|
||||
//
|
||||
// 用「指针位置 → 下标」而不是逐行 mouseenter:行是虚拟化的,滚动时同一个 DOM 节点会被
|
||||
// 复用成别的行,靠 enter/leave 记下的「上一行」会失效(高亮停在错误的行上)。这里在滚动
|
||||
// 时也用最后记录的指针 Y 重算一次,于是滚轮滚动时高亮依然跟得上。
|
||||
|
||||
/** 鼠标所在行的下标(-1 = 不在任何行上)。 */
|
||||
const hoverIndex = ref(-1)
|
||||
/** 最后一次指针的 clientY(NaN = 指针不在树上)。 */
|
||||
let pointerClientY = Number.NaN
|
||||
|
||||
function updateHover(): void {
|
||||
const viewport = viewports?.[0]
|
||||
if (!viewport || Number.isNaN(pointerClientY)) {
|
||||
hoverIndex.value = -1
|
||||
return
|
||||
}
|
||||
// 两侧视口处于同一水平线、行高也一致,所以一个下标对两边都成立
|
||||
const y = pointerClientY - viewport.getBoundingClientRect().top
|
||||
if (y < 0 || y >= viewport.clientHeight) {
|
||||
hoverIndex.value = -1
|
||||
return
|
||||
}
|
||||
const index = Math.floor((y + scrollTop.value) / ROW_HEIGHT)
|
||||
hoverIndex.value = index >= 0 && index < rows.value.length ? index : -1
|
||||
}
|
||||
|
||||
function onTreeMouseMove(event: MouseEvent): void {
|
||||
pointerClientY = event.clientY
|
||||
updateHover()
|
||||
}
|
||||
|
||||
function onTreeMouseLeave(): void {
|
||||
pointerClientY = Number.NaN
|
||||
hoverIndex.value = -1
|
||||
}
|
||||
|
||||
const onLeftScroll = (): void => {
|
||||
if (!viewports) return
|
||||
scrollTop.value = viewports[0].scrollTop
|
||||
mirrorScroll(viewports[0], viewports[1])
|
||||
updateHover()
|
||||
}
|
||||
const onRightScroll = (): void => {
|
||||
if (!viewports) return
|
||||
scrollTop.value = viewports[1].scrollTop
|
||||
mirrorScroll(viewports[1], viewports[0])
|
||||
updateHover()
|
||||
}
|
||||
|
||||
// 滚动的真实容器是 reka-ui 的 viewport(`.cm-*` 那套同理,原生滚动被它接管)。
|
||||
// 两侧的 ScrollArea 始终渲染(空态 / 扫描中也一样),因此挂载后即可取到,无需等数据。
|
||||
onMounted(async () => {
|
||||
// 扫描进度是**全局**事件(Rust 不区分选项卡):按 scanSeq 过滤,只认本轮扫描的进度。
|
||||
// 注册失败不该影响其余初始化(虚拟化与滚动联动才是主体)—— 进度只是锦上添花。
|
||||
try {
|
||||
unlistenProgress = await listen<DiffScanProgress>(EVENTS.diffScanProgress, event => {
|
||||
if (event.payload.scanId !== scanSeq) return
|
||||
scanProgress.value = event.payload
|
||||
})
|
||||
} catch {
|
||||
/* 注册失败就静默降级为「扫描中…」,不影响扫描本身 */
|
||||
}
|
||||
|
||||
const found = treeRootRef.value?.querySelectorAll<HTMLElement>('[data-reka-scroll-area-viewport]')
|
||||
if (!found || found.length < 2) return
|
||||
const left = found[0]
|
||||
const right = found[1]
|
||||
if (!left || !right) return
|
||||
viewports = [left, right]
|
||||
left.addEventListener('scroll', onLeftScroll, { passive: true })
|
||||
right.addEventListener('scroll', onRightScroll, { passive: true })
|
||||
// 视口高度是虚拟化的另一个输入:它随窗口尺寸 / 分栏变化,用 ResizeObserver 跟住
|
||||
viewportHeight.value = left.clientHeight
|
||||
viewportObserver = new ResizeObserver(() => {
|
||||
viewportHeight.value = viewports?.[0]?.clientHeight ?? 0
|
||||
})
|
||||
viewportObserver.observe(left)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
viewports?.[0].removeEventListener('scroll', onLeftScroll)
|
||||
viewports?.[1].removeEventListener('scroll', onRightScroll)
|
||||
viewports = null
|
||||
viewportObserver?.disconnect()
|
||||
viewportObserver = null
|
||||
unlistenProgress?.()
|
||||
unlistenProgress = null
|
||||
})
|
||||
|
||||
/**
|
||||
* 换过滤条件 / 重新扫描后两侧回到顶部。
|
||||
*
|
||||
* 不复位的话,原来滚到很靠下时新内容可能停在中间甚至底部,用户会以为「结果没变」。
|
||||
* 两侧一起设 0(而不是走镜像):此处语义就是「从头看」,显式置顶比镜像更直白。
|
||||
*/
|
||||
watch([() => session.value.filter, () => session.value.report], () => {
|
||||
scrollTop.value = 0
|
||||
if (!viewports) return
|
||||
viewports[0].scrollTop = 0
|
||||
viewports[1].scrollTop = 0
|
||||
})
|
||||
|
||||
// ===== 键盘可达性 =====
|
||||
//
|
||||
// 行是 div,本身不可聚焦 —— 键盘用户完全用不了。这里按 ARIA tree 的常规做法补上:
|
||||
// 行 `role="treeitem"`(带 aria-level / aria-expanded / aria-selected),并用
|
||||
// **roving tabindex**(同一时刻只有一个行可 Tab 到)避免 Tab 要穿过上千行;方向键在
|
||||
// `rows` 上移动,Enter / 空格与鼠标点击同义。
|
||||
//
|
||||
// 与虚拟化的配合:目标行在窗口外时先把它滚进视口、等这一帧渲染完再 `focus` ——
|
||||
// 否则要聚焦的元素在虚拟化下根本不在 DOM 里。
|
||||
|
||||
/** 当前键盘活动行。存 **relPath** 而不是下标:过滤 / 折叠 / 重新扫描都会让下标失效。 */
|
||||
const activeRelPath = ref('')
|
||||
/** 活动行在 `rows` 里的下标;存的路径已不在当前行集里时回落到第一行。 */
|
||||
const activeRowIndex = computed(() => {
|
||||
const index = rows.value.findIndex(row => row.node.relPath === activeRelPath.value)
|
||||
return index >= 0 ? index : 0
|
||||
})
|
||||
|
||||
function isActive(index: number): boolean {
|
||||
return index === activeRowIndex.value
|
||||
}
|
||||
|
||||
/** 直接设置两侧的滚动位置(键盘导航用;两侧联动会随之对齐)。 */
|
||||
function scrollBoth(top: number): void {
|
||||
scrollTop.value = top
|
||||
if (!viewports) return
|
||||
viewports[0].scrollTop = top
|
||||
viewports[1].scrollTop = top
|
||||
}
|
||||
|
||||
/** 让第 index 行进入视口(必要时滚动)。 */
|
||||
function revealIndex(index: number): void {
|
||||
const top = index * ROW_HEIGHT
|
||||
const bottom = top + ROW_HEIGHT
|
||||
if (top < scrollTop.value) scrollBoth(top)
|
||||
else if (bottom > scrollTop.value + viewportHeight.value) {
|
||||
scrollBoth(bottom - viewportHeight.value)
|
||||
}
|
||||
}
|
||||
|
||||
/** 移动活动行,并按需滚动 + 聚焦。 */
|
||||
function moveActive(index: number): void {
|
||||
const total = rows.value.length
|
||||
if (!total) return
|
||||
const clamped = Math.max(0, Math.min(index, total - 1))
|
||||
const row = rows.value[clamped]
|
||||
if (!row) return
|
||||
activeRelPath.value = row.node.relPath
|
||||
revealIndex(clamped)
|
||||
void nextTick(() => {
|
||||
treeRootRef.value?.querySelector<HTMLElement>('[data-active-row]')?.focus()
|
||||
})
|
||||
}
|
||||
|
||||
/** 第 index 行的最近祖先(`rows` 是深度优先展平,往前找第一个深度更小的行)。 */
|
||||
function parentIndexOf(index: number): number {
|
||||
const depth = rows.value[index]?.depth ?? 0
|
||||
for (let i = index - 1; i >= 0; i--) {
|
||||
if ((rows.value[i]?.depth ?? 0) < depth) return i
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
/** 点击 / Tab 到某一行时把它记为活动行(roving tabindex 的锚点)。 */
|
||||
function onRowFocus(node: TreeNode): void {
|
||||
activeRelPath.value = node.relPath
|
||||
}
|
||||
|
||||
function onTreeKeydown(event: KeyboardEvent): void {
|
||||
const total = rows.value.length
|
||||
if (!total) return
|
||||
const index = activeRowIndex.value
|
||||
const row = rows.value[index]
|
||||
if (!row) return
|
||||
switch (event.key) {
|
||||
case 'ArrowDown':
|
||||
event.preventDefault()
|
||||
moveActive(index + 1)
|
||||
break
|
||||
case 'ArrowUp':
|
||||
event.preventDefault()
|
||||
moveActive(index - 1)
|
||||
break
|
||||
case 'ArrowRight':
|
||||
event.preventDefault()
|
||||
// 折叠的目录先展开;否则移动到下一行(若下一行是子项,那正是「第一个子项」)
|
||||
if (row.node.isDir && session.value.collapsed.has(row.node.relPath)) {
|
||||
toggleDir(row.node.relPath)
|
||||
} else {
|
||||
moveActive(index + 1)
|
||||
}
|
||||
break
|
||||
case 'ArrowLeft':
|
||||
event.preventDefault()
|
||||
// 展开的目录先折叠;否则回到父目录
|
||||
if (row.node.isDir && !session.value.collapsed.has(row.node.relPath)) {
|
||||
toggleDir(row.node.relPath)
|
||||
} else {
|
||||
const parent = parentIndexOf(index)
|
||||
if (parent >= 0) moveActive(parent)
|
||||
}
|
||||
break
|
||||
case 'Home':
|
||||
event.preventDefault()
|
||||
moveActive(0)
|
||||
break
|
||||
case 'End':
|
||||
event.preventDefault()
|
||||
moveActive(total - 1)
|
||||
break
|
||||
case 'Enter':
|
||||
case ' ':
|
||||
event.preventDefault()
|
||||
onRowClick(row.node)
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({ compare, setRoot, loadDropped })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- 整块铺不透明底色:窗根是透明窗(mica/acrylic),不给底色的话「路径输入行 + 文件树」
|
||||
会透出窗口背景,与旁边面板的观感割裂 -->
|
||||
<div class="flex min-h-0 flex-1 flex-col bg-background">
|
||||
<!-- 控制行:扫描 + 过滤 + 两个开关 -->
|
||||
<div class="flex h-8 shrink-0 items-center gap-1 border-b border-border px-2">
|
||||
<Button size="sm" class="h-6" :disabled="!ready || session.scanning" @click="compare">
|
||||
<Loader2 v-if="session.scanning" class="size-3.5 animate-spin" />
|
||||
<RefreshCw v-else class="size-3.5" />
|
||||
扫描
|
||||
</Button>
|
||||
|
||||
<div class="mx-1 h-4 w-px shrink-0 bg-border" />
|
||||
|
||||
<Button
|
||||
v-for="item in FILTERS"
|
||||
:key="item.id"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 px-2 text-[11px]"
|
||||
:class="
|
||||
session.filter === item.id
|
||||
? 'bg-primary-soft font-medium text-primary-soft-text'
|
||||
: 'text-fg-secondary hover:text-foreground'
|
||||
"
|
||||
@click="session.filter = item.id"
|
||||
>
|
||||
{{ item.label }}
|
||||
</Button>
|
||||
|
||||
<div class="ml-auto flex shrink-0 items-center gap-1">
|
||||
<Button variant="ghost" size="sm" class="h-6 px-2 text-[11px]" @click="setAllCollapsed(false)">
|
||||
展开全部
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" class="h-6 px-2 text-[11px]" @click="setAllCollapsed(true)">
|
||||
折叠全部
|
||||
</Button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm px-1.5 py-0.5 text-[11px] transition-colors"
|
||||
:class="
|
||||
session.skipBuild
|
||||
? 'bg-primary-soft font-medium text-primary-soft-text'
|
||||
: 'text-fg-secondary hover:bg-hover'
|
||||
"
|
||||
title="跳过 node_modules / .git / target 等常见构建目录"
|
||||
@click="session.skipBuild = !session.skipBuild"
|
||||
>
|
||||
跳过构建目录
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm px-1.5 py-0.5 text-[11px] transition-colors"
|
||||
:class="
|
||||
session.compareContent
|
||||
? 'bg-primary-soft font-medium text-primary-soft-text'
|
||||
: 'text-fg-secondary hover:bg-hover'
|
||||
"
|
||||
title="大小相同、时间戳不同时读内容逐字节比对(更准,也更慢)"
|
||||
@click="session.compareContent = !session.compareContent"
|
||||
>
|
||||
比对内容
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 左右两棵结构树(滚动联动,见脚本里的滚动镜像;方向键导航的 keydown 挂在这层容器上,
|
||||
事件从聚焦的行冒泡上来 —— 两侧共用一套导航) -->
|
||||
<div
|
||||
ref="treeRootRef"
|
||||
class="flex min-h-0 flex-1"
|
||||
@keydown="onTreeKeydown"
|
||||
@mousemove="onTreeMouseMove"
|
||||
@mouseleave="onTreeMouseLeave"
|
||||
>
|
||||
<div
|
||||
v-for="side in SIDES"
|
||||
:key="side"
|
||||
class="flex min-w-0 flex-1 flex-col"
|
||||
:class="side === 'b' ? 'border-l border-border' : ''"
|
||||
>
|
||||
<!-- 该侧的根路径:可自由输入,也可用图标按钮选 -->
|
||||
<div class="flex h-8 shrink-0 items-center gap-1 border-b border-border px-1.5">
|
||||
<Input
|
||||
:model-value="rootOf(side)"
|
||||
class="h-6 flex-1 font-mono text-[11px]"
|
||||
:placeholder="side === 'a' ? '左侧文件夹…' : '右侧文件夹…'"
|
||||
spellcheck="false"
|
||||
@change="(e: Event) => onRootInput(side, e)"
|
||||
@keydown.enter="onRootEnter(side, $event)"
|
||||
/>
|
||||
<Button variant="ghost" size="icon-sm" title="选择文件夹" @click="browse(side)">
|
||||
<FolderOpen class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 列头(名称 / 大小 / 已修改,与 Beyond Compare 的口径一致) -->
|
||||
<div
|
||||
class="flex h-6 shrink-0 items-center gap-2 border-b border-divider px-2 text-[10px] text-muted-foreground"
|
||||
>
|
||||
<span class="min-w-0 flex-1">名称</span>
|
||||
<span class="w-16 shrink-0 text-right">大小</span>
|
||||
<span class="w-24 shrink-0 text-right">已修改</span>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div v-if="!session.report && !session.scanning" class="p-3">
|
||||
<StateBlock
|
||||
variant="empty"
|
||||
title="选择左右两个文件夹开始对比"
|
||||
description="两侧都可以直接输入路径或点文件夹图标选择;也可以把文件夹拖到这一侧"
|
||||
:min-height="160"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="session.scanning"
|
||||
class="flex items-center gap-2 p-3 text-xs text-muted-foreground"
|
||||
>
|
||||
<Loader2 class="size-3.5 animate-spin" />{{ progressText ?? '正在扫描…' }}
|
||||
</div>
|
||||
|
||||
<div v-else-if="!rows.length" class="p-3">
|
||||
<StateBlock
|
||||
variant="empty"
|
||||
:title="session.filter === 'diff' ? '两棵目录树没有差异' : '当前过滤条件下没有条目'"
|
||||
description="换一个过滤条件,或点「全部」查看两侧所有的文件"
|
||||
:min-height="140"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 行虚拟化:上下两个占位 div 撑住未渲染的部分(见脚本里的「行虚拟化」)。
|
||||
这层也是该侧的 ARIA tree —— 左右各一棵(两侧展示的是同一批行的不同侧信息) -->
|
||||
<div v-else role="tree" :aria-label="side === 'a' ? '左侧目录' : '右侧目录'">
|
||||
<div :style="{ height: `${padTop}px` }" aria-hidden="true" />
|
||||
<div
|
||||
v-for="item in visibleRows"
|
||||
:key="item.row.node.relPath"
|
||||
role="treeitem"
|
||||
:aria-level="item.row.depth + 1"
|
||||
:aria-expanded="
|
||||
item.row.node.isDir ? !session.collapsed.has(item.row.node.relPath) : undefined
|
||||
"
|
||||
:aria-selected="isActive(item.index)"
|
||||
:tabindex="isActive(item.index) ? 0 : -1"
|
||||
:data-active-row="isActive(item.index) ? '' : undefined"
|
||||
class="flex cursor-pointer items-center gap-2 pr-2 text-xs focus:outline-none"
|
||||
:class="
|
||||
item.index === hoverIndex ? 'bg-hover' : isActive(item.index) && 'bg-row-selected'
|
||||
"
|
||||
:style="{ height: `${ROW_HEIGHT}px`, paddingLeft: `${4 + item.row.depth * 14}px` }"
|
||||
@click="onRowClick(item.row.node)"
|
||||
@focus="onRowFocus(item.row.node)"
|
||||
>
|
||||
<!-- 展开箭头(两侧共用折叠状态,点哪边都一样;键盘用 → / ← 展开折叠) -->
|
||||
<button
|
||||
v-if="item.row.node.isDir"
|
||||
type="button"
|
||||
tabindex="-1"
|
||||
class="flex size-4 shrink-0 items-center justify-center text-muted-foreground"
|
||||
@click.stop="toggleDir(item.row.node.relPath)"
|
||||
>
|
||||
<ChevronDown
|
||||
v-if="!session.collapsed.has(item.row.node.relPath) && item.row.node.children.length"
|
||||
class="size-3.5"
|
||||
/>
|
||||
<ChevronRight v-else-if="item.row.node.children.length" class="size-3.5" />
|
||||
</button>
|
||||
<span
|
||||
v-else
|
||||
class="ml-0.5 size-1.5 shrink-0 rounded-full"
|
||||
:class="dotClass(item.row.node.entry?.status ?? 'identical')"
|
||||
/>
|
||||
|
||||
<span
|
||||
class="min-w-0 flex-1 truncate"
|
||||
:class="[item.row.node.isDir ? 'font-medium' : '', nameClass(item.row.node, side)]"
|
||||
>
|
||||
{{ item.row.node.name }}
|
||||
</span>
|
||||
|
||||
<!-- 「不同」是按时间戳判定的(大小相同、时间戳不同,但没读内容核对) —— 不能
|
||||
与已确认的差异用同一种语气,故单独标出 -->
|
||||
<span
|
||||
v-if="unverified(item.row.node.entry)"
|
||||
class="shrink-0 rounded-sm bg-warning-soft px-1 text-[9px] text-warning-text"
|
||||
title="两侧大小相同但时间戳不同,且未读内容逐字节比对(文件过大或比对预算用尽)——这是按时间戳判定的差异,未必真的不同"
|
||||
>
|
||||
未核实
|
||||
</span>
|
||||
|
||||
<!-- 目录行:大小 / 已修改不是对比信号,合并成一格(见脚本里的 quietMeta)。
|
||||
宽度 = 4rem + gap(0.5rem) + 6rem,与下面两格的合计严格一致,名字列才不会错位 -->
|
||||
<span
|
||||
v-if="quietMeta(item.row.node)"
|
||||
class="w-[10.5rem] shrink-0 text-right font-mono text-[10px] text-fg-disabled"
|
||||
title="目录的大小与已修改时间不参与对比(大小在 Windows 上无意义,mtime 只是子项变动的副产物)"
|
||||
>
|
||||
—
|
||||
</span>
|
||||
<template v-else>
|
||||
<span class="w-16 shrink-0 text-right font-mono text-[10px] text-muted-foreground">
|
||||
{{ item.row.node.entry && existsOn(item.row.node.entry, side) && !item.row.node.isDir ? formatSize(sizeOn(item.row.node.entry, side)) : '—' }}
|
||||
</span>
|
||||
<span class="w-24 shrink-0 truncate text-right font-mono text-[10px] text-muted-foreground">
|
||||
{{ item.row.node.entry && existsOn(item.row.node.entry, side) ? formatTime(timeOn(item.row.node.entry, side)) : '—' }}
|
||||
</span>
|
||||
</template>
|
||||
</div>
|
||||
<div :style="{ height: `${padBottom}px` }" aria-hidden="true" />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 汇总 -->
|
||||
<footer
|
||||
class="flex h-7 shrink-0 items-center gap-3 border-t border-border px-3 text-[11px] text-muted-foreground"
|
||||
>
|
||||
<span v-if="session.report" class="tabular-nums text-danger-text">不同 {{ summary.different }}</span>
|
||||
<span v-if="session.report" class="tabular-nums text-warning-text">仅左 {{ summary.leftOnly }}</span>
|
||||
<span v-if="session.report" class="tabular-nums text-info-text">仅右 {{ summary.rightOnly }}</span>
|
||||
<span v-if="session.report" class="tabular-nums">相同 {{ summary.identical }}</span>
|
||||
<span v-if="summary.mismatch" class="tabular-nums text-danger-text">
|
||||
类型不一致 {{ summary.mismatch }}
|
||||
</span>
|
||||
<span v-if="session.report?.skippedDirs" class="tabular-nums">
|
||||
已跳过 {{ session.report.skippedDirs }} 个目录
|
||||
</span>
|
||||
<span class="truncate text-muted-foreground">点任意一侧的文件即可新开一个文件对比选项卡</span>
|
||||
|
||||
<span class="ml-auto shrink-0 tabular-nums">
|
||||
<template v-if="session.scanning">{{ progressText ?? '扫描中…' }}</template>
|
||||
<template v-else-if="session.report">
|
||||
{{ session.report.entries.length }} 项 · {{ session.report.elapsedMs }} ms
|
||||
</template>
|
||||
</span>
|
||||
<span v-if="session.report?.truncated" class="shrink-0 text-warning-text">
|
||||
条目已达上限,结果被截断
|
||||
</span>
|
||||
</footer>
|
||||
</div>
|
||||
</template>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* 对比模块的 IPC 客户端:命令名的**唯一落点**。
|
||||
*
|
||||
* 与 `editor/editorClient.ts` 同一理由:命令名与返回类型只在本文件出现一次,
|
||||
* 避免散落在组件里各自手写(后端改字段时前端还会编译通过)。
|
||||
*
|
||||
* 参数名用 snake_case 形态的 camelCase(与 tauri-specta 的调用约定一致)。
|
||||
*/
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import type { DiffFileDoc, DiffSettings, DirDiffReport } from './types'
|
||||
|
||||
export const diffClient = {
|
||||
/**
|
||||
* 读取一侧的文件(文本自动探测编码;二进制只回元信息)。
|
||||
*
|
||||
* 该命令同时登记「已授权可写」,因此随后可以直接 `writeFile` 保存。
|
||||
*/
|
||||
readFile: (path: string) => invoke<DiffFileDoc>('diff_read_file', { path }),
|
||||
|
||||
/**
|
||||
* 把一侧的内容写回磁盘。
|
||||
*
|
||||
* `encoding` / `eol` 必须回传**读取时探测到的值**:否则一次保存就会把 GBK 文件
|
||||
* 变成 UTF-8、CRLF 变成 LF,整个 diff 会因此掀翻。
|
||||
*/
|
||||
writeFile: (path: string, content: string, encoding: string, eol: string) =>
|
||||
invoke<DiffFileDoc>('diff_write_file', { path, content, encoding, eol }),
|
||||
|
||||
/**
|
||||
* 探测路径是文件还是目录(拖入与 `?path=` 时前端拿不到文件系统元信息)。
|
||||
*
|
||||
* 只读一次 `metadata`,不写盘、不需授权。
|
||||
*/
|
||||
pathKind: (path: string) => invoke<'dir' | 'file' | 'missing'>('diff_path_kind', { path }),
|
||||
|
||||
/**
|
||||
* 对比两棵目录树(只读)。
|
||||
*
|
||||
* `skipDirs` 是**目录名**清单(大小写不敏感):默认清单由前端给出(它是界面约定,
|
||||
* 用户能不能改是 UI 的事),后端只负责按它执行。
|
||||
*
|
||||
* `scanId` 由前端生成:后端把它原样放进进度事件(`diff-scan-progress`),前端据此
|
||||
* 只认自己那一轮的进度 —— 事件是全局的,多个选项卡可能同时在扫。
|
||||
*/
|
||||
compareDirs: (
|
||||
scanId: number,
|
||||
left: string,
|
||||
right: string,
|
||||
skipDirs: string[],
|
||||
compareContent: boolean
|
||||
) =>
|
||||
invoke<DirDiffReport>('diff_compare_dirs', { scanId, left, right, skipDirs, compareContent }),
|
||||
|
||||
// ===== 设置 =====
|
||||
getSettings: () => invoke<DiffSettings>('diff_get_settings'),
|
||||
/**
|
||||
* 保存设置。
|
||||
*
|
||||
* Rust 侧保存后会**就地重注册**全局快捷键,因此「改了快捷键立刻生效」,
|
||||
* 不需要前端再调一次注册命令。
|
||||
*/
|
||||
saveSettings: (settings: DiffSettings) =>
|
||||
invoke<DiffSettings>('diff_save_settings', { settings })
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { ModuleConfig } from '@/types/module'
|
||||
import type { SearchIndexItem } from '@/stores/searchIndex'
|
||||
|
||||
/**
|
||||
* 对比工具模块:文本 / 文件 / 文件夹三层对比。
|
||||
*
|
||||
* 规划见 `doc/DIFF_MODULE_PLAN.md`。当前进度 = **P1(文本对比)**:
|
||||
* 双栏 MergeView 已可用;文件对比(P2)与文件夹对比(P3)待做。
|
||||
*
|
||||
* 为什么独立成模块而不是塞进编辑器:编辑器模块的中心对象是「一篇文档的生命周期」
|
||||
* (标签 / 自动保存 / 光标 / 会话恢复),而对比工具是「两个只读视图 + 一棵目录树」,
|
||||
* 没有自动保存、没有文档标签。混进去会让编辑器的窗口与 store 继续膨胀,也会让
|
||||
* `editor-window-*` 这个 capability 的语义变模糊(详见规划 §5)。
|
||||
*/
|
||||
const searchItems: SearchIndexItem[] = [
|
||||
{
|
||||
title: '对比工具',
|
||||
description: '文本 / 文件 / 文件夹对比:双栏差异视图,类 Beyond Compare',
|
||||
keywords: ['对比', '比较', '差异', 'diff', 'compare', '文本对比', '文件对比', '文件夹对比', 'merge']
|
||||
},
|
||||
{
|
||||
title: '打开对比窗口',
|
||||
description: '打开对比工具窗口,粘贴两段文本或(P2 起)拖入文件开始比较',
|
||||
keywords: ['打开', '对比', '窗口', '独立窗口', 'diff', 'compare']
|
||||
}
|
||||
]
|
||||
|
||||
export const moduleConfig: ModuleConfig = {
|
||||
id: 'diff',
|
||||
name: '对比工具',
|
||||
icon: 'diff',
|
||||
description: '文本 / 文件 / 文件夹对比(双栏差异视图;目录对比只读,不做写回)',
|
||||
category: 'tool',
|
||||
defaultEnabled: true,
|
||||
loader: () => import('./DiffModule.vue'),
|
||||
searchItems,
|
||||
// 紧挨编辑器(45):两者同属「处理文本 / 文件」一族
|
||||
order: 50
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* 对比窗口的创建入口(由前端创建,范式同 `editor/openWindow.ts`)。
|
||||
*
|
||||
* # 为什么是单例
|
||||
*
|
||||
* 与编辑器窗口(可多开、按目标判重)不同,对比工具的语义是「比较这一对目标」,
|
||||
* 窗口里本来就同时容纳左右两侧 —— 多开只会让用户分不清哪一对是哪一对。
|
||||
* 因此 label 固定为 `diff-window`,已存在就强制置前。
|
||||
*
|
||||
* # 隐藏创建 + 先应用主题
|
||||
*
|
||||
* 窗口初始底色是白的,而深色主题要等前端读 localStorage 后才应用 —— 直接显示会先
|
||||
* 闪一下纯白。因此 `visible: false` 创建,由 `DiffWindow.vue` 应用完主题(含窗口效果)
|
||||
* 与任务栏身份之后再自己 `show()`(同编辑器 / 终端窗口)。
|
||||
*
|
||||
* # 置前走原生命令
|
||||
*
|
||||
* `SetForegroundWindow` 不受 Windows 前台锁定限制;前端 `setFocus()` 在「本进程不拥有
|
||||
* 前台」时会被系统直接忽略(表现为窗口明明开着却唤不到前面)。同下载窗口 / 快速面板。
|
||||
*/
|
||||
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { WINDOWS } from '@/lib/constants'
|
||||
|
||||
const logger = createLogger('diff')
|
||||
|
||||
const LABEL = WINDOWS.diffWindow
|
||||
|
||||
/**
|
||||
* 打开(或唤出)对比窗口。
|
||||
*
|
||||
* @param target 可选:P2 起用于把某个文件 / 文件夹作为初始目标(写入 URL 查询串)
|
||||
*/
|
||||
export async function openDiffWindow(target?: { path?: string }): Promise<void> {
|
||||
const existing = await WebviewWindow.getByLabel(LABEL)
|
||||
if (existing) {
|
||||
try {
|
||||
await invoke('window_focus_window', { label: LABEL })
|
||||
return
|
||||
} catch (e) {
|
||||
logger.warn(`唤出既有对比窗口失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
const query = target?.path ? `?path=${encodeURIComponent(target.path)}` : ''
|
||||
const win = new WebviewWindow(LABEL, {
|
||||
url: `index.html#${LABEL}${query}`,
|
||||
title: '对比',
|
||||
width: 1180,
|
||||
height: 780,
|
||||
minWidth: 720,
|
||||
minHeight: 460,
|
||||
resizable: true,
|
||||
// 自绘标题栏(与编辑器 / 终端 / 文件窗口一致)
|
||||
decorations: false,
|
||||
// 透明通道用于承载 mica / acrylic
|
||||
transparent: true,
|
||||
shadow: true,
|
||||
center: true,
|
||||
visible: false,
|
||||
focus: false,
|
||||
// 拖入任意文件 / 文件夹作为某一侧目标(P2 起真正使用)
|
||||
dragDropEnabled: true
|
||||
})
|
||||
|
||||
// 不要等到 `tauri://created` 之后才挂错误监听:窗口创建过快时事件可能早于监听注册
|
||||
win.once('tauri://error', e => logger.error(`打开对比窗口失败:${String(e)}`))
|
||||
|
||||
// 补注入拖放支持:wry 只在创建 webview 那一刻扫一次子窗口,运行期新建的窗口拿不到
|
||||
// OLE drop target(拖文件进去是禁止光标)。详见 src-tauri/src/drag_drop.rs
|
||||
//
|
||||
// 注意**不要**放到下面那个 `await` 之后:`tauri://created` 在窗口创建过快时可能早于
|
||||
// 监听注册而永远等不到。Rust 侧会自行重试等待窗口与 WebView2 子窗口就位,因此这里
|
||||
// fire-and-forget 即可。
|
||||
void invoke('window_attach_drag_drop', { label: LABEL }).catch(e => {
|
||||
logger.warn(`拖放补注入失败:${String(e)}`)
|
||||
})
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
win.once('tauri://created', () => resolve())
|
||||
win.once('tauri://error', e => reject(new Error(String(e))))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* 对比模块的前端类型。
|
||||
*
|
||||
* [`DiffStats`] 由 `MergeView` 的 chunk 列表算出(纯前端);[`DiffFileDoc`] 与 Rust 侧
|
||||
* `diff::types::DiffFileDoc` 一一对应(新增字段两侧都要改)。
|
||||
*/
|
||||
|
||||
/** 两侧文本的差异统计(状态栏展示用)。 */
|
||||
export interface DiffStats {
|
||||
/** 变化块数量(MergeView 的 chunk 个数) */
|
||||
chunks: number
|
||||
/** 右侧相对左侧新增的行数 */
|
||||
addedLines: number
|
||||
/** 左侧相对右侧被删除的行数 */
|
||||
removedLines: number
|
||||
/** 左侧行数(空文档为 0,而不是 CM6 报的 1) */
|
||||
linesA: number
|
||||
/** 右侧行数(同左) */
|
||||
linesB: number
|
||||
}
|
||||
|
||||
/** 某一侧的文件状态(来自 `diff_read_file` / `diff_write_file`)。 */
|
||||
export interface DiffFileDoc {
|
||||
/** 绝对路径 */
|
||||
path: string
|
||||
/** 显示名(文件名) */
|
||||
name: string
|
||||
/** 文本内容(换行已统一为 `\n`)。二进制文件为空串 */
|
||||
content: string
|
||||
/** 探测到的编码(`utf-8` / `gbk` / …)。二进制文件为空串 */
|
||||
encoding: string
|
||||
/** 换行风格:"lf" | "crlf"。二进制文件为空串 */
|
||||
eol: string
|
||||
/** 文件字节数 */
|
||||
size: number
|
||||
/** 最后修改时间(Unix 毫秒) */
|
||||
modified: number
|
||||
/** 行数(二进制文件为 0) */
|
||||
lines: number
|
||||
/** 是否超过「大文件」阈值 */
|
||||
large: boolean
|
||||
/** 是否只读(写权限探测失败) */
|
||||
readonly: boolean
|
||||
/** 是否为二进制文件(不渲染 diff,只报「不同」) */
|
||||
binary: boolean
|
||||
}
|
||||
|
||||
/** 一侧的标识(左 = 原始,右 = 对比)。 */
|
||||
export type DiffSide = 'a' | 'b'
|
||||
|
||||
/** 目录对比中一个条目的状态。 */
|
||||
export type DirDiffStatus =
|
||||
/** 仅左侧有 */
|
||||
| 'left-only'
|
||||
/** 仅右侧有 */
|
||||
| 'right-only'
|
||||
/** 两侧都有且内容不同 */
|
||||
| 'different'
|
||||
/** 两侧都有且相同 */
|
||||
| 'identical'
|
||||
/** 同名但一侧是文件、另一侧是目录 */
|
||||
| 'type-mismatch'
|
||||
|
||||
/**
|
||||
* 目录对比中的一个条目(扁平列表,由前端组装成树)。
|
||||
*
|
||||
* 与 Rust 侧 `diff::types::DirDiffEntry` 一一对应。
|
||||
*/
|
||||
export interface DirDiffEntry {
|
||||
/** 相对根的路径,/ 分隔(显示名从前端最后一段取) */
|
||||
relPath: string
|
||||
/** 是否目录(`type-mismatch` 时视为目录) */
|
||||
isDir: boolean
|
||||
status: DirDiffStatus
|
||||
/** 该侧绝对路径;该侧不存在时为空串 */
|
||||
leftPath: string
|
||||
rightPath: string
|
||||
leftSize: number
|
||||
rightSize: number
|
||||
leftModified: number
|
||||
rightModified: number
|
||||
/**
|
||||
* 结论是否由**内容逐字节比对**得出。
|
||||
*
|
||||
* `false` 表示「大小相同、时间戳不同」且未读内容(体积超限 / 预算用尽),
|
||||
* 此时 `different` 是按时间戳判定的 —— 界面上要区别于已确认的差异。
|
||||
*/
|
||||
contentCompared: boolean
|
||||
}
|
||||
|
||||
/** 目录对比的扫描进度(事件负载,与 Rust 侧 `diff::types::DiffScanProgress` 一一对应)。 */
|
||||
export interface DiffScanProgress {
|
||||
/** 本轮扫描的标识(前端生成、随命令传入,据此过滤掉其它选项卡的进度) */
|
||||
scanId: number
|
||||
/** `scan` = 正在遍历目录;`compare` = 正在读内容逐字节核对 */
|
||||
phase: 'scan' | 'compare'
|
||||
/** 已完成数(遍历 = 已过的条目数;核对 = 已比对的文件数) */
|
||||
done: number
|
||||
/** 总数(遍历阶段未知为 0;核对阶段为预算上限) */
|
||||
total: number
|
||||
}
|
||||
|
||||
/** 一次目录对比的结果。 */
|
||||
export interface DirDiffReport {
|
||||
leftRoot: string
|
||||
rightRoot: string
|
||||
entries: DirDiffEntry[]
|
||||
/** 条目数达到上限、遍历被截断 */
|
||||
truncated: boolean
|
||||
/** 按跳过清单略过的目录数 */
|
||||
skippedDirs: number
|
||||
/** 扫描耗时(毫秒) */
|
||||
elapsedMs: number
|
||||
}
|
||||
|
||||
/** 目录对比的过滤条件。 */
|
||||
export type DirFilterId = 'diff' | 'all' | 'left-only' | 'right-only'
|
||||
|
||||
/**
|
||||
* 目录对比选项卡的状态。
|
||||
*
|
||||
* 由 `DiffWindow` 持有(它是选项卡会话的宿主),`DirDiffView` 读写它。
|
||||
*
|
||||
* # 为什么把可变会话对象当 prop 传,而不是逐项 props/emits
|
||||
*
|
||||
* 这里的状态有 8 个字段、且几乎每个都会双向改(输入根路径、切过滤、折叠、扫描结果…)。
|
||||
* 逐项拆成 `v-model` + emitters 会得到十几个 props 与 emits,而它们**本来就是同一个
|
||||
* 东西**(一个选项卡的会话状态)。因此按「共享可变模型」传:`DirDiffView` 直接改字段、
|
||||
* 只把无法自己完成的动作(触发扫描)emit 出去。
|
||||
*/
|
||||
export interface DirSessionState {
|
||||
leftRoot: string
|
||||
rightRoot: string
|
||||
report: DirDiffReport | null
|
||||
scanning: boolean
|
||||
filter: DirFilterId
|
||||
/**
|
||||
* 已折叠的目录相对路径。
|
||||
*
|
||||
* **两侧共用一份**:两个结构树渲染的是同一个并集树(行数与顺序完全一致,只有单元格
|
||||
* 内容不同),共用折叠状态才不会让左右两边错行。
|
||||
*/
|
||||
collapsed: Set<string>
|
||||
skipBuild: boolean
|
||||
compareContent: boolean
|
||||
}
|
||||
|
||||
/** 对比模块设置(与 Rust 侧 `diff::types::DiffSettings` 一一对应)。 */
|
||||
export interface DiffSettings {
|
||||
version: number
|
||||
/** 全局快捷键:打开 / 唤出对比窗口(空串 = 不注册) */
|
||||
openDiffShortcut: string
|
||||
/** 目录对比:默认是否比对内容 */
|
||||
compareContent: boolean
|
||||
/** 目录对比:默认是否跳过常见构建目录 */
|
||||
skipBuildDirs: boolean
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, onUnmounted } from 'vue'
|
||||
import { getCurrentWindow, Effect, EffectState } from '@tauri-apps/api/window'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { LogicalSize } from '@tauri-apps/api/dpi'
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { Pause, Play, X, Minus, FolderOpen, AlertCircle, Loader2, XCircle } from '@lucide/vue'
|
||||
@@ -280,6 +281,12 @@ onMounted(async () => {
|
||||
window.setTimeout(async () => {
|
||||
// 隐藏态下多贴合一次,确保尺寸已对内容就位
|
||||
await applyAutoHeight()
|
||||
// 任务栏身份:窗口级 AUMID(独立任务栏按钮)+ 组合图标;必须在 show() 之前设置
|
||||
try {
|
||||
await invoke('window_set_taskbar_identity', { label: win.label, kind: 'download' })
|
||||
} catch (e) {
|
||||
logger.warn(`设置任务栏身份失败:${String(e)}`)
|
||||
}
|
||||
try { await win.show() } catch { /* 忽略 */ }
|
||||
try { await win.unminimize() } catch { /* 忽略 */ }
|
||||
void commands.downloaderFocusWindow(win.label).catch(() => {})
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* dsh「启动进度」独立窗口(`#dsh-window`)。
|
||||
*
|
||||
* # 用途
|
||||
*
|
||||
* 托盘菜单点「dsh」时,若服务未启动/未就绪,主窗口会先开这个窗口,再同步拉起
|
||||
* 服务(`dsh_start`)—— 用户立刻能看到进度,而不是干等一个没有任何反馈的托盘点击。
|
||||
*
|
||||
* # 职责边界:本窗口只渲染,不编排
|
||||
*
|
||||
* 窗口自己轮询 `dsh_env_status`(本地状态查询,轻量)+ `dsh_log_tail` 渲染进度;
|
||||
* **何时切换到 Web 界面由主窗口负责**(它持有带令牌地址与 `openWebWindow`):
|
||||
* 就绪后主窗口打开 `dsh-web` 窗口并关闭本窗口。这样远端页面永远不会挂在本窗口
|
||||
* 的 label 上(本窗口登记了 capability,不能让远端页面拿到 IPC)。
|
||||
*
|
||||
* # 隐藏创建
|
||||
*
|
||||
* 窗口由前端**隐藏创建**(见 dshStore.openProgressWindow),本组件应用完主题
|
||||
* (含 `setBackgroundColor`)再 show —— 否则深色模式下会先闪一个纯白窗口。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window'
|
||||
import { AlertCircle, Bot, CheckCircle2, Loader2, Minus, X } from '@lucide/vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { applyStoredAccent } from '@/lib/theme'
|
||||
import { STORAGE_KEYS } from '@/lib/constants'
|
||||
import type { DshEnvStatus, DshServerStatus } from '@/types/dsh'
|
||||
|
||||
const logger = createLogger('dsh')
|
||||
const win = getCurrentWindow()
|
||||
|
||||
/** 与 style.css 的 --background 对齐:浅色 #ffffff / 深色 #16161a */
|
||||
const WINDOW_BG = { light: '#ffffff', dark: '#16161a' }
|
||||
|
||||
function readMainTheme(): string {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEYS.appSettings)
|
||||
if (raw) return (JSON.parse(raw) as { theme?: string }).theme ?? 'system'
|
||||
} catch {
|
||||
/* 设置不可读时按跟随系统处理 */
|
||||
}
|
||||
return 'system'
|
||||
}
|
||||
|
||||
function resolveIsDark(theme: string): boolean {
|
||||
if (theme === 'dark') return true
|
||||
if (theme === 'light') return false
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
}
|
||||
|
||||
async function applyTheme() {
|
||||
const root = document.documentElement
|
||||
const theme = readMainTheme()
|
||||
const isDark = resolveIsDark(theme)
|
||||
try {
|
||||
await win.setTheme(theme === 'system' ? null : (theme as 'dark' | 'light'))
|
||||
} catch {
|
||||
/* 平台不支持时忽略 */
|
||||
}
|
||||
try {
|
||||
// 底色单独 try:setTheme 失败不该连带跳过底色,否则仍会白底闪一下
|
||||
await win.setBackgroundColor(isDark ? WINDOW_BG.dark : WINDOW_BG.light)
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
root.classList.toggle('dark', isDark)
|
||||
applyStoredAccent(root, isDark ? 'dark' : 'light', STORAGE_KEYS.appSettings)
|
||||
}
|
||||
|
||||
// ===== 状态 =====
|
||||
|
||||
const server = ref<DshServerStatus | null>(null)
|
||||
const logTail = ref('')
|
||||
/** 距本次打开已过去的秒数(服务启动通常几秒~几十秒,给个可见的时间参照) */
|
||||
const elapsed = ref(0)
|
||||
|
||||
/** 就绪:已监听 + 已拿到带令牌地址(主窗口据此打开界面) */
|
||||
const canOpen = computed(() => !!server.value?.ready && !!server.value?.launchUrl)
|
||||
|
||||
const failed = computed(() => !!server.value?.error)
|
||||
|
||||
/** 阶段文案:按状态逐级推进(就绪由主窗口接手切界面) */
|
||||
const stageText = computed(() => {
|
||||
const s = server.value
|
||||
if (!s) return '读取状态…'
|
||||
if (s.error) return '启动失败'
|
||||
if (s.ready && s.launchUrl) return '已就绪,正在打开界面…'
|
||||
if (s.ready) return '等待访问地址(令牌)…'
|
||||
if (s.running) return '服务启动中…'
|
||||
return '准备启动…'
|
||||
})
|
||||
|
||||
const timer = ref<ReturnType<typeof setInterval> | null>(null)
|
||||
const logTimer = ref<ReturnType<typeof setInterval> | null>(null)
|
||||
|
||||
/**
|
||||
* 状态查询的时间上限(秒)。
|
||||
*
|
||||
* 就绪探测最多 60s(Rust `READY_TIMEOUT`),主窗口的等待也以此为准;留点余量后
|
||||
* 停止查询——否则用户把窗口留在那儿时,会一直以 1Hz 探测 Node 版本。
|
||||
*/
|
||||
const MAX_POLL_SECONDS = 75
|
||||
|
||||
async function refreshState() {
|
||||
try {
|
||||
const env = await invoke<DshEnvStatus>('dsh_env_status')
|
||||
server.value = env.server
|
||||
} catch (e) {
|
||||
logger.error('读取 dsh 状态失败: ' + e)
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshLog() {
|
||||
try {
|
||||
logTail.value = await invoke<string>('dsh_log_tail', { lines: 6 })
|
||||
} catch {
|
||||
/* 日志读取失败不影响进度显示 */
|
||||
}
|
||||
}
|
||||
|
||||
function minimize() {
|
||||
void win.minimize()
|
||||
}
|
||||
function closeWindow() {
|
||||
void win.close()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await applyTheme()
|
||||
// 任务栏身份:窗口级 AUMID(独立任务栏按钮)+ 组合图标;必须在 show() 之前设置
|
||||
try {
|
||||
await invoke('window_set_taskbar_identity', { label: win.label, kind: 'dsh' })
|
||||
} catch (e) {
|
||||
logger.warn(`设置任务栏身份失败:${String(e)}`)
|
||||
}
|
||||
try {
|
||||
await win.show()
|
||||
await win.setFocus()
|
||||
} catch (e) {
|
||||
logger.warn(`显示 dsh 启动窗口失败:${String(e)}`)
|
||||
}
|
||||
|
||||
await refreshState()
|
||||
await refreshLog()
|
||||
timer.value = setInterval(() => {
|
||||
elapsed.value += 1
|
||||
// 到达终态(就绪 / 失败)后停止状态查询:`dsh_env_status` 会探测 Node 版本
|
||||
// (跑一次 `node --version` 子进程),没必要在窗口留守期间持续消耗。
|
||||
// 就绪后主窗口会立刻关掉本窗口;失败时停在错误上即可。
|
||||
if (!canOpen.value && !failed.value && elapsed.value <= MAX_POLL_SECONDS) void refreshState()
|
||||
}, 1000)
|
||||
logTimer.value = setInterval(() => {
|
||||
if (!failed.value) void refreshLog()
|
||||
}, 1500)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (timer.value) clearInterval(timer.value)
|
||||
if (logTimer.value) clearInterval(logTimer.value)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-screen w-screen flex-col overflow-hidden bg-background text-foreground">
|
||||
<!-- 控制栏:标题(兼拖拽区)+ 关闭 -->
|
||||
<div class="flex h-9 shrink-0 items-center gap-1 border-b border-border px-1.5">
|
||||
<div class="flex h-full min-w-0 flex-1 items-center gap-1.5 px-2" data-tauri-drag-region>
|
||||
<Bot class="pointer-events-none size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span class="pointer-events-none truncate text-xs font-medium">DeepSeek Harness</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="icon-sm" @click="minimize">
|
||||
<Minus class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="hover:!bg-destructive hover:!text-destructive-foreground"
|
||||
@click="closeWindow"
|
||||
>
|
||||
<X class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div class="flex min-h-0 flex-1 flex-col gap-3 px-4 py-4">
|
||||
<!-- 阶段:图标 + 文案 + 计时 -->
|
||||
<div class="flex items-center gap-2.5">
|
||||
<CheckCircle2 v-if="canOpen" class="size-4 shrink-0 text-success" />
|
||||
<AlertCircle v-else-if="failed" class="size-4 shrink-0 text-danger" />
|
||||
<Loader2 v-else class="size-4 shrink-0 animate-spin text-primary" />
|
||||
<span class="text-[13px] font-medium" :class="{ 'text-danger': failed }">{{ stageText }}</span>
|
||||
<span class="ml-auto text-[11px] tabular-nums text-muted-foreground">{{ elapsed }}s</span>
|
||||
</div>
|
||||
|
||||
<!-- 失败原因:留在眼前,避免用户只看到托盘「没反应」 -->
|
||||
<div
|
||||
v-if="server?.error"
|
||||
class="rounded-md border border-border bg-danger-soft px-3 py-2 text-[12px] text-danger-text"
|
||||
>
|
||||
{{ server.error }}
|
||||
</div>
|
||||
|
||||
<!-- 启动输出尾部:给「进度」一个可读的落点 -->
|
||||
<div class="flex min-h-0 flex-1 flex-col gap-1.5">
|
||||
<span class="text-[11px] text-muted-foreground">启动输出</span>
|
||||
<pre
|
||||
class="min-h-0 flex-1 overflow-auto whitespace-pre-wrap break-all rounded-md border border-border bg-secondary/40 px-2.5 py-2 font-mono text-[11px] leading-relaxed text-fg-secondary"
|
||||
>{{ logTail || '(暂无输出)' }}</pre>
|
||||
</div>
|
||||
|
||||
<p v-if="canOpen" class="text-[11px] text-muted-foreground">
|
||||
界面即将在独立窗口中打开,本窗口会自动关闭。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,990 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 笔记模块主页面 —— **只做设置与管理,不做编辑**。
|
||||
*
|
||||
* 编辑发生在独立窗口(`openEditorWindow()`),本页负责:库状态与入口、库根管理、
|
||||
* 编辑器偏好。所有设置**即时生效、无保存按钮**。
|
||||
*
|
||||
* 版式遵循 `UI_DESIGN_SYSTEM.md`:
|
||||
* - 模块根 `min-h-full p-5`(滚动归属主滚动区,模块自身不建滚动容器)
|
||||
* - **不渲染 Tab 行**,Tab 注册给标题栏常驻切换器(`useModuleTabs` + `alwaysVisible`)
|
||||
* - 概览用「状态横幅 + 卡片」(§3.4);设置页用「多张 Card + 卡内标题 + `SettingRow`」
|
||||
* (与 dsh / 音乐设置页一致,`SettingGroup` 留给全局设置页那种多分组场景)
|
||||
* - 空态一律 `StateBlock`,不手写占位文案
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { getCurrentWebview } from '@tauri-apps/api/webview'
|
||||
import type { UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { openPath } from '@tauri-apps/plugin-opener'
|
||||
import {
|
||||
BookOpen,
|
||||
CalendarDays,
|
||||
Copy,
|
||||
Database,
|
||||
ExternalLink,
|
||||
Eye,
|
||||
FolderOpen,
|
||||
FolderPlus,
|
||||
Keyboard,
|
||||
Library,
|
||||
NotebookPen,
|
||||
Palette,
|
||||
RefreshCw,
|
||||
Tags,
|
||||
Wrench
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { ConfirmDialog, SettingRow, StateBlock } from '@/components/common'
|
||||
import { useModuleTabs } from '@/lib/use-module-tabs'
|
||||
import { WINDOWS } from '@/lib/constants'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import { openEditorWindow } from './openWindow'
|
||||
import { editorClient } from './editorClient'
|
||||
import { EDITOR_THEME_OPTIONS } from './editor/themes'
|
||||
import WebdavPanel from './components/WebdavPanel.vue'
|
||||
import ImportExportPanel from './components/ImportExportPanel.vue'
|
||||
import NewNoteDialog from './components/NewNoteDialog.vue'
|
||||
import type { ContextMenuStatus, EditorSettings } from '@/types/editor'
|
||||
|
||||
const store = useEditorStore()
|
||||
const logger = createLogger('editor')
|
||||
|
||||
/** 是否正有文件被拖到模块页上方(显示拖入提示遮罩) */
|
||||
const dragOver = ref(false)
|
||||
let unlistenDragDrop: UnlistenFn | null = null
|
||||
|
||||
const activeTab = ref('overview')
|
||||
// Tab 结构(规划 §6.1):概览 / 库 / 编辑器 / 集成。
|
||||
// 「同步」并入「库」(同步是库的属性);「集成」放文件关联 / 右键菜单 / 单实例。
|
||||
useModuleTabs(
|
||||
'editor',
|
||||
activeTab,
|
||||
[
|
||||
{ value: 'overview', label: '概览' },
|
||||
{ value: 'library', label: '库' },
|
||||
{ value: 'editor', label: '编辑器' },
|
||||
{ value: 'integration', label: '集成' }
|
||||
],
|
||||
{ alwaysVisible: true }
|
||||
)
|
||||
|
||||
/**
|
||||
* 模块页拖入文件:为每个路径开一个编辑器窗口(本页只做管理,编辑在独立窗口)。
|
||||
*
|
||||
* 用 Tauri 原生拖放事件(`onDragDropEvent`)而非 HTML5 `drop`:`dragDropEnabled`
|
||||
* 默认开启时 Tauri 会接管 WebView2 的拖放,HTML5 在 Windows 上拿不到外部文件路径。
|
||||
* 注意 Windows UIPI 会拦截拖入以管理员运行的窗口 —— 仅在非提权时可用。
|
||||
*/
|
||||
async function onDroppedPaths(paths: string[]): Promise<void> {
|
||||
for (const path of paths) {
|
||||
try {
|
||||
const options = (await editorClient.pathKind(path)) === 'folder' ? { folder: path } : { path }
|
||||
await openEditorWindow(options)
|
||||
} catch (e) {
|
||||
toast.error(`打开失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** HTML5 dragover:亮遮罩(只有在 Tauri 原生拖放未接管时才会触发,见 onDomDrop)。 */
|
||||
function onDomDragOver(): void {
|
||||
dragOver.value = true
|
||||
}
|
||||
|
||||
/**
|
||||
* HTML5 `drop` 兜底:拦住浏览器默认行为(否则会把文件内容插进页面/编辑器),
|
||||
* 能拿到绝对路径时照样打开。正常情况下拖放由 Tauri 原生处理器接管,这里不会被触发。
|
||||
*/
|
||||
function onDomDrop(event: DragEvent): void {
|
||||
event.preventDefault()
|
||||
dragOver.value = false
|
||||
const files = Array.from(event.dataTransfer?.files ?? [])
|
||||
const paths = files
|
||||
.map(f => (f as File & { path?: string }).path)
|
||||
.filter((p): p is string => !!p)
|
||||
if (paths.length) {
|
||||
void onDroppedPaths(paths)
|
||||
} else if (files.length) {
|
||||
logger.warn(`拖放未走原生通道(files=${files.length},取不到绝对路径)`)
|
||||
toast.error('未取到拖入文件的绝对路径(拖放被浏览器接管),请改用「打开文件」')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// 快捷键在别的模块按下时 App.vue 已把请求挂起并切到本页:挂载即消费
|
||||
if (store.consumeNewNote()) openNewNote()
|
||||
void store.init()
|
||||
void loadContextMenu()
|
||||
const selfWebview = getCurrentWebview()
|
||||
void selfWebview
|
||||
.onDragDropEvent(event => {
|
||||
const payload = event.payload
|
||||
if (payload.type === 'enter' || payload.type === 'over') {
|
||||
dragOver.value = true
|
||||
} else if (payload.type === 'drop') {
|
||||
dragOver.value = false
|
||||
logger.info(`原生拖放 drop:${payload.paths.length} 项`)
|
||||
void onDroppedPaths(payload.paths)
|
||||
} else {
|
||||
dragOver.value = false
|
||||
}
|
||||
})
|
||||
.then(unlisten => {
|
||||
unlistenDragDrop = unlisten
|
||||
})
|
||||
logger.info(`拖放监听已注册:webview=${selfWebview.label}`)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
unlistenDragDrop?.()
|
||||
unlistenDragDrop = null
|
||||
store.disposeListeners()
|
||||
})
|
||||
|
||||
// ===== 全局快捷键请求(Rust 只发事件,App.vue 在应用级转发 / 开窗)=====
|
||||
//
|
||||
// 「新建笔记」:App.vue 收到快捷键后置挂起标记并切到本页,本页**挂载时消费**(快捷键在
|
||||
// 其它模块按下时本页还没挂载,页内 watch 会漏掉),已挂载时则由下面的 watch 消费。
|
||||
const newNoteOpen = ref(false)
|
||||
|
||||
function openNewNote(): void {
|
||||
activeTab.value = 'overview'
|
||||
newNoteOpen.value = true
|
||||
}
|
||||
|
||||
watch(
|
||||
() => store.newNotePending,
|
||||
pending => {
|
||||
if (pending && store.consumeNewNote()) openNewNote()
|
||||
}
|
||||
)
|
||||
|
||||
// 全局快捷键(`Alt+E` 打开编辑器窗口)由 App.vue 在应用级处理(快捷键在任意模块下
|
||||
// 都要可用,不能依赖本页已挂载 —— 见 App.vue 的说明);这里只保留模块内的入口按钮。
|
||||
|
||||
/**
|
||||
* 冷启动的「用 Thing 打开」:命令行留下的文件路径取到后,直接开一个笔记窗口。
|
||||
*
|
||||
* **只在主窗口做**:笔记窗口内部也会渲染本模块(`#editor-window` 是独立入口,
|
||||
* 不走这里),但它的 hash 里已经带了 `?path=`,由 `EditorWindow` 自己打开 ——
|
||||
* 这里再响应一次就会开第二个窗口。
|
||||
*/
|
||||
watch(
|
||||
() => store.pendingOpenTarget,
|
||||
target => {
|
||||
if (!target || isEditorWindow()) return
|
||||
const options = target.kind === 'folder' ? { folder: target.path } : { path: target.path }
|
||||
void openEditorWindow(options).catch(e => toast.error(`打开失败:${String(e)}`))
|
||||
}
|
||||
)
|
||||
|
||||
/** 当前是否运行在编辑器独立窗口里(hash 形如 `#editor-window?...`)。 */
|
||||
function isEditorWindow(): boolean {
|
||||
return window.location.hash.startsWith(`#${WINDOWS.editorWindow}`)
|
||||
}
|
||||
|
||||
// ===== 设置写入(即时生效) =====
|
||||
function commit(patch: Partial<EditorSettings>): void {
|
||||
void store.patchSettings(patch)
|
||||
}
|
||||
|
||||
function onNumber(
|
||||
patchKey: 'fontSize' | 'lineHeight' | 'tabSize' | 'autosaveMs' | 'maxFileSizeMb',
|
||||
event: Event
|
||||
) {
|
||||
const value = Number((event.target as HTMLInputElement).value)
|
||||
if (!Number.isFinite(value)) return
|
||||
commit({ [patchKey]: value } as Partial<EditorSettings>)
|
||||
}
|
||||
|
||||
// ===== 库根 =====
|
||||
const resetRootOpen = ref(false)
|
||||
|
||||
async function pickLibraryRoot(): Promise<void> {
|
||||
try {
|
||||
const selected = await open({ directory: true, multiple: false, title: '选择笔记库目录' })
|
||||
if (typeof selected !== 'string') return
|
||||
await store.setLibraryRoot(selected)
|
||||
toast.success('已切换笔记库')
|
||||
} catch (e) {
|
||||
toast.error(`切换失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function resetLibraryRoot(): Promise<void> {
|
||||
try {
|
||||
await store.setLibraryRoot(null)
|
||||
toast.success('已恢复默认库目录')
|
||||
} catch (e) {
|
||||
toast.error(`恢复失败:${String(e)}`)
|
||||
} finally {
|
||||
resetRootOpen.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function revealRoot(): Promise<void> {
|
||||
if (!store.libraryRoot) return
|
||||
try {
|
||||
await openPath(store.libraryRoot)
|
||||
} catch (e) {
|
||||
toast.error(`打开目录失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function copyRoot(): Promise<void> {
|
||||
if (!store.libraryRoot) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(store.libraryRoot)
|
||||
toast.success('库路径已复制')
|
||||
} catch {
|
||||
toast.error('复制失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function openEditor(): Promise<void> {
|
||||
try {
|
||||
await openEditorWindow()
|
||||
} catch (e) {
|
||||
toast.error(`打开编辑器失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 在编辑器窗口里直接打开磁盘文件(路径来自系统对话框,选择即授权)。 */
|
||||
async function openExternalFile(): Promise<void> {
|
||||
try {
|
||||
const selected = await open({
|
||||
multiple: false,
|
||||
directory: false,
|
||||
title: '打开文件'
|
||||
})
|
||||
if (typeof selected !== 'string') return
|
||||
await editorClient.authorizeFile(selected)
|
||||
await openEditorWindow({ path: selected })
|
||||
} catch (e) {
|
||||
toast.error(`打开文件失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 在编辑器窗口里打开一个本地文件夹(目录面板)。 */
|
||||
async function openFolder(): Promise<void> {
|
||||
try {
|
||||
const selected = await open({ directory: true, multiple: false, title: '打开文件夹' })
|
||||
if (typeof selected !== 'string') return
|
||||
await openEditorWindow({ folder: selected })
|
||||
} catch (e) {
|
||||
toast.error(`打开文件夹失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开一个「最近文件」:库内 `.md` 走笔记语义,其余走库外文件语义。 */
|
||||
async function openRecentFile(entry: { path: string }): Promise<void> {
|
||||
const root = (store.libraryRoot || '').replace(/[\\/]+$/, '')
|
||||
const norm = entry.path.replace(/\//g, '\\').toLowerCase()
|
||||
if (root && norm.startsWith(root.replace(/\//g, '\\').toLowerCase()) && /\.(md|markdown|mdx)$/i.test(entry.path)) {
|
||||
const rel = entry.path.slice(root.length).replace(/^[\\/]+/, '').replace(/\\/g, '/')
|
||||
await openEditorWindow({ relPath: rel })
|
||||
return
|
||||
}
|
||||
await openEditorWindow({ path: entry.path })
|
||||
}
|
||||
|
||||
async function openRecentFolder(entry: { path: string }): Promise<void> {
|
||||
await openEditorWindow({ folder: entry.path })
|
||||
}
|
||||
|
||||
// ===== 系统集成(P4-4) =====
|
||||
const contextMenu = ref<ContextMenuStatus | null>(null)
|
||||
const contextBusy = ref(false)
|
||||
|
||||
async function loadContextMenu(): Promise<void> {
|
||||
try {
|
||||
contextMenu.value = await editorClient.contextMenuStatus()
|
||||
} catch (e) {
|
||||
toast.error(`读取集成状态失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function registerContextMenu(): Promise<void> {
|
||||
contextBusy.value = true
|
||||
try {
|
||||
contextMenu.value = await editorClient.registerContextMenu()
|
||||
toast.success('已注册右键菜单')
|
||||
} catch (e) {
|
||||
toast.error(`注册失败:${String(e)}`)
|
||||
} finally {
|
||||
contextBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function unregisterContextMenu(): Promise<void> {
|
||||
contextBusy.value = true
|
||||
try {
|
||||
contextMenu.value = await editorClient.unregisterContextMenu()
|
||||
toast.success('已卸载右键菜单')
|
||||
} catch (e) {
|
||||
toast.error(`卸载失败:${String(e)}`)
|
||||
} finally {
|
||||
contextBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(activeTab, tab => {
|
||||
if (tab === 'integration') void loadContextMenu()
|
||||
})
|
||||
|
||||
const rebuilding = ref(false)
|
||||
|
||||
async function rebuildIndex(): Promise<void> {
|
||||
rebuilding.value = true
|
||||
try {
|
||||
await store.rebuildIndex()
|
||||
await store.refreshLibrary()
|
||||
toast.success('索引已重建')
|
||||
} catch (e) {
|
||||
toast.error(`重建索引失败:${String(e)}`)
|
||||
} finally {
|
||||
rebuilding.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开今天的日记(不存在则按日记模板创建)。 */
|
||||
async function openDailyNote(): Promise<void> {
|
||||
try {
|
||||
await store.openDailyNote()
|
||||
await openEditorWindow({ relPath: store.currentRelPath })
|
||||
} catch (e) {
|
||||
toast.error(`打开日记失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
const noteCount = computed(() => store.info?.noteCount ?? 0)
|
||||
const rootKind = computed(() => (store.info?.isCustom ? '自定义' : '默认'))
|
||||
/** 索引状态摘要(横幅右侧;索引未就绪时显示占位) */
|
||||
const indexSummary = computed(() => {
|
||||
const stats = store.indexStats
|
||||
if (!stats) return '索引准备中'
|
||||
return `索引 ${stats.noteCount} / 文件 ${stats.fileCount}`
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="relative min-h-full p-5"
|
||||
@dragenter.prevent="onDomDragOver"
|
||||
@dragover.prevent="onDomDragOver"
|
||||
@drop.prevent="onDomDrop"
|
||||
>
|
||||
<Tabs v-model="activeTab" class="flex min-h-full w-full flex-col">
|
||||
<!-- ===== 概览 ===== -->
|
||||
<TabsContent value="overview" class="tab-animate">
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- 状态横幅:状态区 → 指标区 → 操作区(§3.4) -->
|
||||
<Card class="!py-0 !gap-0">
|
||||
<CardContent class="flex flex-wrap items-center gap-x-6 gap-y-3 px-4 py-4">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<span
|
||||
v-if="!store.info"
|
||||
class="flex items-center gap-1.5 text-[13px] text-muted-foreground"
|
||||
>
|
||||
<span class="size-2 rounded-full bg-muted-foreground" />加载中
|
||||
</span>
|
||||
<template v-else>
|
||||
<span class="flex items-center gap-1.5 text-[13px] text-success">
|
||||
<span class="size-2 rounded-full bg-success" />已就绪
|
||||
</span>
|
||||
</template>
|
||||
<span class="text-[13px] text-fg-secondary">本地 Markdown 笔记库</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-24 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">笔记数</span>
|
||||
<span class="text-lg font-semibold tabular-nums">{{ noteCount }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-24 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">库类型</span>
|
||||
<span class="text-lg font-semibold tabular-nums">{{ rootKind }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">库目录</span>
|
||||
<span class="truncate font-mono text-[13px] text-fg-secondary">
|
||||
{{ store.libraryRoot || '—' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-28 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">索引</span>
|
||||
<span class="truncate text-[13px] text-fg-secondary">
|
||||
{{ store.indexing ? '同步中…' : indexSummary }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="ml-auto flex flex-wrap gap-2">
|
||||
<Button size="sm" variant="outline" @click="openDailyNote">
|
||||
<CalendarDays class="size-3.5" />今日日记
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" :disabled="!store.libraryRoot" @click="revealRoot">
|
||||
<FolderOpen class="size-3.5" />打开目录
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" @click="openExternalFile">
|
||||
<FolderOpen class="size-3.5" />打开文件
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" @click="openFolder">
|
||||
<FolderPlus class="size-3.5" />打开文件夹
|
||||
</Button>
|
||||
<Button size="sm" @click="openEditor">
|
||||
<NotebookPen class="size-3.5" />打开编辑器
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 最近打开:文件与文件夹两份列表(与笔记库解耦) -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<BookOpen class="size-4 text-primary" />
|
||||
最近打开
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<StateBlock
|
||||
v-if="!store.recentFiles.length && !store.recentFolders.length"
|
||||
variant="empty"
|
||||
title="还没有打开过文件"
|
||||
description="点上方「打开编辑器 / 打开文件 / 打开文件夹」开始"
|
||||
:min-height="140"
|
||||
/>
|
||||
<div v-else class="flex flex-col gap-4">
|
||||
<div v-if="store.recentFiles.length" class="flex flex-col">
|
||||
<p class="pb-1 text-[11px] font-medium text-muted-foreground">最近文件</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<button
|
||||
v-for="item in store.recentFiles"
|
||||
:key="item.path"
|
||||
type="button"
|
||||
class="flex min-h-13 items-center gap-4 py-2 text-left transition-colors duration-150 outline-none hover:text-primary focus-visible:ring-2 focus-visible:ring-ring/40"
|
||||
:class="item.exists ? '' : 'opacity-50'"
|
||||
@click="openRecentFile(item)"
|
||||
>
|
||||
<span class="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span class="truncate text-[13px] text-foreground">
|
||||
{{ item.name }}
|
||||
<span v-if="!item.exists" class="text-[11px] text-muted-foreground">(已失效)</span>
|
||||
</span>
|
||||
<span class="truncate text-xs text-muted-foreground">{{ item.path }}</span>
|
||||
</span>
|
||||
<ExternalLink class="size-3.5 shrink-0 text-muted-foreground" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="store.recentFolders.length" class="flex flex-col">
|
||||
<p class="pb-1 text-[11px] font-medium text-muted-foreground">最近文件夹</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<button
|
||||
v-for="item in store.recentFolders"
|
||||
:key="item.path"
|
||||
type="button"
|
||||
class="flex min-h-13 items-center gap-4 py-2 text-left transition-colors duration-150 outline-none hover:text-primary focus-visible:ring-2 focus-visible:ring-ring/40"
|
||||
:class="item.exists ? '' : 'opacity-50'"
|
||||
@click="openRecentFolder(item)"
|
||||
>
|
||||
<span class="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span class="truncate text-[13px] text-foreground">
|
||||
{{ item.name }}
|
||||
<span v-if="!item.exists" class="text-[11px] text-muted-foreground">(已失效)</span>
|
||||
</span>
|
||||
<span class="truncate text-xs text-muted-foreground">{{ item.path }}</span>
|
||||
</span>
|
||||
<ExternalLink class="size-3.5 shrink-0 text-muted-foreground" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<!-- ===== 库(库根 / 索引 / 导入导出) ===== -->
|
||||
<TabsContent value="library" class="tab-animate">
|
||||
<div class="flex flex-col gap-4 pb-4">
|
||||
<!-- 笔记库 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Library class="size-4 text-primary" />
|
||||
笔记库
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
笔记以 Markdown 文件形式保存在该目录;切换库只改变指向,原目录内容不会被移动
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="库目录" :description="store.libraryRoot || '—'">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" :disabled="!store.libraryRoot" @click="copyRoot">
|
||||
<Copy class="size-3.5" />复制
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :disabled="!store.libraryRoot" @click="revealRoot">
|
||||
<FolderOpen class="size-3.5" />浏览
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" @click="pickLibraryRoot">
|
||||
<NotebookPen class="size-3.5" />切换…
|
||||
</Button>
|
||||
<Button
|
||||
v-if="store.info?.isCustom"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="text-muted-foreground"
|
||||
@click="resetRootOpen = true"
|
||||
>
|
||||
恢复默认
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="重新扫描" description="在应用外新增或修改文件后,手动刷新库内容">
|
||||
<Button variant="outline" size="sm" @click="store.refreshLibrary()">
|
||||
<RefreshCw class="size-3.5" />刷新
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 索引与检索(P1) -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Database class="size-4 text-primary" />
|
||||
索引与检索
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
全文检索与标签依赖一份 SQLite 索引(存放在库内 <code class="font-mono">.editor/</code>)。
|
||||
它只是加速层:删掉也能从 Markdown 文件完整重建,不影响笔记本身。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow
|
||||
label="索引状态"
|
||||
:description="store.indexStats?.dbPath || '尚未建立索引'"
|
||||
>
|
||||
<div class="flex items-center gap-3 text-[13px] text-fg-secondary">
|
||||
<span class="tabular-nums">笔记 {{ store.indexStats?.noteCount ?? 0 }}</span>
|
||||
<span class="tabular-nums">文件 {{ store.indexStats?.fileCount ?? 0 }}</span>
|
||||
<span class="flex items-center gap-1 tabular-nums">
|
||||
<Tags class="size-3.5" />{{ store.indexStats?.tagCount ?? 0 }}
|
||||
</span>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="重建索引" description="按文件重新解析标题、标签与双链(库很大时需要一点时间)">
|
||||
<Button variant="outline" size="sm" :disabled="rebuilding || store.indexing" @click="rebuildIndex">
|
||||
<RefreshCw class="size-3.5" :class="rebuilding && 'animate-spin'" />重建
|
||||
</Button>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="外部改动监听" description="库内文件在应用外被修改时提醒(监听始终开启)">
|
||||
<span class="flex items-center gap-1.5 text-xs text-success">
|
||||
<span class="size-2 rounded-full bg-success" />已启用
|
||||
</span>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="单文件大小上限"
|
||||
description="超过该大小的文件会关闭所见即所得 / 折叠 / 补全,单位 MB"
|
||||
control-width="wide"
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
:model-value="store.settings.maxFileSizeMb"
|
||||
@change="onNumber('maxFileSizeMb', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 导入 / 导出(P2) -->
|
||||
<ImportExportPanel />
|
||||
|
||||
<!-- WebDAV 备份 / 同步(原「同步」页,并入库页) -->
|
||||
<WebdavPanel />
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<!-- ===== 编辑器 ===== -->
|
||||
<TabsContent value="editor" class="tab-animate">
|
||||
<div class="flex flex-col gap-4 pb-4">
|
||||
<!-- 编辑器外观 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Palette class="size-4 text-primary" />
|
||||
编辑器外观
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="配色方案" description="「跟随主应用主题」关闭时,窗口按本方案取色与深浅" control-width="wide">
|
||||
<Select
|
||||
:model-value="String(store.settings.editorTheme)"
|
||||
@update:model-value="v => commit({ editorTheme: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in EDITOR_THEME_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="跟随主应用主题" description="打开时编辑器窗口整体跟随主应用主题;关闭时由上方「配色方案」决定,窗口内外深浅一致">
|
||||
<Switch
|
||||
:model-value="store.settings.followAppTheme"
|
||||
@update:model-value="v => commit({ followAppTheme: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字体族" description="留空使用内置等宽字体栈" control-width="wide">
|
||||
<Input
|
||||
:model-value="store.settings.fontFamily"
|
||||
placeholder="Cascadia Code, Consolas, …"
|
||||
@change="(e: Event) => commit({ fontFamily: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字号" description="单位 px" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
min="10"
|
||||
max="32"
|
||||
:model-value="store.settings.fontSize"
|
||||
@change="onNumber('fontSize', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="行高" description="倍数,建议 1.5 ~ 2.0" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
step="0.1"
|
||||
min="1"
|
||||
max="3"
|
||||
:model-value="store.settings.lineHeight"
|
||||
@change="onNumber('lineHeight', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字体连字" description="启用 ligatures(如 => 显示为箭头)">
|
||||
<Switch
|
||||
:model-value="store.settings.ligatures"
|
||||
@update:model-value="v => commit({ ligatures: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="显示行号">
|
||||
<Switch
|
||||
:model-value="store.settings.showLineNumbers"
|
||||
@update:model-value="v => commit({ showLineNumbers: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="显示大纲"
|
||||
description="在编辑区右侧抽屉显示标题树(Ctrl+Shift+O 可临时切换)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.showOutline"
|
||||
@update:model-value="v => commit({ showOutline: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 编辑器行为 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Eye class="size-4 text-primary" />
|
||||
编辑器行为
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow
|
||||
label="所见即所得"
|
||||
description="Live Preview:语法符号在非光标行隐藏、光标行显形;关闭后为纯源码 + 高亮"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.livePreview"
|
||||
@update:model-value="v => commit({ livePreview: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="默认视图" description="新开编辑器窗口时的初始视图" control-width="wide">
|
||||
<Select
|
||||
:model-value="String(store.settings.defaultView)"
|
||||
@update:model-value="v => commit({ defaultView: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="wysiwyg">所见即所得</SelectItem>
|
||||
<SelectItem value="source">源码</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="自动保存" description="停止输入后延迟保存,单位毫秒;0 = 关闭(仅 Ctrl+S)" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
max="10000"
|
||||
step="100"
|
||||
:model-value="store.settings.autosaveMs"
|
||||
@change="onNumber('autosaveMs', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="Tab 宽度" description="按空格数计" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="8"
|
||||
:model-value="store.settings.tabSize"
|
||||
@change="onNumber('tabSize', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="自动补全"
|
||||
description="括号自动闭合与代码补全(大文件会临时关闭)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.autocomplete"
|
||||
@update:model-value="v => commit({ autocomplete: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="识别 [[双链]]"
|
||||
description="按 Obsidian 语义解析双链并写入索引(反链面板留待后续)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.wikilink"
|
||||
@update:model-value="v => commit({ wikilink: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="复用文档窗口"
|
||||
description="同一篇笔记重复打开时聚焦已有窗口,而不是开出第二个(两个窗口会自动保存,后写的覆盖先写的)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.reuseWindow"
|
||||
@update:model-value="v => commit({ reuseWindow: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="导出时高亮代码"
|
||||
description="关闭后导出的 HTML 里代码块是纯黑白,适合黑白打印机"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.exportHighlight"
|
||||
@update:model-value="v => commit({ exportHighlight: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="新建时选模板"
|
||||
description="关闭后用上次选中的模板直接新建"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.showTemplatePicker"
|
||||
@update:model-value="v => commit({ showTemplatePicker: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 全局快捷键(P2) -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Keyboard class="size-4 text-primary" />
|
||||
全局快捷键
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
留空即不注册。格式如 <code class="font-mono">Ctrl+Shift+N</code>;与本应用其它模块
|
||||
的快捷键冲突时会注册失败(日志里会写明是谁占了)。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="新建笔记" description="任意界面按下都打开新建对话框" control-width="wide">
|
||||
<Input
|
||||
:model-value="store.settings.newNoteShortcut"
|
||||
placeholder="Ctrl+Shift+N"
|
||||
@change="(e: Event) => commit({ newNoteShortcut: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow label="打开编辑器窗口" control-width="wide">
|
||||
<Input
|
||||
:model-value="store.settings.openEditorShortcut"
|
||||
placeholder="未设置"
|
||||
@change="(e: Event) => commit({ openEditorShortcut: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<!-- ===== 集成(系统集成) ===== -->
|
||||
<TabsContent value="integration" class="tab-animate">
|
||||
<div class="flex flex-col gap-4 pb-4">
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Wrench class="size-4 text-primary" />
|
||||
系统集成
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
让编辑器融入系统:双击文档打开、资源管理器右键、全局快捷键。所有注册都走用户级
|
||||
(免管理员);开发模式下 exe 路径不稳定,因此<b>右键菜单默认不自动注册</b>。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow
|
||||
label="文件关联"
|
||||
description="双击 .md / .markdown / .mdx 用本应用打开(由安装器写入)"
|
||||
>
|
||||
<span class="flex items-center gap-1.5 text-xs text-success">
|
||||
<span class="size-2 rounded-full bg-success" />已启用
|
||||
</span>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="单实例"
|
||||
description="应用已运行时再次打开文件会转交给既有实例,不新起进程"
|
||||
>
|
||||
<span class="flex items-center gap-1.5 text-xs text-success">
|
||||
<span class="size-2 rounded-full bg-success" />已启用
|
||||
</span>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="资源管理器右键菜单"
|
||||
:description="
|
||||
contextMenu?.registered
|
||||
? '已注册「用 Thing 编辑器打开」(文件 / 文件夹 / 目录背景)'
|
||||
: '未注册;注册后可在资源管理器右键直接打开'
|
||||
"
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<span
|
||||
v-if="contextMenu?.registered"
|
||||
class="flex items-center gap-1.5 text-xs text-success"
|
||||
>
|
||||
<span class="size-2 rounded-full bg-success" />已注册
|
||||
</span>
|
||||
<Button
|
||||
v-if="!contextMenu?.registered"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
:disabled="contextBusy"
|
||||
@click="registerContextMenu"
|
||||
>
|
||||
注册
|
||||
</Button>
|
||||
<Button
|
||||
v-else
|
||||
size="sm"
|
||||
variant="outline"
|
||||
:disabled="contextBusy"
|
||||
@click="unregisterContextMenu"
|
||||
>
|
||||
卸载
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="可执行文件路径"
|
||||
:description="contextMenu?.exePath || '—'"
|
||||
>
|
||||
<span
|
||||
v-if="contextMenu?.isDev"
|
||||
class="rounded-sm bg-warning-soft px-1.5 py-0.5 text-[10px] text-warning"
|
||||
>
|
||||
开发模式
|
||||
</span>
|
||||
<span v-else class="text-xs text-muted-foreground">安装目录</span>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="全局快捷键"
|
||||
description="打开编辑器 / 新建笔记的键位在「编辑器」页配置"
|
||||
>
|
||||
<span class="text-xs text-muted-foreground">见「编辑器」页</span>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="resetRootOpen"
|
||||
title="恢复默认库目录"
|
||||
description="笔记不会丢失:仅把库根指回应用数据目录下的默认位置,原目录内容保持不动。"
|
||||
confirm-text="恢复默认"
|
||||
@confirm="resetLibraryRoot"
|
||||
/>
|
||||
|
||||
<!-- 全局快捷键(Ctrl+Shift+N)触发的新建对话框:落在库根 -->
|
||||
<NewNoteDialog v-model:open="newNoteOpen" dir-rel="" />
|
||||
|
||||
<!-- 拖入提示遮罩(Tauri 原生拖放事件驱动) -->
|
||||
<div
|
||||
v-if="dragOver"
|
||||
class="pointer-events-none absolute inset-0 z-50 flex items-center justify-center bg-background/70 backdrop-blur-sm"
|
||||
>
|
||||
<div
|
||||
class="flex flex-col items-center gap-1.5 rounded-lg border-2 border-dashed border-primary px-8 py-6 text-center"
|
||||
>
|
||||
<NotebookPen class="size-6 text-primary" />
|
||||
<span class="text-sm font-medium">松开以打开</span>
|
||||
<span class="text-xs text-muted-foreground">
|
||||
文件 / 文件夹会在新的编辑器窗口打开
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,218 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 反链面板:当前笔记的**出链**与**入链**。
|
||||
*
|
||||
* # 数据从哪来
|
||||
*
|
||||
* 全部来自 SQLite 索引的 `links` 表(写入索引时已把 `[[名字]]` 按 Obsidian 语义
|
||||
* 「全库按名解析」成库内相对路径)。因此这里不需要扫全库 —— 一次 `editor_backlinks`
|
||||
* 调用就把两侧都取回。
|
||||
*
|
||||
* # 未解析链接为什么值得显示
|
||||
*
|
||||
* `[[还不存在的笔记]]` 在 Obsidian 里是一个**新建入口**,不是错误。面板把它单独列在
|
||||
* 「未解析」分组下并允许一键创建 —— 这正是双链笔记「先写链接、后补内容」的用法。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ArrowUpRight, Link2, Link2Off, Loader2, RefreshCw } from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import { editorClient } from '../editorClient'
|
||||
import type { NoteBacklinks, NoteLink } from '@/types/editor'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 当前笔记的库内相对路径(空串 = 没有笔记,面板显示空态) */
|
||||
relPath: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 打开某篇笔记 */
|
||||
open: [relPath: string]
|
||||
/** 已用某个名字新建了一篇(未解析链接的一键创建);上层据此展开树 */
|
||||
create: [name: string]
|
||||
}>()
|
||||
|
||||
const store = useEditorStore()
|
||||
const data = ref<NoteBacklinks | null>(null)
|
||||
const loading = ref(false)
|
||||
|
||||
/** 已解析的出链 */
|
||||
const resolvedOutgoing = computed(() =>
|
||||
(data.value?.outgoing ?? []).filter(item => item.resolved)
|
||||
)
|
||||
/** 未解析的出链(可一键新建) */
|
||||
const unresolvedOutgoing = computed(() =>
|
||||
(data.value?.outgoing ?? []).filter(item => !item.resolved && item.kind !== 'url')
|
||||
)
|
||||
/** 外部链接(`[](https://…)`):只展示不可跳转到库内 */
|
||||
const externalOutgoing = computed(() =>
|
||||
(data.value?.outgoing ?? []).filter(item => item.kind === 'url')
|
||||
)
|
||||
|
||||
async function load(): Promise<void> {
|
||||
if (!props.relPath) {
|
||||
data.value = null
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
try {
|
||||
data.value = await editorClient.backlinks(props.relPath)
|
||||
} catch (e) {
|
||||
// 索引还没建立时这里会失败:不是错误,只是「暂时没有数据」
|
||||
data.value = null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.relPath, store.indexStats?.noteCount],
|
||||
() => void load(),
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
/** 点击未解析链接:按名字新建一篇(`createNote` 会顺带把它打开)。 */
|
||||
async function createMissing(link: NoteLink): Promise<void> {
|
||||
try {
|
||||
await store.createNote(currentDirOf(props.relPath), link.target)
|
||||
emit('create', link.target)
|
||||
await load()
|
||||
} catch (e) {
|
||||
toast.error(`新建失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 新笔记落在当前笔记所在目录(与 Obsidian「同目录优先」的习惯一致)。 */
|
||||
function currentDirOf(relPath: string): string {
|
||||
const parts = relPath.split('/')
|
||||
parts.pop()
|
||||
return parts.join('/')
|
||||
}
|
||||
|
||||
function targetOf(link: NoteLink): string {
|
||||
// URL 类型直接交给系统浏览器由上层处理;这里统一用 relPath(可能为空)
|
||||
return link.relPath || link.target
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="flex h-6 shrink-0 items-center gap-1.5 border-b border-border px-2 text-[11px] text-muted-foreground">
|
||||
<Link2 class="size-3" />
|
||||
<span>双链</span>
|
||||
<span class="ml-auto tabular-nums">
|
||||
被 {{ data?.incomingSources ?? 0 }} 篇引用 · 出链 {{ resolvedOutgoing.length + unresolvedOutgoing.length }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm p-0.5 hover:bg-active"
|
||||
title="刷新"
|
||||
@click="load"
|
||||
>
|
||||
<RefreshCw class="size-3" :class="loading && 'animate-spin'" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-1.5 py-2">
|
||||
<div v-if="loading && !data" class="flex items-center justify-center gap-2 p-4">
|
||||
<Loader2 class="size-3.5 animate-spin text-muted-foreground" />
|
||||
<span class="text-xs text-muted-foreground">正在查询链接…</span>
|
||||
</div>
|
||||
|
||||
<StateBlock
|
||||
v-else-if="!relPath"
|
||||
variant="empty"
|
||||
title="未打开笔记"
|
||||
description="打开一篇笔记后这里会显示它的双链"
|
||||
:min-height="120"
|
||||
/>
|
||||
|
||||
<StateBlock
|
||||
v-else-if="!data?.incoming.length && !data?.outgoing.length"
|
||||
variant="empty"
|
||||
title="还没有链接"
|
||||
description="在正文里写 [[另一篇笔记]],或在别处引用这篇"
|
||||
:min-height="120"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<!-- 入链 -->
|
||||
<p v-if="data?.incoming.length" class="px-1 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase">
|
||||
被引用({{ data.incomingSources }})
|
||||
</p>
|
||||
<button
|
||||
v-for="link in data?.incoming ?? []"
|
||||
:key="`in-${link.relPath}-${link.target}`"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-left text-xs text-fg-secondary transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
@click="emit('open', link.relPath)"
|
||||
>
|
||||
<ArrowUpRight class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.title }}</span>
|
||||
<span class="ml-auto shrink-0 truncate text-[10px] text-fg-disabled">{{ link.relPath }}</span>
|
||||
</button>
|
||||
|
||||
<!-- 已解析出链 -->
|
||||
<p
|
||||
v-if="resolvedOutgoing.length"
|
||||
class="px-1 pt-3 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase"
|
||||
>
|
||||
指向({{ resolvedOutgoing.length }})
|
||||
</p>
|
||||
<button
|
||||
v-for="link in resolvedOutgoing"
|
||||
:key="`out-${link.relPath}`"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-left text-xs text-fg-secondary transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
@click="emit('open', targetOf(link))"
|
||||
>
|
||||
<Link2 class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.title }}</span>
|
||||
</button>
|
||||
|
||||
<!-- 未解析出链(可一键新建) -->
|
||||
<p
|
||||
v-if="unresolvedOutgoing.length"
|
||||
class="px-1 pt-3 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase"
|
||||
>
|
||||
未解析({{ unresolvedOutgoing.length }})
|
||||
</p>
|
||||
<button
|
||||
v-for="link in unresolvedOutgoing"
|
||||
:key="`miss-${link.target}`"
|
||||
type="button"
|
||||
class="group flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-left text-xs text-muted-foreground transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
title="点击新建这篇笔记"
|
||||
@click="createMissing(link)"
|
||||
>
|
||||
<Link2Off class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.target }}</span>
|
||||
<span class="ml-auto shrink-0 text-[10px] opacity-0 group-hover:opacity-100">新建</span>
|
||||
</button>
|
||||
|
||||
<!-- 外部链接 -->
|
||||
<p
|
||||
v-if="externalOutgoing.length"
|
||||
class="px-1 pt-3 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase"
|
||||
>
|
||||
外部链接({{ externalOutgoing.length }})
|
||||
</p>
|
||||
<a
|
||||
v-for="link in externalOutgoing"
|
||||
:key="`url-${link.target}`"
|
||||
class="flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-xs text-fg-secondary transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
:href="link.target"
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
>
|
||||
<ArrowUpRight class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.target }}</span>
|
||||
</a>
|
||||
</template>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,920 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 本地目录面板(P3-5 / P5-2):以**懒加载文件树**浏览并操作用户真实文件系统。
|
||||
*
|
||||
* 与「笔记库」面板的本质区别:
|
||||
* - 库是**沙箱**(根目录内、相对路径、走索引);目录是**看盘**(任意路径、
|
||||
* 绝对路径、不进索引、不做全文检索);
|
||||
* - 树是**懒加载**的:根 = 打开的文件夹(`store.dirListing`),子目录在展开时才经
|
||||
* `editor_read_dir` 拉一层并缓存 —— 大目录不再一次全量列举,展开哪层读哪层。
|
||||
*
|
||||
* 所有写操作都是**显式动作**,且删除一律走系统回收站(Rust 侧 `editor_delete_path`)。
|
||||
*
|
||||
* # 多选与拖拽(P5-2)
|
||||
*
|
||||
* 单击保持「进目录(展开/收起)/ 打开文件」;`Ctrl/Cmd+单击` 切换选中、`Shift+单击`
|
||||
* 范围选中。选中非空时底部出现批量操作条(批量重命名 / 删除所选)。行可拖拽到
|
||||
* 文件夹行完成移动。
|
||||
*
|
||||
* # 结构性操作后的刷新策略
|
||||
*
|
||||
* 新建 / 重命名 / 删除 / 移动都会让**已缓存的路径**失真 —— 统一走 `invalidate()`:
|
||||
* 清空子层缓存 → 重读根 → 并行重读所有已展开目录。展开的目录通常只有几个,代价可忽略;
|
||||
* 换来的是「缓存里的路径永远有效」这条不变量(拖放目标、选中集都按路径工作)。
|
||||
*/
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import {
|
||||
AppWindow,
|
||||
ArrowUp,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
ExternalLink,
|
||||
FilePlus,
|
||||
FileText,
|
||||
Folder,
|
||||
FolderInput,
|
||||
FolderOpen,
|
||||
FolderPlus,
|
||||
Loader2,
|
||||
LocateFixed,
|
||||
Pencil,
|
||||
RotateCw,
|
||||
SquarePen,
|
||||
Trash2,
|
||||
X
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import { ConfirmDialog, StateBlock } from '@/components/common'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import { editorClient } from '../editorClient'
|
||||
import { openEditorWindow } from '../openWindow'
|
||||
import type { DirEntry } from '@/types/editor'
|
||||
|
||||
const store = useEditorStore()
|
||||
|
||||
const filter = ref('')
|
||||
|
||||
// ===== 懒加载树 =====
|
||||
|
||||
/** 树行:条目 + 层级(缩进用) */
|
||||
interface TreeRow {
|
||||
entry: DirEntry
|
||||
depth: number
|
||||
}
|
||||
|
||||
/** 已展开的目录(值 = 该目录的子层已请求/已缓存) */
|
||||
const expanded = ref<Set<string>>(new Set())
|
||||
/** 子层缓存:目录绝对路径 → 其子项(Rust 保证目录在前、各自按名排序) */
|
||||
const childrenMap = ref<Map<string, DirEntry[]>>(new Map())
|
||||
/** 正在加载子层的目录(行内转圈用) */
|
||||
const loadingDirs = ref<Set<string>>(new Set())
|
||||
/** 新建文件 / 文件夹的目标目录(空串 = 根) */
|
||||
const selectedDir = ref('')
|
||||
|
||||
const rootEntries = computed<DirEntry[]>(() => store.dirListing?.entries ?? [])
|
||||
const rootCwd = computed(() => store.dirListing?.cwd ?? '')
|
||||
|
||||
const cwdName = computed(() => {
|
||||
const cwd = rootCwd.value
|
||||
if (!cwd) return '本地目录'
|
||||
return cwd.split(/[\\/]/).filter(Boolean).pop() ?? cwd
|
||||
})
|
||||
|
||||
/** 目录名过滤:命中自身或任一**已加载**后代才可见;过滤时全部按展开渲染。 */
|
||||
const rows = computed<TreeRow[]>(() => {
|
||||
const kw = filter.value.trim().toLowerCase()
|
||||
const out: TreeRow[] = []
|
||||
|
||||
const matches = (entry: DirEntry, kids: DirEntry[] | undefined): boolean => {
|
||||
if (!kw) return true
|
||||
if (entry.name.toLowerCase().includes(kw)) return true
|
||||
return (kids ?? []).some(k => matches(k, childrenMap.value.get(k.path)))
|
||||
}
|
||||
|
||||
const walk = (list: DirEntry[], depth: number) => {
|
||||
for (const entry of list) {
|
||||
const kids = childrenMap.value.get(entry.path)
|
||||
if (!matches(entry, kids)) continue
|
||||
out.push({ entry, depth })
|
||||
if (entry.kind !== 'dir') continue
|
||||
const open = expanded.value.has(entry.path) || !!kw
|
||||
if (open) walk(kids ?? [], depth + 1)
|
||||
}
|
||||
}
|
||||
walk(rootEntries.value, 0)
|
||||
return out
|
||||
})
|
||||
|
||||
/** 拉取一个目录的子层并写入缓存(已缓存则跳过)。 */
|
||||
async function loadChildren(path: string): Promise<void> {
|
||||
if (childrenMap.value.has(path)) return
|
||||
const loading = new Set(loadingDirs.value)
|
||||
loading.add(path)
|
||||
loadingDirs.value = loading
|
||||
try {
|
||||
const listing = await editorClient.readDir(path)
|
||||
const map = new Map(childrenMap.value)
|
||||
map.set(path, listing.entries)
|
||||
childrenMap.value = map
|
||||
} catch (e) {
|
||||
// 读失败就收起来,别留一个「展开但永远是空的」目录
|
||||
const next = new Set(expanded.value)
|
||||
next.delete(path)
|
||||
expanded.value = next
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
const done = new Set(loadingDirs.value)
|
||||
done.delete(path)
|
||||
loadingDirs.value = done
|
||||
}
|
||||
}
|
||||
|
||||
function toggleDir(entry: DirEntry): void {
|
||||
const next = new Set(expanded.value)
|
||||
if (next.has(entry.path)) {
|
||||
next.delete(entry.path)
|
||||
} else {
|
||||
next.add(entry.path)
|
||||
selectedDir.value = entry.path
|
||||
void loadChildren(entry.path)
|
||||
}
|
||||
expanded.value = next
|
||||
}
|
||||
|
||||
/**
|
||||
* 结构性操作后的统一失效:清空缓存 → 重读根 → 并行重读已展开目录。
|
||||
*
|
||||
* 「清空缓存」而不是逐个修补:重命名 / 移动会让后代路径整体变化,逐个推导既啰嗦
|
||||
* 又容易漏;重新拉取已展开的几层是最不容易出错的兜底。
|
||||
*/
|
||||
async function invalidate(): Promise<void> {
|
||||
childrenMap.value = new Map()
|
||||
await store.readDir(rootCwd.value)
|
||||
await Promise.all([...expanded.value].map(p => loadChildren(p)))
|
||||
}
|
||||
|
||||
// 换根(打开 / 上一级 / 重新打开):树状态与选择全部重置
|
||||
watch(
|
||||
() => store.dirListing?.cwd,
|
||||
() => {
|
||||
childrenMap.value = new Map()
|
||||
expanded.value = new Set()
|
||||
loadingDirs.value = new Set()
|
||||
selectedDir.value = ''
|
||||
filter.value = ''
|
||||
selected.value = new Set()
|
||||
lastIndex.value = -1
|
||||
}
|
||||
)
|
||||
|
||||
// ===== 多选 =====
|
||||
const selected = ref<Set<string>>(new Set())
|
||||
const lastIndex = ref(-1)
|
||||
|
||||
const allKnown = computed<DirEntry[]>(() => {
|
||||
const out = [...rootEntries.value]
|
||||
for (const kids of childrenMap.value.values()) out.push(...kids)
|
||||
return out
|
||||
})
|
||||
|
||||
const selectedEntries = computed(() => allKnown.value.filter(e => selected.value.has(e.path)))
|
||||
|
||||
function toggleSelect(entry: DirEntry): void {
|
||||
const next = new Set(selected.value)
|
||||
if (next.has(entry.path)) next.delete(entry.path)
|
||||
else next.add(entry.path)
|
||||
selected.value = next
|
||||
}
|
||||
|
||||
function rangeSelect(entry: TreeRow): void {
|
||||
const list = rows.value
|
||||
const to = list.findIndex(e => e.entry.path === entry.entry.path)
|
||||
const from = lastIndex.value >= 0 ? lastIndex.value : to
|
||||
const [lo, hi] = from <= to ? [from, to] : [to, from]
|
||||
const next = new Set(selected.value)
|
||||
for (let i = lo; i <= hi; i++) {
|
||||
const item = list[i]
|
||||
if (item) next.add(item.entry.path)
|
||||
}
|
||||
selected.value = next
|
||||
}
|
||||
|
||||
// ===== 导航与打开 =====
|
||||
async function openFolder(): Promise<void> {
|
||||
try {
|
||||
await store.openFolderDialog()
|
||||
} catch (e) {
|
||||
toast.error(`打开文件夹失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在已打开文件夹里一键建一个临时文本文件(免命名,建完直接打开)。
|
||||
*
|
||||
* 建在**根**下;命名走「`新建文本.txt` → `新建文本 2.txt` → …」:不弹框才叫一键,
|
||||
* 所以得自己避开重名(用根列表判断占用;真撞上了后端会报错,toast 会带出原因)。
|
||||
*/
|
||||
async function createTempFile(): Promise<void> {
|
||||
const used = new Set(rootEntries.value.map(e => e.name.toLowerCase()))
|
||||
let name = '新建文本.txt'
|
||||
for (let i = 2; used.has(name.toLowerCase()) && i < 1000; i++) {
|
||||
name = `新建文本 ${i}.txt`
|
||||
}
|
||||
try {
|
||||
await createIn(selectedDir.value || rootCwd.value, 'file', name)
|
||||
toast.success(`已创建 ${name}`)
|
||||
} catch (e) {
|
||||
toast.error(`新建文件失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function goUp(): Promise<void> {
|
||||
const parent = store.dirListing?.parent
|
||||
if (!parent) return
|
||||
try {
|
||||
await store.readDir(parent)
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh(): Promise<void> {
|
||||
if (!rootCwd.value) return
|
||||
try {
|
||||
await invalidate()
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 定位当前文件 =====
|
||||
//
|
||||
// 树是懒加载的,「定位」必须顺着路径逐级展开并**按需拉取**中间层,否则目标行根本
|
||||
// 不在 `rows` 里。虚线是:只对当前打开的库外文件(`fileDoc.path`)且确实位于本目录根
|
||||
// 之下时才提供入口 —— 否则点了也没有意义。
|
||||
|
||||
/** 树内容容器(滚动目标用) */
|
||||
const treeRef = ref<HTMLElement | null>(null)
|
||||
/** 需要短暂高亮的路径(定位反馈) */
|
||||
const locateTarget = ref('')
|
||||
|
||||
function normalizePath(p: string): string {
|
||||
return p.replace(/\//g, '\\').replace(/\\+$/, '')
|
||||
}
|
||||
|
||||
const currentFilePath = computed(() => {
|
||||
if (store.kind === 'file') return store.fileDoc?.path ?? ''
|
||||
// 库内笔记也可定位:只要它所在的库目录被当作本地目录打开过,就能在这棵树里找到
|
||||
if (store.kind === 'note' && store.currentRelPath) return store.noteAbsPath(store.currentRelPath)
|
||||
return ''
|
||||
})
|
||||
|
||||
/** 当前文件是否在本目录根之下(决定定位按钮是否出现)。 */
|
||||
const canLocateCurrent = computed(() => {
|
||||
const file = currentFilePath.value
|
||||
const root = rootCwd.value
|
||||
if (!file || !root) return false
|
||||
const fn = normalizePath(file).toLowerCase()
|
||||
const rn = normalizePath(root).toLowerCase()
|
||||
return fn.startsWith(`${rn}\\`)
|
||||
})
|
||||
|
||||
/** 某个目录当前可见的子项(根走 `dirListing`,其余走子层缓存)。 */
|
||||
function entriesOf(dir: string): DirEntry[] {
|
||||
if (normalizePath(dir).toLowerCase() === normalizePath(rootCwd.value).toLowerCase()) {
|
||||
return rootEntries.value
|
||||
}
|
||||
return childrenMap.value.get(dir) ?? []
|
||||
}
|
||||
|
||||
/** 确保某目录的子层已缓存(根无需加载)。 */
|
||||
async function ensureChildren(dir: string): Promise<void> {
|
||||
if (normalizePath(dir).toLowerCase() === normalizePath(rootCwd.value).toLowerCase()) return
|
||||
if (!childrenMap.value.has(dir)) await loadChildren(dir)
|
||||
}
|
||||
|
||||
/** 展开到当前文件的父目录,滚动到该行并短暂高亮。 */
|
||||
async function locateCurrent(): Promise<void> {
|
||||
const file = currentFilePath.value
|
||||
const root = rootCwd.value
|
||||
if (!file || !root || !canLocateCurrent.value) return
|
||||
// 过滤会隐藏目标行,先清掉
|
||||
filter.value = ''
|
||||
const rootNorm = normalizePath(root)
|
||||
const relative = normalizePath(file).slice(rootNorm.length).replace(/^\\+/, '')
|
||||
const segments = relative.split('\\').filter(Boolean)
|
||||
segments.pop() // 去掉文件名,只展开到父目录
|
||||
|
||||
const next = new Set(expanded.value)
|
||||
let current = rootNorm
|
||||
for (const segment of segments) {
|
||||
await ensureChildren(current)
|
||||
const found = entriesOf(current).find(e => e.kind === 'dir' && e.name === segment)
|
||||
if (!found) {
|
||||
current = ''
|
||||
break
|
||||
}
|
||||
next.add(found.path)
|
||||
current = found.path
|
||||
}
|
||||
expanded.value = next
|
||||
if (!current) return
|
||||
await ensureChildren(current) // 让目标文件行出现在列表里
|
||||
|
||||
locateTarget.value = file
|
||||
await nextTick()
|
||||
const rows = treeRef.value?.querySelectorAll<HTMLElement>('[data-path]')
|
||||
const target = rows ? Array.from(rows).find(el => el.dataset.path === file) : undefined
|
||||
target?.scrollIntoView({ block: 'center' })
|
||||
window.setTimeout(() => {
|
||||
if (locateTarget.value === file) locateTarget.value = ''
|
||||
}, 1400)
|
||||
}
|
||||
|
||||
function openEntry(entry: DirEntry): void {
|
||||
if (entry.kind === 'dir') {
|
||||
toggleDir(entry)
|
||||
} else {
|
||||
void store.openDoc(entry.path).catch(e => toast.error(`打开失败:${String(e)}`))
|
||||
}
|
||||
}
|
||||
|
||||
async function openInNewWindow(entry: DirEntry): Promise<void> {
|
||||
try {
|
||||
if (entry.kind === 'dir') await openEditorWindow({ folder: entry.path, dedupe: false })
|
||||
else await openEditorWindow({ path: entry.path, dedupe: false })
|
||||
} catch (e) {
|
||||
toast.error(`在新窗口打开失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function onRowClick(entry: TreeRow, event: MouseEvent): void {
|
||||
const index = rows.value.findIndex(e => e.entry.path === entry.entry.path)
|
||||
if (event.ctrlKey || event.metaKey) {
|
||||
toggleSelect(entry.entry)
|
||||
lastIndex.value = index
|
||||
return
|
||||
}
|
||||
if (event.shiftKey) {
|
||||
rangeSelect(entry)
|
||||
return
|
||||
}
|
||||
if (selected.value.size > 0) selected.value = new Set()
|
||||
lastIndex.value = index
|
||||
openEntry(entry.entry)
|
||||
}
|
||||
|
||||
// ===== 拖拽移动 =====
|
||||
const dragging = ref('')
|
||||
/** 当前作为放置目标的文件夹路径(高亮用) */
|
||||
const dropTarget = ref('')
|
||||
|
||||
function onDragStart(entry: DirEntry, event: DragEvent): void {
|
||||
dragging.value = entry.path
|
||||
event.dataTransfer?.setData('text/plain', entry.path)
|
||||
if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move'
|
||||
}
|
||||
|
||||
function onDragOver(entry: DirEntry, event: DragEvent): void {
|
||||
if (entry.kind !== 'dir' || !dragging.value || dragging.value === entry.path) return
|
||||
event.preventDefault()
|
||||
if (event.dataTransfer) event.dataTransfer.dropEffect = 'move'
|
||||
dropTarget.value = entry.path
|
||||
}
|
||||
|
||||
async function onDrop(entry: DirEntry, event: DragEvent): Promise<void> {
|
||||
event.preventDefault()
|
||||
const src = dragging.value
|
||||
dragging.value = ''
|
||||
dropTarget.value = ''
|
||||
if (!src || entry.kind !== 'dir' || src === entry.path) return
|
||||
try {
|
||||
await editorClient.movePath(src, entry.path)
|
||||
await invalidate()
|
||||
} catch (e) {
|
||||
toast.error(`移动失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function onDragEnd(): void {
|
||||
dragging.value = ''
|
||||
dropTarget.value = ''
|
||||
}
|
||||
|
||||
// ===== 新建 / 重命名(目标 = 选中的目录,缺省根) =====
|
||||
type PromptMode = 'file' | 'folder' | 'rename'
|
||||
const promptOpen = ref(false)
|
||||
const promptMode = ref<PromptMode>('file')
|
||||
const promptValue = ref('')
|
||||
const promptTarget = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
const promptTitle = computed(() => {
|
||||
if (promptMode.value === 'file') return '新建文件'
|
||||
if (promptMode.value === 'folder') return '新建文件夹'
|
||||
return '重命名'
|
||||
})
|
||||
|
||||
const promptTargetLabel = computed(() => {
|
||||
if (promptMode.value === 'rename') return ''
|
||||
const dir = selectedDir.value || rootCwd.value
|
||||
if (!dir) return ''
|
||||
const name = dir.split(/[\\/]/).filter(Boolean).pop() ?? dir
|
||||
return `位置:${name}`
|
||||
})
|
||||
|
||||
function openPrompt(mode: PromptMode, target = '', initial = ''): void {
|
||||
promptMode.value = mode
|
||||
promptTarget.value = target
|
||||
promptValue.value = initial
|
||||
promptOpen.value = true
|
||||
}
|
||||
|
||||
/** 在指定目录下新建文件 / 文件夹;成功后失效缓存并(文件)打开。 */
|
||||
async function createIn(dir: string, kind: 'file' | 'folder', name: string): Promise<void> {
|
||||
if (!dir) return
|
||||
if (kind === 'file') {
|
||||
const path = await editorClient.createFile(dir, name)
|
||||
await invalidate()
|
||||
await store.recordRecentFile(path, name)
|
||||
await store.openFile(path)
|
||||
} else {
|
||||
await editorClient.createDir(dir, name)
|
||||
await invalidate()
|
||||
// 新建的文件夹就地展开,让用户立刻看到它
|
||||
const next = new Set(expanded.value)
|
||||
next.add(dir)
|
||||
expanded.value = next
|
||||
void loadChildren(dir)
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmPrompt(): Promise<void> {
|
||||
const name = promptValue.value.trim()
|
||||
if (!name) {
|
||||
toast.error('名称不能为空')
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
try {
|
||||
if (promptMode.value === 'file') {
|
||||
await createIn(selectedDir.value || rootCwd.value, 'file', name)
|
||||
} else if (promptMode.value === 'folder') {
|
||||
await createIn(selectedDir.value || rootCwd.value, 'folder', name)
|
||||
} else {
|
||||
await editorClient.renamePath(promptTarget.value, name)
|
||||
await invalidate()
|
||||
}
|
||||
promptOpen.value = false
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 批量重命名(模板化) =====
|
||||
const batchOpen = ref(false)
|
||||
const batchTemplate = ref('{name}')
|
||||
const batchBusy = ref(false)
|
||||
|
||||
/** 模板占位符:{name} 原名(去扩展名)、{ext} 扩展名(含点)、{n} 序号(1 起) */
|
||||
function renderTemplate(entry: DirEntry, index: number): string {
|
||||
const dot = entry.name.lastIndexOf('.')
|
||||
const stem = dot > 0 ? entry.name.slice(0, dot) : entry.name
|
||||
const ext = dot > 0 ? entry.name.slice(dot) : ''
|
||||
return batchTemplate.value
|
||||
.replace(/\{name\}/g, stem)
|
||||
.replace(/\{ext\}/g, ext)
|
||||
.replace(/\{n\}/g, String(index + 1))
|
||||
}
|
||||
|
||||
const batchPreview = computed(() =>
|
||||
selectedEntries.value.map((entry, index) => ({
|
||||
entry,
|
||||
next: renderTemplate(entry, index).trim()
|
||||
}))
|
||||
)
|
||||
|
||||
function openBatch(): void {
|
||||
if (!selectedEntries.value.length) return
|
||||
batchTemplate.value = '{name}'
|
||||
batchOpen.value = true
|
||||
}
|
||||
|
||||
async function confirmBatch(): Promise<void> {
|
||||
const items = batchPreview.value
|
||||
if (items.some(i => !i.next)) {
|
||||
toast.error('新名称不能为空')
|
||||
return
|
||||
}
|
||||
if (new Set(items.map(i => i.next)).size !== items.length) {
|
||||
toast.error('新名称存在重复')
|
||||
return
|
||||
}
|
||||
batchBusy.value = true
|
||||
try {
|
||||
const failed: string[] = []
|
||||
for (const item of items) {
|
||||
try {
|
||||
await editorClient.renamePath(item.entry.path, item.next)
|
||||
} catch (e) {
|
||||
failed.push(`${item.next}:${String(e)}`)
|
||||
}
|
||||
}
|
||||
await invalidate()
|
||||
if (failed.length) toast.error(`部分失败:${failed.join(';')}`)
|
||||
else toast.success(`已重命名 ${items.length} 项`)
|
||||
batchOpen.value = false
|
||||
selected.value = new Set()
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
batchBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 删除 =====
|
||||
const confirmOpen = ref(false)
|
||||
const deleteTargets = ref<DirEntry[]>([])
|
||||
|
||||
function askDelete(list: DirEntry[]): void {
|
||||
if (!list.length) return
|
||||
deleteTargets.value = list
|
||||
confirmOpen.value = true
|
||||
}
|
||||
|
||||
async function doDelete(): Promise<void> {
|
||||
const list = deleteTargets.value
|
||||
if (!list.length) return
|
||||
try {
|
||||
const report = await editorClient.deletePath(list.map(e => e.path))
|
||||
await invalidate()
|
||||
if (report.removed > 0) toast.success(`已移入回收站 ${report.removed} 项`)
|
||||
if (report.failed.length) toast.error(report.failed.join(';'))
|
||||
selected.value = new Set()
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
confirmOpen.value = false
|
||||
deleteTargets.value = []
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 右键菜单(行内 4 个按钮改到这里) =====
|
||||
const menuOpen = ref(false)
|
||||
const menuX = ref(0)
|
||||
const menuY = ref(0)
|
||||
const menuEntry = ref<DirEntry | null>(null)
|
||||
|
||||
/** 菜单项数(用于贴边翻转时的预估高度) */
|
||||
const MENU_ITEMS = 6
|
||||
const MENU_WIDTH = 184
|
||||
|
||||
/** 右键打开菜单;若该行不在选中集内,则把选中集改为「仅它」。 */
|
||||
function openMenu(event: MouseEvent, entry: DirEntry): void {
|
||||
if (!selected.value.has(entry.path)) selected.value = new Set([entry.path])
|
||||
menuEntry.value = entry
|
||||
const height = MENU_ITEMS * 28 + 16
|
||||
menuX.value = Math.max(8, Math.min(event.clientX, window.innerWidth - MENU_WIDTH - 8))
|
||||
menuY.value = Math.max(8, Math.min(event.clientY, window.innerHeight - height - 8))
|
||||
menuOpen.value = true
|
||||
}
|
||||
|
||||
function closeMenu(): void {
|
||||
menuOpen.value = false
|
||||
menuEntry.value = null
|
||||
}
|
||||
|
||||
/** 删除目标:右键行在选中集内时删整批,否则只删它。 */
|
||||
const menuDeleteTargets = computed<DirEntry[]>(() => {
|
||||
const entry = menuEntry.value
|
||||
if (!entry) return []
|
||||
return selected.value.has(entry.path) ? selectedEntries.value : [entry]
|
||||
})
|
||||
|
||||
function menuOpenEntry(): void {
|
||||
const entry = menuEntry.value
|
||||
closeMenu()
|
||||
if (entry) openEntry(entry)
|
||||
}
|
||||
|
||||
function menuNewWindow(): void {
|
||||
const entry = menuEntry.value
|
||||
closeMenu()
|
||||
if (entry) void openInNewWindow(entry)
|
||||
}
|
||||
|
||||
function menuReveal(): void {
|
||||
const entry = menuEntry.value
|
||||
closeMenu()
|
||||
if (entry) store.revealPath(entry.path)
|
||||
}
|
||||
|
||||
function menuRename(): void {
|
||||
const entry = menuEntry.value
|
||||
closeMenu()
|
||||
if (entry) openPrompt('rename', entry.path, entry.name)
|
||||
}
|
||||
|
||||
function menuDelete(): void {
|
||||
const targets = menuDeleteTargets.value
|
||||
closeMenu()
|
||||
askDelete(targets)
|
||||
}
|
||||
|
||||
// 不默认加载主目录:默认态就是「打开文件夹」入口,由用户显式选择
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<!-- 默认态:尚未打开任何文件夹时,面板本身就是一个「打开文件夹」入口 -->
|
||||
<div v-if="!store.dirListing" class="flex min-h-0 flex-1 items-center justify-center">
|
||||
<StateBlock
|
||||
variant="empty"
|
||||
title="未打开文件夹"
|
||||
description="选择一个本地文件夹后,可在其中浏览、打开与编辑文件"
|
||||
:min-height="180"
|
||||
>
|
||||
<template #action>
|
||||
<Button size="sm" @click="openFolder">
|
||||
<FolderOpen class="size-3.5" />打开文件夹
|
||||
</Button>
|
||||
</template>
|
||||
</StateBlock>
|
||||
</div>
|
||||
|
||||
<!-- 工具条:上一级 / 刷新 / 打开文件夹 -->
|
||||
<div v-if="store.dirListing" class="flex h-8 shrink-0 items-center gap-0.5 px-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="上一级"
|
||||
:disabled="!store.dirListing?.parent"
|
||||
@click="goUp"
|
||||
>
|
||||
<ArrowUp class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="store.dirLoading ? '正在读取…' : '刷新'"
|
||||
:disabled="store.dirLoading"
|
||||
@click="refresh"
|
||||
>
|
||||
<RotateCw class="size-3.5" :class="store.dirLoading && 'animate-spin'" />
|
||||
</Button>
|
||||
<!-- 定位当前文件:仅当前打开的文件位于本目录之下时出现(否则无意义) -->
|
||||
<Button
|
||||
v-if="canLocateCurrent"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="定位当前文件(展开目录树并高亮)"
|
||||
@click="locateCurrent"
|
||||
>
|
||||
<LocateFixed class="size-3.5" />
|
||||
</Button>
|
||||
<span class="ml-1 truncate text-[11px] font-medium text-fg-secondary" :title="store.dirListing?.cwd">
|
||||
{{ cwdName }}
|
||||
</span>
|
||||
<div class="ml-auto flex items-center gap-0.5">
|
||||
<Button variant="ghost" size="icon-sm" title="新建文件(在选中的目录 / 根)" @click="openPrompt('file')">
|
||||
<FilePlus class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="新建文件夹(在选中的目录 / 根)" @click="openPrompt('folder')">
|
||||
<FolderPlus class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="新建临时文本文件(一键创建,不弹命名框)"
|
||||
:disabled="store.dirLoading"
|
||||
@click="createTempFile"
|
||||
>
|
||||
<SquarePen class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="打开文件夹…" @click="openFolder">
|
||||
<FolderOpen class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 过滤 -->
|
||||
<div v-if="store.dirListing" class="shrink-0 px-2 pb-2">
|
||||
<div class="relative">
|
||||
<Input v-model="filter" placeholder="按名称过滤…" class="h-7 pr-6 text-[11px]" />
|
||||
<button
|
||||
v-if="filter"
|
||||
type="button"
|
||||
class="absolute top-1/2 right-1.5 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
@click="filter = ''"
|
||||
>
|
||||
<X class="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 树 -->
|
||||
<ScrollArea v-if="store.dirListing" class="min-h-0 flex-1">
|
||||
<div ref="treeRef" class="px-1.5 pb-2">
|
||||
<div v-if="store.dirLoading && !rootEntries.length" class="flex items-center justify-center gap-2 p-4">
|
||||
<Loader2 class="size-3.5 animate-spin text-muted-foreground" />
|
||||
<span class="text-[11px] text-muted-foreground">正在读取目录…</span>
|
||||
</div>
|
||||
|
||||
<StateBlock
|
||||
v-else-if="!rows.length"
|
||||
variant="empty"
|
||||
:title="filter ? '没有匹配项' : '空目录'"
|
||||
:description="filter ? undefined : '换个目录,或点右上角打开一个文件夹'"
|
||||
:min-height="140"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<div
|
||||
v-for="row in rows"
|
||||
:key="row.entry.path"
|
||||
:data-path="row.entry.path"
|
||||
class="group flex h-7 cursor-pointer items-center gap-1 rounded-sm pr-1.5 transition-colors duration-150"
|
||||
:class="[
|
||||
selected.has(row.entry.path)
|
||||
? 'bg-primary-soft text-primary-soft-text'
|
||||
: currentFilePath === row.entry.path
|
||||
? 'bg-row-selected text-primary-soft-text'
|
||||
: 'text-fg-secondary hover:bg-row-hover hover:text-foreground',
|
||||
dropTarget === row.entry.path && 'ring-1 ring-primary ring-inset',
|
||||
locateTarget === row.entry.path && 'ring-2 ring-primary ring-inset'
|
||||
]"
|
||||
:style="{ paddingLeft: `${row.depth * 12 + 4}px` }"
|
||||
:title="row.entry.path"
|
||||
draggable="true"
|
||||
@dragstart="onDragStart(row.entry, $event)"
|
||||
@dragover="onDragOver(row.entry, $event)"
|
||||
@drop="onDrop(row.entry, $event)"
|
||||
@dragend="onDragEnd"
|
||||
@click="onRowClick(row, $event)"
|
||||
@contextmenu.prevent="openMenu($event, row.entry)"
|
||||
>
|
||||
<!-- 目录行:展开箭头(懒加载不转圈 —— 目录树展开是高频动作,闪烁比等待更烦)
|
||||
文件行:占位对齐 + 文件图标 -->
|
||||
<template v-if="row.entry.kind === 'dir'">
|
||||
<component
|
||||
:is="expanded.has(row.entry.path) ? ChevronDown : ChevronRight"
|
||||
class="size-3.5 shrink-0 opacity-70"
|
||||
/>
|
||||
<Folder class="size-3.5 shrink-0 opacity-80" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="w-3.5 shrink-0" />
|
||||
<FileText class="size-3.5 shrink-0 opacity-70" />
|
||||
</template>
|
||||
<span class="truncate text-xs">{{ row.entry.name }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<!-- 批量操作条(有选中时) -->
|
||||
<div
|
||||
v-if="store.dirListing && selected.size"
|
||||
class="flex h-8 shrink-0 items-center gap-1 border-t border-border px-2 text-[11px] text-muted-foreground"
|
||||
>
|
||||
<span class="tabular-nums">已选 {{ selected.size }} 项</span>
|
||||
<div class="ml-auto flex items-center gap-1">
|
||||
<Button variant="outline" size="sm" @click="openBatch">
|
||||
<FolderInput class="size-3.5" />批量重命名
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" @click="askDelete(selectedEntries)">
|
||||
<Trash2 class="size-3.5" />删除
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="取消选择" @click="selected = new Set()">
|
||||
<X class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右键菜单:文件行的操作(原行内 4 个按钮移到这里) -->
|
||||
<template v-if="menuOpen && menuEntry">
|
||||
<div class="fixed inset-0 z-40" @click="closeMenu" @contextmenu.prevent="closeMenu" />
|
||||
<div
|
||||
class="fixed z-50 min-w-[184px] overflow-hidden rounded-md border border-border bg-card py-1 text-xs text-foreground shadow-md"
|
||||
:style="{ left: `${menuX}px`, top: `${menuY}px` }"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="menuOpenEntry"
|
||||
>
|
||||
<FolderOpen class="size-3.5 opacity-70" />打开
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="menuNewWindow"
|
||||
>
|
||||
<AppWindow class="size-3.5 opacity-70" />在新窗口打开
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="menuReveal"
|
||||
>
|
||||
<ExternalLink class="size-3.5 opacity-70" />在资源管理器中显示
|
||||
</button>
|
||||
<div class="my-1 h-px bg-divider" />
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="menuRename"
|
||||
>
|
||||
<Pencil class="size-3.5 opacity-70" />重命名
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="menuDelete"
|
||||
>
|
||||
<Trash2 class="size-3.5 opacity-70" />
|
||||
删除{{ menuDeleteTargets.length > 1 ? ` (${menuDeleteTargets.length})` : '' }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 名称输入 -->
|
||||
<Dialog :open="promptOpen" @update:open="promptOpen = $event">
|
||||
<DialogContent class="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ promptTitle }}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Input
|
||||
v-model="promptValue"
|
||||
:placeholder="promptMode === 'rename' ? '新名称' : '名称'"
|
||||
@keydown.enter="confirmPrompt"
|
||||
/>
|
||||
<p v-if="promptTargetLabel" class="text-[11px] text-muted-foreground">{{ promptTargetLabel }}</p>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" :disabled="busy" @click="promptOpen = false">取消</Button>
|
||||
<Button :disabled="busy" @click="confirmPrompt">确定</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- 批量重命名 -->
|
||||
<Dialog :open="batchOpen" @update:open="batchOpen = $event">
|
||||
<DialogContent class="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>批量重命名({{ selectedEntries.length }} 项)</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div class="flex flex-col gap-2">
|
||||
<Input v-model="batchTemplate" placeholder="名称模板" />
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
占位符:<code class="font-mono">{name}</code> 原名 ·
|
||||
<code class="font-mono">{ext}</code> 扩展名 ·
|
||||
<code class="font-mono">{n}</code> 序号
|
||||
</p>
|
||||
<ScrollArea class="max-h-60 rounded-sm border border-border">
|
||||
<div class="divide-y divide-divider">
|
||||
<div
|
||||
v-for="item in batchPreview"
|
||||
:key="item.entry.path"
|
||||
class="flex items-center gap-2 px-2 py-1 text-xs"
|
||||
>
|
||||
<span class="min-w-0 flex-1 truncate text-fg-secondary">{{ item.entry.name }}</span>
|
||||
<span class="shrink-0 text-muted-foreground">→</span>
|
||||
<span class="min-w-0 flex-1 truncate text-foreground">{{ item.next || '(空)' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" :disabled="batchBusy" @click="batchOpen = false">取消</Button>
|
||||
<Button :disabled="batchBusy" @click="confirmBatch">重命名</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- 删除确认(走回收站) -->
|
||||
<ConfirmDialog
|
||||
v-model:open="confirmOpen"
|
||||
title="删除确认"
|
||||
variant="danger"
|
||||
confirm-text="移入回收站"
|
||||
:description="
|
||||
deleteTargets.length > 1
|
||||
? `将把选中的 ${deleteTargets.length} 项移入系统回收站(不是永久删除)。`
|
||||
: `将把「${deleteTargets[0]?.name}」移入系统回收站(不是永久删除)。`
|
||||
"
|
||||
@confirm="doDelete"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,73 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 编辑区右侧抽屉(P3-4):承载「大纲 / 双链」。
|
||||
*
|
||||
* 为什么把它们从侧栏挪出来:侧栏描述的是「去哪找文件」,而大纲与双链描述的是
|
||||
* **当前文档**。混在一起会让侧栏在「导航」与「文档信息」两种语义之间摇摆。
|
||||
*/
|
||||
import { Link2, ListTree, Share2, X } from '@lucide/vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { SegmentedNav } from '@/components/common'
|
||||
import MarkdownOutline from './MarkdownOutline.vue'
|
||||
import BacklinksPanel from './BacklinksPanel.vue'
|
||||
import LinkGraph from './LinkGraph.vue'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
|
||||
const props = defineProps<{
|
||||
mode: 'outline' | 'links' | 'graph'
|
||||
/** 编辑器当前光标行(大纲高亮用) */
|
||||
cursorLine: number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:mode': [mode: 'outline' | 'links' | 'graph']
|
||||
close: []
|
||||
jump: [from: number]
|
||||
open: [relPath: string]
|
||||
create: []
|
||||
}>()
|
||||
|
||||
const store = useEditorStore()
|
||||
|
||||
const NAV_ITEMS = [
|
||||
{ value: 'outline', label: '大纲', icon: ListTree },
|
||||
{ value: 'links', label: '双链', icon: Link2 },
|
||||
{ value: 'graph', label: '图谱', icon: Share2 }
|
||||
]
|
||||
|
||||
function setMode(mode: string): void {
|
||||
if (mode === 'links' || mode === 'graph') emit('update:mode', mode)
|
||||
else emit('update:mode', 'outline')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="flex h-full min-h-0 w-64 shrink-0 flex-col border-l border-border">
|
||||
<div class="flex h-11 shrink-0 items-center gap-1 border-b border-border px-2">
|
||||
<SegmentedNav
|
||||
:model-value="props.mode"
|
||||
:items="NAV_ITEMS"
|
||||
block
|
||||
@update:model-value="setMode"
|
||||
/>
|
||||
<Button variant="ghost" size="icon-sm" title="关闭抽屉" @click="emit('close')">
|
||||
<X class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<MarkdownOutline
|
||||
v-if="props.mode === 'outline'"
|
||||
class="min-h-0 flex-1"
|
||||
:cursor-line="props.cursorLine"
|
||||
@jump="emit('jump', $event)"
|
||||
/>
|
||||
<BacklinksPanel
|
||||
v-else-if="props.mode === 'links'"
|
||||
class="min-h-0 flex-1"
|
||||
:rel-path="store.currentRelPath"
|
||||
@open="emit('open', $event)"
|
||||
@create="emit('create')"
|
||||
/>
|
||||
<LinkGraph v-else class="min-h-0 flex-1" @open="emit('open', $event)" />
|
||||
</aside>
|
||||
</template>
|
||||
@@ -0,0 +1,437 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* CM6 编辑器宿主。
|
||||
*
|
||||
* 职责:装配 EditorView、把文档变更回写 store(含自动保存防抖)、
|
||||
* 按设置热重配置(主题/排版/行号/Live Preview 开关/语言)。
|
||||
*
|
||||
* # 编辑器实例为什么不是响应式的
|
||||
*
|
||||
* EditorView 存普通变量、不进 `ref`:把它放进 Vue 响应式系统会让整个 CM state 树
|
||||
* 被 Proxy 包一层,既慢又容易被误触发(CM6 的 state 是不可变对象,语义上就不该
|
||||
* 被 Vue 追踪)。
|
||||
*
|
||||
* # 「整篇替换」的判据是 docRevision,不是内容字符串
|
||||
*
|
||||
* 只比对内容会把用户自己的每一次输入也当成外部替换(光标被弹回行首);
|
||||
* 只比对路径又漏掉「同一篇被外部改动后重载」。因此用 store 里的自增
|
||||
* `docRevision`:只有在**整篇装载**(打开/重载)时才替换文档。
|
||||
*
|
||||
* # 语言是异步来的
|
||||
*
|
||||
* 语言包按需 `import()`(见 `editor/languages.ts`)。这里 watch 的是
|
||||
* `store.language`(一个 thunk),拿到后就地 `setLanguageExtension`;
|
||||
* 旧语言的过期结果由 store 里的令牌机制丢弃,这里不需要再判一次。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { EditorView } from '@codemirror/view'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import {
|
||||
createEditorState,
|
||||
jumpToPosition,
|
||||
reconfigureEditor,
|
||||
setLanguageExtension,
|
||||
type EditorConfig
|
||||
} from '../editor/core'
|
||||
import { editorBackground } from '../editor/themes'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { LanguageLoader } from '../editor/languages'
|
||||
import type { EditorState, Extension } from '@codemirror/state'
|
||||
|
||||
const logger = createLogger('editor')
|
||||
|
||||
const props = defineProps<{
|
||||
/**
|
||||
* 编辑器**窗口**当前是否深色(由 EditorWindow 按「跟随主应用主题 / 配色方案」推导)。
|
||||
* 用于:跟随应用时按它取深浅变体,配色方案为「跟随系统」时按它取 VS Code 深/浅。
|
||||
*/
|
||||
isDark: boolean
|
||||
/** 是否启用 Live Preview */
|
||||
livePreview: boolean
|
||||
/**
|
||||
* 绑定的标签 id(并排副面板用)。
|
||||
*
|
||||
* 缺省(主面板)= 绑定 store 的**扁平活动文档**;给出 id 时 = 绑定该标签**自己的缓冲**
|
||||
* (读 `tab.content`、写 `tab.content` 并置脏、保存走 `saveTab`)。副面板永远绑定非活动
|
||||
* 标签,因此不会与主面板争抢扁平 state。
|
||||
*/
|
||||
tabId?: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 光标移动(行号 1 起,列号 1 起) */
|
||||
'cursor-moved': [line: number, column: number]
|
||||
/** 点击了 `[[wikilink]]`(`target` 是去掉 `#` 与别名后的笔记名) */
|
||||
'wikilink': [target: string]
|
||||
}>()
|
||||
|
||||
const store = useEditorStore()
|
||||
const hostRef = ref<HTMLDivElement | null>(null)
|
||||
|
||||
/** 是否为「绑定某个标签」的副面板(否则为主面板,读扁平 state)。 */
|
||||
const isPane = computed(() => !!props.tabId)
|
||||
/** 副面板绑定的标签(主面板为 null)。 */
|
||||
const boundTab = computed(() =>
|
||||
props.tabId ? store.tabs.find(t => t.id === props.tabId) ?? null : null
|
||||
)
|
||||
|
||||
/** 需要读取的文档属性:主面板取扁平 state,副面板取标签缓冲。 */
|
||||
const paneContent = computed(() => (isPane.value ? boundTab.value?.content ?? '' : store.content))
|
||||
const paneLarge = computed(() =>
|
||||
isPane.value ? boundTab.value?.fileDoc?.large ?? false : store.fileDoc?.large ?? false
|
||||
)
|
||||
const paneKind = computed(() => (isPane.value ? boundTab.value?.kind ?? 'none' : store.kind))
|
||||
const paneRelPath = computed(() =>
|
||||
isPane.value ? boundTab.value?.relPath ?? '' : store.currentRelPath
|
||||
)
|
||||
const paneRevision = computed(() =>
|
||||
isPane.value ? boundTab.value?.docRevision ?? 0 : store.docRevision
|
||||
)
|
||||
const paneLanguage = computed<LanguageLoader>(() =>
|
||||
isPane.value ? boundTab.value?.language ?? (() => Promise.resolve(null)) : store.language
|
||||
)
|
||||
|
||||
/**
|
||||
* 编辑器外壳底色:跟随当前**实际生效**的主题。
|
||||
*
|
||||
* CM6 只会绘制 `.cm-editor` 覆盖到的区域,正文下方留白等仍由外壳容器显示;
|
||||
* 若外壳透明就会透出窗口的 mica 背景(表现为「编辑器背景是透明的」)。
|
||||
*/
|
||||
const hostBackground = computed(() =>
|
||||
editorBackground(String(store.settings.editorTheme), store.settings.followAppTheme, props.isDark)
|
||||
)
|
||||
|
||||
let view: EditorView | null = null
|
||||
let autosaveTimer: ReturnType<typeof setTimeout> | null = null
|
||||
/** 已应用的文档版本,避免重复整篇替换 */
|
||||
let appliedRevision = -1
|
||||
/** 语言令牌:丢弃过期的异步加载结果(与 store 里的令牌是两层保险) */
|
||||
let languageSeq = 0
|
||||
|
||||
/**
|
||||
* 每个标签自己的 EditorState(撤销历史随标签保留)。
|
||||
*
|
||||
* CM6 的撤销历史挂在 **EditorState 的字段**上,没有「只导出历史」的公开 API,因此
|
||||
* 「按标签保存撤销历史」就等于「按标签保存整个 state」:切换标签时把当前 state
|
||||
* 收进缓存、把目标标签的 state 装回同一个 `EditorView`。缓存只保留仍打开的标签
|
||||
* (见下方按标签集合的清理 watch),关闭标签即释放。
|
||||
*/
|
||||
const stateCache = new Map<string, EditorState>()
|
||||
/** 当前 view 装载的是哪个标签的 state(空串 = 未绑定)。 */
|
||||
let boundKey = ''
|
||||
|
||||
/** 当前面板的缓存键:主面板 = 活动标签,副面板 = 它绑定的标签。 */
|
||||
function paneKey(): string {
|
||||
if (isPane.value) return props.tabId ?? ''
|
||||
return store.activeTabId || ''
|
||||
}
|
||||
|
||||
function currentConfig(): EditorConfig {
|
||||
const s = store.settings
|
||||
const large = paneLarge.value
|
||||
const note = paneKind.value === 'note'
|
||||
return {
|
||||
livePreview: props.livePreview,
|
||||
showLineNumbers: s.showLineNumbers,
|
||||
tabSize: s.tabSize,
|
||||
fontFamily: s.fontFamily,
|
||||
fontSize: s.fontSize,
|
||||
lineHeight: s.lineHeight,
|
||||
ligatures: s.ligatures,
|
||||
theme: String(s.editorTheme),
|
||||
followAppTheme: s.followAppTheme,
|
||||
isDark: props.isDark,
|
||||
// 初始语言留空:语言由 applyLanguage 单独设置(见下方 watch),
|
||||
// 放在这里会让每次 reconfigure 都把语言重置一遍(异步加载的结果被抹掉)
|
||||
language: () => null,
|
||||
largeFile: large,
|
||||
autocomplete: s.autocomplete,
|
||||
wikilink: s.wikilink && note,
|
||||
onWikilink: target => emit('wikilink', target),
|
||||
// 图片预览只在库内笔记里有意义(库外文件没有库根上下文)
|
||||
currentRelPath: note ? paneRelPath.value : '',
|
||||
images: note
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造一个**全新的**编辑器状态(初次装配 / 无法复用缓存时)。
|
||||
*
|
||||
* # 为什么整篇装载必须换 state,而不是 dispatch 一次替换
|
||||
*
|
||||
* CM6 的撤销历史是 `history()` 里的状态字段,按**同一个 EditorState** 记录。
|
||||
* 若用 `dispatch({changes: 全文替换})` 装载另一个文件,新文档会继承上一份文档的
|
||||
* 撤销栈:随后的 Ctrl+Z 就会把别的文件的历史改动「回退」进当前标签页。
|
||||
* `EditorView.setState` 会连同历史字段一起换成新的状态(焦点保留)。
|
||||
*
|
||||
* 可复用的标签状态由 `stateCache` 提供(见上方);这里只负责「缓存不可用」的情形:
|
||||
* 首次打开、或该标签的内容已在别处被改过(并排副面板编辑 / 外部重载)。
|
||||
*/
|
||||
function buildState(doc: string): EditorState {
|
||||
return createEditorState({
|
||||
doc,
|
||||
config: currentConfig(),
|
||||
onDocChanged: next => {
|
||||
if (isPane.value && props.tabId) store.setTabContent(props.tabId, next)
|
||||
else store.setContent(next)
|
||||
scheduleAutosave()
|
||||
},
|
||||
// 副面板的光标不该覆盖状态栏(状态栏跟随活动文档)
|
||||
onSelectionChanged: (line, column) => {
|
||||
if (!isPane.value) emit('cursor-moved', line, column)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function scheduleAutosave(): void {
|
||||
const ms = store.settings.autosaveMs
|
||||
if (!ms) return
|
||||
if (autosaveTimer) clearTimeout(autosaveTimer)
|
||||
autosaveTimer = setTimeout(() => {
|
||||
autosaveTimer = null
|
||||
void persist().catch(() => undefined)
|
||||
}, ms)
|
||||
}
|
||||
|
||||
/** 落盘:主面板存活动文档,副面板存它绑定的标签。 */
|
||||
function persist(): Promise<void> {
|
||||
return isPane.value && props.tabId ? store.saveTab(props.tabId) : store.saveCurrent()
|
||||
}
|
||||
|
||||
function flushAutosave(): void {
|
||||
if (autosaveTimer) {
|
||||
clearTimeout(autosaveTimer)
|
||||
autosaveTimer = null
|
||||
}
|
||||
void persist().catch(() => undefined)
|
||||
}
|
||||
|
||||
/** 加载并应用当前文档的语言扩展。 */
|
||||
async function applyLanguage(seq: number): Promise<void> {
|
||||
if (!view) return
|
||||
let extension: Extension | null = null
|
||||
try {
|
||||
extension = await paneLanguage.value()
|
||||
} catch (e) {
|
||||
logger.warn(`语言扩展加载失败:${String(e)}`)
|
||||
}
|
||||
// 期间用户又切了文档 → 这次结果作废
|
||||
if (seq !== languageSeq || !view) return
|
||||
setLanguageExtension(view, extension)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (!hostRef.value) return
|
||||
view = new EditorView({
|
||||
parent: hostRef.value,
|
||||
state: buildState(paneContent.value)
|
||||
})
|
||||
boundKey = paneKey()
|
||||
if (boundKey) stateCache.set(boundKey, view.state)
|
||||
appliedRevision = paneRevision.value
|
||||
void applyLanguage(++languageSeq)
|
||||
})
|
||||
|
||||
/**
|
||||
* 整篇装载(切标签 / 打开笔记 / 打开文件 / 重载):换入目标文档的状态。
|
||||
*
|
||||
* 用 `docRevision` 而不是路径:重载同一篇时路径没变,但内容必须被换掉。
|
||||
*
|
||||
* 两条路:
|
||||
* - **切标签**(缓存键变了)且该标签的缓存内容与当前内容一致 → 装回缓存 state,
|
||||
* 撤销历史 / 选区随之保留;
|
||||
* - 否则(首次打开、同标签重载、内容已在别处被改过)→ 重建全新 state。
|
||||
*/
|
||||
watch(
|
||||
paneRevision,
|
||||
revision => {
|
||||
if (!view) return
|
||||
if (autosaveTimer) {
|
||||
clearTimeout(autosaveTimer)
|
||||
autosaveTimer = null
|
||||
}
|
||||
if (appliedRevision === revision) return
|
||||
appliedRevision = revision
|
||||
|
||||
const key = paneKey()
|
||||
const switching = key !== boundKey
|
||||
// 离开当前文档前把它的 state 收回缓存(撤销历史 + 选区都在里面)
|
||||
if (boundKey && switching) stateCache.set(boundKey, view.state)
|
||||
|
||||
// 只复用「换到另一个标签」且内容对得上的缓存。内容不一致说明该标签在别处
|
||||
// 被改过(并排副面板编辑 / 外部重载),旧 state 的文档与撤销历史都不能再用。
|
||||
const cached = switching && key ? stateCache.get(key) : undefined
|
||||
if (cached && cached.doc.toString() === paneContent.value) {
|
||||
view.setState(cached)
|
||||
boundKey = key
|
||||
// 缓存期间设置可能变过:主题 / 排版 / Live Preview / wikilink 重新配置。
|
||||
// 语言不进 reconfigure(见 currentConfig 的注释),由下面的 applyLanguage 负责。
|
||||
try {
|
||||
reconfigureEditor(view, currentConfig())
|
||||
} catch (e) {
|
||||
logger.error(`恢复标签状态后重配置失败:${String(e)}`)
|
||||
}
|
||||
void applyLanguage(++languageSeq)
|
||||
return
|
||||
}
|
||||
|
||||
// 目标光标行要在 setState **之前**取:新状态的 selection 变化会被
|
||||
// updateListener 回写成 1,之后再读就只剩第 1 行了。
|
||||
const restoreLine = isPane.value ? 1 : store.cursorLine
|
||||
// 重建状态而不是 dispatch 整篇替换:撤销历史必须随文档隔离(见 buildState)
|
||||
view.setState(buildState(paneContent.value))
|
||||
boundKey = key
|
||||
if (key) stateCache.set(key, view.state)
|
||||
// 标签切换 / 会话恢复:按 store.cursorLine 复位光标(默认第 1 行不动)
|
||||
if (restoreLine > 1) {
|
||||
const line = Math.min(restoreLine, view.state.doc.lines)
|
||||
const pos = view.state.doc.line(line).from
|
||||
view.dispatch({ selection: { anchor: pos }, scrollIntoView: false })
|
||||
}
|
||||
void applyLanguage(++languageSeq)
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* 标签集合变化时丢掉已关闭标签的状态。
|
||||
*
|
||||
* 每个缓存项持有一整份文档 + 撤销栈,不清理会随「开过多少文件」一直增长。
|
||||
* 副面板的缓存只有它自己绑定的那一个标签,同样随标签关闭失效。
|
||||
*/
|
||||
watch(
|
||||
() => store.tabs.map(t => t.id).join('\u0000'),
|
||||
() => {
|
||||
if (!stateCache.size) return
|
||||
const alive = new Set(store.tabs.map(t => t.id))
|
||||
for (const key of stateCache.keys()) {
|
||||
if (!alive.has(key)) stateCache.delete(key)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
/** 语言变化(异步加载完成 / 切换到另一种语言)。 */
|
||||
watch(paneLanguage, () => {
|
||||
void applyLanguage(++languageSeq)
|
||||
})
|
||||
|
||||
/**
|
||||
* 切换笔记:Live Preview 的图片预览按「相对当前笔记所在目录」解析目标,
|
||||
* 因此换一篇就要重建一次装饰(把新的 `currentRelPath` 交给它)。
|
||||
*
|
||||
* 只动 mode 与 wikilink 两个 compartment:语言由 `applyLanguage` 单独负责,
|
||||
* 在这里一并 reconfigure 会把刚异步加载好的语言重置掉。
|
||||
*/
|
||||
watch(paneRelPath, () => {
|
||||
if (!view) return
|
||||
try {
|
||||
reconfigureEditor(view, currentConfig())
|
||||
} catch (e) {
|
||||
logger.error(`切换笔记后重配置失败:${String(e)}`)
|
||||
}
|
||||
})
|
||||
|
||||
/** 设置 / 深浅 / 视图模式 / 文档类型变化:热重配置,不重建编辑器。 */
|
||||
watch(
|
||||
() => [store.settings, props.isDark, props.livePreview, paneLarge.value],
|
||||
() => {
|
||||
if (!view) return
|
||||
try {
|
||||
reconfigureEditor(view, currentConfig())
|
||||
} catch (e) {
|
||||
logger.error(`重配置编辑器失败:${String(e)}`)
|
||||
}
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
flushAutosave()
|
||||
view?.destroy()
|
||||
view = null
|
||||
stateCache.clear()
|
||||
boundKey = ''
|
||||
})
|
||||
|
||||
defineExpose({
|
||||
focus: () => view?.focus(),
|
||||
getView: () => view,
|
||||
/** 大纲点击跳转 */
|
||||
jumpTo: (position: number) => {
|
||||
if (view) jumpToPosition(view, position)
|
||||
},
|
||||
/**
|
||||
* 跳转到某行某列(统一搜索器的「在目录 / 库中查找」结果点击用)。
|
||||
*
|
||||
* 行号可能来自**稍早的**检索结果,用户在此期间可能已编辑 —— 越界一律夹到文档
|
||||
* 范围内(同 `jumpToPosition` 的取舍:跳到近似位置好过整块报错)。
|
||||
*/
|
||||
jumpToLine: (line: number, column = 1) => {
|
||||
if (!view) return
|
||||
const total = view.state.doc.lines
|
||||
const number = Math.max(1, Math.min(Math.floor(line), total))
|
||||
const info = view.state.doc.line(number)
|
||||
const anchor = Math.min(info.to, info.from + Math.max(0, column - 1))
|
||||
view.dispatch({ selection: { anchor }, scrollIntoView: true })
|
||||
view.focus()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
ref="hostRef"
|
||||
class="editor-host h-full min-h-0 overflow-hidden"
|
||||
:style="{ background: hostBackground }"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.editor-host :deep(.cm-editor) {
|
||||
height: 100%;
|
||||
/* 不写 background: transparent —— 让 CM6 主题自己的底色生效(见 themes.ts) */
|
||||
}
|
||||
.editor-host :deep(.cm-scroller) {
|
||||
padding: 12px 8px 32px;
|
||||
overflow: auto;
|
||||
/* 滚动条与项目 ScrollArea 一致:细轨 + 圆角 thumb(同终端 xterm 的做法) */
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--border) transparent;
|
||||
}
|
||||
.editor-host :deep(.cm-scroller)::-webkit-scrollbar {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
}
|
||||
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-thumb {
|
||||
background: var(--border);
|
||||
border: 3px solid transparent;
|
||||
border-radius: 9999px;
|
||||
background-clip: padding-box;
|
||||
}
|
||||
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--muted-foreground);
|
||||
background-clip: padding-box;
|
||||
}
|
||||
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-corner {
|
||||
background: transparent;
|
||||
}
|
||||
.editor-host :deep(.cm-editor.cm-focused) {
|
||||
outline: none;
|
||||
}
|
||||
/* 统一搜索器的命中高亮:改用应用语义色,而不是 @codemirror/search 自带的黄/橙
|
||||
—— 自带色在浅色主题下几乎看不见,也与应用观感割裂 */
|
||||
.editor-host :deep(.cm-searchMatch) {
|
||||
background: color-mix(in srgb, var(--primary) 26%, transparent);
|
||||
outline: none;
|
||||
border-radius: 2px;
|
||||
}
|
||||
.editor-host :deep(.cm-searchMatch.cm-searchMatch-selected) {
|
||||
background: color-mix(in srgb, var(--primary) 55%, transparent);
|
||||
}
|
||||
/* 笔记正文里正文与标题之间留些气口,Live Preview 下更接近阅读视图 */
|
||||
.editor-host :deep(.cm-content) {
|
||||
padding-bottom: 24vh;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,942 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 统一搜索器(Find / Replace,IDEA 风格浮动卡片)。
|
||||
*
|
||||
* # 为什么要把「编辑器自带查找」与「笔记库检索」合到这里
|
||||
*
|
||||
* 原来有两套搜索:CM6 自带面板(只能查当前文件)与侧栏 FTS5 索引检索(只能查笔记库,
|
||||
* 只有片段没有行号、不支持正则)。用户要在两者之间来回切换,且都不能「在当前目录里
|
||||
* 搜一段正则」。这里把三者收进**一个**输入区,用「范围」切换:
|
||||
*
|
||||
* ```text
|
||||
* 当前文件 → CM6 search API(实时高亮 + N/M + 替换)
|
||||
* 目录 → Rust 逐行 grep + 批量替换,结果落到**底部结果面板**
|
||||
* 笔记库 → 同一个 grep,检索根换成库根
|
||||
* ```
|
||||
*
|
||||
* # 为什么是横跨编辑列的条(而不是悬浮小卡片)
|
||||
*
|
||||
* 照 IDEA 的 Find 栏:横跨编辑区宽度、压在内容上方、不遮挡正文。窄卡片会把长目录路径
|
||||
* 与过滤条件挤成一行放不下,横条则能从容分行排布。
|
||||
*
|
||||
* # 结果为什么不在这里显示
|
||||
*
|
||||
* 结果列表搬到了编辑列底部的 `SearchResultsPanel`:卡片宽度有限(预览截断得厉害),
|
||||
* 而且卡片一关结果就没了 —— 但「先搜完、再逐条点开看」才是这个功能的真实用法。
|
||||
* 因此卡片只负责**发起检索**,结果 / 历史 / 面板开关都归 `editorSearchStore`。
|
||||
*
|
||||
* # 为什么两种范围的行为不同
|
||||
*
|
||||
* - 当前文件是**内存里的字符串**,边打字边搜没有成本 → 防抖 120ms 实时搜;
|
||||
* - 当前目录 / 笔记库是**磁盘扫描** → 只在回车 / 点搜索时执行一次,绝不边打字边扫盘。
|
||||
*
|
||||
* # 关键词从选中文本来
|
||||
*
|
||||
* `Ctrl+F` 打开时把**当前选中的文本**填进关键词(IDEA / VS Code 行为);跨行选区不算,
|
||||
* 见 `prefillFromSelection`。
|
||||
*
|
||||
* # 目录范围的替换是破坏性的
|
||||
*
|
||||
* 目录 / 笔记库的「全部替换」会**直接改写磁盘文件**:它走 Rust 的批量替换,而不是编辑器
|
||||
* 缓冲区。因此必须先过确认框,后端按每个文件的原编码写回,并把跳过的文件逐个回报
|
||||
* (见 `grep.rs::replace_in_path`)。
|
||||
*
|
||||
* # 检索条件(目录 / 库范围)
|
||||
*
|
||||
* - **检索只在回车 / 点搜索按钮时发起**:切范围、改目录、改过滤、点历史条目都**只改
|
||||
* 条件不搜**。磁盘扫描既慢又不知道什么时候来的结果,必须由一个明确动作触发;
|
||||
* - **目录**:可自由输入的输入框(默认侧栏打开的目录 / 当前文件所在目录),右侧图标
|
||||
* 打开系统选择器;
|
||||
* - **文件类型 / 跳过目录**(**仅目录范围**):各带一个开关与输入框(`|` 或 `,` 分隔)。
|
||||
* 跳过目录清单是后端**唯一**的跳过依据,所以清空它就会连 `node_modules` 一起搜 ——
|
||||
* 这是用户明确要求时才会做的事。笔记库范围不暴露这两个条件(见 `pathFilters`);
|
||||
* - 关键词 / 替换串 / 目录 / 类型 / 跳过目录都带**图标历史**(见 `SearchHistoryInput`):
|
||||
* 点输入框右侧的历史图标才展开,聚焦不打断输入。点历史只填值。这组历史是
|
||||
* 「刚输入过什么」,与结果面板里那份「检索记录」(按条件重跑)是两回事。
|
||||
*
|
||||
* # 编码
|
||||
*
|
||||
* 目录 / 库范围**不假设 UTF-8**:后端按每个文件自己的编码解码(预览即原文),替换也按
|
||||
* 原编码写回。编码装不下替换内容的文件会被跳过并列出,绝不做有损写入。
|
||||
*
|
||||
* # Esc 关闭
|
||||
*
|
||||
* `Esc` 由根节点统一接管(`@keydown.esc`):搜索栏里有七八个输入框与按钮,逐个挂
|
||||
* 处理器既啰嗦又容易漏 —— 而「Esc 关掉搜索栏」在哪个控件上按都该成立。事件从子控件
|
||||
* 冒泡到根节点即可覆盖全部。
|
||||
*
|
||||
* # 为什么高亮不用 v-html
|
||||
*
|
||||
* 结果预览来自用户文件正文,`v-html` 是自找的 XSS 面。Rust 回传的是命中下标,
|
||||
* 底部结果面板用 `pieces()` 切成「普通 / 命中」两段文本,永远走插值渲染。
|
||||
*/
|
||||
import { computed, nextTick, reactive, ref, watch } from 'vue'
|
||||
import {
|
||||
CaseSensitive,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
ChevronUp,
|
||||
FileType,
|
||||
FolderOpen,
|
||||
FolderX,
|
||||
Loader2,
|
||||
Regex,
|
||||
ReplaceAll,
|
||||
RotateCcw,
|
||||
Search,
|
||||
WholeWord,
|
||||
X
|
||||
} from '@lucide/vue'
|
||||
// 别名:`open` 与本组件的 `open` prop 同名,会和模板里的绑定撞名
|
||||
import { open as openDialog } from '@tauri-apps/plugin-dialog'
|
||||
import { EditorView } from '@codemirror/view'
|
||||
import {
|
||||
SearchQuery,
|
||||
replaceAll as cmReplaceAll,
|
||||
replaceNext as cmReplaceNext,
|
||||
setSearchQuery
|
||||
} from '@codemirror/search'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ConfirmDialog } from '@/components/common'
|
||||
import { editorClient } from '../editorClient'
|
||||
import SearchHistoryInput from './SearchHistoryInput.vue'
|
||||
import { useEditorSearchStore } from '@/stores/editorSearchStore'
|
||||
import type { PathReplaceResult } from '@/types/editor'
|
||||
|
||||
/** 搜索范围:当前文件 / 当前目录 / 笔记库 */
|
||||
export type SearchScope = 'file' | 'dir' | 'library'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 卡片是否可见 */
|
||||
open: boolean
|
||||
scope: SearchScope
|
||||
/** 「当前目录」的检索根(绝对路径;空串 = 无可用目录) */
|
||||
dirPath: string
|
||||
/** 笔记库根(绝对路径;空串 = 尚未设置库) */
|
||||
libraryPath: string
|
||||
/** 取当前 CM6 视图(未打开文档时为 null) */
|
||||
getView: () => EditorView | null
|
||||
/**
|
||||
* 当前活动文档的装载版本(`editorStore.docRevision`)。
|
||||
*
|
||||
* 切换标签 / 重载文档时它会自增,用来把「当前文件」范围的搜索**换成新标签**做:
|
||||
* 命中下标是旧文档的字符偏移,不重算就会算错计数、甚至在更短的新文档里越界。
|
||||
*/
|
||||
docRevision: number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
'update:scope': [value: SearchScope]
|
||||
/** 结果点击:打开文件并跳到某行某列 */
|
||||
'open-file': [payload: { path: string; line: number; column: number }]
|
||||
/** 目录 / 库的批量替换已完成(磁盘文件已被改写,调用方需要重载当前文档) */
|
||||
replaced: [result: PathReplaceResult]
|
||||
}>()
|
||||
|
||||
const isFile = computed(() => props.scope === 'file')
|
||||
|
||||
/**
|
||||
* 用户显式指定的检索目录(`null` = 用默认:侧栏打开的目录 / 当前文件所在目录)。
|
||||
*
|
||||
* 只存在组件内存里,不落设置:它是「这一次想在哪找」的临时意图,不该在下次开窗口时
|
||||
* 悄悄把范围指回某个旧目录。卡片关掉再打开会保留(组件不卸载),符合「刚选过」的预期。
|
||||
*/
|
||||
const customDir = ref<string | null>(null)
|
||||
|
||||
/**
|
||||
* 「目录」范围实际用的检索根:用户手填 / 选过的优先,否则用默认(侧栏打开的目录 /
|
||||
* 当前文件所在目录)。
|
||||
*
|
||||
* 用 `??` 而不是 `||` —— 用户把输入框清空是**有效状态**(会提示「请指定检索目录」),
|
||||
* 不该被当成「没填」而悄悄回落到默认值。
|
||||
*/
|
||||
const dirRoot = computed(() => customDir.value ?? props.dirPath)
|
||||
|
||||
/** 目录输入框的绑定:读时回落默认值,写时记成「用户指定的目录」。 */
|
||||
const dirValue = computed({
|
||||
get: () => dirRoot.value,
|
||||
set: value => {
|
||||
customDir.value = value
|
||||
}
|
||||
})
|
||||
|
||||
/** 检索根(目录 / 笔记库) */
|
||||
const activeDir = computed(() => (props.scope === 'dir' ? dirRoot.value : props.libraryPath))
|
||||
|
||||
// ===== 输入与选项 =====
|
||||
const pattern = ref('')
|
||||
const replaceText = ref('')
|
||||
const showReplace = ref(false)
|
||||
const caseSensitive = ref(false)
|
||||
const wholeWord = ref(false)
|
||||
const regex = ref(false)
|
||||
|
||||
/**
|
||||
* 文件类型默认值:`*.*` = 全部文件(Windows 习惯)。后端也把 `*` / `*.*` 当「全部」
|
||||
* 处理,否则无扩展名的 `Makefile` 会被默认值意外排除。
|
||||
*/
|
||||
const DEFAULT_FILE_TYPES = '*.*'
|
||||
|
||||
/**
|
||||
* 跳过目录名默认值。
|
||||
*
|
||||
* **必须与 Rust `grep.rs::DEFAULT_SKIP_DIRS` 一致** —— 这里是展示源(用户看到的初值),
|
||||
* 那边是字段缺省时的兜底。后端已不再无条件跳过点目录,清单是唯一依据。
|
||||
*/
|
||||
const DEFAULT_SKIP_DIRS =
|
||||
'debug|.vs|.git|.svn|.hg|.idea|.vscode|node_modules|target|dist|build|out|.cache|__pycache__|.venv|venv|vendor|.next|coverage|.tmp-build'
|
||||
|
||||
/** 文件类型过滤开关(关掉 = 不按类型过滤,等于全部文件) */
|
||||
const useFileTypes = ref(true)
|
||||
const fileTypes = ref(DEFAULT_FILE_TYPES)
|
||||
/** 跳过目录开关(关掉 = 不跳过任何目录,连 node_modules 一起搜) */
|
||||
const useSkipDirs = ref(true)
|
||||
const skipDirs = ref(DEFAULT_SKIP_DIRS)
|
||||
|
||||
// ===== 历史记录 =====
|
||||
//
|
||||
// 落 localStorage 而不是模块设置:这是搜索卡片自己的「用过什么」,跨窗口共享、重启后
|
||||
// 还在(与编辑器会话同一姿态),但不需要进 settings.json 受设置版本迁移管。
|
||||
|
||||
const HISTORY_KEY = 'thing_editor_search_history'
|
||||
/** 每组历史最多留多少条 */
|
||||
const HISTORY_MAX = 20
|
||||
|
||||
interface SearchHistory {
|
||||
pattern: string[]
|
||||
replace: string[]
|
||||
dir: string[]
|
||||
fileTypes: string[]
|
||||
skipDirs: string[]
|
||||
}
|
||||
|
||||
function emptyHistory(): SearchHistory {
|
||||
return { pattern: [], replace: [], dir: [], fileTypes: [], skipDirs: [] }
|
||||
}
|
||||
|
||||
function loadHistory(): SearchHistory {
|
||||
const base = emptyHistory()
|
||||
try {
|
||||
const raw = localStorage.getItem(HISTORY_KEY)
|
||||
if (!raw) return base
|
||||
const parsed = JSON.parse(raw) as Partial<SearchHistory>
|
||||
for (const key of Object.keys(base) as Array<keyof SearchHistory>) {
|
||||
const value = parsed[key]
|
||||
if (Array.isArray(value)) {
|
||||
base[key] = value.filter(v => typeof v === 'string' && v.trim()).slice(0, HISTORY_MAX)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* 坏数据一律当空历史,不影响搜索 */
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
const history = reactive<SearchHistory>(loadHistory())
|
||||
|
||||
function saveHistory(): void {
|
||||
try {
|
||||
localStorage.setItem(HISTORY_KEY, JSON.stringify(history))
|
||||
} catch {
|
||||
/* 忽略存储失败 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 记一条历史(去重 + 置顶 + 限量)。空串不记。 */
|
||||
function remember(key: keyof SearchHistory, value: string): void {
|
||||
const text = value.trim()
|
||||
if (!text) return
|
||||
history[key] = [text, ...history[key].filter(item => item !== text)].slice(0, HISTORY_MAX)
|
||||
saveHistory()
|
||||
}
|
||||
|
||||
function forget(key: keyof SearchHistory, value: string): void {
|
||||
history[key] = history[key].filter(item => item !== value)
|
||||
saveHistory()
|
||||
}
|
||||
|
||||
function clearHistory(key: keyof SearchHistory): void {
|
||||
history[key] = []
|
||||
saveHistory()
|
||||
}
|
||||
|
||||
// ===== 当前文件范围 =====
|
||||
const matchCount = ref(0)
|
||||
const currentMatch = ref(0)
|
||||
/** 命中的字符区间(用于上一个 / 下一个导航) */
|
||||
let fileMatches: Array<{ from: number; to: number }> = []
|
||||
|
||||
// ===== 目录 / 笔记库范围 =====
|
||||
//
|
||||
// 状态(结果 / 历史 / 底部面板)都在 `editorSearchStore` 里:结果面板与状态栏按钮也要
|
||||
// 读它,而这个卡片一关(`v-if`)本地 state 就没了 —— 面板却还得继续显示上次的结果。
|
||||
|
||||
const searchStore = useEditorSearchStore()
|
||||
const results = computed(() => searchStore.results)
|
||||
const searching = computed(() => searchStore.searching)
|
||||
|
||||
const patternRef = ref<InstanceType<typeof SearchHistoryInput> | null>(null)
|
||||
|
||||
const scopeHint = computed(() => {
|
||||
if (props.scope === 'file') return ''
|
||||
if (props.scope === 'library') return props.libraryPath || '尚未设置笔记库'
|
||||
return dirRoot.value || '请指定检索目录'
|
||||
})
|
||||
|
||||
/**
|
||||
* 当前选区里可作关键词的文本(空串 = 没有可用的单行选中)。
|
||||
*
|
||||
* 只取「非空且不跨行」的选区:跨行片段当关键词没有意义 —— 当前文件里换行只是字面量,
|
||||
* 磁盘 grep 又是逐行匹配的,拿一整段代码当搜索词只会得到 0 命中。
|
||||
*/
|
||||
function selectionKeyword(): string {
|
||||
const view = props.getView()
|
||||
if (!view) return ''
|
||||
const range = view.state.selection.main
|
||||
if (range.empty) return ''
|
||||
const text = view.state.sliceDoc(range.from, range.to)
|
||||
if (!text || text.includes('\n') || text.includes('\r')) return ''
|
||||
return text
|
||||
}
|
||||
|
||||
/**
|
||||
* Ctrl+F 打开时用**当前选中的文本**填关键词(IDEA / VS Code 的行为)。
|
||||
*
|
||||
* 没有可用的选中时沿用上一次的关键词,由调用方在输入框里全选,方便直接覆盖输入。
|
||||
*/
|
||||
function prefillFromSelection(): void {
|
||||
const text = selectionKeyword()
|
||||
if (!text) return
|
||||
pattern.value = text
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索栏**已经打开**时再次 Ctrl+F。
|
||||
*
|
||||
* - 有新选中文本、且与输入框内容不同 → 换进输入框并全选(便于直接覆盖输入);
|
||||
* - 没有可填充的新文本(未选中,或选中与当前关键词相同)→ 仅把焦点放回输入框。
|
||||
*
|
||||
* 两种情况下**都要聚焦**:Ctrl+F 的语义是「回到查找框」,不该因为选区恰好与关键词
|
||||
* 相同就毫无反应。
|
||||
*/
|
||||
function refillFromSelection(): void {
|
||||
const text = selectionKeyword()
|
||||
if (text && text !== pattern.value) {
|
||||
pattern.value = text
|
||||
void nextTick(() => patternRef.value?.focusAndSelect())
|
||||
return
|
||||
}
|
||||
void nextTick(() => patternRef.value?.focus())
|
||||
}
|
||||
|
||||
defineExpose({ refillFromSelection })
|
||||
|
||||
// ===== 当前文件:CM6 search API =====
|
||||
|
||||
function buildQuery(): SearchQuery {
|
||||
return new SearchQuery({
|
||||
search: pattern.value,
|
||||
caseSensitive: caseSensitive.value,
|
||||
regexp: regex.value,
|
||||
wholeWord: wholeWord.value,
|
||||
replace: replaceText.value
|
||||
})
|
||||
}
|
||||
|
||||
/** 清掉编辑器里的命中高亮(关闭卡片 / 清空关键词时)。 */
|
||||
function clearFileHighlights(): void {
|
||||
const view = props.getView()
|
||||
if (!view) return
|
||||
view.dispatch({ effects: setSearchQuery.of(new SearchQuery({ search: '' })) })
|
||||
matchCount.value = 0
|
||||
currentMatch.value = 0
|
||||
fileMatches = []
|
||||
}
|
||||
|
||||
/**
|
||||
* 选中第 index 处命中(0 起)并把该行**滚动到页面垂直居中**。
|
||||
*
|
||||
* 不用 `scrollIntoView: true`(CM6 默认的最小滚动):命中在视口下方时它只会把命中行
|
||||
* 顶到**最后一行**,上下没有余量,看不出前后文。显式 `y: 'center'` 让命中居中。
|
||||
*/
|
||||
function selectMatch(index: number): void {
|
||||
const view = props.getView()
|
||||
const range = fileMatches[index]
|
||||
if (!view || !range) return
|
||||
view.dispatch({
|
||||
selection: { anchor: range.from, head: range.to },
|
||||
effects: EditorView.scrollIntoView(range.from, { y: 'center' })
|
||||
})
|
||||
}
|
||||
|
||||
function runFileSearch(): void {
|
||||
const view = props.getView()
|
||||
if (!view) {
|
||||
clearFileHighlights()
|
||||
return
|
||||
}
|
||||
const query = buildQuery()
|
||||
if (!query.valid) {
|
||||
// 空关键词或非法正则:清掉高亮,但不弹错(用户还在输入过程中)
|
||||
view.dispatch({ effects: setSearchQuery.of(new SearchQuery({ search: '' })) })
|
||||
matchCount.value = 0
|
||||
currentMatch.value = 0
|
||||
fileMatches = []
|
||||
return
|
||||
}
|
||||
|
||||
// 先把查询写进编辑器状态(高亮随之渲染),再自行枚举命中做 N/M 与导航
|
||||
view.dispatch({ effects: setSearchQuery.of(query) })
|
||||
const collected: Array<{ from: number; to: number }> = []
|
||||
const cursor = query.getCursor(view.state)
|
||||
for (let step = cursor.next(); !step.done; step = cursor.next()) {
|
||||
collected.push(step.value)
|
||||
// 上限只是防止病态文档把枚举拖死;正常文档远达不到
|
||||
if (collected.length >= 20000) break
|
||||
}
|
||||
fileMatches = collected
|
||||
matchCount.value = collected.length
|
||||
if (!collected.length) {
|
||||
currentMatch.value = 0
|
||||
return
|
||||
}
|
||||
|
||||
// 落到「当前选区起点之后的第一处」,没有则回到第一处(同 IDEA 的落点规则)
|
||||
const from = view.state.selection.main.from
|
||||
let index = collected.findIndex(range => range.from >= from)
|
||||
if (index < 0) index = 0
|
||||
currentMatch.value = index + 1
|
||||
selectMatch(index)
|
||||
}
|
||||
|
||||
/** 上一个 / 下一个(循环)。 */
|
||||
function stepFile(delta: number): void {
|
||||
const total = matchCount.value
|
||||
if (!total) return
|
||||
let index = currentMatch.value - 1
|
||||
if (index < 0) index = delta > 0 ? -1 : 0
|
||||
index = (index + delta + total) % total
|
||||
currentMatch.value = index + 1
|
||||
selectMatch(index)
|
||||
}
|
||||
|
||||
/** 替换当前命中。 */
|
||||
function replaceCurrent(): void {
|
||||
const view = props.getView()
|
||||
if (!view || !pattern.value) return
|
||||
remember('replace', replaceText.value)
|
||||
view.dispatch({ effects: setSearchQuery.of(buildQuery()) })
|
||||
cmReplaceNext(view)
|
||||
runFileSearch()
|
||||
}
|
||||
|
||||
/** 全部替换。 */
|
||||
function replaceAll(): void {
|
||||
const view = props.getView()
|
||||
if (!view || !pattern.value) return
|
||||
remember('replace', replaceText.value)
|
||||
view.dispatch({ effects: setSearchQuery.of(buildQuery()) })
|
||||
cmReplaceAll(view)
|
||||
runFileSearch()
|
||||
}
|
||||
|
||||
// ===== 当前目录 / 笔记库:Rust 逐行 grep =====
|
||||
|
||||
/** 选一个目录作为「目录」范围的检索根。 */
|
||||
async function pickDir(): Promise<void> {
|
||||
const selected = await openDialog({ directory: true, multiple: false, title: '选择检索目录' })
|
||||
if (typeof selected !== 'string') return
|
||||
customDir.value = selected
|
||||
// 只改条件,不顺手搜一次:检索一律由「回车 / 点搜索按钮」发起(见 submit)
|
||||
}
|
||||
|
||||
/** 恢复默认检索根(侧栏打开的目录 / 当前文件所在目录)。 */
|
||||
function resetDir(): void {
|
||||
customDir.value = null
|
||||
}
|
||||
|
||||
/**
|
||||
* 目录范围共用的过滤选项。
|
||||
*
|
||||
* - 笔记库范围**不暴露**这两个条件:库是「找笔记」的场景,按类型 / 目录过滤只会添乱。
|
||||
* 类型送 `null`(不过滤),跳过目录送 `null` 让后端用它内置的默认清单兜底(避免
|
||||
* 走 `.git` / `node_modules`,那是安全网而不是用户配置项);
|
||||
* - 开关关掉时:类型送 `null`(不过滤),跳过目录送**空串**(明确「不跳过任何目录」)——
|
||||
* 送 `null` 会退回后端默认清单,正好是关掉开关的反效果。
|
||||
*/
|
||||
function pathFilters(): { fileTypes: string | null; skipDirs: string | null } {
|
||||
if (props.scope === 'library') return { fileTypes: null, skipDirs: null }
|
||||
return {
|
||||
fileTypes: useFileTypes.value ? fileTypes.value : null,
|
||||
skipDirs: useSkipDirs.value ? skipDirs.value : ''
|
||||
}
|
||||
}
|
||||
|
||||
/** 记下这次检索用到的条件(只在真正发起检索时记,边打字不写历史)。 */
|
||||
function rememberPathInputs(): void {
|
||||
remember('pattern', pattern.value)
|
||||
remember('dir', activeDir.value)
|
||||
// 只有目录范围才用到这两个条件
|
||||
if (props.scope !== 'dir') return
|
||||
if (useFileTypes.value) remember('fileTypes', fileTypes.value)
|
||||
if (useSkipDirs.value) remember('skipDirs', skipDirs.value)
|
||||
}
|
||||
|
||||
async function runPathSearch(): Promise<void> {
|
||||
const keyword = pattern.value.trim()
|
||||
if (!keyword || props.scope === 'file') return
|
||||
const dir = activeDir.value
|
||||
if (!dir) {
|
||||
searchStore.error = scopeHint.value
|
||||
searchStore.results = null
|
||||
return
|
||||
}
|
||||
await searchStore.runQuery({
|
||||
dir,
|
||||
pattern: pattern.value,
|
||||
caseSensitive: caseSensitive.value,
|
||||
wholeWord: wholeWord.value,
|
||||
regex: regex.value,
|
||||
// 后端已把命中总数统计完整;这里只要尽量多的预览(后端夹在 1..=5000),
|
||||
// 界面由结果面板分段渲染,不会一次挂出几千行
|
||||
limit: 5000,
|
||||
...pathFilters()
|
||||
})
|
||||
// 结果现在在底部面板里展示(`SearchResultsPanel`),此处只负责把条件记进输入框历史
|
||||
rememberPathInputs()
|
||||
}
|
||||
|
||||
/** 回车 / 点搜索:按当前范围分派。 */
|
||||
function submit(backwards = false): void {
|
||||
// 显式提交才算「搜过一次」:当前文件范围是边打字边搜的,不能每个字符都进历史
|
||||
remember('pattern', pattern.value)
|
||||
if (isFile.value) stepFile(backwards ? -1 : 1)
|
||||
else void runPathSearch()
|
||||
}
|
||||
|
||||
// ===== 当前目录 / 笔记库:批量替换(会改写磁盘) =====
|
||||
|
||||
const replacing = ref(false)
|
||||
const replaceConfirmOpen = ref(false)
|
||||
|
||||
/**
|
||||
* 确认框文案:把「会影响什么」说清楚 —— `ConfirmDialog` 的用途就在于此
|
||||
* (规范明确不用 `window.confirm`,正是因为它承载不了这句话)。
|
||||
*/
|
||||
const replaceConfirmText = computed(() => {
|
||||
const r = results.value
|
||||
const files = r?.files.length ?? 0
|
||||
const total = r?.total ?? 0
|
||||
const to = replaceText.value || '(空)'
|
||||
let text =
|
||||
`将在 ${files} 个文件中,把 ${total} 处「${pattern.value}」替换为「${to}」。` +
|
||||
'此操作直接改写磁盘文件,无法在编辑器里撤销。' +
|
||||
'每个文件按它自己的原编码写回;编码装不下替换内容的文件会跳过并在结果里列出。'
|
||||
if (r?.truncated) {
|
||||
text += `命中总数超出单次替换上限(5000 处),本次只替换前面一部分,完成后可再次执行。`
|
||||
}
|
||||
return text
|
||||
})
|
||||
|
||||
function askPathReplace(): void {
|
||||
if (!results.value?.total || !pattern.value.trim() || replacing.value) return
|
||||
replaceConfirmOpen.value = true
|
||||
}
|
||||
|
||||
/** 「全部替换」按钮的提示(写在这里而不是模板里,避免模板表达式的空值收窄问题)。 */
|
||||
const pathReplaceTitle = computed(() => {
|
||||
const r = results.value
|
||||
if (!r?.total) return '先检索出结果,再替换'
|
||||
return `在 ${r.totalFiles} 个文件中替换 ${r.total} 处(改写磁盘,会先确认)`
|
||||
})
|
||||
|
||||
async function runPathReplace(): Promise<void> {
|
||||
replaceConfirmOpen.value = false
|
||||
const dir = activeDir.value
|
||||
if (!dir) return
|
||||
replacing.value = true
|
||||
try {
|
||||
const result = await editorClient.replaceInPath({
|
||||
dir,
|
||||
pattern: pattern.value,
|
||||
replacement: replaceText.value,
|
||||
caseSensitive: caseSensitive.value,
|
||||
wholeWord: wholeWord.value,
|
||||
regex: regex.value,
|
||||
// 替换仍是「改写磁盘」的有界操作(后端停在文件边界),上限用满 5000
|
||||
limit: 5000,
|
||||
...pathFilters()
|
||||
})
|
||||
remember('replace', replaceText.value)
|
||||
rememberPathInputs()
|
||||
// 结果面板里的行号 / 预览已经全部过期 —— 按原条件重扫一次(顺带刷新记录里的命中数)
|
||||
await runPathSearch()
|
||||
emit('replaced', result)
|
||||
} catch (e) {
|
||||
searchStore.error = String(e)
|
||||
} finally {
|
||||
replacing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
emit('update:open', false)
|
||||
}
|
||||
|
||||
function setScope(scope: SearchScope): void {
|
||||
if (props.scope === scope) return
|
||||
emit('update:scope', scope)
|
||||
}
|
||||
|
||||
// ===== 联动 =====
|
||||
|
||||
let debounce: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
// 边打字边搜只对「当前文件」成立:目录 / 库是磁盘扫描,交给回车触发
|
||||
watch([pattern, caseSensitive, wholeWord, regex], () => {
|
||||
if (!props.open || !isFile.value) return
|
||||
if (debounce) clearTimeout(debounce)
|
||||
debounce = setTimeout(() => {
|
||||
debounce = null
|
||||
runFileSearch()
|
||||
}, 120)
|
||||
})
|
||||
|
||||
// 换范围:切到「当前文件」时立即重算高亮(内存里搜,没有成本)。
|
||||
// 切到目录 / 库**不**自动搜 —— 检索一律由回车 / 点搜索按钮发起(见 submit)
|
||||
watch(
|
||||
() => props.scope,
|
||||
scope => {
|
||||
if (debounce) clearTimeout(debounce)
|
||||
if (scope === 'file') runFileSearch()
|
||||
}
|
||||
)
|
||||
|
||||
// 说明:**不**在目录根变化时清空结果面板。
|
||||
//
|
||||
// 面板展示的是「某条检索记录的结果」,它自带完整条件(目录 / 关键词 / 过滤),是自洽的;
|
||||
// 用户在卡片里改目录或改关键词,都不该把已经搜出来的结果擦掉 —— 那会让「先搜完再慢慢看」
|
||||
// 这个主要用法失效。要换内容就再搜一次,结果会整体替换。
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
open => {
|
||||
if (!open) {
|
||||
clearFileHighlights()
|
||||
return
|
||||
}
|
||||
// 先看有没有选中文本要带进来,再决定关键词从哪儿来
|
||||
prefillFromSelection()
|
||||
void nextTick(() => patternRef.value?.focusAndSelect())
|
||||
// 打开卡片:当前文件范围立即重算高亮;目录 / 库不开搜(要搜得自己按回车)
|
||||
if (isFile.value) runFileSearch()
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* 切换标签 / 重载文档:当前文件范围的搜索跟着换到新文档重算一次。
|
||||
*
|
||||
* `fileMatches` / `matchCount` 是**旧文档的字符偏移**,不重算的话计数会停留在上一篇的
|
||||
* 数字,「上一个 / 下一个」还会拿旧偏移去 dispatch 选区 —— 新文档更短时越界报错,
|
||||
* 表现就是「切到新标签后搜索失灵」。
|
||||
*
|
||||
* 用 `flush: 'post'`:编辑器里文档的整篇替换由 `EditorHost` 的 pre watcher 完成,
|
||||
* post 回调保证跑在它**之后**,否则会拿还没换过的旧文档去搜。目录 / 笔记库范围不重算
|
||||
* —— 那是磁盘扫描,一律由回车 / 点搜索按钮发起。
|
||||
*/
|
||||
watch(
|
||||
() => props.docRevision,
|
||||
() => {
|
||||
if (!props.open || !isFile.value) return
|
||||
runFileSearch()
|
||||
},
|
||||
{ flush: 'post' }
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="flex w-full shrink-0 flex-col border-b-2 border-primary/60 bg-popover text-popover-foreground"
|
||||
@keydown.esc.prevent="close"
|
||||
>
|
||||
<!-- 第 1 行:关键词 + 计数 + 匹配选项 + 上一个 / 下一个 + 关闭 -->
|
||||
<div class="flex h-8 items-center gap-0.5 px-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="showReplace ? '收起替换' : '展开替换'"
|
||||
@click="showReplace = !showReplace"
|
||||
>
|
||||
<component :is="showReplace ? ChevronDown : ChevronRight" class="size-3.5" />
|
||||
</Button>
|
||||
|
||||
<SearchHistoryInput
|
||||
ref="patternRef"
|
||||
v-model="pattern"
|
||||
:history="history.pattern"
|
||||
:placeholder="
|
||||
scope === 'file' ? '在当前文件中查找…' : scope === 'dir' ? '在目录中查找…' : '在笔记库中查找…'
|
||||
"
|
||||
class="w-[420px] min-w-[140px]"
|
||||
input-class="h-6 text-xs"
|
||||
@submit="submit(false)"
|
||||
@submit-backwards="submit(true)"
|
||||
@remove-history="forget('pattern', $event)"
|
||||
@clear-history="clearHistory('pattern')"
|
||||
/>
|
||||
|
||||
<!-- 计数只在当前文件范围有意义(目录 / 库的结果数在底部结果面板) -->
|
||||
<span
|
||||
v-if="isFile"
|
||||
class="min-w-[52px] shrink-0 text-right text-[11px] tabular-nums text-muted-foreground"
|
||||
>
|
||||
{{ matchCount ? `${currentMatch}/${matchCount}` : '无结果' }}
|
||||
</span>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="caseSensitive ? '区分大小写:开' : '区分大小写:关'"
|
||||
:class="caseSensitive && 'bg-active text-foreground'"
|
||||
@click="caseSensitive = !caseSensitive"
|
||||
>
|
||||
<CaseSensitive class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="wholeWord ? '全词匹配:开' : '全词匹配:关'"
|
||||
:class="wholeWord && 'bg-active text-foreground'"
|
||||
@click="wholeWord = !wholeWord"
|
||||
>
|
||||
<WholeWord class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="regex ? '正则表达式:开' : '正则表达式:关'"
|
||||
:class="regex && 'bg-active text-foreground'"
|
||||
@click="regex = !regex"
|
||||
>
|
||||
<Regex class="size-3.5" />
|
||||
</Button>
|
||||
|
||||
<template v-if="isFile">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="上一个 (Shift+Enter)"
|
||||
:disabled="!matchCount"
|
||||
@click="stepFile(-1)"
|
||||
>
|
||||
<ChevronUp class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="下一个 (Enter)"
|
||||
:disabled="!matchCount"
|
||||
@click="stepFile(1)"
|
||||
>
|
||||
<ChevronDown class="size-3.5" />
|
||||
</Button>
|
||||
</template>
|
||||
<Button v-else variant="ghost" size="icon-sm" title="搜索 (Enter)" @click="submit(false)">
|
||||
<Loader2 v-if="searching" class="size-3.5 animate-spin" />
|
||||
<Search v-else class="size-3.5" />
|
||||
</Button>
|
||||
|
||||
<!-- 选项 / 导航按钮紧跟输入框左移,只有关闭按钮留在最右 -->
|
||||
<div class="flex-1" />
|
||||
|
||||
<Button variant="ghost" size="icon-sm" title="关闭 (Esc)" @click="close">
|
||||
<X class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 第 2 行:替换。当前文件走 CM6(改内存),目录 / 库走 Rust 批量替换(改写磁盘) -->
|
||||
<div v-if="showReplace" class="flex h-8 items-center gap-0.5 px-2">
|
||||
<!-- 空位 = 上一行那个 size-7(28px)的展开按钮,**行内间距也必须一样**(gap-0.5)
|
||||
才能让两个输入框的左边缘严格重合(`gap-1` 会多推出去 2px) -->
|
||||
<div class="w-7 shrink-0" />
|
||||
<SearchHistoryInput
|
||||
v-model="replaceText"
|
||||
:history="history.replace"
|
||||
placeholder="替换为…"
|
||||
class="w-[420px] min-w-[140px]"
|
||||
input-class="h-6 text-xs"
|
||||
@submit="isFile ? replaceCurrent() : askPathReplace()"
|
||||
@remove-history="forget('replace', $event)"
|
||||
@clear-history="clearHistory('replace')"
|
||||
/>
|
||||
<template v-if="isFile">
|
||||
<Button variant="outline" size="sm" :disabled="!matchCount" @click="replaceCurrent">
|
||||
替换
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :disabled="!matchCount" @click="replaceAll">
|
||||
全部替换
|
||||
</Button>
|
||||
</template>
|
||||
<Button
|
||||
v-else
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="!results?.total || replacing"
|
||||
:title="pathReplaceTitle"
|
||||
@click="askPathReplace"
|
||||
>
|
||||
<Loader2 v-if="replacing" class="size-3 animate-spin" />
|
||||
<ReplaceAll v-else class="size-3" />
|
||||
全部替换
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 第 3 行:范围 + 检索根 -->
|
||||
<div class="flex items-center gap-1 border-t border-border px-2 py-1">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm px-1.5 py-0.5 text-[11px] transition-colors duration-150"
|
||||
:class="
|
||||
scope === 'file'
|
||||
? 'bg-active text-foreground'
|
||||
: 'text-fg-secondary hover:bg-hover hover:text-foreground'
|
||||
"
|
||||
@click="setScope('file')"
|
||||
>
|
||||
当前文件
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm px-1.5 py-0.5 text-[11px] transition-colors duration-150"
|
||||
:class="
|
||||
scope === 'dir'
|
||||
? 'bg-active text-foreground'
|
||||
: 'text-fg-secondary hover:bg-hover hover:text-foreground'
|
||||
"
|
||||
title="在目录中查找(默认为侧栏打开的目录 / 当前文件所在目录,可手动输入或选择)"
|
||||
@click="setScope('dir')"
|
||||
>
|
||||
目录
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm px-1.5 py-0.5 text-[11px] transition-colors duration-150 disabled:pointer-events-none disabled:opacity-50"
|
||||
:class="
|
||||
scope === 'library'
|
||||
? 'bg-active text-foreground'
|
||||
: 'text-fg-secondary hover:bg-hover hover:text-foreground'
|
||||
"
|
||||
:disabled="!libraryPath"
|
||||
title="在笔记库根目录中查找"
|
||||
@click="setScope('library')"
|
||||
>
|
||||
笔记库
|
||||
</button>
|
||||
|
||||
<!-- 检索根:目录范围可自由输入,右侧图标打开系统选择器;库范围只读展示 -->
|
||||
<template v-if="scope === 'dir'">
|
||||
<SearchHistoryInput
|
||||
v-model="dirValue"
|
||||
:history="history.dir"
|
||||
placeholder="输入或选择检索目录…"
|
||||
input-class="h-6 font-mono text-[11px]"
|
||||
class="ml-1 min-w-0 flex-1"
|
||||
@submit="runPathSearch()"
|
||||
@remove-history="forget('dir', $event)"
|
||||
@clear-history="clearHistory('dir')"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="shrink-0"
|
||||
title="打开系统目录选择器"
|
||||
@click="pickDir"
|
||||
>
|
||||
<FolderOpen class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
v-if="customDir !== null"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="shrink-0"
|
||||
title="恢复默认目录(侧栏打开的目录 / 当前文件所在目录)"
|
||||
@click="resetDir"
|
||||
>
|
||||
<RotateCcw class="size-3.5" />
|
||||
</Button>
|
||||
</template>
|
||||
<span v-else-if="scopeHint" class="ml-2 min-w-0 flex-1 truncate text-[10px] text-fg-disabled" :title="scopeHint">
|
||||
{{ scopeHint }}
|
||||
</span>
|
||||
<span v-else-if="!isFile && !pattern.trim()" class="ml-2 text-[10px] text-fg-disabled">
|
||||
输入关键词后按回车检索
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- 第 4 行:过滤条件。**只有目录范围**需要 —— 笔记库是「找笔记」,过滤只会添乱 -->
|
||||
<div v-if="scope === 'dir'" class="flex items-center gap-4 border-t border-border px-2 py-1">
|
||||
<div class="flex w-72 shrink-0 items-center gap-1.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="shrink-0"
|
||||
:title="useFileTypes ? '按文件类型过滤:开' : '按文件类型过滤:关(搜全部文件)'"
|
||||
:class="useFileTypes && 'bg-active text-foreground'"
|
||||
@click="useFileTypes = !useFileTypes"
|
||||
>
|
||||
<FileType class="size-3.5" />
|
||||
</Button>
|
||||
<span class="shrink-0 text-xs text-foreground">文件类型</span>
|
||||
<SearchHistoryInput
|
||||
v-model="fileTypes"
|
||||
:history="history.fileTypes"
|
||||
:disabled="!useFileTypes"
|
||||
placeholder="*.*|*.ts|*.vue"
|
||||
input-class="h-6 font-mono text-[11px]"
|
||||
class="min-w-0 flex-1"
|
||||
@submit="runPathSearch()"
|
||||
@remove-history="forget('fileTypes', $event)"
|
||||
@clear-history="clearHistory('fileTypes')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="shrink-0"
|
||||
:title="useSkipDirs ? '按清单跳过目录:开' : '不跳过任何目录(含 node_modules 等)'"
|
||||
:class="useSkipDirs && 'bg-active text-foreground'"
|
||||
@click="useSkipDirs = !useSkipDirs"
|
||||
>
|
||||
<FolderX class="size-3.5" />
|
||||
</Button>
|
||||
<span class="shrink-0 text-xs text-foreground">跳过目录</span>
|
||||
<SearchHistoryInput
|
||||
v-model="skipDirs"
|
||||
:history="history.skipDirs"
|
||||
:disabled="!useSkipDirs"
|
||||
placeholder="node_modules|.git|dist"
|
||||
input-class="h-6 font-mono text-[11px]"
|
||||
class="min-w-0 flex-1"
|
||||
@submit="runPathSearch()"
|
||||
@remove-history="forget('skipDirs', $event)"
|
||||
@clear-history="clearHistory('skipDirs')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 目录 / 库替换的确认:这是会改写磁盘的不可逆操作,必须让用户看清影响面 -->
|
||||
<ConfirmDialog
|
||||
v-model:open="replaceConfirmOpen"
|
||||
variant="danger"
|
||||
title="在目录中替换"
|
||||
:description="replaceConfirmText"
|
||||
confirm-text="全部替换"
|
||||
:loading="replacing"
|
||||
@confirm="runPathReplace"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,420 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 编辑器窗口内的设置对话框。
|
||||
*
|
||||
* # 为什么把主界面的设置搬到这里
|
||||
*
|
||||
* 「库」与「编辑器」两页的设置本来只在主模块页可达 —— 用户把编辑器窗口拖到副屏、
|
||||
* 或在专注写作时,改个字号 / 换库都得先切回主界面。这里把这些**高频设置**就地暴露
|
||||
* 出来(导入导出 / WebDAV 这类重面板不搬)。
|
||||
*
|
||||
* # 改完即全局生效
|
||||
*
|
||||
* 读写都走当前窗口的 `editorStore`:`patchSettings` 落盘后 Rust 广播 `editor-settings`
|
||||
* 事件,主窗口与其它编辑器窗口据此重新读取设置;库根同理(`editor-library-changed`)。
|
||||
* 因此这里没有「保存」按钮,也不需要与主窗口做额外同步。
|
||||
*/
|
||||
import { ref } from 'vue'
|
||||
import { open as openDialog } from '@tauri-apps/plugin-dialog'
|
||||
import { openPath } from '@tauri-apps/plugin-opener'
|
||||
import {
|
||||
Copy,
|
||||
FolderOpen,
|
||||
Library,
|
||||
NotebookPen,
|
||||
Palette,
|
||||
RefreshCw,
|
||||
Settings,
|
||||
Tags
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { ConfirmDialog, SegmentedNav, SettingGroup, SettingRow } from '@/components/common'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import { EDITOR_THEME_OPTIONS } from '../editor/themes'
|
||||
import type { EditorSettings } from '@/types/editor'
|
||||
|
||||
defineProps<{ open: boolean }>()
|
||||
const emit = defineEmits<{ 'update:open': [value: boolean] }>()
|
||||
|
||||
const store = useEditorStore()
|
||||
|
||||
/** 当前分区(默认「编辑器设置」—— 在编辑器窗口里调整外观 / 行为是最常见的诉求) */
|
||||
const section = ref<'library' | 'editor'>('editor')
|
||||
const sections = [
|
||||
{ value: 'library', label: '库设置', icon: Library },
|
||||
{ value: 'editor', label: '编辑器设置', icon: Palette }
|
||||
]
|
||||
|
||||
// ===== 设置写入(即时生效) =====
|
||||
function commit(patch: Partial<EditorSettings>): void {
|
||||
void store.patchSettings(patch)
|
||||
}
|
||||
|
||||
function onNumber(
|
||||
patchKey: 'fontSize' | 'lineHeight' | 'tabSize' | 'autosaveMs' | 'maxFileSizeMb',
|
||||
event: Event
|
||||
): void {
|
||||
const value = Number((event.target as HTMLInputElement).value)
|
||||
if (!Number.isFinite(value)) return
|
||||
commit({ [patchKey]: value } as Partial<EditorSettings>)
|
||||
}
|
||||
|
||||
// ===== 库根 =====
|
||||
const resetRootOpen = ref(false)
|
||||
|
||||
async function pickLibraryRoot(): Promise<void> {
|
||||
try {
|
||||
const selected = await openDialog({ directory: true, multiple: false, title: '选择笔记库目录' })
|
||||
if (typeof selected !== 'string') return
|
||||
await store.setLibraryRoot(selected)
|
||||
toast.success('已切换笔记库')
|
||||
} catch (e) {
|
||||
toast.error(`切换失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function resetLibraryRoot(): Promise<void> {
|
||||
try {
|
||||
await store.setLibraryRoot(null)
|
||||
toast.success('已恢复默认库目录')
|
||||
} catch (e) {
|
||||
toast.error(`恢复失败:${String(e)}`)
|
||||
} finally {
|
||||
resetRootOpen.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function revealRoot(): Promise<void> {
|
||||
if (!store.libraryRoot) return
|
||||
try {
|
||||
await openPath(store.libraryRoot)
|
||||
} catch (e) {
|
||||
toast.error(`打开目录失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function copyRoot(): Promise<void> {
|
||||
if (!store.libraryRoot) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(store.libraryRoot)
|
||||
toast.success('库路径已复制')
|
||||
} catch {
|
||||
toast.error('复制失败')
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 索引 =====
|
||||
const rebuilding = ref(false)
|
||||
|
||||
async function rebuildIndex(): Promise<void> {
|
||||
rebuilding.value = true
|
||||
try {
|
||||
await store.rebuildIndex()
|
||||
await store.refreshLibrary()
|
||||
toast.success('索引已重建')
|
||||
} catch (e) {
|
||||
toast.error(`重建索引失败:${String(e)}`)
|
||||
} finally {
|
||||
rebuilding.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="open" @update:open="emit('update:open', $event)">
|
||||
<DialogContent class="max-h-[85vh] sm:max-w-2xl">
|
||||
<DialogHeader class="shrink-0">
|
||||
<DialogTitle class="flex items-center gap-2 text-base">
|
||||
<Settings class="size-4 text-primary" />
|
||||
设置
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<SegmentedNav v-model="section" :items="sections" block class="shrink-0" />
|
||||
|
||||
<ScrollArea class="max-h-[60vh] pr-3">
|
||||
<!-- ===== 库设置 ===== -->
|
||||
<div v-if="section === 'library'" class="flex flex-col gap-4 pb-1">
|
||||
<SettingGroup
|
||||
title="笔记库"
|
||||
description="笔记以 Markdown 文件形式保存在该目录;切换库只改变指向,原目录内容不会被移动"
|
||||
>
|
||||
<SettingRow label="库目录" :description="store.libraryRoot || '—'">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" :disabled="!store.libraryRoot" @click="copyRoot">
|
||||
<Copy class="size-3.5" />复制
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :disabled="!store.libraryRoot" @click="revealRoot">
|
||||
<FolderOpen class="size-3.5" />浏览
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" @click="pickLibraryRoot">
|
||||
<NotebookPen class="size-3.5" />切换…
|
||||
</Button>
|
||||
<Button
|
||||
v-if="store.info?.isCustom"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="text-muted-foreground"
|
||||
@click="resetRootOpen = true"
|
||||
>
|
||||
恢复默认
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="重新扫描" description="在应用外新增或修改文件后,手动刷新库内容">
|
||||
<Button variant="outline" size="sm" @click="store.refreshLibrary()">
|
||||
<RefreshCw class="size-3.5" />刷新
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</SettingGroup>
|
||||
|
||||
<SettingGroup
|
||||
title="索引与检索"
|
||||
description="全文检索与标签依赖库内的 SQLite 索引;删掉也能从 Markdown 文件完整重建"
|
||||
>
|
||||
<SettingRow label="索引状态" :description="store.indexStats?.dbPath || '尚未建立索引'">
|
||||
<div class="flex items-center gap-3 text-[13px] text-fg-secondary">
|
||||
<span class="tabular-nums">笔记 {{ store.indexStats?.noteCount ?? 0 }}</span>
|
||||
<span class="tabular-nums">文件 {{ store.indexStats?.fileCount ?? 0 }}</span>
|
||||
<span class="flex items-center gap-1 tabular-nums">
|
||||
<Tags class="size-3.5" />{{ store.indexStats?.tagCount ?? 0 }}
|
||||
</span>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="重建索引"
|
||||
description="按文件重新解析标题、标签与双链(库很大时需要一点时间)"
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="rebuilding || store.indexing"
|
||||
@click="rebuildIndex"
|
||||
>
|
||||
<RefreshCw class="size-3.5" :class="rebuilding && 'animate-spin'" />重建
|
||||
</Button>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="单文件大小上限"
|
||||
description="超过该大小的文件会关闭所见即所得 / 折叠 / 补全,单位 MB"
|
||||
control-width="wide"
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
:model-value="store.settings.maxFileSizeMb"
|
||||
@change="onNumber('maxFileSizeMb', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
</SettingGroup>
|
||||
</div>
|
||||
|
||||
<!-- ===== 编辑器设置 ===== -->
|
||||
<div v-else class="flex flex-col gap-4 pb-1">
|
||||
<SettingGroup title="编辑器外观">
|
||||
<SettingRow
|
||||
label="配色方案"
|
||||
description="「跟随主应用主题」关闭时,窗口按本方案取色与深浅"
|
||||
control-width="wide"
|
||||
>
|
||||
<Select
|
||||
:model-value="String(store.settings.editorTheme)"
|
||||
@update:model-value="v => commit({ editorTheme: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in EDITOR_THEME_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="跟随主应用主题" description="打开时编辑器窗口整体跟随主应用主题;关闭时由上方「配色方案」决定,窗口内外深浅一致">
|
||||
<Switch
|
||||
:model-value="store.settings.followAppTheme"
|
||||
@update:model-value="v => commit({ followAppTheme: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字体族" description="留空使用内置等宽字体栈" control-width="wide">
|
||||
<Input
|
||||
:model-value="store.settings.fontFamily"
|
||||
placeholder="Cascadia Code, Consolas, …"
|
||||
@change="(e: Event) => commit({ fontFamily: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字号" description="单位 px" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
min="10"
|
||||
max="32"
|
||||
:model-value="store.settings.fontSize"
|
||||
@change="onNumber('fontSize', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="行高" description="倍数,建议 1.5 ~ 2.0" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
step="0.1"
|
||||
min="1"
|
||||
max="3"
|
||||
:model-value="store.settings.lineHeight"
|
||||
@change="onNumber('lineHeight', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字体连字" description="启用 ligatures(如 => 显示为箭头)">
|
||||
<Switch
|
||||
:model-value="store.settings.ligatures"
|
||||
@update:model-value="v => commit({ ligatures: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="显示行号">
|
||||
<Switch
|
||||
:model-value="store.settings.showLineNumbers"
|
||||
@update:model-value="v => commit({ showLineNumbers: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="显示大纲"
|
||||
description="在编辑区右侧抽屉显示标题树(Ctrl+Shift+O 可临时切换)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.showOutline"
|
||||
@update:model-value="v => commit({ showOutline: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</SettingGroup>
|
||||
|
||||
<SettingGroup title="编辑器行为">
|
||||
<SettingRow
|
||||
label="所见即所得"
|
||||
description="Live Preview:语法符号在非光标行隐藏、光标行显形;关闭后为纯源码 + 高亮"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.livePreview"
|
||||
@update:model-value="v => commit({ livePreview: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="默认视图" description="新开编辑器窗口时的初始视图" control-width="wide">
|
||||
<Select
|
||||
:model-value="String(store.settings.defaultView)"
|
||||
@update:model-value="v => commit({ defaultView: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="wysiwyg">所见即所得</SelectItem>
|
||||
<SelectItem value="source">源码</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="自动保存"
|
||||
description="停止输入后延迟保存,单位毫秒;0 = 关闭(仅 Ctrl+S)"
|
||||
control-width="wide"
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
max="10000"
|
||||
step="100"
|
||||
:model-value="store.settings.autosaveMs"
|
||||
@change="onNumber('autosaveMs', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="Tab 宽度" description="按空格数计" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="8"
|
||||
:model-value="store.settings.tabSize"
|
||||
@change="onNumber('tabSize', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="自动补全" description="括号自动闭合与代码补全(大文件会临时关闭)">
|
||||
<Switch
|
||||
:model-value="store.settings.autocomplete"
|
||||
@update:model-value="v => commit({ autocomplete: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="识别 [[双链]]"
|
||||
description="按 Obsidian 语义解析双链并写入索引(反链面板留待后续)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.wikilink"
|
||||
@update:model-value="v => commit({ wikilink: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="复用文档窗口"
|
||||
description="同一篇笔记重复打开时聚焦已有窗口,而不是开出第二个"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.reuseWindow"
|
||||
@update:model-value="v => commit({ reuseWindow: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="导出时高亮代码"
|
||||
description="关闭后导出的 HTML 里代码块是纯黑白,适合黑白打印机"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.exportHighlight"
|
||||
@update:model-value="v => commit({ exportHighlight: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="新建时选模板" description="关闭后用上次选中的模板直接新建">
|
||||
<Switch
|
||||
:model-value="store.settings.showTemplatePicker"
|
||||
@update:model-value="v => commit({ showTemplatePicker: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</SettingGroup>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="resetRootOpen"
|
||||
title="恢复默认库目录"
|
||||
description="笔记不会丢失:仅把库根指回应用数据目录下的默认位置,原目录内容保持不动。"
|
||||
confirm-text="恢复默认"
|
||||
@confirm="resetLibraryRoot"
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,607 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 文档标签栏(P4-5)。
|
||||
*
|
||||
* 一个编辑器窗口内可同时打开多篇文档,每个标签**独立**保存内容、编码 / 换行、
|
||||
* 视图模式与未保存状态。标签的「脏」指示点用 store 的 `tabViews`:活动标签取
|
||||
* 实时值(正在敲字),后台标签取切换时收回的快照。
|
||||
*
|
||||
* # Markdown 标签多一个「预览」按钮
|
||||
*
|
||||
* 预览状态同样**按标签独立**(`previewIds` 由父组件 `EditorWindow` 持有并渲染面板):
|
||||
* 一个标签在预览渲染结果时,切到别的标签仍是正常的编辑器 —— 这与「视图模式按标签存」
|
||||
* 的模型一致(见 `DocumentTab.viewMode`)。按钮只对 `tab.markdown` 出现:非 Markdown
|
||||
* 文档(代码 / 配置 / 纯文本)没有可渲染的语义。
|
||||
*
|
||||
* # 右键菜单
|
||||
*
|
||||
* - **关闭类**(当前 / 其他 / 左 / 右 / 全部)涉及脏数据确认,统一 `emit` 给
|
||||
* `EditorWindow` 走既有确认流程;「关闭未修改」无脏数据风险,就地调用 store。
|
||||
* - **位置 / 窗口类**(所在文件夹 / 资源管理器 / 新窗口 / 移动新窗口)只读 store 与系统;
|
||||
* 其中「移动到新窗口」先落盘再开新窗口、最后关掉本标签。
|
||||
* - **视图类**(并排分屏 / 固定)分别 `emit('split')` 与写 store。
|
||||
* - **文件类**(重命名 / 复制名字 / 路径 / 相对路径)。
|
||||
*
|
||||
* # 拖拽重排与溢出下拉
|
||||
*
|
||||
* 标签支持 HTML5 拖拽重排(`store.moveTab`)。标签溢出横向滚动时,右侧出现下拉按钮,
|
||||
* 汇总列出所有标签以便快速跳转 —— 否则藏在滚动区外的标签很难被发现。
|
||||
*/
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import {
|
||||
AppWindow,
|
||||
ChevronDown,
|
||||
ClipboardCopy,
|
||||
Columns2,
|
||||
Copy,
|
||||
ExternalLink,
|
||||
Eye,
|
||||
FileCode2,
|
||||
FileText,
|
||||
FileX,
|
||||
FolderOpen,
|
||||
Pencil,
|
||||
Pin,
|
||||
PinOff,
|
||||
X
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import { openEditorWindow } from '../openWindow'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 正处于预览状态的标签 id(每个标签独立) */
|
||||
previewIds: string[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [id: string]
|
||||
/** 切换某个标签的预览状态 */
|
||||
'toggle-preview': [id: string]
|
||||
'close-others': [id: string]
|
||||
'close-left': [id: string]
|
||||
'close-right': [id: string]
|
||||
'close-all': []
|
||||
/** 把某个标签放到副面板与当前文档并排 */
|
||||
split: [id: string]
|
||||
}>()
|
||||
|
||||
const store = useEditorStore()
|
||||
|
||||
const isPreviewing = (id: string) => props.previewIds.includes(id)
|
||||
|
||||
// ===== 标签的目标解析 =====
|
||||
|
||||
type Tab = (typeof store.tabs)[number]
|
||||
|
||||
function tabOf(id: string): Tab | undefined {
|
||||
return store.tabs.find(t => t.id === id)
|
||||
}
|
||||
|
||||
/** 标签对应文件的**真实文件名**(含扩展名;重命名对话框的初值)。 */
|
||||
function tabFileName(id: string): string {
|
||||
const tab = tabOf(id)
|
||||
if (!tab) return ''
|
||||
const source = tab.kind === 'note' ? tab.relPath : tab.path
|
||||
return source.split(/[\\/]/).filter(Boolean).pop() ?? tab.name
|
||||
}
|
||||
|
||||
/** 标签对应文件的**绝对路径**(复制 / 定位 / 打开所在文件夹用)。 */
|
||||
function tabAbsPath(id: string): string {
|
||||
const tab = tabOf(id)
|
||||
if (!tab) return ''
|
||||
if (tab.kind === 'note') return store.noteAbsPath(tab.relPath)
|
||||
// 活动文件的真值在扁平 state 上,后台标签取收回的快照
|
||||
return id === store.activeTabId ? (store.fileDoc?.path ?? tab.path) : tab.path
|
||||
}
|
||||
|
||||
/** 标签对应文件的**相对路径**(仅库内笔记有意义)。 */
|
||||
function tabRelPath(id: string): string {
|
||||
const tab = tabOf(id)
|
||||
return tab && tab.kind === 'note' ? tab.relPath : ''
|
||||
}
|
||||
|
||||
// ===== 拖拽重排(Pointer Events)=====
|
||||
//
|
||||
// **为什么不用 HTML5 拖放**:编辑器窗口为了接收 OS 文件拖入而设了 `dragDropEnabled: true`
|
||||
// (见 openWindow.ts),WebView2 的原生 OLE drop target 会拦截窗口内所有 HTML5 DnD ——
|
||||
// `dragover` 的 `preventDefault()` 不生效,拖动时显示「禁止」光标。Pointer Events 不走
|
||||
// 那条管线,与 Tauri 原生拖放零冲突(同侧栏宽度拖拽、结果面板高度拖拽的范式)。
|
||||
|
||||
const dragId = ref('')
|
||||
const dragOverId = ref('')
|
||||
/** 指针采集元素(releasePointerCapture 用) */
|
||||
let dragEl: HTMLElement | null = null
|
||||
/** 本次拖拽是否真的发生了重排:抑制紧随其后的 click,避免误激活 */
|
||||
let reordered = false
|
||||
|
||||
function onTabPointerDown(id: string, event: PointerEvent): void {
|
||||
if (event.button !== 0) return
|
||||
// 点在预览 / 关闭按钮上时不启动拖拽(否则会与按钮的 click 抢指针)
|
||||
if ((event.target as HTMLElement).closest('button')) return
|
||||
dragEl = event.currentTarget as HTMLElement
|
||||
dragId.value = id
|
||||
dragOverId.value = ''
|
||||
reordered = false
|
||||
dragEl.setPointerCapture(event.pointerId)
|
||||
window.addEventListener('pointermove', onTabPointerMove)
|
||||
window.addEventListener('pointerup', onTabPointerUp)
|
||||
window.addEventListener('pointercancel', onTabPointerUp)
|
||||
}
|
||||
|
||||
function onTabPointerMove(event: PointerEvent): void {
|
||||
if (!dragId.value) return
|
||||
const over = (document.elementFromPoint(event.clientX, event.clientY) as HTMLElement | null)
|
||||
?.closest<HTMLElement>('[data-tab-id]')
|
||||
const overId = over?.dataset.tabId ?? ''
|
||||
dragOverId.value = overId && overId !== dragId.value ? overId : ''
|
||||
}
|
||||
|
||||
function onTabPointerUp(event: PointerEvent): void {
|
||||
window.removeEventListener('pointermove', onTabPointerMove)
|
||||
window.removeEventListener('pointerup', onTabPointerUp)
|
||||
window.removeEventListener('pointercancel', onTabPointerUp)
|
||||
try {
|
||||
dragEl?.releasePointerCapture(event.pointerId)
|
||||
} catch {
|
||||
/* 指针已释放,忽略 */
|
||||
}
|
||||
dragEl = null
|
||||
const from = dragId.value
|
||||
const over = dragOverId.value
|
||||
dragId.value = ''
|
||||
dragOverId.value = ''
|
||||
if (!from || !over || from === over) return
|
||||
const to = store.tabs.findIndex(t => t.id === over)
|
||||
if (to < 0) return
|
||||
store.moveTab(from, to)
|
||||
reordered = true
|
||||
// click 在 pointerup 之后同批次派发;等它走完再复位
|
||||
window.setTimeout(() => {
|
||||
reordered = false
|
||||
}, 0)
|
||||
}
|
||||
|
||||
/** 标签点击:拖拽刚结束的那一下不再激活(否则拖完会顺带跳一下)。 */
|
||||
function onTabClick(id: string): void {
|
||||
if (reordered) return
|
||||
store.activateTab(id)
|
||||
}
|
||||
|
||||
// ===== 溢出下拉 =====
|
||||
|
||||
const stripRef = ref<HTMLElement | null>(null)
|
||||
const overflowing = ref(false)
|
||||
const overflowOpen = ref(false)
|
||||
let resizeObserver: ResizeObserver | null = null
|
||||
|
||||
function updateOverflow(): void {
|
||||
const el = stripRef.value
|
||||
overflowing.value = !!el && el.scrollWidth > el.clientWidth + 1
|
||||
if (!overflowing.value) overflowOpen.value = false
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (stripRef.value) {
|
||||
resizeObserver = new ResizeObserver(updateOverflow)
|
||||
resizeObserver.observe(stripRef.value)
|
||||
}
|
||||
window.addEventListener('resize', updateOverflow)
|
||||
void nextTick(updateOverflow)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
resizeObserver?.disconnect()
|
||||
resizeObserver = null
|
||||
window.removeEventListener('resize', updateOverflow)
|
||||
window.removeEventListener('pointermove', onTabPointerMove)
|
||||
window.removeEventListener('pointerup', onTabPointerUp)
|
||||
window.removeEventListener('pointercancel', onTabPointerUp)
|
||||
})
|
||||
|
||||
// 标签数量 / 名称变化都可能改变宽度
|
||||
watch(
|
||||
() => store.tabViews.map(t => `${t.id}:${t.name}:${t.dirty}:${t.pinned}`).join('|'),
|
||||
() => void nextTick(updateOverflow)
|
||||
)
|
||||
|
||||
/** 从下拉列表切换标签:激活并把该标签滚进可视区。 */
|
||||
function pickTab(id: string): void {
|
||||
overflowOpen.value = false
|
||||
store.activateTab(id)
|
||||
void nextTick(() => {
|
||||
stripRef.value?.querySelector(`[data-tab-id="${id}"]`)?.scrollIntoView({ inline: 'nearest', block: 'nearest' })
|
||||
})
|
||||
}
|
||||
|
||||
// ===== 右键菜单 =====
|
||||
|
||||
const menuOpen = ref(false)
|
||||
const menuX = ref(0)
|
||||
const menuY = ref(0)
|
||||
/** 右键作用的标签 id(关闭菜单后仍保留,供重命名对话框使用) */
|
||||
const menuTabId = ref('')
|
||||
|
||||
const MENU_WIDTH = 216
|
||||
/** 菜单项行数(用于贴边翻转时预估高度:16 项 + 3 条分隔线) */
|
||||
const MENU_HEIGHT = 16 * 28 + 3 * 9 + 16
|
||||
|
||||
const menuIndex = computed(() => store.tabs.findIndex(t => t.id === menuTabId.value))
|
||||
const menuTab = computed(() => tabOf(menuTabId.value))
|
||||
const hasLeft = computed(() => menuIndex.value > 0)
|
||||
const hasRight = computed(() => menuIndex.value >= 0 && menuIndex.value < store.tabs.length - 1)
|
||||
const hasOthers = computed(() => store.tabs.length > 1)
|
||||
const hasUnmodified = computed(() =>
|
||||
store.tabs.some(t => !t.pinned && !(t.id === store.activeTabId ? store.dirty : t.dirty))
|
||||
)
|
||||
|
||||
function openMenu(event: MouseEvent, id: string): void {
|
||||
menuTabId.value = id
|
||||
menuX.value = Math.max(8, Math.min(event.clientX, window.innerWidth - MENU_WIDTH - 8))
|
||||
menuY.value = Math.max(8, Math.min(event.clientY, window.innerHeight - MENU_HEIGHT - 8))
|
||||
menuOpen.value = true
|
||||
}
|
||||
|
||||
function closeMenu(): void {
|
||||
menuOpen.value = false
|
||||
}
|
||||
|
||||
/** 关闭菜单后执行(菜单是纯操作入口,不保留焦点)。 */
|
||||
function run(action: () => void): void {
|
||||
closeMenu()
|
||||
action()
|
||||
}
|
||||
|
||||
function openContainingFolder(): void {
|
||||
const path = tabAbsPath(menuTabId.value)
|
||||
const dir = path.slice(0, Math.max(path.lastIndexOf('\\'), path.lastIndexOf('/')))
|
||||
if (!dir) {
|
||||
toast.error('无法确定所在文件夹')
|
||||
return
|
||||
}
|
||||
void store
|
||||
.openFolder(dir)
|
||||
.then(() => store.setSideView('directory'))
|
||||
.catch(e => toast.error(`打开文件夹失败:${String(e)}`))
|
||||
}
|
||||
|
||||
function revealInExplorer(): void {
|
||||
const path = tabAbsPath(menuTabId.value)
|
||||
if (path) store.revealPath(path)
|
||||
}
|
||||
|
||||
async function openInNewWindow(): Promise<void> {
|
||||
const tab = tabOf(menuTabId.value)
|
||||
if (!tab) return
|
||||
try {
|
||||
if (tab.kind === 'note') await openEditorWindow({ relPath: tab.relPath, dedupe: false })
|
||||
else await openEditorWindow({ path: tabAbsPath(tab.id), dedupe: false })
|
||||
} catch (e) {
|
||||
toast.error(`在新窗口打开失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 移动到新窗口:先落盘(保住未保存改动),再开新窗口,最后关掉本标签。 */
|
||||
async function moveToNewWindow(): Promise<void> {
|
||||
const id = menuTabId.value
|
||||
const tab = tabOf(id)
|
||||
if (!tab) return
|
||||
try {
|
||||
await store.saveTab(id)
|
||||
} catch (e) {
|
||||
toast.error(`保存失败,未移动:${String(e)}`)
|
||||
return
|
||||
}
|
||||
try {
|
||||
if (tab.kind === 'note') await openEditorWindow({ relPath: tab.relPath, dedupe: false })
|
||||
else await openEditorWindow({ path: tabAbsPath(id), dedupe: false })
|
||||
} catch (e) {
|
||||
toast.error(`打开新窗口失败:${String(e)}`)
|
||||
return
|
||||
}
|
||||
emit('close', id)
|
||||
}
|
||||
|
||||
function togglePin(): void {
|
||||
const tab = tabOf(menuTabId.value)
|
||||
if (tab) store.setTabPinned(tab.id, !tab.pinned)
|
||||
}
|
||||
|
||||
async function copyName(): Promise<void> {
|
||||
const name = tabFileName(menuTabId.value)
|
||||
if (!name) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(name)
|
||||
toast.success('已复制文件名')
|
||||
} catch {
|
||||
toast.error('复制失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function copyPath(): Promise<void> {
|
||||
const path = tabAbsPath(menuTabId.value)
|
||||
if (!path) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(path)
|
||||
toast.success('已复制文件路径')
|
||||
} catch {
|
||||
toast.error('复制失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function copyRelPath(): Promise<void> {
|
||||
const rel = tabRelPath(menuTabId.value)
|
||||
if (!rel) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(rel)
|
||||
toast.success('已复制相对路径')
|
||||
} catch {
|
||||
toast.error('复制失败')
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 重命名 =====
|
||||
|
||||
const renameOpen = ref(false)
|
||||
const renameValue = ref('')
|
||||
const renameBusy = ref(false)
|
||||
|
||||
function startRename(): void {
|
||||
renameValue.value = tabFileName(menuTabId.value)
|
||||
renameOpen.value = true
|
||||
}
|
||||
|
||||
async function confirmRename(): Promise<void> {
|
||||
const name = renameValue.value.trim()
|
||||
if (!name) {
|
||||
toast.error('名称不能为空')
|
||||
return
|
||||
}
|
||||
renameBusy.value = true
|
||||
try {
|
||||
await store.renameTab(menuTabId.value, name)
|
||||
renameOpen.value = false
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
renameBusy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative flex h-8 shrink-0 items-stretch border-b border-border">
|
||||
<div ref="stripRef" class="flex min-w-0 flex-1 items-stretch gap-0.5 overflow-x-auto px-1">
|
||||
<div
|
||||
v-for="tab in store.tabViews"
|
||||
:key="tab.id"
|
||||
:data-tab-id="tab.id"
|
||||
class="group flex max-w-52 min-w-0 cursor-pointer items-center gap-1.5 rounded-t-sm border-b-2 px-2 text-xs transition-colors duration-150"
|
||||
:class="[
|
||||
tab.id === store.activeTabId
|
||||
? 'border-primary bg-row-selected text-foreground'
|
||||
: 'border-transparent text-fg-secondary hover:bg-row-hover hover:text-foreground',
|
||||
dragId === tab.id && 'opacity-40',
|
||||
dragOverId === tab.id && 'ring-1 ring-primary ring-inset'
|
||||
]"
|
||||
:title="tab.name"
|
||||
@pointerdown="onTabPointerDown(tab.id, $event)"
|
||||
@click="onTabClick(tab.id)"
|
||||
@contextmenu.prevent="openMenu($event, tab.id)"
|
||||
>
|
||||
<Pin v-if="tab.pinned" class="size-3 shrink-0 text-primary" title="已固定" />
|
||||
<FileText v-if="tab.kind === 'note'" class="size-3.5 shrink-0 opacity-70" />
|
||||
<FileCode2 v-else class="size-3.5 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ tab.name }}</span>
|
||||
<span v-if="tab.dirty" class="shrink-0 font-medium text-primary" title="有未保存的改动">*</span>
|
||||
<!-- 预览:仅 Markdown 标签出现;**常驻可见**(不做 hover 才显形,否则用户不知道有这个能力) -->
|
||||
<button
|
||||
v-if="tab.markdown"
|
||||
type="button"
|
||||
class="shrink-0 rounded-sm p-0.5 transition-colors hover:bg-active"
|
||||
:class="isPreviewing(tab.id) ? 'bg-active text-primary' : 'text-muted-foreground hover:text-foreground'"
|
||||
:title="isPreviewing(tab.id) ? '退出预览,回到编辑器' : '预览渲染后的 Markdown'"
|
||||
@click.stop="emit('toggle-preview', tab.id)"
|
||||
>
|
||||
<Eye class="size-3" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-sm p-0.5 opacity-0 transition-opacity hover:bg-active group-hover:opacity-100"
|
||||
title="关闭标签(Ctrl+W)"
|
||||
@click.stop="emit('close', tab.id)"
|
||||
>
|
||||
<X class="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 溢出下拉:标签太多时汇总列出,避免藏在滚动区外 -->
|
||||
<button
|
||||
v-if="overflowing"
|
||||
type="button"
|
||||
class="flex shrink-0 items-center px-1 text-muted-foreground transition-colors hover:bg-row-hover hover:text-foreground"
|
||||
title="全部标签"
|
||||
@click="overflowOpen = !overflowOpen"
|
||||
>
|
||||
<ChevronDown class="size-3.5" />
|
||||
</button>
|
||||
<template v-if="overflowOpen">
|
||||
<div class="fixed inset-0 z-40" @click="overflowOpen = false" />
|
||||
<div
|
||||
class="absolute top-full right-0 z-50 max-h-72 w-64 overflow-y-auto rounded-md border border-border bg-card py-1 text-xs shadow-md"
|
||||
>
|
||||
<button
|
||||
v-for="tab in store.tabViews"
|
||||
:key="tab.id"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
:class="tab.id === store.activeTabId ? 'text-foreground' : 'text-fg-secondary'"
|
||||
@click="pickTab(tab.id)"
|
||||
>
|
||||
<Pin v-if="tab.pinned" class="size-3 shrink-0 text-primary" />
|
||||
<FileText v-if="tab.kind === 'note'" class="size-3.5 shrink-0 opacity-70" />
|
||||
<FileCode2 v-else class="size-3.5 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ tab.name }}</span>
|
||||
<span v-if="tab.dirty" class="shrink-0 font-medium text-primary">*</span>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 右键菜单 -->
|
||||
<template v-if="menuOpen">
|
||||
<div class="fixed inset-0 z-40" @click="closeMenu" @contextmenu.prevent="closeMenu" />
|
||||
<div
|
||||
class="fixed z-50 min-w-[216px] overflow-hidden rounded-md border border-border bg-card py-1 text-xs text-foreground shadow-md"
|
||||
:style="{ left: `${menuX}px`, top: `${menuY}px` }"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="run(() => emit('close', menuTabId))"
|
||||
>
|
||||
<X class="size-3.5 opacity-70" />关闭当前文件
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover disabled:pointer-events-none disabled:opacity-40"
|
||||
:disabled="!hasOthers"
|
||||
@click="run(() => emit('close-others', menuTabId))"
|
||||
>
|
||||
<X class="size-3.5 opacity-70" />关闭其他文件
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover disabled:pointer-events-none disabled:opacity-40"
|
||||
:disabled="!hasLeft"
|
||||
@click="run(() => emit('close-left', menuTabId))"
|
||||
>
|
||||
<X class="size-3.5 opacity-70" />关闭左边所有
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover disabled:pointer-events-none disabled:opacity-40"
|
||||
:disabled="!hasRight"
|
||||
@click="run(() => emit('close-right', menuTabId))"
|
||||
>
|
||||
<X class="size-3.5 opacity-70" />关闭右边所有
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="run(() => emit('close-all'))"
|
||||
>
|
||||
<X class="size-3.5 opacity-70" />关闭所有文件
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover disabled:pointer-events-none disabled:opacity-40"
|
||||
:disabled="!hasUnmodified"
|
||||
@click="run(() => store.closeUnmodifiedTabs())"
|
||||
>
|
||||
<FileX class="size-3.5 opacity-70" />关闭未修改标签
|
||||
</button>
|
||||
|
||||
<div class="my-1 h-px bg-divider" />
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="run(openContainingFolder)"
|
||||
>
|
||||
<FolderOpen class="size-3.5 opacity-70" />打开所在文件夹
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="run(revealInExplorer)"
|
||||
>
|
||||
<ExternalLink class="size-3.5 opacity-70" />在资源管理器打开
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="run(openInNewWindow)"
|
||||
>
|
||||
<AppWindow class="size-3.5 opacity-70" />在新窗口打开
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="run(moveToNewWindow)"
|
||||
>
|
||||
<AppWindow class="size-3.5 opacity-70" />移动到新窗口
|
||||
</button>
|
||||
|
||||
<div class="my-1 h-px bg-divider" />
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover disabled:pointer-events-none disabled:opacity-40"
|
||||
:disabled="menuTabId === store.activeTabId"
|
||||
@click="run(() => emit('split', menuTabId))"
|
||||
>
|
||||
<Columns2 class="size-3.5 opacity-70" />并排分屏
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="run(togglePin)"
|
||||
>
|
||||
<PinOff v-if="menuTab?.pinned" class="size-3.5 opacity-70" />
|
||||
<Pin v-else class="size-3.5 opacity-70" />
|
||||
{{ menuTab?.pinned ? '取消固定' : '固定标签' }}
|
||||
</button>
|
||||
|
||||
<div class="my-1 h-px bg-divider" />
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="run(startRename)"
|
||||
>
|
||||
<Pencil class="size-3.5 opacity-70" />重命名文件
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="run(copyName)"
|
||||
>
|
||||
<Copy class="size-3.5 opacity-70" />复制文件名
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
|
||||
@click="run(copyPath)"
|
||||
>
|
||||
<ClipboardCopy class="size-3.5 opacity-70" />复制文件路径
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover disabled:pointer-events-none disabled:opacity-40"
|
||||
:disabled="menuTab?.kind !== 'note'"
|
||||
@click="run(copyRelPath)"
|
||||
>
|
||||
<Copy class="size-3.5 opacity-70" />复制相对路径
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 重命名文件 -->
|
||||
<Dialog :open="renameOpen" @update:open="renameOpen = $event">
|
||||
<DialogContent class="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>重命名文件</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Input v-model="renameValue" placeholder="文件名(含扩展名)" @keydown.enter="confirmRename" />
|
||||
<DialogFooter>
|
||||
<Button variant="outline" :disabled="renameBusy" @click="renameOpen = false">取消</Button>
|
||||
<Button :disabled="renameBusy" @click="confirmRename">确定</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,302 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 顶部快捷操作行(原「工具栏」)。
|
||||
*
|
||||
* # 为什么只有图标
|
||||
*
|
||||
* 文件名在**窗口标题**与**标签栏**里都有了,工具栏再显示一遍是重复信息;按钮文字
|
||||
* 也会把这一行撑得很宽。因此整行统一为图标按钮,标题(含快捷键)走 tooltip。
|
||||
*
|
||||
* # 一行里放两类东西
|
||||
*
|
||||
* 1. **侧栏导航**(库 / 目录 / 最近)—— 从侧栏内部搬上来,侧栏只留内容;
|
||||
* 2. **文档操作**(在路径中查找 / 打开 / 快速打开 / 保存 / 视图 / 导出)+ 笔记的
|
||||
* Markdown 格式化。检索不再是「侧栏的一个视图」,而是统一搜索器(EditorSearch),
|
||||
* 因此这个按钮只负责把搜索器叫出来,不参与侧栏高亮。
|
||||
*
|
||||
* 配色快切已移除:主题是配置项,只在模块设置页出现,避免两个入口改同一份设置。
|
||||
*/
|
||||
import {
|
||||
Bold,
|
||||
Code,
|
||||
Eye,
|
||||
FileDown,
|
||||
FilePlus,
|
||||
FileSearch,
|
||||
FolderOpen,
|
||||
FolderTree,
|
||||
Heading1,
|
||||
Heading2,
|
||||
Heading3,
|
||||
History,
|
||||
Italic,
|
||||
Library,
|
||||
Link,
|
||||
List,
|
||||
ListChecks,
|
||||
Loader2,
|
||||
PanelLeft,
|
||||
Quote,
|
||||
Save,
|
||||
Search,
|
||||
SquareCode,
|
||||
Strikethrough
|
||||
} from '@lucide/vue'
|
||||
import { ref } from 'vue'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { toast } from 'vue-sonner'
|
||||
import type { Command } from '@codemirror/view'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import { editorClient } from '../editorClient'
|
||||
import { editorCommands } from '../editor/keymap'
|
||||
import type { NoteViewMode } from '@/types/editor'
|
||||
|
||||
type SideView = 'library' | 'directory' | 'recent'
|
||||
|
||||
const props = defineProps<{
|
||||
apply: (command: Command) => void
|
||||
viewMode: NoteViewMode
|
||||
dirty: boolean
|
||||
saving: boolean
|
||||
/** 侧栏是否可见(决定开关按钮的状态与 tooltip) */
|
||||
sidebarVisible: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:viewMode': [value: NoteViewMode]
|
||||
save: []
|
||||
'open-file': []
|
||||
/** 新建临时文件(草稿) */
|
||||
'new-file': []
|
||||
'quick-open': []
|
||||
'toggle-sidebar': []
|
||||
nav: [view: SideView]
|
||||
/** 打开统一搜索器(在路径中查找) */
|
||||
'open-search': []
|
||||
}>()
|
||||
|
||||
const store = useEditorStore()
|
||||
|
||||
const run = (command: Command) => props.apply(command)
|
||||
|
||||
const exporting = ref(false)
|
||||
|
||||
/** 侧栏导航按钮当前是否处于「选中」状态(侧栏可见且视图匹配)。 */
|
||||
function isActive(view: SideView): boolean {
|
||||
return props.sidebarVisible && store.sideView === view
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出当前 Markdown 文档为 HTML(笔记与库外 `.md` 文件都支持)。
|
||||
*
|
||||
* 两条落盘路径,因为两者的「真相位置」不同:
|
||||
* - **笔记**:走库语义 `exportNote`(库内相对路径,磁盘上的那一份为准);
|
||||
* - **库外文件**:目标路径来自系统对话框,先 `authorizeFile` 再 `writeFile`
|
||||
* (文件的写入是严格的:没登记过的路径一律拒绝)。
|
||||
*
|
||||
* 渲染链路(markdown-it + DOMPurify + highlight.js)**按需 import**:
|
||||
* 它约 1MB,而导出是低频动作 —— 静态引入会让「打开编辑器窗口」这个最常见的动作
|
||||
* 也背上这份体积。
|
||||
*/
|
||||
async function exportHtml(): Promise<void> {
|
||||
if (!store.hasDocument) return
|
||||
const isNote = store.kind === 'note'
|
||||
const relPath = store.currentRelPath
|
||||
if (isNote && !relPath) return
|
||||
exporting.value = true
|
||||
try {
|
||||
const doc = isNote
|
||||
? await editorClient.readNote(relPath)
|
||||
: { name: store.fileDoc?.name ?? 'document.md', content: store.content }
|
||||
const base = doc.name.replace(/\.(md|markdown|mdx)$/i, '')
|
||||
const { renderNoteHtml } = await import('../editor/markdownExport')
|
||||
const html = renderNoteHtml({
|
||||
title: (isNote && store.currentName) || base,
|
||||
fileName: doc.name,
|
||||
markdown: doc.content,
|
||||
highlight: store.settings.exportHighlight
|
||||
})
|
||||
const dest = await open({
|
||||
title: '导出为 HTML',
|
||||
defaultPath: `${base}.html`,
|
||||
filters: [{ name: 'HTML 文件', extensions: ['html'] }]
|
||||
})
|
||||
if (typeof dest !== 'string') return
|
||||
const saved = isNote
|
||||
? await editorClient.exportNote(relPath, html, dest)
|
||||
: await writeExternalHtml(dest, html)
|
||||
toast.success(`已导出:${saved}`)
|
||||
} catch (e) {
|
||||
toast.error(`导出失败:${String(e)}`)
|
||||
} finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 库外文件的导出落盘:先登记授权(路径来自系统对话框),再按 UTF-8 写入。 */
|
||||
async function writeExternalHtml(dest: string, html: string): Promise<string> {
|
||||
await editorClient.authorizeFile(dest)
|
||||
await editorClient.writeFile(dest, html, 'utf-8', 'lf')
|
||||
return dest
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="flex h-9 shrink-0 items-center gap-0.5 overflow-x-auto border-b border-border px-2"
|
||||
>
|
||||
<!-- 侧栏开关 -->
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="sidebarVisible ? '隐藏侧栏' : '显示侧栏'"
|
||||
@click="emit('toggle-sidebar')"
|
||||
>
|
||||
<PanelLeft class="size-3.5" />
|
||||
</Button>
|
||||
|
||||
<div class="mx-1 h-4 w-px shrink-0 bg-divider" />
|
||||
|
||||
<!-- 侧栏导航:库 / 目录 / 最近 -->
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="笔记库"
|
||||
:class="isActive('library') && 'bg-active text-foreground'"
|
||||
@click="emit('nav', 'library')"
|
||||
>
|
||||
<Library class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="本地目录"
|
||||
:class="isActive('directory') && 'bg-active text-foreground'"
|
||||
@click="emit('nav', 'directory')"
|
||||
>
|
||||
<FolderTree class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="在路径中查找 (Ctrl+Shift+F)"
|
||||
@click="emit('open-search')"
|
||||
>
|
||||
<Search class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="最近打开"
|
||||
:class="isActive('recent') && 'bg-active text-foreground'"
|
||||
@click="emit('nav', 'recent')"
|
||||
>
|
||||
<History class="size-3.5" />
|
||||
</Button>
|
||||
|
||||
<div class="mx-1 h-4 w-px shrink-0 bg-divider" />
|
||||
|
||||
<!-- 文档操作 -->
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="新建临时文件(草稿,存放在应用数据目录;关闭时可选择保存到别处或删除)"
|
||||
@click="emit('new-file')"
|
||||
>
|
||||
<FilePlus class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="打开磁盘文件 (Ctrl+O)" @click="emit('open-file')">
|
||||
<FolderOpen class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="快速打开 (Ctrl+P)" @click="emit('quick-open')">
|
||||
<FileSearch class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="dirty ? '保存 (Ctrl+S)' : '没有需要保存的改动'"
|
||||
:disabled="!dirty || saving"
|
||||
@click="emit('save')"
|
||||
>
|
||||
<Loader2 v-if="saving" class="size-3.5 animate-spin" />
|
||||
<Save v-else class="size-3.5" />
|
||||
</Button>
|
||||
<!-- 视图切换 / 导出 / 格式化:只对 Markdown 有意义(笔记与库外 .md 文件同样开放) -->
|
||||
<Button
|
||||
v-if="store.isMarkdown"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="viewMode === 'wysiwyg' ? '切到源码视图 (Ctrl+Shift+M)' : '切到所见即所得 (Ctrl+Shift+M)'"
|
||||
@click="emit('update:viewMode', viewMode === 'wysiwyg' ? 'source' : 'wysiwyg')"
|
||||
>
|
||||
<Eye class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
v-if="store.isMarkdown"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:disabled="exporting"
|
||||
title="导出为独立 HTML(可离线打开或系统打印成 PDF)"
|
||||
@click="exportHtml"
|
||||
>
|
||||
<Loader2 v-if="exporting" class="size-3.5 animate-spin" />
|
||||
<FileDown v-else class="size-3.5" />
|
||||
</Button>
|
||||
|
||||
<template v-if="store.isMarkdown">
|
||||
<div class="mx-1 h-4 w-px shrink-0 bg-divider" />
|
||||
<Button variant="ghost" size="icon-sm" title="加粗 (Ctrl+B)" @click="run(editorCommands.bold)">
|
||||
<Bold class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="斜体 (Ctrl+I)" @click="run(editorCommands.italic)">
|
||||
<Italic class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="删除线 (Ctrl+Shift+X)"
|
||||
@click="run(editorCommands.strikethrough)"
|
||||
>
|
||||
<Strikethrough class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="行内代码 (Ctrl+E)"
|
||||
@click="run(editorCommands.inlineCode)"
|
||||
>
|
||||
<Code class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="链接 (Ctrl+K)" @click="run(editorCommands.link)">
|
||||
<Link class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="一级标题 (Ctrl+1)" @click="run(editorCommands.heading(1))">
|
||||
<Heading1 class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="二级标题 (Ctrl+2)" @click="run(editorCommands.heading(2))">
|
||||
<Heading2 class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="三级标题 (Ctrl+3)" @click="run(editorCommands.heading(3))">
|
||||
<Heading3 class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="无序列表" @click="run(editorCommands.bulletList)">
|
||||
<List class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="任务列表" @click="run(editorCommands.taskList)">
|
||||
<ListChecks class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="引用" @click="run(editorCommands.quote)">
|
||||
<Quote class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="代码块 (Ctrl+Shift+C)"
|
||||
@click="run(editorCommands.codeBlock)"
|
||||
>
|
||||
<SquareCode class="size-3.5" />
|
||||
</Button>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,314 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 导入 / 导出面板(主模块页「库」区)。
|
||||
*
|
||||
* # 三条链路,各自的风险点
|
||||
*
|
||||
* - **导入**:批量写库,唯一硬规则是「绝不覆盖」(重名加序号),选择即授权;
|
||||
* - **导出 HTML**:渲染在前端(`markdownExport`),落盘在后端 —— 后端不碰渲染、
|
||||
* 前端不碰文件系统,各自只做自己擅长且可审计的那一半;
|
||||
* - **导出 zip**:整库或某个目录打包,方便分享/迁移。
|
||||
*
|
||||
* # 为什么导出 HTML 的路径要用户选两次(先选笔记、再选保存位置)
|
||||
*
|
||||
* 批量导出(一次选目录、每篇一个 HTML)看起来更省事,但「一篇笔记配一个 assets 目录」
|
||||
* 的结构很难在浏览器里可靠实现(`<base>` 与相对路径在不同浏览器行为不一致)。
|
||||
* 这里只做**单篇 → 单文件**,路径语义清晰:导出文件和笔记在库内同级时相对路径依然有效。
|
||||
*/
|
||||
import { computed, ref } from 'vue'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { openPath } from '@tauri-apps/plugin-opener'
|
||||
import {
|
||||
FileDown,
|
||||
FileUp,
|
||||
FolderInput,
|
||||
FolderOutput,
|
||||
Loader2,
|
||||
NotebookPen
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { SettingRow } from '@/components/common'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import { editorClient } from '../editorClient'
|
||||
|
||||
const store = useEditorStore()
|
||||
|
||||
const busy = ref<'import' | 'export' | 'zip' | null>(null)
|
||||
|
||||
/**
|
||||
* 「当前打开的笔记」这个选项的哨兵值。
|
||||
*
|
||||
* **不能用空串**:reka-ui 的 `Select` 把空串保留给「清空选择、显示 placeholder」,
|
||||
* 放一个 `value=""` 的 `SelectItem` 会直接抛
|
||||
* 「A <SelectItem /> must have a value prop that is not an empty string」。
|
||||
* 用哨兵值 + 调用点翻译,比「把空串当合法值」更清楚:哨兵名本身就说明了语义。
|
||||
*/
|
||||
const CURRENT_NOTE = '__current__'
|
||||
/** 「整个库」这个选项的哨兵值(同上,空串留给 placeholder) */
|
||||
const WHOLE_LIBRARY = '__all__'
|
||||
|
||||
/** 导出 HTML 的目标笔记(`CURRENT_NOTE` = 当前打开的笔记) */
|
||||
const exportTarget = ref(CURRENT_NOTE)
|
||||
|
||||
/** 库内目录选项(导出 zip 时限定范围) */
|
||||
const dirOptions = computed(() => {
|
||||
const dirs = store.entries.filter(e => e.isDir).map(e => e.relPath)
|
||||
return [{ value: WHOLE_LIBRARY, label: '整个库' }, ...dirs.map(d => ({ value: d, label: d }))]
|
||||
})
|
||||
/** 导出 zip 的范围(`WHOLE_LIBRARY` = 整库) */
|
||||
const zipScope = ref(WHOLE_LIBRARY)
|
||||
|
||||
/**
|
||||
* 可导出的笔记。
|
||||
*
|
||||
* 当前笔记只作为**第一个选项**出现(而不是「空串代表当前」)—— 这样列表里每一项
|
||||
* 都有明确的值,用户也能在「当前笔记」与具体路径之间切换。
|
||||
*/
|
||||
const noteOptions = computed(() => {
|
||||
const files = store.entries.filter(e => !e.isDir)
|
||||
const options: Array<{ value: string; label: string }> = []
|
||||
if (store.currentRelPath) {
|
||||
options.push({ value: CURRENT_NOTE, label: `当前笔记(${store.currentName})` })
|
||||
}
|
||||
options.push(...files.map(f => ({ value: f.relPath, label: f.relPath })))
|
||||
return options
|
||||
})
|
||||
|
||||
/** 导入:文件 / 目录 / zip 都走同一个入口(后端按扩展名判别)。 */
|
||||
async function doImport(kind: 'file' | 'dir'): Promise<void> {
|
||||
try {
|
||||
const selected = await open(
|
||||
kind === 'dir'
|
||||
? { directory: true, multiple: false, title: '选择要导入的文件夹' }
|
||||
: {
|
||||
directory: false,
|
||||
multiple: false,
|
||||
title: '选择要导入的文件或 zip',
|
||||
filters: [
|
||||
{ name: 'Markdown / Zip', extensions: ['md', 'markdown', 'zip'] },
|
||||
{ name: '全部文件', extensions: ['*'] }
|
||||
]
|
||||
}
|
||||
)
|
||||
if (typeof selected !== 'string') return
|
||||
busy.value = 'import'
|
||||
const report = await editorClient.import(selected, '')
|
||||
await store.refreshLibrary()
|
||||
await store.syncIndex()
|
||||
const renamed = report.renamed ? `,${report.renamed} 篇重名已加序号` : ''
|
||||
const skipped = report.skipped ? `,跳过 ${report.skipped} 个非笔记文件` : ''
|
||||
toast.success(`导入 ${report.imported} 个文件${renamed}${skipped}`)
|
||||
if (report.failures.length) {
|
||||
toast.warning(`${report.failures.length} 条失败:${report.failures[0]}`)
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`导入失败:${String(e)}`)
|
||||
} finally {
|
||||
busy.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 导出单篇 HTML:渲染在本地做,落盘交给后端。 */
|
||||
async function doExportHtml(): Promise<void> {
|
||||
// 哨兵值翻译成真实路径(见 `CURRENT_NOTE` 的说明)
|
||||
const relPath = exportTarget.value === CURRENT_NOTE ? store.currentRelPath : exportTarget.value
|
||||
if (!relPath) {
|
||||
toast.error(store.currentRelPath ? '请先选择要导出的笔记' : '请先在编辑器里打开一篇笔记')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const doc = await editorClient.readNote(relPath)
|
||||
// **动态引入**:`markdownExport` 会拉进 markdown-it + DOMPurify + highlight.js
|
||||
// (实测约 1MB),而导出是低频动作。静态引入会让「笔记」模块页一打开就下载
|
||||
// 这三个包(chunk 从 ~130kB 涨到 1.1MB),把首屏拖垮。
|
||||
const { renderNoteHtml } = await import('../editor/markdownExport')
|
||||
const html = renderNoteHtml({
|
||||
// 标题用笔记自己的显示名,而不是「当前笔记」那个下拉标签
|
||||
title: doc.name.replace(/\.md$/i, ''),
|
||||
fileName: doc.name,
|
||||
markdown: doc.content,
|
||||
highlight: store.settings.exportHighlight
|
||||
})
|
||||
const suggested = doc.name.replace(/\.md$/i, '') + '.html'
|
||||
const dest = await open({
|
||||
title: '导出为 HTML',
|
||||
defaultPath: suggested,
|
||||
filters: [{ name: 'HTML 文件', extensions: ['html'] }]
|
||||
})
|
||||
if (typeof dest !== 'string') return
|
||||
busy.value = 'export'
|
||||
const saved = await editorClient.exportNote(relPath, html, dest)
|
||||
toast.success(`已导出:${saved}`, {
|
||||
action: { label: '打开', onClick: () => void openPath(saved) }
|
||||
})
|
||||
} catch (e) {
|
||||
toast.error(`导出失败:${String(e)}`)
|
||||
} finally {
|
||||
busy.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 导出 zip(整库或某个目录)。 */
|
||||
async function doExportZip(): Promise<void> {
|
||||
try {
|
||||
// 哨兵值翻译:`WHOLE_LIBRARY` → 不传范围(后端按「整库」处理)
|
||||
const scope = zipScope.value === WHOLE_LIBRARY ? '' : zipScope.value
|
||||
const scopeLabel = scope ? scope.replace(/\//g, '-') : 'thing-notes'
|
||||
const dest = await open({
|
||||
title: '导出 zip',
|
||||
defaultPath: `${scopeLabel}.zip`,
|
||||
filters: [{ name: 'Zip 压缩包', extensions: ['zip'] }]
|
||||
})
|
||||
if (typeof dest !== 'string') return
|
||||
busy.value = 'zip'
|
||||
const saved = await editorClient.exportZip(dest, scope || undefined)
|
||||
toast.success(`已导出:${saved}`, {
|
||||
action: { label: '打开目录', onClick: () => void openPath(saved.replace(/[\\/][^\\/]+$/, '')) }
|
||||
})
|
||||
} catch (e) {
|
||||
toast.error(`导出失败:${String(e)}`)
|
||||
} finally {
|
||||
busy.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 把内置模板写到库内 `templates/`,方便用户直接改。 */
|
||||
async function exportTemplates(): Promise<void> {
|
||||
try {
|
||||
const written = await store.exportBuiltinTemplates()
|
||||
if (written.length) {
|
||||
toast.success(`已写入 ${written.length} 个内置模板到 templates/`)
|
||||
} else {
|
||||
toast.info('templates/ 里已有这些模板,未覆盖')
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`写入模板失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- ===== 导入 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<FileUp class="size-4 text-primary" />
|
||||
导入
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
导入 Markdown 目录 / 单文件 / zip 包。**同名笔记不会被覆盖**,会自动加序号;
|
||||
图片等附件进 <code class="font-mono">assets/</code>,其它类型文件忽略。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="导入文件夹" description="保留子目录结构,跳过隐藏目录与 __MACOSX">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="!!busy"
|
||||
@click="doImport('dir')"
|
||||
>
|
||||
<Loader2 v-if="busy === 'import'" class="size-3.5 animate-spin" />
|
||||
<FolderInput v-else class="size-3.5" />
|
||||
选择文件夹
|
||||
</Button>
|
||||
</SettingRow>
|
||||
<SettingRow label="导入文件 / zip" description="单个 .md 或一个压缩包">
|
||||
<Button variant="outline" size="sm" :disabled="!!busy" @click="doImport('file')">
|
||||
<FileUp class="size-3.5" />选择文件
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 导出 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<FileDown class="size-4 text-primary" />
|
||||
导出
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
HTML 为**单文件、零外链**(样式内联),可离线双击打开或直接用系统打印成 PDF;
|
||||
正文经过消毒,笔记里嵌的脚本不会被执行。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="导出笔记" description="Markdown → 独立 HTML" control-width="wide">
|
||||
<div class="flex w-full flex-col gap-2">
|
||||
<Select v-model="exportTarget">
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in noteOptions" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
size="sm"
|
||||
class="self-start"
|
||||
:disabled="!!busy"
|
||||
@click="doExportHtml"
|
||||
>
|
||||
<Loader2 v-if="busy === 'export'" class="size-3.5 animate-spin" />
|
||||
<FileDown v-else class="size-3.5" />
|
||||
导出 HTML
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="导出 zip" description="整库或某个目录(含 assets/,不含 .editor/)" control-width="wide">
|
||||
<div class="flex w-full flex-col gap-2">
|
||||
<Select v-model="zipScope">
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in dirOptions" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="self-start"
|
||||
:disabled="!!busy"
|
||||
@click="doExportZip"
|
||||
>
|
||||
<Loader2 v-if="busy === 'zip'" class="size-3.5 animate-spin" />
|
||||
<FolderOutput v-else class="size-3.5" />
|
||||
导出 zip
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="内置模板"
|
||||
description="把日记 / 会议纪要等内置模板写到库内 templates/,改完即刻生效"
|
||||
>
|
||||
<Button variant="outline" size="sm" @click="exportTemplates">
|
||||
<NotebookPen class="size-3.5" />写入 templates/
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 说明:导入目标目录固定为库根(保持与 zip 内结构一致),因此这里只给提示 -->
|
||||
<p class="px-1 text-[11px] text-muted-foreground">
|
||||
提示:导入的笔记都落在库根下(保留源目录结构)。想放到别处,导入后拖到目标目录即可。
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,473 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 编辑器侧栏:**库 / 目录 / 最近** 三段。
|
||||
*
|
||||
* 「检索」已不再是侧栏的一个视图 —— 它并入了统一搜索器(`EditorSearch.vue`),
|
||||
* 那一处同时覆盖「当前文件 / 当前目录 / 笔记库」,侧栏只保留「去哪找文件」的导航。
|
||||
*
|
||||
* # 两个并列的「根」
|
||||
*
|
||||
* - **笔记库**:沙箱 + 索引 + front-matter + 双链(相对库根路径)
|
||||
* - **本地目录**:任意路径 + 不进索引 + 无 front-matter 语义(真实文件系统)
|
||||
*
|
||||
* 两者是并列的导航能力,编辑对象(文件本身)才是模块中心。
|
||||
*
|
||||
* # 大纲 / 双链去哪了
|
||||
*
|
||||
* 它们描述的是**当前文档**而不是「去哪找文件」,因此移到编辑区右侧抽屉
|
||||
* (见 `DrawerPanel.vue`)。侧栏只回答「去哪找」。
|
||||
*
|
||||
* 版式沿用终端「文件管理器」(`ScrollArea` 滚动、`bg-row-selected` 选中、
|
||||
* 紧凑输入 `h-7 text-xs`、空态用 `StateBlock`)。
|
||||
*
|
||||
* # 字号比主界面「小一号」
|
||||
*
|
||||
* 侧栏是窄栏(256px)且常年挂在那里,行名与标题若用正文尺寸会显得拥挤、抢视线。
|
||||
* 因此列表行统一 `text-xs`(12px)、标题与提示再用 `text-[11px]` / `text-[10px]` 递减 ——
|
||||
* 层级拉开,密度也更接近 JetBrains 的工具窗口。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
FilePlus,
|
||||
FileText,
|
||||
Folder,
|
||||
FolderPlus,
|
||||
Loader2,
|
||||
Pencil,
|
||||
RotateCw,
|
||||
Trash2,
|
||||
X
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { ConfirmDialog, StateBlock } from '@/components/common'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import type { LibraryEntry, LibraryTreeNode } from '@/types/editor'
|
||||
import DirectoryPanel from './DirectoryPanel.vue'
|
||||
import RecentPanel from './RecentPanel.vue'
|
||||
import NewNoteDialog from './NewNoteDialog.vue'
|
||||
|
||||
const emit = defineEmits<{ open: [relPath: string] }>()
|
||||
|
||||
const store = useEditorStore()
|
||||
|
||||
/** 已展开的目录 */
|
||||
const expanded = ref<Set<string>>(new Set())
|
||||
/** 名称过滤 */
|
||||
const filter = ref('')
|
||||
/** 当前选中的目录(新建目标;空串 = 库根) */
|
||||
const selectedDir = ref('')
|
||||
|
||||
/** 侧栏视图由顶部操作行控制(`store.sideView`),这里只管内容 */
|
||||
const view = computed(() => store.sideView)
|
||||
|
||||
defineExpose({
|
||||
/** 由 EditorWindow 在顶部导航触发时调用 */
|
||||
showLibrary: () => store.setSideView('library'),
|
||||
/** 由 EditorWindow 在 `?folder=` 打开时调用 */
|
||||
showDirectory: () => store.setSideView('directory'),
|
||||
/** 由 EditorWindow 在 Ctrl+Shift+N 时调用 */
|
||||
showNewNote: () => {
|
||||
store.setSideView('library')
|
||||
void startNewNote()
|
||||
}
|
||||
})
|
||||
|
||||
// ===== 扁平化 + 过滤 =====
|
||||
const flatNodes = computed(() => {
|
||||
const keyword = filter.value.trim().toLowerCase()
|
||||
const out: Array<{ entry: LibraryEntry; depth: number }> = []
|
||||
|
||||
const matches = (node: LibraryTreeNode): boolean => {
|
||||
if (!keyword) return true
|
||||
if (node.entry.name.toLowerCase().includes(keyword)) return true
|
||||
return node.children.some(matches)
|
||||
}
|
||||
|
||||
const walk = (nodes: LibraryTreeNode[], depth: number) => {
|
||||
for (const node of nodes) {
|
||||
if (!matches(node)) continue
|
||||
out.push({ entry: node.entry, depth })
|
||||
const open = expanded.value.has(node.entry.relPath) || !!keyword
|
||||
if (node.entry.isDir && open) walk(node.children, depth + 1)
|
||||
}
|
||||
}
|
||||
walk(store.tree, 0)
|
||||
return out
|
||||
})
|
||||
|
||||
watch(
|
||||
() => store.currentRelPath,
|
||||
relPath => {
|
||||
if (!relPath) return
|
||||
// 展开当前笔记的所有祖先目录,保证选中项可见
|
||||
const parts = relPath.split('/')
|
||||
parts.pop()
|
||||
let prefix = ''
|
||||
const next = new Set(expanded.value)
|
||||
for (const part of parts) {
|
||||
prefix = prefix ? `${prefix}/${part}` : part
|
||||
next.add(prefix)
|
||||
}
|
||||
expanded.value = next
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
const isExpanded = (relPath: string) => expanded.value.has(relPath)
|
||||
|
||||
const toggleDir = (entry: LibraryEntry) => {
|
||||
const next = new Set(expanded.value)
|
||||
if (next.has(entry.relPath)) next.delete(entry.relPath)
|
||||
else next.add(entry.relPath)
|
||||
expanded.value = next
|
||||
selectedDir.value = entry.relPath
|
||||
}
|
||||
|
||||
const onRowClick = (entry: LibraryEntry) => {
|
||||
if (entry.isDir) {
|
||||
toggleDir(entry)
|
||||
return
|
||||
}
|
||||
emit('open', entry.relPath)
|
||||
}
|
||||
|
||||
const targetLabel = computed(() => (selectedDir.value ? selectedDir.value : '库根'))
|
||||
|
||||
// ===== 新建笔记(走带模板选择的对话框) =====
|
||||
const newNoteOpen = ref(false)
|
||||
|
||||
/**
|
||||
* 新建笔记入口。
|
||||
*
|
||||
* `showTemplatePicker` 关闭时**跳过对话框**,用「未命名」+ 上次的模板直接建 ——
|
||||
* 这是「快速记一笔」的路径,多一个对话框就多一次打断。名字建好后可以就地重命名。
|
||||
*/
|
||||
async function startNewNote(): Promise<void> {
|
||||
if (store.settings.showTemplatePicker) {
|
||||
newNoteOpen.value = true
|
||||
return
|
||||
}
|
||||
try {
|
||||
const stamp = new Date()
|
||||
const name = `未命名 ${stamp.getHours()}${String(stamp.getMinutes()).padStart(2, '0')}`
|
||||
await store.createNote(selectedDir.value, name, store.lastTemplateId || undefined)
|
||||
if (store.currentRelPath) revealNote(store.currentRelPath)
|
||||
} catch (e) {
|
||||
toast.error(`新建失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 新建完成后展开新笔记的祖先目录,让它在树里可见 */
|
||||
function revealNote(relPath: string): void {
|
||||
const parts = relPath.split('/')
|
||||
parts.pop()
|
||||
const next = new Set(expanded.value)
|
||||
let prefix = ''
|
||||
for (const part of parts) {
|
||||
prefix = prefix ? `${prefix}/${part}` : part
|
||||
next.add(prefix)
|
||||
}
|
||||
expanded.value = next
|
||||
store.setSideView('library')
|
||||
}
|
||||
|
||||
function onCreated(relPath: string): void {
|
||||
revealNote(relPath)
|
||||
}
|
||||
|
||||
// ===== 名称输入对话框(新建文件夹 / 重命名) =====
|
||||
type PromptMode = 'folder' | 'rename'
|
||||
const promptOpen = ref(false)
|
||||
const promptMode = ref<PromptMode>('folder')
|
||||
const promptValue = ref('')
|
||||
const promptTarget = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
const promptTitle = computed(() => (promptMode.value === 'folder' ? '新建文件夹' : '重命名'))
|
||||
|
||||
function openPrompt(mode: PromptMode, target: string, initial = '') {
|
||||
promptMode.value = mode
|
||||
promptTarget.value = target
|
||||
promptValue.value = initial
|
||||
promptOpen.value = true
|
||||
}
|
||||
|
||||
async function confirmPrompt() {
|
||||
const name = promptValue.value.trim()
|
||||
if (!name) {
|
||||
toast.error('名称不能为空')
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
try {
|
||||
if (promptMode.value === 'folder') {
|
||||
await store.createFolder(selectedDir.value, name)
|
||||
} else {
|
||||
await store.renameEntry(promptTarget.value, name)
|
||||
}
|
||||
promptOpen.value = false
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 删除确认 =====
|
||||
const confirmOpen = ref(false)
|
||||
const deleteTarget = ref<LibraryEntry | null>(null)
|
||||
|
||||
function askDelete(entry: LibraryEntry) {
|
||||
deleteTarget.value = entry
|
||||
confirmOpen.value = true
|
||||
}
|
||||
|
||||
async function doDelete() {
|
||||
const entry = deleteTarget.value
|
||||
if (!entry) return
|
||||
try {
|
||||
await store.deleteEntry(entry.relPath)
|
||||
toast.success(`已删除「${entry.name}」`)
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
confirmOpen.value = false
|
||||
deleteTarget.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function rebuildIndex(): Promise<void> {
|
||||
await store.rebuildIndex()
|
||||
await store.refreshLibrary()
|
||||
toast.success('索引已重建')
|
||||
}
|
||||
|
||||
// ===== 宽度拖拽 =====
|
||||
//
|
||||
// 与底部结果面板(SearchResultsPanel)同一套 Pointer Events + setPointerCapture 范式:
|
||||
// 指针被捕获后拖出窗口边界也不丢事件。宽度落 localStorage,下次打开保持。
|
||||
const WIDTH_KEY = 'thing_editor_sidebar_width'
|
||||
const MIN_WIDTH = 200
|
||||
const MAX_WIDTH = 520
|
||||
|
||||
function loadWidth(): number {
|
||||
try {
|
||||
const raw = localStorage.getItem(WIDTH_KEY)
|
||||
const n = raw ? Number(raw) : NaN
|
||||
return Number.isFinite(n) ? Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, n)) : 256
|
||||
} catch {
|
||||
return 256
|
||||
}
|
||||
}
|
||||
|
||||
const width = ref(loadWidth())
|
||||
const resizing = ref(false)
|
||||
let dragStartX = 0
|
||||
let dragStartWidth = 0
|
||||
|
||||
function onResizeStart(event: PointerEvent): void {
|
||||
dragStartX = event.clientX
|
||||
dragStartWidth = width.value
|
||||
resizing.value = true
|
||||
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
|
||||
}
|
||||
|
||||
function onResizeMove(event: PointerEvent): void {
|
||||
if (!resizing.value) return
|
||||
// 往右拖 = 侧栏变宽
|
||||
width.value = Math.round(Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, dragStartWidth + (event.clientX - dragStartX))))
|
||||
}
|
||||
|
||||
function onResizeEnd(event: PointerEvent): void {
|
||||
if (!resizing.value) return
|
||||
resizing.value = false
|
||||
;(event.currentTarget as HTMLElement).releasePointerCapture(event.pointerId)
|
||||
try {
|
||||
localStorage.setItem(WIDTH_KEY, String(width.value))
|
||||
} catch {
|
||||
/* 忽略存储失败 */
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside
|
||||
class="relative flex h-full min-h-0 shrink-0 flex-col border-r border-border"
|
||||
:style="{ width: `${width}px` }"
|
||||
>
|
||||
<!-- 头部:仅库视图需要库操作(导航已在顶部操作行) -->
|
||||
<div
|
||||
v-if="view === 'library'"
|
||||
class="flex h-9 shrink-0 items-center gap-1 border-b border-border px-2"
|
||||
>
|
||||
<span class="ml-1 text-xs font-medium text-foreground">笔记库</span>
|
||||
<div class="ml-auto flex items-center gap-0.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="store.settings.showTemplatePicker ? '新建笔记(可选模板)' : '新建笔记'"
|
||||
@click="startNewNote"
|
||||
>
|
||||
<FilePlus class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="新建文件夹" @click="openPrompt('folder', selectedDir)">
|
||||
<FolderPlus class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="store.indexing ? '正在重建索引…' : '重建索引'"
|
||||
:disabled="store.indexing"
|
||||
@click="rebuildIndex"
|
||||
>
|
||||
<RotateCw class="size-3.5" :class="store.indexing && 'animate-spin'" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 库视图 ===== -->
|
||||
<template v-if="view === 'library'">
|
||||
<div class="shrink-0 px-2 py-2">
|
||||
<div class="relative">
|
||||
<Input v-model="filter" placeholder="按名称过滤…" class="h-7 pr-6 text-[11px]" />
|
||||
<button
|
||||
v-if="filter"
|
||||
type="button"
|
||||
class="absolute top-1/2 right-1.5 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
@click="filter = ''"
|
||||
>
|
||||
<X class="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-1.5 px-0.5 text-[10px] text-muted-foreground">
|
||||
新建目标:<span class="text-fg-secondary">{{ targetLabel }}</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-1.5 pb-2">
|
||||
<div v-if="store.loading" class="flex items-center justify-center gap-2 p-4">
|
||||
<Loader2 class="size-3.5 animate-spin text-muted-foreground" />
|
||||
<span class="text-[11px] text-muted-foreground">正在扫描库…</span>
|
||||
</div>
|
||||
|
||||
<StateBlock
|
||||
v-else-if="!flatNodes.length"
|
||||
variant="empty"
|
||||
:title="filter ? '没有匹配的笔记' : '笔记库为空'"
|
||||
:description="filter ? undefined : '点上方按钮新建第一篇笔记'"
|
||||
:min-height="140"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<div
|
||||
v-for="item in flatNodes"
|
||||
:key="item.entry.relPath"
|
||||
class="group flex h-7 cursor-pointer items-center gap-1 rounded-sm pr-1 transition-colors duration-150"
|
||||
:class="
|
||||
store.currentRelPath === item.entry.relPath
|
||||
? 'bg-row-selected text-primary-soft-text'
|
||||
: 'text-fg-secondary hover:bg-row-hover hover:text-foreground'
|
||||
"
|
||||
:style="{ paddingLeft: `${item.depth * 12 + 4}px` }"
|
||||
@click="onRowClick(item.entry)"
|
||||
>
|
||||
<component
|
||||
:is="
|
||||
item.entry.isDir
|
||||
? isExpanded(item.entry.relPath)
|
||||
? ChevronDown
|
||||
: ChevronRight
|
||||
: FileText
|
||||
"
|
||||
class="size-3.5 shrink-0 opacity-70"
|
||||
/>
|
||||
<Folder v-if="item.entry.isDir" class="size-3.5 shrink-0 opacity-80" />
|
||||
<span class="truncate text-xs">{{ item.entry.name }}</span>
|
||||
|
||||
<div class="ml-auto flex shrink-0 items-center gap-0.5 opacity-0 group-hover:opacity-100">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm p-0.5 hover:bg-active"
|
||||
title="重命名"
|
||||
@click.stop="openPrompt('rename', item.entry.relPath, item.entry.name)"
|
||||
>
|
||||
<Pencil class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm p-0.5 hover:bg-active"
|
||||
title="删除"
|
||||
@click.stop="askDelete(item.entry)"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</template>
|
||||
|
||||
<!-- ===== 目录视图(本地文件系统) ===== -->
|
||||
<DirectoryPanel v-else-if="view === 'directory'" class="min-h-0 flex-1" />
|
||||
|
||||
<!-- ===== 最近视图 ===== -->
|
||||
<RecentPanel v-else class="min-h-0 flex-1" />
|
||||
|
||||
<!--
|
||||
右边缘拖拽手柄:4px 宽、贴住整条右边框(比边框线好点中),hover / 拖动时高亮。
|
||||
拖动实时改宽,松手落盘 —— 与底部结果面板的高度拖拽同一套交互。
|
||||
-->
|
||||
<div
|
||||
class="absolute inset-y-0 right-0 z-10 w-1 cursor-col-resize touch-none select-none transition-colors duration-150 hover:bg-primary/30"
|
||||
:class="resizing && 'bg-primary/40'"
|
||||
title="拖动调整侧栏宽度"
|
||||
@pointerdown="onResizeStart"
|
||||
@pointermove="onResizeMove"
|
||||
@pointerup="onResizeEnd"
|
||||
@pointercancel="onResizeEnd"
|
||||
/>
|
||||
</aside>
|
||||
|
||||
<!-- 名称输入对话框 -->
|
||||
<Dialog :open="promptOpen" @update:open="promptOpen = $event">
|
||||
<DialogContent class="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ promptTitle }}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Input
|
||||
v-model="promptValue"
|
||||
:placeholder="promptMode === 'folder' ? '文件夹名称' : '名称'"
|
||||
@keydown.enter="confirmPrompt"
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" :disabled="busy" @click="promptOpen = false">取消</Button>
|
||||
<Button :disabled="busy" @click="confirmPrompt">确定</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- 删除确认 -->
|
||||
<ConfirmDialog
|
||||
v-model:open="confirmOpen"
|
||||
title="删除确认"
|
||||
variant="danger"
|
||||
confirm-text="删除"
|
||||
:description="
|
||||
deleteTarget?.isDir
|
||||
? `将删除文件夹「${deleteTarget?.name}」及其全部内容,此操作不可撤销。`
|
||||
: `将删除「${deleteTarget?.name}」,此操作不可撤销。`
|
||||
"
|
||||
@confirm="doDelete"
|
||||
/>
|
||||
|
||||
<!-- 新建笔记(名称 + 模板) -->
|
||||
<NewNoteDialog v-model:open="newNoteOpen" :dir-rel="selectedDir" @created="onCreated" />
|
||||
</template>
|
||||
@@ -0,0 +1,215 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 双链图谱(P5-4):把 `editor_link_graph` 的内部链接边画成力导向图。
|
||||
*
|
||||
* 布局是**一次性计算**(不跑动画):简化 Fruchterman-Reingold 迭代若干轮后
|
||||
* 归一化到 viewBox,再用静态 SVG 渲染。理由是图谱打开频率低、节点规模小,
|
||||
* 省掉 requestAnimationFrame 循环能让组件保持「无副作用」、易于推理。
|
||||
*
|
||||
* 点击节点 → 打开对应笔记。当前笔记节点高亮。
|
||||
*/
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { Loader2, Share2 } from '@lucide/vue'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
|
||||
const emit = defineEmits<{ open: [relPath: string] }>()
|
||||
|
||||
const store = useEditorStore()
|
||||
|
||||
/** 节点上限:超过则只画前 N 个(避免 O(n²) 迭代在大库上卡住主线程) */
|
||||
const NODE_LIMIT = 400
|
||||
const WIDTH = 520
|
||||
const HEIGHT = 520
|
||||
const PADDING = 24
|
||||
const ITERATIONS = 180
|
||||
|
||||
interface GNode {
|
||||
id: string
|
||||
label: string
|
||||
x: number
|
||||
y: number
|
||||
deg: number
|
||||
}
|
||||
interface GEdge {
|
||||
a: number
|
||||
b: number
|
||||
}
|
||||
|
||||
const layout = computed(() => {
|
||||
const index = new Map<string, number>()
|
||||
const nodes: GNode[] = []
|
||||
const addNode = (id: string): number => {
|
||||
const found = index.get(id)
|
||||
if (found !== undefined) return found
|
||||
if (nodes.length >= NODE_LIMIT) return -1
|
||||
const label = (id.split('/').pop() ?? id).replace(/\.md$/i, '')
|
||||
index.set(id, nodes.length)
|
||||
nodes.push({ id, label, x: 0, y: 0, deg: 0 })
|
||||
return nodes.length - 1
|
||||
}
|
||||
|
||||
const edges: GEdge[] = []
|
||||
for (const e of store.linkGraph) {
|
||||
const a = addNode(e.from)
|
||||
const b = addNode(e.to)
|
||||
if (a < 0 || b < 0) continue
|
||||
edges.push({ a, b })
|
||||
nodes[a]!.deg += 1
|
||||
nodes[b]!.deg += 1
|
||||
}
|
||||
if (!nodes.length) return { nodes: [], edges: [], truncated: false }
|
||||
|
||||
const n = nodes.length
|
||||
// 初始环形布局
|
||||
for (let i = 0; i < n; i++) {
|
||||
const angle = (i / n) * Math.PI * 2
|
||||
nodes[i]!.x = Math.cos(angle) * 200
|
||||
nodes[i]!.y = Math.sin(angle) * 200
|
||||
}
|
||||
|
||||
// 简化 FR:斥力 O(n²) + 沿边引力
|
||||
const k = Math.sqrt((400 * 400) / Math.max(n, 1))
|
||||
const temp0 = 80
|
||||
for (let it = 0; it < ITERATIONS; it++) {
|
||||
const temp = temp0 * (1 - it / ITERATIONS)
|
||||
const dx = new Float64Array(n)
|
||||
const dy = new Float64Array(n)
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
let vx = nodes[i]!.x - nodes[j]!.x
|
||||
let vy = nodes[i]!.y - nodes[j]!.y
|
||||
let d2 = vx * vx + vy * vy
|
||||
if (d2 < 0.01) {
|
||||
vx = 0.1 * (i - j) || 0.1
|
||||
vy = 0.1
|
||||
d2 = vx * vx + vy * vy
|
||||
}
|
||||
const d = Math.sqrt(d2)
|
||||
const f = (k * k) / d
|
||||
dx[i] += (vx / d) * f
|
||||
dy[i] += (vy / d) * f
|
||||
dx[j] -= (vx / d) * f
|
||||
dy[j] -= (vy / d) * f
|
||||
}
|
||||
}
|
||||
for (const e of edges) {
|
||||
const vx = nodes[e.a]!.x - nodes[e.b]!.x
|
||||
const vy = nodes[e.a]!.y - nodes[e.b]!.y
|
||||
const d = Math.max(Math.sqrt(vx * vx + vy * vy), 0.01)
|
||||
const f = (d * d) / k
|
||||
dx[e.a] -= (vx / d) * f
|
||||
dy[e.a] -= (vy / d) * f
|
||||
dx[e.b] += (vx / d) * f
|
||||
dy[e.b] += (vy / d) * f
|
||||
}
|
||||
for (let i = 0; i < n; i++) {
|
||||
const len = Math.max(Math.sqrt(dx[i]! * dx[i]! + dy[i]! * dy[i]!), 0.001)
|
||||
const step = Math.min(len, temp) / len
|
||||
nodes[i]!.x += dx[i]! * step
|
||||
nodes[i]!.y += dy[i]! * step
|
||||
}
|
||||
}
|
||||
|
||||
// 归一化到 viewBox(等比缩放 + 居中)
|
||||
let minX = Infinity
|
||||
let minY = Infinity
|
||||
let maxX = -Infinity
|
||||
let maxY = -Infinity
|
||||
for (const nd of nodes) {
|
||||
minX = Math.min(minX, nd.x)
|
||||
minY = Math.min(minY, nd.y)
|
||||
maxX = Math.max(maxX, nd.x)
|
||||
maxY = Math.max(maxY, nd.y)
|
||||
}
|
||||
const scale = Math.min(
|
||||
(WIDTH - PADDING * 2) / Math.max(maxX - minX, 1),
|
||||
(HEIGHT - PADDING * 2) / Math.max(maxY - minY, 1)
|
||||
)
|
||||
const ox = (WIDTH - (maxX - minX) * scale) / 2 - minX * scale
|
||||
const oy = (HEIGHT - (maxY - minY) * scale) / 2 - minY * scale
|
||||
|
||||
return {
|
||||
nodes: nodes.map(nd => ({ ...nd, x: nd.x * scale + ox, y: nd.y * scale + oy })),
|
||||
edges,
|
||||
truncated: store.linkGraph.length > 0 && nodes.length >= NODE_LIMIT
|
||||
}
|
||||
})
|
||||
|
||||
const radius = (deg: number): number => Math.min(3 + deg * 1.2, 9)
|
||||
const showLabels = computed(() => layout.value.nodes.length <= 60)
|
||||
const isCurrent = (id: string): boolean => store.currentRelPath === id
|
||||
|
||||
onMounted(() => {
|
||||
void store.loadLinkGraph()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="flex h-6 shrink-0 items-center gap-1.5 border-b border-border px-2 text-[11px] text-muted-foreground">
|
||||
<Share2 class="size-3" />
|
||||
<span>双链图谱</span>
|
||||
<span class="ml-auto tabular-nums">{{ layout.nodes.length }} 节点 · {{ layout.edges.length }} 边</span>
|
||||
</div>
|
||||
|
||||
<div v-if="store.loadingGraph && !layout.nodes.length" class="flex items-center justify-center gap-2 p-4">
|
||||
<Loader2 class="size-3.5 animate-spin text-muted-foreground" />
|
||||
<span class="text-xs text-muted-foreground">正在构建图谱…</span>
|
||||
</div>
|
||||
|
||||
<StateBlock
|
||||
v-else-if="!layout.nodes.length"
|
||||
variant="empty"
|
||||
title="还没有双链"
|
||||
description="在笔记里写 [[另一篇]] 建立链接,图谱会显示它们的关系"
|
||||
:min-height="140"
|
||||
/>
|
||||
|
||||
<ScrollArea v-else class="min-h-0 flex-1">
|
||||
<div class="px-1.5 py-2">
|
||||
<svg :viewBox="`0 0 ${WIDTH} ${HEIGHT}`" class="w-full select-none">
|
||||
<line
|
||||
v-for="(edge, i) in layout.edges"
|
||||
:key="`e${i}`"
|
||||
:x1="layout.nodes[edge.a]?.x"
|
||||
:y1="layout.nodes[edge.a]?.y"
|
||||
:x2="layout.nodes[edge.b]?.x"
|
||||
:y2="layout.nodes[edge.b]?.y"
|
||||
class="stroke-border"
|
||||
stroke-width="1"
|
||||
/>
|
||||
<g
|
||||
v-for="node in layout.nodes"
|
||||
:key="node.id"
|
||||
class="cursor-pointer"
|
||||
@click="emit('open', node.id)"
|
||||
>
|
||||
<title>{{ node.id }}</title>
|
||||
<circle
|
||||
:cx="node.x"
|
||||
:cy="node.y"
|
||||
:r="radius(node.deg)"
|
||||
:class="isCurrent(node.id) ? 'fill-primary' : 'fill-muted-foreground'"
|
||||
/>
|
||||
<text
|
||||
v-if="showLabels"
|
||||
:x="node.x"
|
||||
:y="node.y - radius(node.deg) - 2"
|
||||
text-anchor="middle"
|
||||
class="fill-foreground"
|
||||
font-size="9"
|
||||
>
|
||||
{{ node.label }}
|
||||
</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
<p v-if="layout.truncated" class="px-1 pt-1 text-[11px] text-muted-foreground">
|
||||
节点较多,仅显示前 {{ NODE_LIMIT }} 个。
|
||||
</p>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,84 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 笔记大纲(标题树)。
|
||||
*
|
||||
* 结构与渲染分离:标题提取是纯函数 `extractOutline`(可单测,见 `editor/outline.ts`),
|
||||
* 本组件只负责「层级缩进 + 当前标题高亮 + 点击跳转」。
|
||||
*
|
||||
* # 当前标题怎么算
|
||||
*
|
||||
* 用编辑器的光标行号(由 `EditorWindow` 通过 props 传入)与标题行号比较,取
|
||||
* 「最后一个行号 ≤ 光标行」的标题。**不用滚动位置**:Live Preview 下装饰会让
|
||||
* 每行高度不一致,按像素反推当前标题很容易差一行,而光标位置是精确的。
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
import { Hash, ListTree } from '@lucide/vue'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 编辑器当前光标所在行(1 起;0 = 未知) */
|
||||
cursorLine: number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ jump: [from: number] }>()
|
||||
|
||||
const store = useEditorStore()
|
||||
|
||||
/** 最浅一级标题的层级(让缩进从 0 开始,而不是每篇都从 h2 缩进一档) */
|
||||
const minLevel = computed(() =>
|
||||
store.outline.reduce((min, item) => Math.min(min, item.level), 6)
|
||||
)
|
||||
|
||||
const currentIndex = computed(() => {
|
||||
if (!props.cursorLine) return -1
|
||||
let found = -1
|
||||
for (let index = 0; index < store.outline.length; index++) {
|
||||
const heading = store.outline[index]
|
||||
if (heading && heading.line <= props.cursorLine) found = index
|
||||
else break
|
||||
}
|
||||
return found
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="flex h-6 shrink-0 items-center gap-1.5 border-b border-border px-2 text-[11px] text-muted-foreground">
|
||||
<ListTree class="size-3" />
|
||||
<span>大纲</span>
|
||||
<span class="ml-auto tabular-nums">{{ store.outline.length }} 个标题</span>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-1.5 py-2">
|
||||
<StateBlock
|
||||
v-if="!store.outline.length"
|
||||
variant="empty"
|
||||
title="还没有标题"
|
||||
description="用 # 开头写一行标题,这里会自动生成大纲"
|
||||
:min-height="120"
|
||||
/>
|
||||
<button
|
||||
v-for="(heading, index) in store.outline"
|
||||
:key="`${heading.line}-${heading.from}`"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-1 rounded-sm py-1 pr-1 text-left text-xs transition-colors duration-150"
|
||||
:class="
|
||||
index === currentIndex
|
||||
? 'bg-row-selected text-primary-soft-text'
|
||||
: 'text-fg-secondary hover:bg-row-hover hover:text-foreground'
|
||||
"
|
||||
:style="{ paddingLeft: `${(heading.level - minLevel) * 12 + 6}px` }"
|
||||
@click="emit('jump', heading.from)"
|
||||
>
|
||||
<Hash class="size-3 shrink-0 opacity-60" />
|
||||
<span class="truncate" :class="heading.level <= 2 ? 'font-medium' : ''">
|
||||
{{ heading.text || '(空标题)' }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,136 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 新建笔记对话框(名称 + 模板)。
|
||||
*
|
||||
* # 为什么把模板选择放进「新建」而不是设置页
|
||||
*
|
||||
* 模板是**每次新建时的决策**(今天写日记、明天写会议纪要),把它藏在设置里意味着
|
||||
* 用户得先改设置再新建、改两次。这里做成对话框里的一个下拉:默认选中上次用过的那个,
|
||||
* 一路回车就能建。
|
||||
*
|
||||
* # 名称即标题
|
||||
*
|
||||
* 输入的名称同时作为文件名与 front-matter 里的 `title`。不额外要一个「标题」字段:
|
||||
* 「文件名和标题不一样」在文件即真相的模型里只会带来困惑(重命名文件后标题不同步)。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { NotebookPen } from '@lucide/vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
/** 新建目标目录(库内相对路径,空串 = 库根) */
|
||||
dirRel: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
created: [relPath: string]
|
||||
}>()
|
||||
|
||||
const store = useEditorStore()
|
||||
const name = ref('')
|
||||
const templateId = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
const dirLabel = computed(() => props.dirRel || '库根')
|
||||
|
||||
/** 默认选中:上次用过的模板 → 空白笔记 → 第一个可用模板 */
|
||||
function pickDefaultTemplate(): void {
|
||||
if (templateId.value) return
|
||||
if (store.lastTemplateId && store.templates.some(t => t.id === store.lastTemplateId)) {
|
||||
templateId.value = store.lastTemplateId
|
||||
return
|
||||
}
|
||||
const blank = store.templates.find(t => t.name === '空白笔记')
|
||||
templateId.value = blank?.id ?? store.templates[0]?.id ?? ''
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async open => {
|
||||
if (!open) return
|
||||
name.value = ''
|
||||
busy.value = false
|
||||
if (!store.templates.length) await store.loadTemplates()
|
||||
pickDefaultTemplate()
|
||||
}
|
||||
)
|
||||
|
||||
async function confirm(): Promise<void> {
|
||||
const title = name.value.trim()
|
||||
if (!title) return
|
||||
busy.value = true
|
||||
try {
|
||||
await store.createNote(props.dirRel, title, templateId.value || undefined)
|
||||
emit('created', store.currentRelPath)
|
||||
emit('update:open', false)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="open" @update:open="emit('update:open', $event)">
|
||||
<DialogContent class="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>新建笔记</DialogTitle>
|
||||
<DialogDescription>
|
||||
目标目录:{{ dirLabel }} · 名称同时作为文件名与 front-matter 的 title
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="flex flex-col gap-3">
|
||||
<Input
|
||||
v-model="name"
|
||||
placeholder="笔记名称"
|
||||
autofocus
|
||||
@keydown.enter="confirm"
|
||||
/>
|
||||
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<span class="text-xs text-muted-foreground">模板</span>
|
||||
<Select v-model="templateId">
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="item in store.templates" :key="item.id" :value="item.id">
|
||||
{{ item.name }}{{ item.builtin ? '(内置)' : '' }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span
|
||||
v-if="store.templates.find(t => t.id === templateId)?.description"
|
||||
class="line-clamp-2 text-[11px] text-muted-foreground"
|
||||
>
|
||||
{{ store.templates.find(t => t.id === templateId)?.description }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" :disabled="busy" @click="emit('update:open', false)">取消</Button>
|
||||
<Button :disabled="busy || !name.trim()" @click="confirm">
|
||||
<NotebookPen class="size-3.5" />新建
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,185 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 快速打开(`Ctrl+P`):库内文件跳转,类 VS Code。
|
||||
*
|
||||
* # 为什么在本地过滤而不是每次都查后端
|
||||
*
|
||||
* 库内笔记清单在打开面板时一次性取回(上限 1000 条,`editor_list_notes`),
|
||||
* 之后的每一次按键都只是对这份内存清单做子串匹配。这样输入零延迟 —— 而「按关键词
|
||||
* 找文件」本来就是模糊匹配,走 FTS5 反而会因为分词器把文件名切碎而给出意外结果
|
||||
* (FTS 是给正文用的)。
|
||||
*
|
||||
* # 排序:连续匹配 > 前缀 > 词首 > 位置靠前
|
||||
*
|
||||
* 单纯按「是否包含」排序会让 `笔记.md` 与 `我的笔记归档.md` 并列,用户真正想找的
|
||||
* 通常是名字更短、匹配更靠前的那个。这里用一个小的评分函数把「匹配质量」显式化,
|
||||
* 而不是依赖清单的顺序。
|
||||
*/
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { CornerDownLeft, FileText, Search } from '@lucide/vue'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import type { NoteSearchHit } from '@/types/editor'
|
||||
|
||||
const props = defineProps<{ open: boolean }>()
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
select: [relPath: string]
|
||||
}>()
|
||||
|
||||
const store = useEditorStore()
|
||||
const keyword = ref('')
|
||||
const active = ref(0)
|
||||
const panelRef = ref<HTMLDivElement | null>(null)
|
||||
|
||||
/** 输入框聚焦:`Input` 是对 reka-ui 的包装,不保证暴露内部 `<input>`,直接查 DOM。 */
|
||||
async function focusInput(): Promise<void> {
|
||||
await nextTick()
|
||||
panelRef.value?.querySelector('input')?.focus()
|
||||
}
|
||||
|
||||
/** 匹配质量评分(越小越靠前)。 */
|
||||
function score(hit: NoteSearchHit, needle: string): number {
|
||||
const title = hit.title.toLowerCase()
|
||||
const path = hit.relPath.toLowerCase()
|
||||
const at = title.indexOf(needle)
|
||||
if (at === 0) return 0
|
||||
if (at > 0) return 1
|
||||
if (path.includes(`/${needle}`)) return 2
|
||||
if (path.includes(needle)) return 3
|
||||
return 99
|
||||
}
|
||||
|
||||
const results = computed<NoteSearchHit[]>(() => {
|
||||
const needle = keyword.value.trim().toLowerCase()
|
||||
if (!needle) return store.quickOpenList.slice(0, 200)
|
||||
return store.quickOpenList
|
||||
.map(hit => ({ hit, rank: score(hit, needle) }))
|
||||
.filter(item => item.rank < 99)
|
||||
.sort((a, b) => a.rank - b.rank || b.hit.modified - a.hit.modified)
|
||||
.slice(0, 200)
|
||||
.map(item => item.hit)
|
||||
})
|
||||
|
||||
/** 标题里命中关键词的位置(渲染高亮用)。 */
|
||||
function titleParts(hit: NoteSearchHit): Array<{ text: string; hit: boolean }> {
|
||||
const needle = keyword.value.trim().toLowerCase()
|
||||
if (!needle) return [{ text: hit.title, hit: false }]
|
||||
const at = hit.title.toLowerCase().indexOf(needle)
|
||||
if (at < 0) return [{ text: hit.title, hit: false }]
|
||||
return [
|
||||
{ text: hit.title.slice(0, at), hit: false },
|
||||
{ text: hit.title.slice(at, at + needle.length), hit: true },
|
||||
{ text: hit.title.slice(at + needle.length), hit: false }
|
||||
].filter(part => part.text.length > 0)
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
emit('update:open', false)
|
||||
}
|
||||
|
||||
function choose(hit: NoteSearchHit | undefined): void {
|
||||
if (!hit) return
|
||||
emit('select', hit.relPath)
|
||||
close()
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === 'ArrowDown') {
|
||||
event.preventDefault()
|
||||
active.value = Math.min(active.value + 1, results.value.length - 1)
|
||||
} else if (event.key === 'ArrowUp') {
|
||||
event.preventDefault()
|
||||
active.value = Math.max(active.value - 1, 0)
|
||||
} else if (event.key === 'Enter') {
|
||||
event.preventDefault()
|
||||
choose(results.value[active.value])
|
||||
} else if (event.key === 'Escape') {
|
||||
event.preventDefault()
|
||||
close()
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async open => {
|
||||
if (!open) return
|
||||
keyword.value = ''
|
||||
active.value = 0
|
||||
await store.loadQuickOpen()
|
||||
await focusInput()
|
||||
}
|
||||
)
|
||||
|
||||
watch(keyword, () => {
|
||||
active.value = 0
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Transition
|
||||
enter-active-class="transition-opacity duration-150"
|
||||
leave-active-class="transition-opacity duration-150"
|
||||
enter-from-class="opacity-0"
|
||||
leave-to-class="opacity-0"
|
||||
>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-start justify-center bg-black/40 pt-[12vh]"
|
||||
@click.self="close"
|
||||
>
|
||||
<div
|
||||
ref="panelRef"
|
||||
class="flex max-h-[60vh] w-[min(560px,92vw)] flex-col overflow-hidden rounded-lg border border-border bg-popover text-popover-foreground shadow-lg"
|
||||
@keydown="onKeydown"
|
||||
>
|
||||
<div class="relative shrink-0 border-b border-border p-2">
|
||||
<Search class="absolute top-1/2 left-4 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
v-model="keyword"
|
||||
placeholder="按名称跳转到笔记…"
|
||||
class="h-8 border-0 bg-transparent pl-7 text-[13px] shadow-none focus-visible:ring-0"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="p-1">
|
||||
<StateBlock
|
||||
v-if="!results.length"
|
||||
variant="empty"
|
||||
title="没有匹配的笔记"
|
||||
:min-height="100"
|
||||
/>
|
||||
<button
|
||||
v-for="(hit, index) in results"
|
||||
:key="hit.relPath"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left"
|
||||
:class="index === active ? 'bg-row-selected text-primary-soft-text' : 'hover:bg-row-hover'"
|
||||
@mouseenter="active = index"
|
||||
@click="choose(hit)"
|
||||
>
|
||||
<FileText class="size-3.5 shrink-0 opacity-70" />
|
||||
<span class="min-w-0 flex-1 truncate text-xs">
|
||||
<template v-for="(part, partIndex) in titleParts(hit)" :key="partIndex">
|
||||
<mark v-if="part.hit" class="rounded-xs bg-primary-soft px-0.5 text-primary-soft-text">{{ part.text }}</mark>
|
||||
<template v-else>{{ part.text }}</template>
|
||||
</template>
|
||||
</span>
|
||||
<span class="max-w-[45%] shrink-0 truncate text-[10px] text-fg-disabled">{{ hit.relPath }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<div class="flex h-7 shrink-0 items-center gap-3 border-t border-border px-3 text-[10px] text-muted-foreground">
|
||||
<span class="flex items-center gap-1"><CornerDownLeft class="size-3" />打开</span>
|
||||
<span>↑↓ 选择</span>
|
||||
<span>Esc 关闭</span>
|
||||
<span class="ml-auto tabular-nums">{{ results.length }} / {{ store.quickOpenList.length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</template>
|
||||
@@ -0,0 +1,159 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 最近记录面板(P3-6):最近文件 + 最近文件夹两份列表。
|
||||
*
|
||||
* 「文件」与「文件夹」**分开存**(`settings.json` 的 `recentFiles` / `recentFolders`):
|
||||
* 两者用途不同(打开文档 vs 打开目录),混在一起会让「最近文件夹」被文件挤掉。
|
||||
* 记录与笔记库解耦 —— 库可以换 / 删,历史不该跟着丢。
|
||||
*
|
||||
* 失效项(路径已不存在)灰显但仍可点击清理由此产生的困惑:点击会给出明确失败提示,
|
||||
* 而不是静默什么都不做。
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
import { ExternalLink, FileText, Folder, History } from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useEditorStore } from '@/stores/editorStore'
|
||||
import type { RecentEntry } from '@/types/editor'
|
||||
|
||||
const store = useEditorStore()
|
||||
|
||||
const files = computed(() => store.recentFiles)
|
||||
const folders = computed(() => store.recentFolders)
|
||||
|
||||
/** 取所在目录(同时兼容 `\` 与 `/`)。 */
|
||||
function parentDir(fullPath: string): string {
|
||||
const index = Math.max(fullPath.lastIndexOf('\\'), fullPath.lastIndexOf('/'))
|
||||
return index > 0 ? fullPath.slice(0, index) : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 路径尾部摘要:只保留末尾若干字符并前置省略号(例:`...ways\Downloads`)。
|
||||
*
|
||||
* 做「一眼看出在哪儿」的提示,完整路径仍由行的 `title` 提供。短路径整段显示,
|
||||
* 长路径保留末尾 14 个字符 —— 前面的盘符与中间层级对辨认位置帮助不大,省略它们
|
||||
* 反而让列表更整齐。目录项与文件项都取**所在目录**,名字里已经有的末级不再重复。
|
||||
*/
|
||||
function pathTail(fullPath: string): string {
|
||||
const dir = parentDir(fullPath).replace(/\//g, '\\')
|
||||
if (!dir) return ''
|
||||
return dir.length <= 18 ? dir : `...${dir.slice(-14)}`
|
||||
}
|
||||
|
||||
async function openFile(entry: RecentEntry): Promise<void> {
|
||||
try {
|
||||
await store.openDoc(entry.path)
|
||||
} catch (e) {
|
||||
toast.error(`打开失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个「最近文件夹」:读目录 + **切到侧栏的「目录」视图**。
|
||||
*
|
||||
* 只 `openFolder` 是不够的 —— 它只把 `dirListing` 读进 store,而侧栏还停在「最近」页,
|
||||
* 于是用户点了一下什么都「没发生」(同一个列表还在那儿)。切视图才是点击应有的反馈:
|
||||
* 跳到本地文件夹侧栏,直接看到这棵目录树。
|
||||
*
|
||||
* 先 await 再切:目录列举是异步的,提前切会先渲染一帧空态。
|
||||
*/
|
||||
async function openFolder(entry: RecentEntry): Promise<void> {
|
||||
try {
|
||||
await store.openFolder(entry.path)
|
||||
store.setSideView('directory')
|
||||
} catch (e) {
|
||||
toast.error(`打开文件夹失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<StateBlock
|
||||
v-if="!files.length && !folders.length"
|
||||
variant="empty"
|
||||
title="还没有最近记录"
|
||||
description="打开过的文件与文件夹会出现在这里"
|
||||
:min-height="160"
|
||||
/>
|
||||
|
||||
<ScrollArea v-else class="min-h-0 flex-1">
|
||||
<div class="px-1.5 py-2">
|
||||
<!-- 最近文件 -->
|
||||
<div v-if="files.length" class="mb-2">
|
||||
<div class="flex h-6 items-center gap-1.5 px-1.5 text-[11px] font-medium text-muted-foreground">
|
||||
<FileText class="size-3" />
|
||||
<span>最近文件</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-auto text-muted-foreground hover:text-foreground"
|
||||
@click="store.clearRecentFiles()"
|
||||
>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-for="entry in files"
|
||||
:key="entry.path"
|
||||
class="group flex h-7 w-full cursor-pointer items-center gap-1.5 rounded-sm px-1.5 text-left text-xs transition-colors duration-150 hover:bg-row-hover"
|
||||
:class="entry.exists ? 'text-fg-secondary hover:text-foreground' : 'text-fg-disabled'"
|
||||
:title="entry.path"
|
||||
@click="openFile(entry)"
|
||||
>
|
||||
<FileText class="size-3.5 shrink-0 opacity-70" />
|
||||
<span class="truncate">
|
||||
{{ entry.name }}<span v-if="pathTail(entry.path)" class="text-muted-foreground">({{ pathTail(entry.path) }})</span>
|
||||
</span>
|
||||
<span v-if="!entry.exists" class="shrink-0 text-[10px]">(已失效)</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-auto rounded-sm p-0.5 opacity-0 group-hover:opacity-100 hover:bg-active"
|
||||
title="在资源管理器中显示"
|
||||
@click.stop="store.revealPath(entry.path)"
|
||||
>
|
||||
<ExternalLink class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 最近文件夹 -->
|
||||
<div v-if="folders.length">
|
||||
<div class="flex h-6 items-center gap-1.5 px-1.5 text-[11px] font-medium text-muted-foreground">
|
||||
<Folder class="size-3" />
|
||||
<span>最近文件夹</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-auto text-muted-foreground hover:text-foreground"
|
||||
@click="store.clearRecentFolders()"
|
||||
>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-for="entry in folders"
|
||||
:key="entry.path"
|
||||
class="group flex h-7 w-full cursor-pointer items-center gap-1.5 rounded-sm px-1.5 text-left text-xs transition-colors duration-150 hover:bg-row-hover"
|
||||
:class="entry.exists ? 'text-fg-secondary hover:text-foreground' : 'text-fg-disabled'"
|
||||
:title="entry.path"
|
||||
@click="openFolder(entry)"
|
||||
>
|
||||
<History class="size-3.5 shrink-0 opacity-70" />
|
||||
<span class="truncate">
|
||||
{{ entry.name }}<span v-if="pathTail(entry.path)" class="text-muted-foreground">({{ pathTail(entry.path) }})</span>
|
||||
</span>
|
||||
<span v-if="!entry.exists" class="shrink-0 text-[10px]">(已失效)</span>
|
||||
<button
|
||||
type="button"
|
||||
class="ml-auto rounded-sm p-0.5 opacity-0 group-hover:opacity-100 hover:bg-active"
|
||||
title="在资源管理器中显示"
|
||||
@click.stop="store.revealPath(entry.path)"
|
||||
>
|
||||
<ExternalLink class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user