diff --git a/bun.lock b/bun.lock index 0404974..d12d128 100644 --- a/bun.lock +++ b/bun.lock @@ -8,12 +8,18 @@ "@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", @@ -26,9 +32,11 @@ "@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.12.0", - "@tauri-apps/plugin-autostart": "^2.6.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", @@ -43,6 +51,8 @@ "@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", @@ -293,6 +303,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=="], @@ -551,6 +565,10 @@ "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=="], @@ -677,6 +695,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=="], diff --git a/doc/EDITOR_MODULE_PLAN.md b/doc/EDITOR_MODULE_PLAN.md index 0839768..d013fce 100644 --- a/doc/EDITOR_MODULE_PLAN.md +++ b/doc/EDITOR_MODULE_PLAN.md @@ -74,7 +74,7 @@ ### 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/源码。 diff --git a/package-lock.json b/package-lock.json index 0dbd12a..218c879 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,20 +1,49 @@ { "name": "thing", - "version": "26.9.4", + "version": "26.9.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "thing", - "version": "26.9.4", + "version": "26.9.5", "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/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", @@ -25,6 +54,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", @@ -36,7 +70,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", @@ -111,6 +146,426 @@ "keyv": "^5.6.0" } }, + "node_modules/@codemirror/autocomplete": { + "version": "6.20.3", + "resolved": "https://registry.npmmirror.com/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz", + "integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.17.0", + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@codemirror/commands": { + "version": "6.11.1", + "resolved": "https://registry.npmmirror.com/@codemirror/commands/-/commands-6.11.1.tgz", + "integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.7.0", + "@codemirror/view": "^6.27.0", + "@lezer/common": "^1.1.0" + } + }, + "node_modules/@codemirror/lang-angular": { + "version": "0.1.4", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-angular/-/lang-angular-0.1.4.tgz", + "integrity": "sha512-oap+gsltb/fzdlTQWD6BFF4bSLKcDnlxDsLdePiJpCVNKWXSTAbiiQeYI3UmES+BLAdkmIC1WjyztC1pi/bX4g==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-cpp": { + "version": "6.0.3", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-cpp/-/lang-cpp-6.0.3.tgz", + "integrity": "sha512-URM26M3vunFFn9/sm6rzqrBzDgfWuDixp85uTY49wKudToc2jTHUrKIGGKs+QWND+YLofNNZpxcNGRynFJfvgA==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@lezer/cpp": "^1.0.0" + } + }, + "node_modules/@codemirror/lang-css": { + "version": "6.3.1", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-css/-/lang-css-6.3.1.tgz", + "integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-go": { + "version": "6.0.1", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-go/-/lang-go-6.0.1.tgz", + "integrity": "sha512-7fNvbyNylvqCphW9HD6WFnRpcDjr+KXX/FgqXy5H5ZS0eC5edDljukm/yNgYkwTsgp2busdod50AOTIy6Jikfg==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-html": { + "version": "6.4.12", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-html/-/lang-html-6.4.12.tgz", + "integrity": "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-java": { + "version": "6.0.2", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-java/-/lang-java-6.0.2.tgz", + "integrity": "sha512-m5Nt1mQ/cznJY7tMfQTJchmrjdjQ71IDs+55d1GAa8DGaB8JXWsVCkVT284C3RTASaY43YknrK2X3hPO/J3MOQ==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@lezer/java": "^1.0.0" + } + }, + "node_modules/@codemirror/lang-javascript": { + "version": "6.2.5", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz", + "integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-jinja": { + "version": "6.0.1", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-jinja/-/lang-jinja-6.0.1.tgz", + "integrity": "sha512-P5kyHLObzjtbGj16h+hyvZTxJhSjBEeSx4wMjbnAf3b0uwTy2+F0zGjMZL4PQOm/mh2eGZ5xUDVZXgwP783Nsw==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-json": { + "version": "6.0.2", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-json/-/lang-json-6.0.2.tgz", + "integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@lezer/json": "^1.0.0" + } + }, + "node_modules/@codemirror/lang-less": { + "version": "6.0.2", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-less/-/lang-less-6.0.2.tgz", + "integrity": "sha512-EYdQTG22V+KUUk8Qq582g7FMnCZeEHsyuOJisHRft/mQ+ZSZ2w51NupvDUHiqtsOy7It5cHLPGfHQLpMh9bqpQ==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-liquid": { + "version": "6.3.3", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-liquid/-/lang-liquid-6.3.3.tgz", + "integrity": "sha512-U9EnyzWuAx1TX3MZSKDXydKH734n1Aogk/ijKdW+jdIwmbf9zSPQYOIKggC/b2PTRjQb7ddvMktmxnfTLuv/SQ==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-markdown": { + "version": "6.5.2", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-markdown/-/lang-markdown-6.5.2.tgz", + "integrity": "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-php": { + "version": "6.0.2", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-php/-/lang-php-6.0.2.tgz", + "integrity": "sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-python": { + "version": "6.2.1", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-python/-/lang-python-6.2.1.tgz", + "integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-rust": { + "version": "6.0.2", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-rust/-/lang-rust-6.0.2.tgz", + "integrity": "sha512-EZaGjCUegtiU7kSMvOfEZpaCReowEf3yNidYu7+vfuGTm9ow4mthAparY5hisJqOHmJowVH3Upu+eJlUji6qqA==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@lezer/rust": "^1.0.0" + } + }, + "node_modules/@codemirror/lang-sass": { + "version": "6.0.2", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-sass/-/lang-sass-6.0.2.tgz", + "integrity": "sha512-l/bdzIABvnTo1nzdY6U+kPAC51czYQcOErfzQ9zSm9D8GmNPD0WTW8st/CJwBTPLO8jlrbyvlSEcN20dc4iL0Q==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-sql": { + "version": "6.10.0", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz", + "integrity": "sha512-6ayPkEd/yRw0XKBx5uAiToSgGECo/GY2NoJIHXIIQh1EVwLuKoU8BP/qK0qH5NLXAbtJRLuT73hx7P9X34iO4w==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-vue": { + "version": "0.1.3", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-vue/-/lang-vue-0.1.3.tgz", + "integrity": "sha512-QSKdtYTDRhEHCfo5zOShzxCmqKJvgGrZwDQSdbvCRJ5pRLWBS7pD/8e/tH44aVQT6FKm0t6RVNoSUWHOI5vNug==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-wast": { + "version": "6.0.2", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-wast/-/lang-wast-6.0.2.tgz", + "integrity": "sha512-Imi2KTpVGm7TKuUkqyJ5NRmeFWF7aMpNiwHnLQe0x9kmrxElndyH0K6H/gXtWwY6UshMRAhpENsgfpSwsgmC6Q==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@codemirror/lang-xml": { + "version": "6.1.0", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-xml/-/lang-xml-6.1.0.tgz", + "integrity": "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/lang-yaml": { + "version": "6.1.3", + "resolved": "https://registry.npmmirror.com/@codemirror/lang-yaml/-/lang-yaml-6.1.3.tgz", + "integrity": "sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/language": { + "version": "6.13.1", + "resolved": "https://registry.npmmirror.com/@codemirror/language/-/language-6.13.1.tgz", + "integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/streamparser": "^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" + } + }, + "node_modules/@codemirror/language-data": { + "version": "6.5.2", + "resolved": "https://registry.npmmirror.com/@codemirror/language-data/-/language-data-6.5.2.tgz", + "integrity": "sha512-CPkWBKrNS8stYbEU5kwBwTf3JB1kghlbh4FSAwzGW2TEscdeHHH4FGysREW86Mqnj3Qn09s0/6Ea/TutmoTobg==", + "license": "MIT", + "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" + } + }, + "node_modules/@codemirror/legacy-modes": { + "version": "6.5.5", + "resolved": "https://registry.npmmirror.com/@codemirror/legacy-modes/-/legacy-modes-6.5.5.tgz", + "integrity": "sha512-9ltT214oMb3Y1w5eAZMSigzrjzZnMI2Wa3Feq73rU/i4C56MkwrpfswfQYOr28C5pXr6dWwspNTMyeHXlzWMxg==", + "license": "MIT", + "dependencies": { + "@codemirror/streamparser": "^6.0.0" + } + }, + "node_modules/@codemirror/lint": { + "version": "6.9.7", + "resolved": "https://registry.npmmirror.com/@codemirror/lint/-/lint-6.9.7.tgz", + "integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.42.0", + "crelt": "^1.0.5" + } + }, + "node_modules/@codemirror/search": { + "version": "6.7.2", + "resolved": "https://registry.npmmirror.com/@codemirror/search/-/search-6.7.2.tgz", + "integrity": "sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.37.0", + "crelt": "^1.0.5" + } + }, + "node_modules/@codemirror/state": { + "version": "6.7.6", + "resolved": "https://registry.npmmirror.com/@codemirror/state/-/state-6.7.6.tgz", + "integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==", + "license": "MIT", + "dependencies": { + "@marijn/find-cluster-break": "^1.0.0" + } + }, + "node_modules/@codemirror/streamparser": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/@codemirror/streamparser/-/streamparser-6.0.0.tgz", + "integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==", + "license": "MIT" + }, + "node_modules/@codemirror/theme-one-dark": { + "version": "6.1.3", + "resolved": "https://registry.npmmirror.com/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz", + "integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "@lezer/highlight": "^1.0.0" + } + }, + "node_modules/@codemirror/view": { + "version": "6.43.14", + "resolved": "https://registry.npmmirror.com/@codemirror/view/-/view-6.43.14.tgz", + "integrity": "sha512-hC45YnmJNR1rz42OF57BLoQNFMV12/13drnvibDsR2quNDmldcb4WvYVV81hFQg56i9lcqQMEDqilhX2QDcGQQ==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.7.0", + "crelt": "^1.0.6", + "style-mod": "^4.1.0", + "w3c-keyname": "^2.2.4" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.12", "resolved": "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", @@ -863,6 +1318,183 @@ "dev": true, "license": "MIT" }, + "node_modules/@lezer/common": { + "version": "1.5.3", + "resolved": "https://registry.npmmirror.com/@lezer/common/-/common-1.5.3.tgz", + "integrity": "sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==", + "license": "MIT" + }, + "node_modules/@lezer/cpp": { + "version": "1.1.6", + "resolved": "https://registry.npmmirror.com/@lezer/cpp/-/cpp-1.1.6.tgz", + "integrity": "sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@lezer/css": { + "version": "1.3.9", + "resolved": "https://registry.npmmirror.com/@lezer/css/-/css-1.3.9.tgz", + "integrity": "sha512-ZmzgvTOBdJWGIsY/ItAfN7UW8DV802oZG+jeG6E508SwEzz5YhuAajptpWPICvIyqYAD2+VjMdOS40GgGkyEOQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.3.0" + } + }, + "node_modules/@lezer/go": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/@lezer/go/-/go-1.0.1.tgz", + "integrity": "sha512-xToRsYxwsgJNHTgNdStpcvmbVuKxTapV0dM0wey1geMMRc9aggoVyKgzYp41D2/vVOx+Ii4hmE206kvxIXBVXQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.3.0" + } + }, + "node_modules/@lezer/highlight": { + "version": "1.2.5", + "resolved": "https://registry.npmmirror.com/@lezer/highlight/-/highlight-1.2.5.tgz", + "integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.3.0" + } + }, + "node_modules/@lezer/html": { + "version": "1.3.13", + "resolved": "https://registry.npmmirror.com/@lezer/html/-/html-1.3.13.tgz", + "integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@lezer/java": { + "version": "1.1.5", + "resolved": "https://registry.npmmirror.com/@lezer/java/-/java-1.1.5.tgz", + "integrity": "sha512-JppTd1iKHpeNlLYw/Zl8JX7zSY5HqAzK4zZ05lpn8l8Sk7Fo5KAKiDiMiezKoT5lfeC2xZf8HeKp1tSctj4G6Q==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@lezer/javascript": { + "version": "1.5.6", + "resolved": "https://registry.npmmirror.com/@lezer/javascript/-/javascript-1.5.6.tgz", + "integrity": "sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.1.3", + "@lezer/lr": "^1.3.0" + } + }, + "node_modules/@lezer/json": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/@lezer/json/-/json-1.0.3.tgz", + "integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@lezer/lr": { + "version": "1.4.11", + "resolved": "https://registry.npmmirror.com/@lezer/lr/-/lr-1.4.11.tgz", + "integrity": "sha512-UwgZcl1R66H2hDzBrA7kWyYmX6s8p5TQ+e/t7CuvgCtBEPxbEPaHYHu+pJBvTvDotEJpuQkJjbXuHiw5Cixxgw==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@lezer/markdown": { + "version": "1.8.0", + "resolved": "https://registry.npmmirror.com/@lezer/markdown/-/markdown-1.8.0.tgz", + "integrity": "sha512-X6w3A2NpyhdtGqTWRJB8gR4QDXBaFMbTOs780ZdZ15KKCfBXOQTKcB3Vr+W6tqJHVlealt53tLmHRvOqPTQgYA==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.5.0", + "@lezer/highlight": "^1.0.0" + } + }, + "node_modules/@lezer/php": { + "version": "1.0.6", + "resolved": "https://registry.npmmirror.com/@lezer/php/-/php-1.0.6.tgz", + "integrity": "sha512-QJ2xNXPmsm/Z3IpThq8fnJrEIVpxhsIoj6GZBW0JYEd/l9zxpJZW216X4fzqQY4vgpdGIumypvI4uQjd4tnYtw==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.1.0" + } + }, + "node_modules/@lezer/python": { + "version": "1.1.19", + "resolved": "https://registry.npmmirror.com/@lezer/python/-/python-1.1.19.tgz", + "integrity": "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@lezer/rust": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/@lezer/rust/-/rust-1.0.3.tgz", + "integrity": "sha512-XxErOjZzQ7yJt1agUT4fu9qQvESZ3acgoxpPaPTPOiUx+duCjaVAtZGFIgphkHxlN05djdVAIOy/wItShMEjqQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@lezer/sass": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/@lezer/sass/-/sass-1.1.0.tgz", + "integrity": "sha512-3mMGdCTUZ/84ArHOuXWQr37pnf7f+Nw9ycPUeKX+wu19b7pSMcZGLbaXwvD2APMBDOGxPmpK/O6S1v1EvLoqgQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@lezer/xml": { + "version": "1.0.6", + "resolved": "https://registry.npmmirror.com/@lezer/xml/-/xml-1.0.6.tgz", + "integrity": "sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@lezer/yaml": { + "version": "1.0.4", + "resolved": "https://registry.npmmirror.com/@lezer/yaml/-/yaml-1.0.4.tgz", + "integrity": "sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.4.0" + } + }, "node_modules/@lucide/vue": { "version": "1.48.0", "resolved": "https://registry.npmmirror.com/@lucide/vue/-/vue-1.48.0.tgz", @@ -872,6 +1504,12 @@ "vue": ">=3.0.1" } }, + "node_modules/@marijn/find-cluster-break": { + "version": "1.0.4", + "resolved": "https://registry.npmmirror.com/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", + "integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==", + "license": "MIT" + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmmirror.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -910,6 +1548,40 @@ "node": ">= 8" } }, + "node_modules/@replit/codemirror-lang-csharp": { + "version": "6.2.0", + "resolved": "https://registry.npmmirror.com/@replit/codemirror-lang-csharp/-/codemirror-lang-csharp-6.2.0.tgz", + "integrity": "sha512-6utbaWkoymhoAXj051mkRp+VIJlpwUgCX9Toevz3YatiZsz512fw3OVCedXQx+WcR0wb6zVHjChnuxqfCLtFVQ==", + "license": "MIT", + "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" + } + }, + "node_modules/@replit/codemirror-lang-svelte": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/@replit/codemirror-lang-svelte/-/codemirror-lang-svelte-6.0.0.tgz", + "integrity": "sha512-U2OqqgMM6jKelL0GNWbAmqlu1S078zZNoBqlJBW+retTc5M4Mha6/Y2cf4SVg6ddgloJvmcSpt4hHrVoM4ePRA==", + "license": "MIT", + "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" + } + }, "node_modules/@rollup/rollup-android-arm-eabi": { "version": "4.62.2", "resolved": "https://registry.npmmirror.com/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz", @@ -1516,7 +2188,9 @@ } }, "node_modules/@tauri-apps/api": { - "version": "2.11.1", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/api/-/api-2.12.1.tgz", + "integrity": "sha512-DeyFHa3wynpyoqTDikDEDGTJIq4LQ5USfolQGRmGIWT6JMADyxZBTDa5cAdT3tDg73rUXufPaCwN7aXBos4OnQ==", "license": "Apache-2.0 OR MIT", "funding": { "type": "opencollective", @@ -1524,7 +2198,9 @@ } }, "node_modules/@tauri-apps/cli": { - "version": "2.11.4", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli/-/cli-2.12.1.tgz", + "integrity": "sha512-kEDEiGzG+yAc5FeLxtXpES/VN+F2C8H0r4gDVtfRLKxT9np9101d9REG/Kgo2lr0hKi0IpDsODiHnU3+naOmLg==", "dev": true, "license": "Apache-2.0 OR MIT", "bin": { @@ -1538,23 +2214,23 @@ "url": "https://opencollective.com/tauri" }, "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" + "@tauri-apps/cli-darwin-arm64": "2.12.1", + "@tauri-apps/cli-darwin-x64": "2.12.1", + "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.1", + "@tauri-apps/cli-linux-arm64-gnu": "2.12.1", + "@tauri-apps/cli-linux-arm64-musl": "2.12.1", + "@tauri-apps/cli-linux-riscv64-gnu": "2.12.1", + "@tauri-apps/cli-linux-x64-gnu": "2.12.1", + "@tauri-apps/cli-linux-x64-musl": "2.12.1", + "@tauri-apps/cli-win32-arm64-msvc": "2.12.1", + "@tauri-apps/cli-win32-ia32-msvc": "2.12.1", + "@tauri-apps/cli-win32-x64-msvc": "2.12.1" } }, "node_modules/@tauri-apps/cli-darwin-arm64": { - "version": "2.11.4", - "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.11.4.tgz", - "integrity": "sha512-1ryOF3ZhpZ/nemHV5zVwBQBz9jDGKmKPvWPADOhc83ig0P4bMc2iER4NbC6r9sjeIZ6RVQ4g3RZIYvezhcl4TQ==", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.1.tgz", + "integrity": "sha512-8bMnbpJ2jKO/ufrOPL65EMHC3ptw7fzeraoQkwibyfGLqIl+UCWsC0152kmNbW6r9NvVQduXqAZF5mH1QgTWhw==", "cpu": [ "arm64" ], @@ -1569,9 +2245,9 @@ } }, "node_modules/@tauri-apps/cli-darwin-x64": { - "version": "2.11.4", - "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.11.4.tgz", - "integrity": "sha512-uFsGQAAfuyz1k/yGLmkWfkBlgKAqZfxqlHmLWx81QU27RJWfmbNHCIq8T8w1e+VClleIuZUjpHWfoE4E3DLo3A==", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.1.tgz", + "integrity": "sha512-G+2qte8GNqNlEZ9ftd21rbu/APVkl3r/nzNDI7LVxEoqJWVNe9GbEgQUMH1r4PHT20Z2UxR3KjCkltIb0e/Wjg==", "cpu": [ "x64" ], @@ -1586,9 +2262,9 @@ } }, "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": { - "version": "2.11.4", - "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.11.4.tgz", - "integrity": "sha512-IaHZn5CdBL21oUmjiVOS1ctw6Ip1O0pjp70FwOWmYz1myWe0SY96ZIj2FYf7pT0m8bI2h/hrs5ZbEXXh44/MkQ==", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.1.tgz", + "integrity": "sha512-5b3n4DaTW+A1Zntnh4Yn44VyLrlPEpB8kMOBRfWkzNnzolBk+AYhKIfKjCLmoC8Mob3ETodxAEOMkE2YPKEWzQ==", "cpu": [ "arm" ], @@ -1603,13 +2279,16 @@ } }, "node_modules/@tauri-apps/cli-linux-arm64-gnu": { - "version": "2.11.4", - "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.11.4.tgz", - "integrity": "sha512-N41/ukTRVe6XSuUTESuFdGeOW2i7k62tK+6gHK5Kd5/q5RPvvi19GaWAVPPb9u95HSGmTChSolBfzynUsssFaA==", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.1.tgz", + "integrity": "sha512-APArHhDu+8pXSCkCQmvaz1nD3d8WTmlCoSS/oG475TJ6AATBvyQOAmf5qELgsQ4s2+8MOsop0Zd699RKELF1Cw==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "Apache-2.0 OR MIT", "optional": true, "os": [ @@ -1620,13 +2299,16 @@ } }, "node_modules/@tauri-apps/cli-linux-arm64-musl": { - "version": "2.11.4", - "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.11.4.tgz", - "integrity": "sha512-v277UnT/fB64xAfSroL5N3Km3tLmvATWqJJw/wRI+g6o+HkeD0slyE7gOhNs1MbjE41R7bQOTxMVoL3aomUJmw==", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.1.tgz", + "integrity": "sha512-JaCxcLoV0oGtllVkLr4UAHWG/wTfkEunnUqnsEsGYOp0VRxnUwHg63wFBD0jU2ul5eFfSLIDS4RF2gfzsSo5Jg==", "cpu": [ "arm64" ], "dev": true, + "libc": [ + "musl" + ], "license": "Apache-2.0 OR MIT", "optional": true, "os": [ @@ -1637,13 +2319,16 @@ } }, "node_modules/@tauri-apps/cli-linux-riscv64-gnu": { - "version": "2.11.4", - "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.11.4.tgz", - "integrity": "sha512-qqgNkQ2u1yZHxjhxsZaxUtRDW8dIqIYm33rx/mzwQv0SfY9x1B+iraj8vWeFiXjjSVVhEMepXSOts1TqPzvXNQ==", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.1.tgz", + "integrity": "sha512-K5+VXM7+SGVDwZleA2+lMgvbTVuA5e1tkiVEawu1Yxj26ZyEfO8h8xTC1rBdRX2xgJDSwCk6vPUBCS6i+Z5slQ==", "cpu": [ "riscv64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "Apache-2.0 OR MIT", "optional": true, "os": [ @@ -1654,13 +2339,16 @@ } }, "node_modules/@tauri-apps/cli-linux-x64-gnu": { - "version": "2.11.4", - "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.11.4.tgz", - "integrity": "sha512-2VRNWl84FOH0m2giiDkO2h0QXlcMJeX+zJDpI5kDIQAx6s+geF3v48F4DXfJez4GS/FdoDGnPnw1C2iYGbQ7bQ==", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.1.tgz", + "integrity": "sha512-Z1QGPr49HJZMktu+Spu6Q1b/f9ANadXvqZZZt2645ua1x1ev6prOgp85eiGv2jRzohFEMLo6aJyaLjLUX5KIvA==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "glibc" + ], "license": "Apache-2.0 OR MIT", "optional": true, "os": [ @@ -1671,13 +2359,16 @@ } }, "node_modules/@tauri-apps/cli-linux-x64-musl": { - "version": "2.11.4", - "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.11.4.tgz", - "integrity": "sha512-o9GyhYor/nc7xarmwDE3ka2szuW3uuZzXjHWh64Q8YX5AtSgxdQkFWzrY4O8KiGtVNvFBI14H3Q49Qj5TOIP/A==", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.1.tgz", + "integrity": "sha512-nHuEhRPOMSJ/8RRhtMRxB9B9lVr7xxpe4DapBz8x1GIau3vdzjHHJ1hAfmw+PyayPLZ6XoaVIHPgI17rX6ii8w==", "cpu": [ "x64" ], "dev": true, + "libc": [ + "musl" + ], "license": "Apache-2.0 OR MIT", "optional": true, "os": [ @@ -1688,9 +2379,9 @@ } }, "node_modules/@tauri-apps/cli-win32-arm64-msvc": { - "version": "2.11.4", - "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.11.4.tgz", - "integrity": "sha512-ld5Ehb598m0VkYyylRPNeCFsBe/km0jxis6KgMpl3IGY6I/i1RwQXO05I1AsXUXO2WC6AvB/Lw4qTf/asiuEiQ==", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.1.tgz", + "integrity": "sha512-I0oPk2uGh86R8dAs2X5OxSP+/GqSc8jh1Px3l8EqrocSNivsRHDTh2k3PVOqdv163dlV6PIVvmhZAbH/lPfZrA==", "cpu": [ "arm64" ], @@ -1705,9 +2396,9 @@ } }, "node_modules/@tauri-apps/cli-win32-ia32-msvc": { - "version": "2.11.4", - "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.11.4.tgz", - "integrity": "sha512-12Hxi0XX/H5VFxO/bGgHkFWhml9VMgEOu9CidjeCeTNQ1l6fpUlbiGgSP7CLI3PFtW9/FfbeHieZ+kyWK5H7CA==", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.1.tgz", + "integrity": "sha512-baNZRBfepAJ5qNFRMwzgBk94xQmkcmTZrNDjZjnzrq2vAaTC3NAhallb/zo3hyoCGQlMS13sdovktrg46NZz6Q==", "cpu": [ "ia32" ], @@ -1722,7 +2413,9 @@ } }, "node_modules/@tauri-apps/cli-win32-x64-msvc": { - "version": "2.11.4", + "version": "2.12.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.1.tgz", + "integrity": "sha512-dIFaKslrzcbesb+bBh+E1R9km241pHyj32w6D9FPtvQeYpRUFbiCLEa/2S+S0UnIytfxepp4P+X8IerGqnXeYg==", "cpu": [ "x64" ], @@ -1737,37 +2430,39 @@ } }, "node_modules/@tauri-apps/plugin-autostart": { - "version": "2.5.1", - "resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-autostart/-/plugin-autostart-2.5.1.tgz", - "integrity": "sha512-zS/xx7yzveCcotkA+8TqkI2lysmG2wvQXv2HGAVExITmnFfHAdj1arGsbbfs3o6EktRHf6l34pJxc3YGG2mg7w==", + "version": "2.6.0", + "resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-autostart/-/plugin-autostart-2.6.0.tgz", + "integrity": "sha512-myppl3C/dygGbn7Inmm3LqsAQ7SSsT3KtNpSt/e+fA5J7xeCIf8H+LMiE1tkS7mKzTfChCutfZCt0FQkrL/YdA==", "license": "MIT OR Apache-2.0", "dependencies": { - "@tauri-apps/api": "^2.8.0" + "@tauri-apps/api": "^2.12.0" } }, "node_modules/@tauri-apps/plugin-dialog": { - "version": "2.7.2", - "resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-dialog/-/plugin-dialog-2.7.2.tgz", - "integrity": "sha512-pX0IGm1I3I6wc+zeKYcq1GSqogK6okCNX5fOdaNU5ab1AjGS6l1E5wFNjEb7meg7ZFSp0JUs+0jQGQNyOvLrsg==", + "version": "2.8.1", + "resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-dialog/-/plugin-dialog-2.8.1.tgz", + "integrity": "sha512-/DtE3B62JgpYuWFL5ATXM6KOXUq7pca7cJWOgSqULhZsgyjLk0PWKek1dbRDvhNBW6flNsOfWphsKnb+738Dmw==", "license": "MIT OR Apache-2.0", "dependencies": { - "@tauri-apps/api": "^2.11.0" + "@tauri-apps/api": "^2.12.0" } }, "node_modules/@tauri-apps/plugin-global-shortcut": { - "version": "2.3.2", - "resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-global-shortcut/-/plugin-global-shortcut-2.3.2.tgz", - "integrity": "sha512-UReHNXrLvpEjylE4jb4oCYiy96uRykPUthoCQCmRXYrd5hs5X9DrW+qOn7GLW57EJN4tdK8bgK5twBTz2NOxzA==", + "version": "2.4.0", + "resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-global-shortcut/-/plugin-global-shortcut-2.4.0.tgz", + "integrity": "sha512-XBA4PcRjRdJBp/jwFxc5YZ/yKhZuslpOG/pGaNfhnRDVGMQfoXEKMv/6A6vjzfKLUxr8ml3ay8o2W8Rk6mHICA==", "license": "MIT OR Apache-2.0", "dependencies": { - "@tauri-apps/api": "^2.11.0" + "@tauri-apps/api": "^2.12.0" } }, "node_modules/@tauri-apps/plugin-opener": { - "version": "2.5.4", + "version": "2.7.0", + "resolved": "https://registry.npmmirror.com/@tauri-apps/plugin-opener/-/plugin-opener-2.7.0.tgz", + "integrity": "sha512-mBorYfVKh9Lt7s4ZFtKbMUTxBw+Y/sVmSlKCtkkoBgMTC/DIbt/kaPm67L/2djAUqDI1wbixy5OHHVmipjuGMw==", "license": "MIT OR Apache-2.0", "dependencies": { - "@tauri-apps/api": "^2.11.0" + "@tauri-apps/api": "^2.12.0" } }, "node_modules/@types/esrecurse": { @@ -1788,6 +2483,31 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/@types/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/markdown-it": { + "version": "14.2.0", + "resolved": "https://registry.npmmirror.com/@types/markdown-it/-/markdown-it-14.2.0.tgz", + "integrity": "sha512-NoQ2yGlLWj4wpxMs+TYmRKk3thDrQ97agr7sFqfLsAlvoS8SNQuTrlObhFqG9iugdTtgOE9jpJ6FNM4ZGsa5xQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/linkify-it": "^5", + "@types/mdurl": "^2" + } + }, + "node_modules/@types/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/@types/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/node": { "version": "26.1.1", "resolved": "https://registry.npmmirror.com/@types/node/-/node-26.1.1.tgz", @@ -1814,6 +2534,13 @@ "integrity": "sha512-7HP+rZGE2p886PKV9c9OJzLBI6BBJu1O7lJGYnPyG3fS4/duUCcngkNCjsLwIMV+WMqANe3tt4irrXHSIe68OQ==", "license": "MIT" }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmmirror.com/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT", + "optional": true + }, "node_modules/@types/web-bluetooth": { "version": "0.0.21", "resolved": "https://registry.npmmirror.com/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", @@ -2102,6 +2829,25 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/@uiw/codemirror-themes": { + "version": "4.25.12", + "resolved": "https://registry.npmmirror.com/@uiw/codemirror-themes/-/codemirror-themes-4.25.12.tgz", + "integrity": "sha512-3bLX6C+gstr82SmY2FAj2TfHXnl2SnC+whRZJmRsv82wMhG8RZlZVy+o0rLuGRIPD9acuY0gpouHVRNUnzBj3g==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0" + }, + "funding": { + "url": "https://jaywcjlove.github.io/#/sponsor" + }, + "peerDependencies": { + "@codemirror/language": ">=6.0.0", + "@codemirror/state": ">=6.0.0", + "@codemirror/view": ">=6.0.0" + } + }, "node_modules/@vitejs/plugin-vue": { "version": "5.2.4", "dev": true, @@ -2465,6 +3211,22 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/argparse": { + "version": "3.0.2", + "resolved": "https://registry.npmmirror.com/argparse/-/argparse-3.0.2.tgz", + "integrity": "sha512-mFdDM6WqWKraGLsVb+C9CahPnzTXOefAOLq3jYcca2YZ8bEWpr++Tzj+zSaKW9+X9L5uSxcm1AZ3Y6aZJ09OhQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "PSF-2.0" + }, "node_modules/aria-hidden": { "version": "1.2.6", "resolved": "https://registry.npmmirror.com/aria-hidden/-/aria-hidden-1.2.6.tgz", @@ -2574,6 +3336,27 @@ "node": ">=6" } }, + "node_modules/codemirror-lang-elixir": { + "version": "4.0.1", + "resolved": "https://registry.npmmirror.com/codemirror-lang-elixir/-/codemirror-lang-elixir-4.0.1.tgz", + "integrity": "sha512-z6W/XB4b7TZrp9EZYBGVq93vQfvKbff+1iM8YZaVErL0dguBAeLmVRlEv1NuDZHOP1qjJ3NwyibkUkNWn7q9VQ==", + "license": "Apache-2.0", + "dependencies": { + "@codemirror/language": "^6.0.0", + "lezer-elixir": "^1.0.0" + } + }, + "node_modules/codemirror-lang-makefile": { + "version": "0.1.1", + "resolved": "https://registry.npmmirror.com/codemirror-lang-makefile/-/codemirror-lang-makefile-0.1.1.tgz", + "integrity": "sha512-aCmX0TIj88pQDFeBLmfhiE1ZYmLcWf2c9hk0pscbshCk1x1JO1314q67fbpSaPWm86fl8+wZ2gFuNPlVJ2iFzw==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz", @@ -2607,6 +3390,12 @@ "url": "https://github.com/sponsors/mesqueeb" } }, + "node_modules/crelt": { + "version": "1.0.7", + "resolved": "https://registry.npmmirror.com/crelt/-/crelt-1.0.7.tgz", + "integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==", + "license": "MIT" + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -2697,6 +3486,15 @@ "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", "license": "MIT" }, + "node_modules/dompurify": { + "version": "3.4.16", + "resolved": "https://registry.npmmirror.com/dompurify/-/dompurify-3.4.16.tgz", + "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -3228,6 +4026,15 @@ "he": "bin/he" } }, + "node_modules/highlight.js": { + "version": "11.12.0", + "resolved": "https://registry.npmmirror.com/highlight.js/-/highlight.js-11.12.0.tgz", + "integrity": "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/hookable": { "version": "5.5.3", "resolved": "https://registry.npmmirror.com/hookable/-/hookable-5.5.3.tgz", @@ -3367,6 +4174,16 @@ "node": ">= 0.8.0" } }, + "node_modules/lezer-elixir": { + "version": "1.1.3", + "resolved": "https://registry.npmmirror.com/lezer-elixir/-/lezer-elixir-1.1.3.tgz", + "integrity": "sha512-Ymc58/WhxdZS9yEOlnKbF3rdeBdFcPm4OEm26KMqA1Za9vztXi7I5qwGw1KxYmm3Nv0iDHq//EQyBwSEzKG9Mg==", + "license": "Apache-2.0", + "dependencies": { + "@lezer/highlight": "^1.2.0", + "@lezer/lr": "^1.3.0" + } + }, "node_modules/lightningcss": { "version": "1.32.0", "license": "MPL-2.0", @@ -3612,6 +4429,25 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/linkify-it": { + "version": "6.1.0", + "resolved": "https://registry.npmmirror.com/linkify-it/-/linkify-it-6.1.0.tgz", + "integrity": "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "uc.micro": "^3.0.0" + } + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-6.0.0.tgz", @@ -3635,6 +4471,51 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/markdown-it": { + "version": "15.0.2", + "resolved": "https://registry.npmmirror.com/markdown-it/-/markdown-it-15.0.2.tgz", + "integrity": "sha512-q4IGxMv56jCqT4OCRCADBoDP3LO4MhmTXjFbphHPXs4g3j9Xg5RDnxqN8IF/3vIWEU+VCnUq+7JUg/cfy2E6Qw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "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" + } + }, + "node_modules/markdown-it/node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmmirror.com/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/mdurl": { + "version": "2.1.0", + "resolved": "https://registry.npmmirror.com/mdurl/-/mdurl-2.1.0.tgz", + "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==", + "license": "MIT" + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmmirror.com/merge2/-/merge2-1.4.1.tgz", @@ -3945,6 +4826,15 @@ "node": ">=6" } }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmmirror.com/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/qified": { "version": "0.10.1", "resolved": "https://registry.npmmirror.com/qified/-/qified-0.10.1.tgz", @@ -4210,6 +5100,12 @@ "node": ">=8" } }, + "node_modules/style-mod": { + "version": "4.1.4", + "resolved": "https://registry.npmmirror.com/style-mod/-/style-mod-4.1.4.tgz", + "integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==", + "license": "MIT" + }, "node_modules/superjson": { "version": "2.2.6", "resolved": "https://registry.npmmirror.com/superjson/-/superjson-2.2.6.tgz", @@ -4352,6 +5248,12 @@ "typescript": ">=4.8.4 <6.1.0" } }, + "node_modules/uc.micro": { + "version": "3.0.0", + "resolved": "https://registry.npmmirror.com/uc.micro/-/uc.micro-3.0.0.tgz", + "integrity": "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw==", + "license": "MIT" + }, "node_modules/undici-types": { "version": "8.3.0", "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-8.3.0.tgz", @@ -4563,6 +5465,12 @@ "typescript": ">=5.0.0" } }, + "node_modules/w3c-keyname": { + "version": "2.2.8", + "resolved": "https://registry.npmmirror.com/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", + "license": "MIT" + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmmirror.com/which/-/which-2.0.2.tgz", diff --git a/package.json b/package.json index 822e2e3..c44b07b 100644 --- a/package.json +++ b/package.json @@ -17,12 +17,18 @@ "@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", @@ -35,9 +41,11 @@ "@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.12.0", - "@tauri-apps/plugin-autostart": "^2.6.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", @@ -52,6 +60,8 @@ "@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", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index c23d652..bf8a8d2 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1694,7 +1694,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.2", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -1967,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]] @@ -2961,7 +2961,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core 0.57.0", + "windows-core 0.61.2", ] [[package]] @@ -4127,7 +4127,7 @@ dependencies = [ "png 0.18.1", "serde", "thiserror 2.0.20", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5378,7 +5378,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5983,7 +5983,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -6040,7 +6040,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -6621,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]] @@ -7644,7 +7644,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -7666,6 +7666,7 @@ dependencies = [ "base64 0.22.1", "bytes", "cbc 0.1.2", + "chardetng", "chrono", "cpal", "dashmap", @@ -8114,7 +8115,7 @@ dependencies = [ "png 0.18.1", "serde", "thiserror 2.0.20", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -8167,7 +8168,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -8565,7 +8566,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.60.2", ] [[package]] @@ -8586,7 +8587,7 @@ dependencies = [ "objc2-foundation", "objc2-quartz-core", "raw-window-handle", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "windows-version", ] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index ea046db..5c7ef11 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -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" diff --git a/src-tauri/capabilities/dsh-window.json b/src-tauri/capabilities/dsh-window.json new file mode 100644 index 0000000..37d4697 --- /dev/null +++ b/src-tauri/capabilities/dsh-window.json @@ -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" + ] +} \ No newline at end of file diff --git a/src-tauri/capabilities/notes-window.json b/src-tauri/capabilities/editor-window.json similarity index 74% rename from src-tauri/capabilities/notes-window.json rename to src-tauri/capabilities/editor-window.json index f54cd26..45d42d5 100644 --- a/src-tauri/capabilities/notes-window.json +++ b/src-tauri/capabilities/editor-window.json @@ -1,8 +1,8 @@ { "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "notes-window", - "description": "Capability for the notes/editor windows (multi-open, label = notes-window-). Needs the CM6 editor's window controls, events (settings/library sync) and opener.", - "windows": ["notes-window-*"], + "identifier": "editor-window", + "description": "Capability for the editor windows (multi-open, label = editor-window-). Needs the CM6 editor's window controls, events (settings/library sync) and opener.", + "windows": ["editor-window-*"], "permissions": [ "core:default", "core:window:allow-show", diff --git a/src-tauri/src/clipboard/suppress.rs b/src-tauri/src/clipboard/suppress.rs index 3df08d3..d8c9d8d 100644 --- a/src-tauri/src/clipboard/suppress.rs +++ b/src-tauri/src/clipboard/suppress.rs @@ -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)) }); } diff --git a/src-tauri/src/constants.rs b/src-tauri/src/constants.rs index 901f151..a4eb3dd 100644 --- a/src-tauri/src/constants.rs +++ b/src-tauri/src/constants.rs @@ -26,9 +26,13 @@ pub mod windows { /// 因此**不登记 capability**:远端页面不应获得任何 Tauri 权限)。 #[allow(dead_code)] pub const DSH_WEB: &str = "dsh-web"; - /// 笔记 / 编辑器独立窗口前缀,实际 label = `${NOTES_WINDOW}-`(可多开) + /// 笔记 / 编辑器独立窗口前缀,实际 label = `${EDITOR_WINDOW}-`(可多开) #[allow(dead_code)] - pub const NOTES_WINDOW: &str = "notes-window"; + pub const EDITOR_WINDOW: &str = "editor-window"; + /// dsh「启动进度」独立窗口(单例,由前端创建)。 + /// 服务就绪后由前端打开真正的 [`DSH_WEB`] 窗口并关闭它。 + #[allow(dead_code)] + pub const DSH_WINDOW: &str = "dsh-window"; } /// Tauri 事件名(与前端 constants::EVENTS 对应) @@ -37,8 +41,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"; @@ -138,23 +146,26 @@ pub mod events { /// 窗口由前端创建(它持有带令牌的地址与 label 判重),Rust 侧只负责注册快捷键。 pub const DSH_OPEN_WINDOW: &str = "dsh-open-window"; // 笔记模块:设置已保存(无负载)。各窗口据以重读设置,实现跨窗口同步(同 terminal-settings) - pub const NOTES_SETTINGS: &str = "notes-settings"; + pub const EDITOR_SETTINGS: &str = "editor-settings"; // 笔记模块:库内容已变更(新建/保存/重命名/删除/切换库根,无负载) - pub const NOTES_LIBRARY_CHANGED: &str = "notes-library-changed"; - // 笔记模块:库内某个文件在**应用外**被改动了(负载见 notes::index_service::NoteFileEvent)。 - // 与 NOTES_LIBRARY_CHANGED 的区别:那个是「本应用改了,重读即可」,这个是 + pub const EDITOR_LIBRARY_CHANGED: &str = "editor-library-changed"; + // 笔记模块:库内某个文件在**应用外**被改动了(负载见 editor::index_service::NoteFileEvent)。 + // 与 EDITOR_LIBRARY_CHANGED 的区别:那个是「本应用改了,重读即可」,这个是 // 「别人改了,当前打开的文档可能已经过时」——前端据此提示而不是静默覆盖。 - pub const NOTES_FILE_CHANGED: &str = "notes-file-changed"; - // 笔记模块:WebDAV 同步进度(负载见 notes::types::SyncProgress)。 + pub const EDITOR_FILE_CHANGED: &str = "editor-file-changed"; + // 笔记模块:WebDAV 同步进度(负载见 editor::types::SyncProgress)。 // 进度事件是高频的,前端按「每 X% 或每 N 条」节流显示即可;Rust 侧逐条发, // 因为节流放在发送端会让「最后一条」容易被丢掉(进度条停在 98%)。 - pub const NOTES_SYNC_PROGRESS: &str = "notes-sync-progress"; + pub const EDITOR_SYNC_PROGRESS: &str = "editor-sync-progress"; // 笔记模块:全局快捷键按下「新建笔记」(无负载,窗口由前端创建) - pub const NOTES_NEW_NOTE: &str = "notes-new-note"; + pub const EDITOR_NEW_NOTE: &str = "editor-new-note"; // 笔记模块:全局快捷键按下「打开编辑器窗口」(无负载) - pub const NOTES_OPEN_EDITOR: &str = "notes-open-editor"; + pub const EDITOR_OPEN_EDITOR: &str = "editor-open-editor"; // 笔记模块:需要打开一个磁盘文件(负载 `{ path }`)。 // 来源有三:① 双击关联的 .md(单实例回调把参数转交过来);② 启动命令行参数; // ③ 系统「打开方式」。三种都只发事件,窗口由前端创建。 - pub const NOTES_OPEN_FILE: &str = "notes-open-file"; + pub const EDITOR_OPEN_FILE: &str = "editor-open-file"; + // 笔记模块:需要打开一个**文件夹**(负载 `{ path }`)。 + // 来源:资源管理器右键「用 Thing 编辑器打开」(目录 / 目录背景)。 + pub const EDITOR_OPEN_FOLDER: &str = "editor-open-folder"; } diff --git a/src-tauri/src/dsh/install.rs b/src-tauri/src/dsh/install.rs index a79bf6b..0ebc4db 100644 --- a/src-tauri/src/dsh/install.rs +++ b/src-tauri/src/dsh/install.rs @@ -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 自己创建;这里先建一次,避免 diff --git a/src-tauri/src/editor/args.rs b/src-tauri/src/editor/args.rs new file mode 100644 index 0000000..3d536bb --- /dev/null +++ b/src-tauri/src/editor/args.rs @@ -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>> = std::sync::OnceLock::new(); + +fn pending_slot() -> &'static Mutex> { + 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 { + pending_slot() + .lock() + .ok() + .and_then(|mut slot| slot.take()) + .map(|target| OpenTargetPayload::from(&target)) +} + +/// 从一组命令行参数里挑出「看起来是要打开的路径」。 +/// +/// 只认「**存在**的路径」,其余一律忽略 —— 宁可漏开一个窗口,也不要因为一个开关 +/// 参数把主窗口的启动逻辑搞乱。目录优先(右键文件夹的场景)。 +pub fn open_target_from_args>(args: I) -> Option { + 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>(args: I) -> Option { + 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); + } +} \ No newline at end of file diff --git a/src-tauri/src/notes/backup.rs b/src-tauri/src/editor/backup.rs similarity index 93% rename from src-tauri/src/notes/backup.rs rename to src-tauri/src/editor/backup.rs index e92e6a6..76231ba 100644 --- a/src-tauri/src/notes/backup.rs +++ b/src-tauri/src/editor/backup.rs @@ -11,7 +11,7 @@ //! # 打包内容 //! //! 库内全部 `.md` 与 `assets/` 下的附件,外加一份 `thing-notes-manifest.json` -//! (记录快照时间、文件数、格式版本)。**不打包 `.notes/`**:里面是索引与同步基线, +//! (记录快照时间、文件数、格式版本)。**不打包 `.editor/`**:里面是索引与同步基线, //! 属于本机私有数据,跟着快照跑到另一台机器上只会误导那边的基线判断。 //! //! # 轮转 @@ -23,8 +23,8 @@ use std::io::Write; use std::path::{Path, PathBuf}; use super::webdav::client::WebdavClient; -use crate::notes::library; -use crate::notes::types::{BackupReport, BackupSnapshot, WebdavSettings}; +use crate::editor::library; +use crate::editor::types::{BackupReport, BackupSnapshot, WebdavSettings}; /// 远端存放快照的目录(相对远端根)。 pub const BACKUP_DIR: &str = "backups"; @@ -63,14 +63,14 @@ pub fn build_snapshot(root: &Path) -> Result<(Vec, u32), String> { if rel.is_empty() { continue; } - // `.notes/` 是本机私有数据(索引 + 同步基线),不进快照 + // `.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("notes", &format!("快照跳过 {rel}(读取失败: {e})")); + crate::logger::log_warn("editor", &format!("快照跳过 {rel}(读取失败: {e})")); continue; } }; @@ -138,7 +138,7 @@ pub fn prune_snapshots(client: &WebdavClient, keep: u32) -> Result, 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("notes", &format!("删除旧快照 {} 失败: {e}", snapshot.name)); + crate::logger::log_warn("editor", &format!("删除旧快照 {} 失败: {e}", snapshot.name)); continue; } pruned.push(snapshot.name); @@ -201,7 +201,7 @@ pub fn restore_snapshot( .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("notes", "快照里有越界路径,已跳过"); + crate::logger::log_warn("editor", "快照里有越界路径,已跳过"); continue; }; let rel = entry_path.to_string_lossy().replace('\\', "/"); @@ -246,17 +246,17 @@ pub fn sync_then_backup( 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("notes", &format!("保存同步基线失败: {e}")); + crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}")); } } else { crate::logger::log_warn( - "notes", + "editor", &format!("本轮有 {} 条失败,不推进同步基线", report.failed), ); // 仍然保存「成功的那些」:SyncState 是按条更新的,未处理的条目保持旧基线, // 于是下一轮会把它们重新算作差异并重试 if let Err(e) = state.save(root) { - crate::logger::log_warn("notes", &format!("保存同步基线失败: {e}")); + crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}")); } } @@ -301,14 +301,14 @@ mod tests { } #[test] - fn snapshot_contains_notes_and_assets_but_not_private_dir() { + 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(".notes")).unwrap(); - std::fs::write(root.join(".notes/notes.db"), "索引不该进快照").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, "两篇笔记 + 一个附件"); @@ -323,7 +323,7 @@ mod tests { 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(".notes")), + !names.iter().any(|n| n.starts_with(".editor")), "私有目录不该进快照: {names:?}" ); diff --git a/src-tauri/src/notes/commands.rs b/src-tauri/src/editor/commands.rs similarity index 78% rename from src-tauri/src/notes/commands.rs rename to src-tauri/src/editor/commands.rs index 304df4d..627f1a1 100644 --- a/src-tauri/src/notes/commands.rs +++ b/src-tauri/src/editor/commands.rs @@ -33,35 +33,35 @@ use super::index_service::{self, IndexService, NoteIndexReport}; use super::library; use super::templates::{self, NoteTemplate}; use super::types::{ - BackupReport, BackupSnapshot, ImportReport, LibraryEntry, LibraryInfo, NoteDoc, NoteSettings, + BackupReport, BackupSnapshot, ImportReport, LibraryEntry, LibraryInfo, NoteDoc, EditorSettings, SyncProgress, }; use super::webdav::{self, WebdavTestResult}; -use super::NotesManager; +use super::EditorManager; use crate::constants::events; /// 通知各窗口「库内容已变更」(新建/保存/重命名/删除/切换库根后)。 fn emit_library_changed(app: &AppHandle) { - if let Err(e) = app.emit(events::NOTES_LIBRARY_CHANGED, ()) { - crate::logger::log_warn("notes", &format!("发出库变更事件失败: {e}")); + 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::NOTES_SETTINGS, ()) { - crate::logger::log_warn("notes", &format!("发出设置变更事件失败: {e}")); + if let Err(e) = app.emit(events::EDITOR_SETTINGS, ()) { + crate::logger::log_warn("editor", &format!("发出设置变更事件失败: {e}")); } } /// 当前库根(按设置解析),并确保目录存在。 -fn current_root(state: &NotesManager) -> PathBuf { +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: &NotesManager) -> Result<&'a IndexService, String> { +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)?; @@ -69,7 +69,7 @@ fn indexed<'a>(app: &AppHandle, state: &NotesManager) -> Result<&'a IndexService } /// 组装库状态概览。 -fn library_info(state: &NotesManager) -> Result { +fn library_info(state: &EditorManager) -> Result { let settings = state.load_settings(); let root = library::resolve_library_root(state.module_dir(), &settings); library::ensure_library(&root)?; @@ -85,21 +85,48 @@ fn library_info(state: &NotesManager) -> Result { }) } -/// 标记「本应用刚写过」,随后把库同步进索引。 +/// 标记「本应用刚**批量**写过」,随后把库同步进索引。 +/// +/// 用于导入 / WebDAV 同步 / 恢复 / 模板导出这类**无法逐路径枚举**的操作:写完之后 +/// 在抑制窗口内的一切文件事件都当作自己写的。 /// /// 顺序重要:先标记(抑制窗口从写入那一刻算起),再同步。这里走全库增量同步而不是 /// 「只索引这一篇」的快路径:单文件快路径要额外拼一份 wikilink 的 `stems` 映射, /// 而不完整的映射会让 `[[某笔记]]` 解析到错误位置;全量同步靠 (mtime,size) 跳过 /// 未变文件,万篇规模也是毫秒级,用一点开销换「索引永远自洽」。 -fn mark_written_then_index(app: &AppHandle, state: &NotesManager) { +fn mark_written_then_index(app: &AppHandle, state: &EditorManager) { match indexed(app, state) { Ok(service) => { - service.mark_write(); + service.mark_write_all(); if let Err(e) = service.sync() { - crate::logger::log_warn("notes", &format!("保存后同步索引失败: {e}")); + crate::logger::log_warn("editor", &format!("保存后同步索引失败: {e}")); } } - Err(e) => crate::logger::log_warn("notes", &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}")), } } @@ -108,18 +135,36 @@ fn mark_written_then_index(app: &AppHandle, state: &NotesManager) { /// 读取笔记模块设置。 #[tauri::command] #[specta::specta] -pub fn notes_get_settings(state: State<'_, NotesManager>) -> Result { +pub fn editor_get_settings(state: State<'_, EditorManager>) -> Result { 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 { + 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 notes_save_settings( +pub fn editor_save_settings( app: AppHandle, - state: State<'_, NotesManager>, - settings: NoteSettings, -) -> Result { + state: State<'_, EditorManager>, + settings: EditorSettings, +) -> Result { let mut next = settings; next.heal(); state.save_settings(&next)?; @@ -133,16 +178,16 @@ pub fn notes_save_settings( /// 当前库状态概览(库根 / 是否自定义 / 笔记数)。 #[tauri::command] #[specta::specta] -pub fn notes_library_info(state: State<'_, NotesManager>) -> Result { +pub fn editor_library_info(state: State<'_, EditorManager>) -> Result { library_info(&state) } /// 设置库根(`None` 或空串 = 恢复默认库根)。 #[tauri::command] #[specta::specta] -pub fn notes_set_library_root( +pub fn editor_set_library_root( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, root: Option, ) -> Result { let cleaned = root.and_then(|r| { @@ -177,7 +222,7 @@ pub fn notes_set_library_root( /// 扫描库,返回扁平条目列表(前端组树)。 #[tauri::command] #[specta::specta] -pub fn notes_scan_library(state: State<'_, NotesManager>) -> Result, String> { +pub fn editor_scan_library(state: State<'_, EditorManager>) -> Result, String> { let root = current_root(&state); library::ensure_library(&root)?; library::scan(&root) @@ -186,7 +231,7 @@ pub fn notes_scan_library(state: State<'_, NotesManager>) -> Result, rel_path: String) -> Result { +pub fn editor_read_note(state: State<'_, EditorManager>, rel_path: String) -> Result { let root = current_root(&state); library::read_note(&root, &rel_path) } @@ -194,15 +239,17 @@ pub fn notes_read_note(state: State<'_, NotesManager>, rel_path: String) -> Resu /// 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。 #[tauri::command] #[specta::specta] -pub fn notes_save_note( +pub fn editor_save_note( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, rel_path: String, content: String, ) -> Result { let root = current_root(&state); + // 先登记「即将写这一篇」,再落盘:notify 的事件可能与写入同时抵达 worker + mark_pending_note_write(&app, &state, &rel_path); let doc = library::write_note(&root, &rel_path, &content)?; - mark_written_then_index(&app, &state); + sync_index_after_write(&app, &state); emit_library_changed(&app); Ok(doc) } @@ -213,9 +260,9 @@ pub fn notes_save_note( /// 模板文件被删掉不该让「新建笔记」这个核心动作失败)。 #[tauri::command] #[specta::specta] -pub fn notes_create_note( +pub fn editor_create_note( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, dir_rel: String, name: String, template_id: Option, @@ -236,7 +283,7 @@ pub fn notes_create_note( /// 打开(或创建)今天的日记:`日记/YYYY-MM-DD.md`。 #[tauri::command] #[specta::specta] -pub fn notes_daily_note(app: AppHandle, state: State<'_, NotesManager>) -> Result { +pub fn editor_daily_note(app: AppHandle, state: State<'_, EditorManager>) -> Result { let root = current_root(&state); let name = templates::daily_note_name(); let dir = "日记"; @@ -261,9 +308,9 @@ pub fn notes_daily_note(app: AppHandle, state: State<'_, NotesManager>) -> Resul /// 新建文件夹。 #[tauri::command] #[specta::specta] -pub fn notes_create_folder( +pub fn editor_create_folder( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, dir_rel: String, name: String, ) -> Result<(), String> { @@ -276,9 +323,9 @@ pub fn notes_create_folder( /// 重命名条目,返回新相对路径。 #[tauri::command] #[specta::specta] -pub fn notes_rename_entry( +pub fn editor_rename_entry( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, rel_path: String, new_name: String, ) -> Result { @@ -287,7 +334,7 @@ pub fn notes_rename_entry( // 改名在索引里是「旧路径消失 + 新路径出现」:增量同步一次比手工删+插更稳 if let Ok(service) = indexed(&app, &state) { if let Err(e) = service.sync() { - crate::logger::log_warn("notes", &format!("改名后同步索引失败: {e}")); + crate::logger::log_warn("editor", &format!("改名后同步索引失败: {e}")); } } emit_library_changed(&app); @@ -297,16 +344,16 @@ pub fn notes_rename_entry( /// 删除条目(目录递归删除)。 #[tauri::command] #[specta::specta] -pub fn notes_delete_entry( +pub fn editor_delete_entry( app: AppHandle, - state: State<'_, NotesManager>, + 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("notes", &format!("删除后同步索引失败: {e}")); + crate::logger::log_warn("editor", &format!("删除后同步索引失败: {e}")); } } emit_library_changed(&app); @@ -318,9 +365,9 @@ pub fn notes_delete_entry( /// 全量重建索引(设置页「重建索引」)。文件不受影响。 #[tauri::command] #[specta::specta] -pub fn notes_rebuild_index( +pub fn editor_rebuild_index( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, ) -> Result { let service = indexed(&app, &state)?; let report = service.rebuild()?; @@ -330,9 +377,9 @@ pub fn notes_rebuild_index( /// 增量同步索引(打开编辑器 / 手动刷新时调用)。 #[tauri::command] #[specta::specta] -pub fn notes_sync_index( +pub fn editor_sync_index( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, ) -> Result { let service = indexed(&app, &state)?; let report = service.sync()?; @@ -350,9 +397,9 @@ fn finish_report(service: &IndexService, report: super::index::NoteSyncReport) - /// 全文检索 / 按标签 / 按目录筛选。 #[tauri::command] #[specta::specta] -pub fn notes_search_notes( +pub fn editor_search_notes( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, query: NoteSearchQuery, ) -> Result { let service = indexed(&app, &state)?; @@ -362,9 +409,9 @@ pub fn notes_search_notes( /// 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。 #[tauri::command] #[specta::specta] -pub fn notes_list_notes( +pub fn editor_list_notes( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, limit: Option, ) -> Result, String> { let service = indexed(&app, &state)?; @@ -374,9 +421,9 @@ pub fn notes_list_notes( /// 标签及计数。 #[tauri::command] #[specta::specta] -pub fn notes_tags( +pub fn editor_tags( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, ) -> Result, String> { let service = indexed(&app, &state)?; service.tags() @@ -385,9 +432,9 @@ pub fn notes_tags( /// 一篇笔记的链接关系(出链 + 入链)。 #[tauri::command] #[specta::specta] -pub fn notes_backlinks( +pub fn editor_backlinks( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, rel_path: String, ) -> Result { let service = indexed(&app, &state)?; @@ -397,9 +444,9 @@ pub fn notes_backlinks( /// 全库链接图(已解析的内部链接边)。 #[tauri::command] #[specta::specta] -pub fn notes_link_graph( +pub fn editor_link_graph( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, ) -> Result, String> { let service = indexed(&app, &state)?; let edges = service.link_graph()?; @@ -421,9 +468,9 @@ pub struct LinkEdge { /// 索引状态(设置页展示:索引数 / 文件数 / 标签数 / 索引文件路径)。 #[tauri::command] #[specta::specta] -pub fn notes_index_stats( +pub fn editor_index_stats( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, ) -> Result { let service = indexed(&app, &state)?; service.stats() @@ -451,8 +498,8 @@ const MAX_ASSET_BYTES: u64 = 8 * 1024 * 1024; #[tauri::command] #[specta::specta] -pub fn notes_read_asset( - state: State<'_, NotesManager>, +pub fn editor_read_asset( + state: State<'_, EditorManager>, rel_path: String, ) -> Result, String> { let root = current_root(&state); @@ -479,7 +526,7 @@ pub fn notes_read_asset( let meta = std::fs::metadata(&path).map_err(|e| format!("读取附件信息失败: {e}"))?; if meta.len() > MAX_ASSET_BYTES { crate::logger::log_info( - "notes", + "editor", &format!("附件过大,跳过内联预览:{rel_path}({} 字节)", meta.len()), ); return Ok(None); @@ -493,11 +540,11 @@ pub fn notes_read_asset( /// 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。 /// /// 前端在注册完事件监听后调用。**不能靠启动时 `emit`** —— 那时 WebView 还没加载完, -/// 事件会直接丢掉(见 `notes/args.rs` 的 `PENDING` 注释)。 +/// 事件会直接丢掉(见 `editor/args.rs` 的 `PENDING` 注释)。 #[tauri::command] #[specta::specta] -pub fn notes_take_pending_file() -> Result, String> { - Ok(super::args::take_pending_file().map(|path| super::files::display_path(&path))) +pub fn editor_take_pending_file() -> Result, String> { + Ok(super::args::take_pending_target()) } /// 打开(读取)库外任意文件。 @@ -506,8 +553,8 @@ pub fn notes_take_pending_file() -> Result, String> { /// 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。 #[tauri::command] #[specta::specta] -pub fn notes_open_file( - state: State<'_, NotesManager>, +pub fn editor_open_file( + state: State<'_, EditorManager>, path: String, ) -> Result { let settings = state.load_settings(); @@ -517,9 +564,9 @@ pub fn notes_open_file( /// 保存库外任意文件(按前端回传的编码与换行写回)。 #[tauri::command] #[specta::specta] -pub fn notes_write_file( +pub fn editor_write_file( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, path: String, content: String, encoding: String, @@ -528,18 +575,32 @@ pub fn notes_write_file( 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) { - service.mark_write(); + // 库外文件的路径语义与库内相对路径不同,这里退回窗口式抑制; + // 真正在库内的 `.md`(被当作普通文件打开)同样受这一窗口保护。 + service.mark_write_all(); } Ok(doc) } +/// 以指定编码重新解码磁盘字节(切换编码用;不写回,只换一种解释方式)。 +#[tauri::command] +#[specta::specta] +pub fn editor_redecode_file( + state: State<'_, EditorManager>, + path: String, + encoding: String, +) -> Result { + let settings = state.load_settings(); + files::redecode_file(&path, &encoding, settings.max_file_size_mb) +} + /// 显式登记一个路径为「可写」。 /// -/// 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `notes_open_file`, +/// 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `editor_open_file`, /// 但用户确实是用系统对话框选的,属于「用户显式选择」)。 #[tauri::command] #[specta::specta] -pub fn notes_authorize_file(path: String) -> Result<(), String> { +pub fn editor_authorize_file(path: String) -> Result<(), String> { if path.trim().is_empty() { return Err("路径为空".to_string()); } @@ -554,8 +615,8 @@ pub fn notes_authorize_file(path: String) -> Result<(), String> { /// 安全得多(写的位置由后端决定,且只落在 `assets/`)。 #[tauri::command] #[specta::specta] -pub fn notes_write_asset( - state: State<'_, NotesManager>, +pub fn editor_write_asset( + state: State<'_, EditorManager>, file_name: String, ext: String, data_base64: String, @@ -577,7 +638,7 @@ pub fn notes_write_asset( /// 就能直接写文件,不需要用户先去资源管理器建目录。 #[tauri::command] #[specta::specta] -pub fn notes_list_templates(state: State<'_, NotesManager>) -> Result, String> { +pub fn editor_list_templates(state: State<'_, EditorManager>) -> Result, String> { let root = current_root(&state); library::ensure_library(&root)?; let _ = templates::ensure_dir(&root); @@ -591,9 +652,9 @@ pub fn notes_list_templates(state: State<'_, NotesManager>) -> Result, + state: State<'_, EditorManager>, name: Option, body: Option, ) -> Result, String> { @@ -623,8 +684,8 @@ pub fn notes_add_template( /// 内置模板没有对应的库内文件,前端据此禁掉「直接编辑」。 #[tauri::command] #[specta::specta] -pub fn notes_read_template( - state: State<'_, NotesManager>, +pub fn editor_read_template( + state: State<'_, EditorManager>, template_id: String, ) -> Result { let root = current_root(&state); @@ -649,9 +710,9 @@ pub struct TemplateSource { /// 从磁盘路径导入(文件 / 目录 / zip 自动判别)。 #[tauri::command] #[specta::specta] -pub fn notes_import( +pub fn editor_import( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, source: String, dest_dir: String, ) -> Result { @@ -668,8 +729,8 @@ pub fn notes_import( /// 已经渲染好的字符串写到用户选定的位置 —— 即「后端不碰渲染逻辑,前端不碰文件系统」。 #[tauri::command] #[specta::specta] -pub fn notes_export_note( - state: State<'_, NotesManager>, +pub fn editor_export_note( + state: State<'_, EditorManager>, rel_path: String, html: String, dest: String, @@ -687,7 +748,7 @@ pub fn notes_export_note( let bytes = html.into_bytes(); std::fs::write(&target, &bytes).map_err(|e| format!("写入导出文件失败: {e}"))?; crate::logger::log_info( - "notes", + "editor", &format!("导出 {} → {}({} 字节)", rel_path, target.display(), bytes.len()), ); Ok(target.to_string_lossy().to_string()) @@ -696,8 +757,8 @@ pub fn notes_export_note( /// 把整库(或某个目录)打包成 zip,返回落盘路径。 #[tauri::command] #[specta::specta] -pub fn notes_export_zip( - state: State<'_, NotesManager>, +pub fn editor_export_zip( + state: State<'_, EditorManager>, dest: String, dir_rel: Option, ) -> Result { @@ -713,7 +774,7 @@ pub fn notes_export_zip( } std::fs::write(&dest_path, &bytes).map_err(|e| format!("写入 zip 失败: {e}"))?; crate::logger::log_info( - "notes", + "editor", &format!("导出 zip:{files} 个文件 → {}", dest_path.display()), ); Ok(dest_path.to_string_lossy().to_string()) @@ -721,13 +782,13 @@ pub fn notes_export_zip( /// 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。 /// -/// 与 [`notes_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」, +/// 与 [`editor_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」, /// 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为 /// 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。 #[tauri::command] #[specta::specta] -pub fn notes_export_snapshot_local( - state: State<'_, NotesManager>, +pub fn editor_export_snapshot_local( + state: State<'_, EditorManager>, dest: Option, ) -> Result { let root = current_root(&state); @@ -745,7 +806,7 @@ pub fn notes_export_snapshot_local( /// 当前 WebDAV 配置状态(设置页展示;**密码只回传「是否已保存」**)。 #[tauri::command] #[specta::specta] -pub fn notes_webdav_status(state: State<'_, NotesManager>) -> Result { +pub fn editor_webdav_status(state: State<'_, EditorManager>) -> Result { let settings = state.load_settings(); let has_password = crate::secrets::secret_read(webdav::KEYRING_PASSWORD) .ok() @@ -773,7 +834,7 @@ pub struct WebdavStatus { /// 保存 WebDAV 密码到系统凭据管理器(传空串 = 删除)。 #[tauri::command] #[specta::specta] -pub fn notes_set_webdav_password(password: String) -> Result<(), String> { +pub fn editor_set_webdav_password(password: String) -> Result<(), String> { if password.trim().is_empty() { return crate::secrets::secret_delete(webdav::KEYRING_PASSWORD); } @@ -783,8 +844,8 @@ pub fn notes_set_webdav_password(password: String) -> Result<(), String> { /// 连接自检(建目录 + 列远端)。 #[tauri::command] #[specta::specta] -pub async fn notes_test_webdav( - state: State<'_, NotesManager>, +pub async fn editor_test_webdav( + state: State<'_, EditorManager>, ) -> Result { let settings = state.load_settings().webdav; run_blocking(move || webdav::test_connection(&settings)).await @@ -793,9 +854,9 @@ pub async fn notes_test_webdav( /// 立即同步(并按设置决定是否追加一次快照备份)。 #[tauri::command] #[specta::specta] -pub async fn notes_sync_now( +pub async fn editor_sync_now( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, ) -> Result { let settings = state.load_settings(); let webdav = settings.webdav.clone(); @@ -804,7 +865,7 @@ pub async fn notes_sync_now( // 让前端先看到「开始同步」(进度事件的第一条由 worker 之外发,总数为 0 表示准备中) let _ = app.emit( - events::NOTES_SYNC_PROGRESS, + events::EDITOR_SYNC_PROGRESS, SyncProgress { done: 0, total: 0, @@ -843,8 +904,8 @@ pub struct SyncOutcome { /// 只做一次 zip 快照备份(不上传增量)。 #[tauri::command] #[specta::specta] -pub async fn notes_backup_now( - state: State<'_, NotesManager>, +pub async fn editor_backup_now( + state: State<'_, EditorManager>, ) -> Result { let settings = state.load_settings(); let webdav = settings.webdav.clone(); @@ -861,8 +922,8 @@ pub async fn notes_backup_now( /// 列出远端已有快照。 #[tauri::command] #[specta::specta] -pub async fn notes_list_backups( - state: State<'_, NotesManager>, +pub async fn editor_list_backups( + state: State<'_, EditorManager>, ) -> Result, String> { let settings = state.load_settings().webdav; run_blocking(move || { @@ -875,9 +936,9 @@ pub async fn notes_list_backups( /// 从远端快照恢复(不覆盖本地已有文件)。 #[tauri::command] #[specta::specta] -pub async fn notes_restore_backup( +pub async fn editor_restore_backup( app: AppHandle, - state: State<'_, NotesManager>, + state: State<'_, EditorManager>, name: String, ) -> Result { let settings = state.load_settings(); diff --git a/src-tauri/src/editor/dirs.rs b/src-tauri/src/editor/dirs.rs new file mode 100644 index 0000000..707ec2a --- /dev/null +++ b/src-tauri/src/editor/dirs.rs @@ -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, +} + +/// 列举本地目录(`path` 为空 = 用户主目录)。 +#[tauri::command] +#[specta::specta] +pub fn editor_read_dir(path: String) -> Result { + local_fs::list_dir(&path) +} + +/// 在 `dir` 下新建一个空文本文件。重名报错(不自动加序号)。 +#[tauri::command] +#[specta::specta] +pub fn editor_create_file(dir: String, name: String) -> Result { + 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 { + 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 { + 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) -> Result { + 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 { + 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 { + let name = validate_name(name)?; + let dir = Path::new(dir.trim()); + if !dir.is_dir() { + return Err("目标目录不存在".to_string()); + } + Ok(dir.join(name)) +} \ No newline at end of file diff --git a/src-tauri/src/notes/export.rs b/src-tauri/src/editor/export.rs similarity index 92% rename from src-tauri/src/notes/export.rs rename to src-tauri/src/editor/export.rs index c75c63e..a1bc180 100644 --- a/src-tauri/src/notes/export.rs +++ b/src-tauri/src/editor/export.rs @@ -5,7 +5,7 @@ //! `backup.rs` 的 zip 是**给同步服务用的**(固定文件名前缀、上传到远端、轮转), //! 本模块的 zip 是**给用户拿走的**(用户选保存位置、可以只导出某个目录)。 //! 两者都打包 `.md` 与 `assets/`,但排除规则不同:用户导出时**包含**点号开头的 -//! 普通目录(除了 `.notes/`)—— 因为「我库里有 `.foo/` 目录,为什么导出后没了」 +//! 普通目录(除了 `.editor/`)—— 因为「我库里有 `.foo/` 目录,为什么导出后没了」 //! 是个更难解释的问题;而同步必须排除它们(避免把本机私有状态推给别人)。 use std::io::Write; @@ -59,7 +59,7 @@ pub fn zip_scope(root: &Path, dir_rel: &str) -> Result<(Vec, u32), String> { continue; } // 私有目录(索引 + 同步基线)任何情况下都不导出 - if rel == ".notes" || rel.starts_with(".notes/") { + if rel == ".editor" || rel.starts_with(".editor/") { continue; } if let Some(prefix) = &filter_prefix { @@ -74,7 +74,7 @@ pub fn zip_scope(root: &Path, dir_rel: &str) -> Result<(Vec, u32), String> { let bytes = match std::fs::read(entry.path()) { Ok(bytes) => bytes, Err(e) => { - crate::logger::log_warn("notes", &format!("导出跳过 {rel}(读取失败: {e})")); + crate::logger::log_warn("editor", &format!("导出跳过 {rel}(读取失败: {e})")); continue; } }; @@ -113,10 +113,10 @@ mod tests { #[test] fn full_export_skips_private_dir_only() { let root = temp_lib("all"); - std::fs::create_dir_all(root.join(".notes")).unwrap(); + 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(".notes/notes.db"), "x").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(); @@ -129,7 +129,7 @@ mod tests { "普通点号目录应被导出: {list:?}" ); assert!( - !list.iter().any(|n| n.starts_with(".notes")), + !list.iter().any(|n| n.starts_with(".editor")), "私有目录不该导出: {list:?}" ); diff --git a/src-tauri/src/notes/files.rs b/src-tauri/src/editor/files.rs similarity index 63% rename from src-tauri/src/notes/files.rs rename to src-tauri/src/editor/files.rs index 96ae951..ae48c91 100644 --- a/src-tauri/src/notes/files.rs +++ b/src-tauri/src/editor/files.rs @@ -10,7 +10,7 @@ //! # 为什么要有授权白名单 //! //! 前端传来的路径一律不可信:一个被污染的 WebView(XSS、恶意依赖)如果能调 -//! `notes_write_file('/Windows/System32/...')`,那就不是编辑器而是任意文件写入漏洞。 +//! `editor_write_file('/Windows/System32/...')`,那就不是编辑器而是任意文件写入漏洞。 //! 做法:只有经过 [`authorize`] 登记过的路径才允许读**写**(读也一并限制,避免拿它 //! 当任意文件读取接口探测磁盘)。授权的三个来源都是用户动作:系统文件对话框、 //! 命令行参数、库本身。 @@ -69,6 +69,15 @@ pub struct FileDoc { 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() } /// 登记一个路径为「已授权可写」。 @@ -105,16 +114,18 @@ pub fn display_path(path: &Path) -> String { } } -/// 探测编码:返回规范名(`utf-8` / `utf-8-bom` / `gbk` / `gb18030` / `big5` / …)。 +/// 探测编码:返回规范名(`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. **GB18030 试解**:GB18030 是 GBK 的超集,用它解 GBK 内容总能成功, -/// 因此作为「非 UTF-8 中文」的兜底(比 GBK 更宽,能覆盖 4 字节生僻字); -/// 4. 都失败则按 UTF-8 有损解码(宁可显示替换字符,也不要打不开文件)。 +/// 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(); @@ -128,15 +139,50 @@ pub fn detect_encoding(bytes: &[u8]) -> String { if std::str::from_utf8(bytes).is_ok() { return "utf-8".to_string(); } - // 非 UTF-8:交给 GB18030 兜底(GBK 的每个序列在 GB18030 下都合法) + // 非 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 { + 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 已剥离)。 -fn decode_bytes(bytes: &[u8], encoding: &str) -> String { +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); @@ -151,7 +197,11 @@ fn decode_bytes(bytes: &[u8], encoding: &str) -> String { } /// 按编码把字符串编成字节(必要时写回 BOM)。 -fn encode_text(text: &str, encoding: &str) -> Result, String> { +/// +/// **不可表示字符绝不静默替换成 `?`**(那是不可逆的数据损坏):先整串试编一次, +/// 若往返比对不一致(说明有字符编不进去),再逐字符定位并报错,让用户改用 UTF-8 +/// 或删除这些字符。 +pub(crate) fn encode_text(text: &str, encoding: &str) -> Result, String> { match encoding { "utf-8-bom" => { let mut out = vec![0xEF, 0xBB, 0xBF]; @@ -163,11 +213,46 @@ fn encode_text(text: &str, encoding: &str) -> Result, String> { if !crate::terminal::encoding::is_supported(&normalized) { return Err(format!("不支持的编码:{other}")); } - Ok(crate::terminal::encoding::encode(text, &normalized)) + 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::>() + .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") { @@ -177,8 +262,25 @@ fn detect_eol(text: &str) -> String { } } -/// 读取任意文件。 +/// 读取任意文件(自动探测编码)。 pub fn read_file(path: &str, max_mb: u32) -> Result { + read_file_inner(path, max_mb, None) +} + +/// 以指定编码**重新解码磁盘字节**(不写回,只换一种解释方式)。 +/// +/// 语义(规划 §5.3):切换编码是「换一种方式解释**磁盘字节**」,而不是「重新解释 +/// 缓冲区文本」—— 因此必须回到磁盘字节重新解码,而不是把编辑器里已有的字符串再转一次。 +pub fn redecode_file(path: &str, encoding: &str, max_mb: u32) -> Result { + 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 { let trimmed = path.trim(); if trimmed.is_empty() { return Err("路径为空".to_string()); @@ -193,7 +295,21 @@ pub fn read_file(path: &str, max_mb: u32) -> Result { } let bytes = std::fs::read(p).map_err(|e| format!("读取文件失败: {e}"))?; - let encoding = detect_encoding(&bytes); + 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 的一份文档只应有一种换行,混合换行会让 @@ -219,6 +335,7 @@ pub fn read_file(path: &str, max_mb: u32) -> Result { .map(|d| d.as_millis() as u64) .unwrap_or(0), large: meta.len() > limit, + readonly: !is_writable(p), }) } @@ -241,6 +358,9 @@ pub fn write_file( 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() @@ -307,11 +427,30 @@ mod tests { } #[test] - fn detects_non_utf8_as_gb18030() { - // 「测试」的 GBK 字节:合法 UTF-8 校验必然失败 - let gbk = crate::terminal::encoding::encode("测试", "gbk"); - assert_eq!(detect_encoding(&gbk), "gb18030"); - assert_eq!(decode_bytes(&gbk, "gb18030"), "测试"); + 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] diff --git a/src-tauri/src/editor/grep.rs b/src-tauri/src/editor/grep.rs new file mode 100644 index 0000000..e6a6603 --- /dev/null +++ b/src-tauri/src/editor/grep.rs @@ -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 { + 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) -> Vec { + 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) -> Option { + 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::>() + .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, + /// 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件) + pub file_types: Option, + /// 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单) + pub skip_dirs: Option, +} + +/// 一处命中(以「行」为单位)。 +#[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, +} + +/// 一次「在路径中查找」的结果。 +#[derive(Debug, Clone, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PathSearchResult { + /// 按文件分组的命中(文件按遍历顺序;超出回传上限的文件不在此列) + pub files: Vec, + /// 全树命中行总数(统计完整,不受 `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, + /// 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件) + pub file_types: Option, + /// 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单) + pub skip_dirs: Option, +} + +/// 一个被修改的文件。 +#[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, + pub files_changed: i64, + pub replacements: i64, + /// 达到上限提前停止:此时**只改了前面一部分文件** + pub truncated: bool, + pub skipped: Vec, +} + +/// 在目录内逐行检索,按文件分组返回。 +pub fn search_in_path(query: PathSearchQuery) -> Result { + 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 = 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 = 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 { + 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 { + 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 = 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 { + 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 { + 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); + } +} \ No newline at end of file diff --git a/src-tauri/src/notes/import.rs b/src-tauri/src/editor/import.rs similarity index 100% rename from src-tauri/src/notes/import.rs rename to src-tauri/src/editor/import.rs diff --git a/src-tauri/src/notes/index.rs b/src-tauri/src/editor/index.rs similarity index 98% rename from src-tauri/src/notes/index.rs rename to src-tauri/src/editor/index.rs index e58b79d..0378762 100644 --- a/src-tauri/src/notes/index.rs +++ b/src-tauri/src/editor/index.rs @@ -3,7 +3,7 @@ //! # 索引不是真相 //! //! 真相永远是库根下的 `.md` 文件(见 `library.rs`)。本模块只是**可随时丢弃重建** -//! 的加速层:删掉 `{库根}/.notes/notes.db` 的唯一后果是下次搜索前要做一次全量扫描。 +//! 的加速层:删掉 `{库根}/.editor/editor.db` 的唯一后果是下次搜索前要做一次全量扫描。 //! 因此这里不写「强一致」逻辑,只保证「一次同步之后索引与文件一致」—— //! 增量同步靠 `(mtime, size)` 快速筛掉未变文件,变了才读内容算 hash。 //! @@ -13,7 +13,7 @@ //! 不需要维护「库 → 索引文件」的映射;把整个库目录拷走时索引一起走,新机器上 //! 第一次搜索只做增量校验而不是全量重建。 //! -//! 代价是「数据库落在用户看得见的目录里」,所以目录名用点号前缀 `.notes/`: +//! 代价是「数据库落在用户看得见的目录里」,所以目录名用点号前缀 `.editor/`: //! 库扫描(`library::scan`)本来就跳过点号开头的目录,它不会出现在侧栏树里; //! P2 的 WebDAV 同步也会按约定排除它。 //! @@ -398,7 +398,7 @@ pub struct NoteSyncReport { } /// 笔记索引(持有 SQLite 连接 + 当前库根)。 -pub struct NotesIndex { +pub struct EditorIndex { conn: Connection, /// 索引所属的库根(库切换时整个索引实例被替换) root: PathBuf, @@ -406,15 +406,17 @@ pub struct NotesIndex { db_path: PathBuf, } -impl NotesIndex { +impl EditorIndex { /// 打开(或创建)某个库根对应的索引。 /// /// 库根切换后由命令层用新库根调用本函数重建实例 —— 索引与库一一对应, /// 不做「一份索引服务多个库」的多态(那需要为每张表加 root 列,得不偿失)。 pub fn open(root: &Path) -> Result { - let dir = root.join(".notes"); + // 惰性迁移旧私有目录(幂等):索引可重建,但同步基线要跟着搬过去 + library::migrate_private_dir(root); + let dir = root.join(library::PRIVATE_DIR); std::fs::create_dir_all(&dir).map_err(|e| format!("创建索引目录失败: {e}"))?; - let db_path = dir.join("notes.db"); + let db_path = dir.join("editor.db"); let conn = Connection::open(&db_path).map_err(|e| format!("打开笔记索引失败: {e}"))?; conn.busy_timeout(std::time::Duration::from_secs(3)) .map_err(|e| format!("设置索引超时失败: {e}"))?; @@ -450,7 +452,7 @@ impl NotesIndex { if version != 0 && version != SCHEMA_VERSION { crate::logger::log_warn( - "notes", + "editor", &format!("索引结构版本 {version} → {SCHEMA_VERSION},按文件重建索引"), ); self.drop_all()?; @@ -563,7 +565,7 @@ impl NotesIndex { continue; } let path = entry.path(); - // 跳过点号目录(含 `.notes/` 自身)与根级 assets/ + // 跳过点号目录(含 `.editor/` 自身)与根级 assets/ if skip_path(&root, path) { continue; } @@ -626,7 +628,7 @@ impl NotesIndex { let bytes = match std::fs::read(&path) { Ok(b) => b, Err(e) => { - crate::logger::log_warn("notes", &format!("索引读取失败 {rel}: {e}")); + crate::logger::log_warn("editor", &format!("索引读取失败 {rel}: {e}")); continue; } }; @@ -1069,7 +1071,7 @@ fn skip_path(root: &Path, path: &Path) -> bool { return false; } let parts: Vec<&str> = rel.split('/').collect(); - // 任何一层是点号开头 → 排除(`.notes/` 索引自身、`.git/` 等) + // 任何一层是点号开头 → 排除(`.editor/` 索引自身、`.git/` 等) if parts.iter().any(|p| p.starts_with('.')) { return true; } @@ -1294,7 +1296,7 @@ mod tests { #[test] fn index_roundtrip_search_tags_and_rebuild() { let root = std::env::temp_dir().join(format!( - "thing-notes-index-test-{}", + "thing-editor-index-test-{}", std::process::id() )); let _ = std::fs::remove_dir_all(&root); @@ -1314,9 +1316,9 @@ mod tests { // 非 .md 与点号目录都不该被索引 std::fs::write(root.join("notes/notes.txt"), "不该被索引").unwrap(); - // 先打开索引(顺带创建 `.notes/` 目录),再往里塞一个「不该被索引」的 .md - let mut index = NotesIndex::open(&root).unwrap(); - std::fs::write(root.join(".notes/ignored.md"), "也不该被索引").unwrap(); + // 先打开索引(顺带创建 `.editor/` 目录),再往里塞一个「不该被索引」的 .md + let mut index = EditorIndex::open(&root).unwrap(); + std::fs::write(root.join(".editor/ignored.md"), "也不该被索引").unwrap(); let report = index.sync().unwrap(); assert_eq!(report.indexed, 2, "只应索引两篇 .md"); @@ -1427,7 +1429,7 @@ mod tests { #[test] fn front_matter_id_and_dates_are_indexed() { let root = std::env::temp_dir().join(format!( - "thing-notes-index-fm-{}", + "thing-editor-index-fm-{}", std::process::id() )); let _ = std::fs::remove_dir_all(&root); @@ -1438,7 +1440,7 @@ mod tests { ) .unwrap(); - let mut index = NotesIndex::open(&root).unwrap(); + let mut index = EditorIndex::open(&root).unwrap(); index.sync().unwrap(); let page = index .search(NoteSearchQuery { diff --git a/src-tauri/src/notes/index_service.rs b/src-tauri/src/editor/index_service.rs similarity index 69% rename from src-tauri/src/notes/index_service.rs rename to src-tauri/src/editor/index_service.rs index 1a33ad8..7c72fac 100644 --- a/src-tauri/src/notes/index_service.rs +++ b/src-tauri/src/editor/index_service.rs @@ -19,8 +19,11 @@ //! 比「回调里发前端事件 → 前端再调一次同步命令」少一次往返,也不会因为前端窗口 //! 关着而漏掉索引更新。 //! -//! 自我保存抑制([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发 -//! `Modify(Data)`,若不抑制,前端就会在用户自己打字时反复弹出「文件已被外部修改」。 +//! 自我保存识别([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发 +//! `Modify(Data)`,若把这类事件也当成「外部修改」,前端就会在用户自己打字时反复 +//! 重载文档 / 弹提示。识别按**库内相对路径**在写入前登记(见 `mark_write_path`), +//! 结果写进事件的 `from_app`,由前端决定是否提示 —— 而不是在这里静默丢弃事件。 +//! 静默丢弃一旦因时序漏判,前端就会把自家的保存当成外部改动而重载。 use std::path::{Path, PathBuf}; use std::sync::mpsc::{self, Receiver, Sender}; @@ -33,21 +36,28 @@ use specta::Type; use tauri::{AppHandle, Emitter}; use super::files; -use super::index::{content_hash, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery, NoteSyncReport, NotesIndex}; +use super::index::{content_hash, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery, NoteSyncReport, EditorIndex}; use super::library; use crate::constants::events; -/// 自我保存抑制窗口:`notes_write_*` 之后这段时间内的文件事件不当作「外部修改」。 +/// 自我写入(自己刚保存)与外部改动之间的**去重窗口**。 /// -/// 取 1200ms:前端自动保存默认 800ms 防抖,加上写盘与 notify 自身的派发延迟, -/// 这个窗口足够覆盖「自己写的」这一类事件,又短到不会吞掉用户紧接着在外部编辑器 -/// 里的另一次保存(那种情况用户本来就刚切过窗口,多等一秒无妨)。 +/// 取 1200ms:一次写入可能被 notify 拆成多条事件(`Modify(Data)` 常伴一条元数据事件), +/// 命中的第一条之后,这段时间内的同路径事件一并算作「自己写的」,既不重复处理, +/// 又不会把窗口拉得太长去吞掉用户紧接着在外部编辑器里的另一次保存。 const SUPPRESS_MS: u64 = 1200; +/// 自我写入登记在「尚未被任何文件事件命中」时的最长存活时间。 +/// +/// 比去重窗口宽得多:notify 的派发延迟可能到秒级,窗口太窄会把「自己刚写的」误判成 +/// 外部修改(重载文档、光标弹回第一行)—— 这正是要避免的事故。登记项一旦被**第一个** +/// 匹配事件消费,就只保留 [`SUPPRESS_MS`] 的去重窗口,不会长期吞掉真正的外部改动。 +const SELF_WRITE_TTL_MS: u64 = 30_000; + /// 单个文件事件的去抖说明。 /// /// worker 是「来一条处理一条」,去抖由三层共同承担:notify 自身的派发合并、 -/// 前端 `notes-library-changed` 的 400ms 防抖、以及自我保存抑制窗口。 +/// 前端 `editor-library-changed` 的 400ms 防抖、以及自我保存抑制窗口。 /// 之所以不在这里再加一个定时器:多一层延迟就多一个「事件丢了谁负责」的疑问, /// 而下游每一层都是幂等的(重复同步同一个文件只是重算一次 hash)。 const _DEBOUNCE_NOTE_MS: u64 = 250; @@ -109,7 +119,7 @@ enum Request { /// 全量重建 Rebuild(Sender>), /// 同步单个文件(监听器投递;文件不存在则从索引移除) - SyncPath(PathBuf, bool), + SyncPath(PathBuf), /// 全文检索 Search(NoteSearchQuery, Sender>), /// 快速打开清单 @@ -126,11 +136,38 @@ enum Request { Retarget(PathBuf, Sender>), } +/// 一条「本应用自己写入」的登记。 +struct SelfWrite { + /// 库内相对路径(`/` 分隔,与 [`library::rel_string`] 的输出一致) + rel: String, + /// 登记时刻(写入之前,见 [`IndexService::mark_write_path`]) + marked: Instant, + /// 首次被文件事件命中的时刻(`None` = 还没等到它的事件) + matched: Option, +} + +/// 丢弃过期的自我写入登记。 +/// +/// - **已命中**:保留 [`SUPPRESS_MS`] —— 覆盖同一次写入产生的重复事件。 +/// - **未命中**:保留 [`SELF_WRITE_TTL_MS`] —— 等它的文件事件到达(notify 延迟可能到秒级)。 +fn prune_self_writes(paths: &mut Vec) { + 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, - /// 自我保存抑制的时间点(`notes_write_*` 写入) - last_write: Mutex>, + /// 批量自我写入的时间点(导入 / WebDAV 同步 / 恢复 / 模板导出这类无法逐路径枚举的操作)。 + /// 窗口内的一切文件事件都当作「自己写的」,不向前端提示外部修改。 + bulk_write: Mutex>, + /// 单个文件的自我写入登记。 + /// 比批量窗口精确:保存 A 不会再顺带吞掉 B 的外部改动事件。 + write_paths: Mutex>, } static SERVICE: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -145,29 +182,72 @@ impl IndexService { let (tx, rx) = mpsc::channel::(); let handle_tx = tx.clone(); std::thread::Builder::new() - .name("notes-index".to_string()) + .name("editor-index".to_string()) .spawn(move || worker_loop(app, rx, handle_tx)) .expect("启动笔记索引线程失败"); Self { tx, - last_write: Mutex::new(None), + bulk_write: Mutex::new(None), + write_paths: Mutex::new(Vec::new()), } } - /// 标记「刚刚由本应用写入了文件」,用于抑制自我触发的「外部修改」提示。 - pub fn mark_write(&self) { - if let Ok(mut slot) = self.last_write.lock() { + /// 标记「刚刚由本应用**批量**写入了文件」(导入 / 同步 / 恢复 / 模板导出)。 + /// 这类操作无法逐路径枚举,窗口内一律视为自我写入。 + pub fn mark_write_all(&self) { + if let Ok(mut slot) = self.bulk_write.lock() { *slot = Some(Instant::now()); } } - fn recently_written(&self) -> bool { - self.last_write + /// 登记「本应用即将写入这个库内相对路径」。 + /// + /// **必须在真正的 `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) + .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 } /// 增量同步整个库。 @@ -252,9 +332,9 @@ impl IndexService { } } -/// worker 主循环:独占 [`NotesIndex`],串行处理所有请求。 +/// worker 主循环:独占 [`EditorIndex`],串行处理所有请求。 fn worker_loop(app: AppHandle, rx: Receiver, handle_tx: Sender) { - let mut index: Option = None; + let mut index: Option = None; let mut watcher: Option = None; let mut watched_root: Option = None; let mut root: Option = None; @@ -288,6 +368,14 @@ fn worker_loop(app: AppHandle, rx: Receiver, handle_tx: Sender 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()); @@ -302,17 +390,17 @@ fn worker_loop(app: AppHandle, rx: Receiver, handle_tx: Sender // 新库的监听器要在回复之后建:先让前端拿到「已切换」的结果 ensure_watcher(&mut watcher, &mut watched_root, &next, &handle_tx); } - Request::SyncPath(path, from_app) => { + 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("notes", &format!("索引不可用: {e}")); + 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, from_app); + sync_one(&app, index.as_mut(), ¤t, &path); } } } @@ -322,9 +410,9 @@ fn worker_loop(app: AppHandle, rx: Receiver, handle_tx: Sender /// 借出索引(必要时按 `root` 打开),并把结果映射成 `Result<_, String>`。 fn with_index( app: &AppHandle, - index: &mut Option, + index: &mut Option, root: &mut Option, - run: impl FnOnce(&mut NotesIndex) -> Result, + run: impl FnOnce(&mut EditorIndex) -> Result, ) -> Result { let Some(current) = root.clone() else { // 不在这里猜库根:命令层每次操作前都会 `retarget` 到当前库根, @@ -339,18 +427,18 @@ fn with_index( } /// 确保索引实例存在且指向 `root`(不匹配则重新打开)。 -fn ensure_index(app: &AppHandle, index: &mut Option, root: &Path) -> Result<(), String> { +fn ensure_index(app: &AppHandle, index: &mut Option, 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("notes", &e); + crate::logger::log_warn("editor", &e); } - let opened = NotesIndex::open(root)?; + let opened = EditorIndex::open(root)?; crate::logger::log_info( - "notes", + "editor", &format!("索引已就绪: {}", opened.db_path().display()), ); // 首次打开时不自动全量同步:库可能很大,交给命令层(打开编辑器 / 重建索引时)触发 @@ -367,7 +455,7 @@ fn ensure_watcher( tx: &Sender, ) { if let Err(e) = ensure_watcher_inner(watcher, watched_root, root, tx) { - crate::logger::log_warn("notes", &e); + crate::logger::log_warn("editor", &e); } } @@ -385,7 +473,7 @@ fn ensure_watcher_inner( let mut next = notify::recommended_watcher(move |event: notify::Result| { let Ok(event) = event else { return }; for path in event_paths(&event) { - let _ = sender.send(Request::SyncPath(path, true)); + let _ = sender.send(Request::SyncPath(path)); } }) .map_err(|e| format!("创建库监听器失败: {e}"))?; @@ -396,11 +484,11 @@ fn ensure_watcher_inner( // 替换旧监听器(drop 即 unwatch) *watcher = Some(next); *watched_root = Some(root.to_path_buf()); - crate::logger::log_info("notes", &format!("库监听已启动: {}", root.display())); + crate::logger::log_info("editor", &format!("库监听已启动: {}", root.display())); Ok(()) } -/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.notes/` 自身)。 +/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.editor/` 自身)。 /// /// 重命名会给出两个路径(旧、新),这里都收下:旧路径在同步时会发现「文件不存在」 /// 而被当作删除处理,新路径自然成为新增 —— 无需专门分辨 RenameMode。 @@ -428,13 +516,10 @@ fn event_paths(event: ¬ify::Event) -> Vec { } /// 就地同步单个文件(含自我保存抑制与前端事件广播)。 -fn sync_one( - app: &AppHandle, - index: Option<&mut NotesIndex>, - root: &Path, - path: &Path, - from_app: bool, -) { +/// +/// 事件是否「本应用自己写的」按**库内相对路径**判定(见 [`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/") { @@ -442,8 +527,10 @@ fn sync_one( } // 自我保存抑制:只影响「是否提示用户」,索引照常更新 - let service = SERVICE.get(); - let self_write = from_app && service.map(|s| s.recently_written()).unwrap_or(false); + 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) { @@ -464,7 +551,7 @@ fn sync_one( &content_hash(&bytes), &stems, ) { - crate::logger::log_warn("notes", &format!("增量索引 {rel} 失败: {e}")); + crate::logger::log_warn("editor", &format!("增量索引 {rel} 失败: {e}")); } } else { return; @@ -474,27 +561,26 @@ fn sync_one( CHANGE_MODIFIED } else { if let Err(e) = index.remove_note(&rel) { - crate::logger::log_warn("notes", &format!("移除索引 {rel} 失败: {e}")); + crate::logger::log_warn("editor", &format!("移除索引 {rel} 失败: {e}")); } CHANGE_REMOVED }; - if self_write { - // 自己写的:索引已更新,前端无需提示(它的编辑器里本来就是最新内容) - return; - } - + // 事件一律发出,用 `from_app` 如实标注来源,由前端决定是否提示/重载。 + // 早期实现是「自己写的就静默不发」,一旦自我写入判定因时序漏过,前端就会把自家 + // 的保存当成外部修改而重载文档(光标弹回第一行)—— 判定留在前端更稳。 let payload = NoteFileEvent { rel_path: rel, abs_path: files::display_path(path), - kind: kind.to_string(), at: std::time::SystemTime::now() + 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::NOTES_FILE_CHANGED, payload) { - crate::logger::log_warn("notes", &format!("发出文件变化事件失败: {e}")); + if let Err(e) = app.emit(events::EDITOR_FILE_CHANGED, payload) { + crate::logger::log_warn("editor", &format!("发出文件变化事件失败: {e}")); } } diff --git a/src-tauri/src/notes/library.rs b/src-tauri/src/editor/library.rs similarity index 87% rename from src-tauri/src/notes/library.rs rename to src-tauri/src/editor/library.rs index b3303ae..eff66db 100644 --- a/src-tauri/src/notes/library.rs +++ b/src-tauri/src/editor/library.rs @@ -9,12 +9,16 @@ use std::path::{Path, PathBuf}; use std::time::UNIX_EPOCH; -use super::types::{LibraryEntry, NoteDoc, NoteSettings}; +use super::types::{LibraryEntry, NoteDoc, EditorSettings}; -/// 默认库根相对模块目录的名字:`{app_data_dir}/notes/library` +/// 默认库根相对模块目录的名字:`{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` 公开:两处扫描(侧栏树 / 索引)必须用同一个深度口径, /// 否则会出现「树里看不到、搜索却搜得到」这种自相矛盾的状态。 @@ -34,15 +38,43 @@ pub fn default_library_root(module_dir: &Path) -> PathBuf { } /// 由设置解析出当前生效的库根。 -pub fn resolve_library_root(module_dir: &Path, settings: &NoteSettings) -> PathBuf { +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), } } -/// 确保库根与其 `assets/` 子目录存在。 +/// 惰性迁移旧私有目录 `.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}"))?; @@ -136,7 +168,7 @@ fn walk(root: &Path, dir: &Path, out: &mut Vec, depth: usize) { let mut files: Vec<(String, PathBuf)> = Vec::new(); for entry in read.flatten() { let name = entry.file_name().to_string_lossy().to_string(); - // 隐藏项(含 `.notes` 之类的私有目录)一律不进库树 + // 隐藏项(含 `.editor` 之类的私有目录)一律不进库树 if name.starts_with('.') { continue; } diff --git a/src-tauri/src/notes/mod.rs b/src-tauri/src/editor/mod.rs similarity index 52% rename from src-tauri/src/notes/mod.rs rename to src-tauri/src/editor/mod.rs index ede3831..b70f036 100644 --- a/src-tauri/src/notes/mod.rs +++ b/src-tauri/src/editor/mod.rs @@ -7,7 +7,7 @@ //! ↓ Tauri IPC ↓ //! commands.rs 命令层 //! ↓ -//! NotesManager(本文件):设置读写 / 库根解析 +//! EditorManager(本文件):设置读写 / 库根解析 //! ↓ //! library.rs 文件系统(路径安全 / 扫描 / 读写 / 增删改移) //! ``` @@ -25,36 +25,48 @@ //! index_service.rs 索引与监听:独占 SQLite 连接的单线程 worker + notify //! ``` //! -//! 设置持久化:`{app_data_dir}/notes/settings.json`(范式同 ai / translate)。 -//! 默认库根:`{app_data_dir}/notes/library`;用户可在设置里改。 +//! 设置持久化:`{app_data_dir}/editor/settings.json`(范式同 ai / translate)。 +//! 默认库根:`{app_data_dir}/editor/library`;用户可在设置里改。 mod args; mod backup; mod commands; +mod dirs; mod export; 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::{ - notes_add_template, notes_authorize_file, notes_backlinks, notes_backup_now, - notes_create_folder, notes_create_note, notes_daily_note, notes_delete_entry, - notes_export_note, notes_export_snapshot_local, notes_export_zip, notes_get_settings, - notes_import, notes_index_stats, notes_library_info, notes_link_graph, notes_list_backups, - notes_list_notes, notes_list_templates, notes_open_file, notes_read_asset, notes_read_note, - notes_read_template, notes_rebuild_index, notes_rename_entry, notes_restore_backup, - notes_save_note, notes_save_settings, notes_scan_library, notes_search_notes, - notes_set_library_root, notes_set_webdav_password, notes_sync_index, notes_sync_now, - notes_tags, notes_take_pending_file, notes_test_webdav, notes_webdav_status, - notes_write_asset, notes_write_file, + 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_file, note_path_from_args, remember_pending_file}; -use types::NoteSettings; +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; @@ -65,19 +77,34 @@ const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500); struct SettingsCache { read_at: Instant, - settings: NoteSettings, + settings: EditorSettings, } -/// 笔记模块管理器(Tauri State)。 -pub struct NotesManager { - /// 模块自身目录:`{app_data_dir}/notes` +/// 笔记 / 编辑器模块管理器(Tauri State)。 +pub struct EditorManager { + /// 模块自身目录:`{app_data_dir}/editor` module_dir: PathBuf, cache: Mutex>, } -impl NotesManager { +/// 一次性迁移 `{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("notes"); + 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, @@ -100,23 +127,23 @@ impl NotesManager { let settings = self.load_settings(); let new_note = settings.new_note_shortcut.clone(); - if let Err(e) = crate::shortcut::register_shortcut(app, "notes-new-note", &new_note, |app| { - if let Err(e) = app.emit(crate::constants::events::NOTES_NEW_NOTE, ()) { - crate::logger::log_warn("notes", &format!("发出新建笔记事件失败: {e}")); + 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("notes", &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, "notes-open-editor", &open_editor, |app| { - if let Err(e) = app.emit(crate::constants::events::NOTES_OPEN_EDITOR, ()) { - crate::logger::log_warn("notes", &format!("发出打开编辑器事件失败: {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("notes", &format!("注册「打开编辑器」快捷键失败: {e}")); + crate::logger::log_warn("editor", &format!("注册「打开编辑器」快捷键失败: {e}")); } } @@ -125,7 +152,7 @@ impl NotesManager { } /// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。 - pub fn load_settings(&self) -> NoteSettings { + 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 { @@ -136,9 +163,11 @@ impl NotesManager { let mut settings = std::fs::read_to_string(self.settings_path()) .ok() - .and_then(|s| serde_json::from_str::(&s).ok()) + .and_then(|s| serde_json::from_str::(&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(), @@ -147,14 +176,14 @@ impl NotesManager { } if healed { if let Err(e) = self.save_settings(&settings) { - crate::logger::log_error("notes", &format!("设置自愈落盘失败: {e}")); + crate::logger::log_error("editor", &format!("设置自愈落盘失败: {e}")); } } settings } /// 保存设置并刷新缓存。 - pub fn save_settings(&self, settings: &NoteSettings) -> Result<(), String> { + 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) diff --git a/src-tauri/src/editor/shell_menu.rs b/src-tauri/src/editor/shell_menu.rs new file mode 100644 index 0000000..ba9b13e --- /dev/null +++ b/src-tauri/src/editor/shell_menu.rs @@ -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 { + imp::register()?; + Ok(editor_context_menu_status()) +} + +/// 卸载右键菜单(删 HKCU 对应项)。 +#[tauri::command] +#[specta::specta] +pub fn editor_unregister_context_menu() -> Result { + 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()) + } +} \ No newline at end of file diff --git a/src-tauri/src/notes/templates.rs b/src-tauri/src/editor/templates.rs similarity index 100% rename from src-tauri/src/notes/templates.rs rename to src-tauri/src/editor/templates.rs diff --git a/src-tauri/src/notes/types.rs b/src-tauri/src/editor/types.rs similarity index 76% rename from src-tauri/src/notes/types.rs rename to src-tauri/src/editor/types.rs index a51e701..fc423b3 100644 --- a/src-tauri/src/notes/types.rs +++ b/src-tauri/src/editor/types.rs @@ -1,6 +1,6 @@ //! 笔记模块的数据模型。 //! -//! 持久化位置:`{app_data_dir}/notes/settings.json`(与 ai / translate / terminal 同一范式)。 +//! 持久化位置:`{app_data_dir}/editor/settings.json`(与 ai / translate / terminal 同一范式)。 //! 容器级 `#[serde(default)]`:新增字段对旧配置文件向后兼容(缺字段取 //! `Default::default()` 的对应值,而不是让整份设置反序列化失败)。 //! @@ -10,8 +10,11 @@ use serde::{Deserialize, Serialize}; use specta::Type; -/// 结构版本号。字段增减时递增,由 [`NoteSettings::heal`] 推进。 -pub const NOTES_SETTINGS_VERSION: u32 = 2; +/// 结构版本号。字段增减时递增,由 [`EditorSettings::heal`] 推进。 +pub const EDITOR_SETTINGS_VERSION: u32 = 4; + +/// 最近文件 / 文件夹各自的保留上限(超出淘汰最旧)。 +pub const RECENT_LIMIT: usize = 20; /// 同步方向。 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] @@ -101,7 +104,7 @@ impl WebdavSettings { } } -/// 同步进度(事件 `notes-sync-progress` 的负载)。 +/// 同步进度(事件 `editor-sync-progress` 的负载)。 #[derive(Debug, Clone, Serialize, Type)] #[serde(rename_all = "camelCase")] pub struct SyncProgress { @@ -155,16 +158,33 @@ pub struct ImportReport { pub failures: Vec, } +/// 最近打开的一个文件 / 文件夹。 +/// +/// `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 NoteSettings { +pub struct EditorSettings { /// 结构版本号 pub version: u32, - /// 自定义库根(`None` = 用默认 `{app_data_dir}/notes/library`) + /// 自定义库根(`None` = 用默认 `{app_data_dir}/editor/library`) pub library_root: Option, /// 编辑器配色方案 key(`"system"` / `"vscode-dark"` / `"vscode-light"` / …) pub editor_theme: String, @@ -208,16 +228,20 @@ pub struct NoteSettings { /// 全局快捷键:新建笔记(空串 = 不注册)。 /// /// 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译同一套), - /// 触发时只发 `notes-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。 + /// 触发时只发 `editor-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。 pub new_note_shortcut: String, /// 全局快捷键:打开编辑器窗口(空串 = 不注册) pub open_editor_shortcut: String, + /// 最近打开的文件(与笔记库解耦;上限 [`RECENT_LIMIT`]) + pub recent_files: Vec, + /// 最近打开的文件夹(与笔记库解耦;上限 [`RECENT_LIMIT`]) + pub recent_folders: Vec, } -impl Default for NoteSettings { +impl Default for EditorSettings { fn default() -> Self { Self { - version: NOTES_SETTINGS_VERSION, + version: EDITOR_SETTINGS_VERSION, library_root: None, editor_theme: "system".to_string(), follow_app_theme: true, @@ -227,7 +251,9 @@ impl Default for NoteSettings { ligatures: false, tab_size: 2, live_preview: true, - autosave_ms: 800, + // 自动保存默认关闭:800ms 一保存会让「保存按钮 / 标签 * 号 / 侧栏」跟着 + // 闪烁,干扰正常编辑。需要的人可在设置里显式开启(见 heal 的 v4 迁移)。 + autosave_ms: 0, default_view: "wysiwyg".to_string(), show_line_numbers: true, show_outline: true, @@ -239,12 +265,14 @@ impl Default for NoteSettings { show_template_picker: true, export_highlight: true, new_note_shortcut: String::new(), - open_editor_shortcut: String::new(), + open_editor_shortcut: "Alt+E".to_string(), + recent_files: Vec::new(), + recent_folders: Vec::new(), } } } -impl NoteSettings { +impl EditorSettings { /// 自愈:把越界/非法取值夹回合法区间,推进版本号。 /// 返回是否发生了变更(由调用方决定是否落盘)。 pub fn heal(&mut self) -> bool { @@ -287,13 +315,47 @@ impl NoteSettings { } } - if self.version < NOTES_SETTINGS_VERSION { - self.version = NOTES_SETTINGS_VERSION; + // 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; + } + + 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(); + } + } } /// 库内一个条目(文件或目录)的扁平描述。 @@ -323,7 +385,7 @@ pub struct LibraryEntry { pub struct LibraryInfo { /// 当前生效的库根绝对路径 pub root: String, - /// 是否为用户自定义库根(false = 默认 `{app_data_dir}/notes/library`) + /// 是否为用户自定义库根(false = 默认 `{app_data_dir}/editor/library`) pub is_custom: bool, /// `.md` 笔记数量(不含目录) pub note_count: u32, diff --git a/src-tauri/src/notes/webdav/client.rs b/src-tauri/src/editor/webdav/client.rs similarity index 98% rename from src-tauri/src/notes/webdav/client.rs rename to src-tauri/src/editor/webdav/client.rs index 5fbd2d1..f1a2d13 100644 --- a/src-tauri/src/notes/webdav/client.rs +++ b/src-tauri/src/editor/webdav/client.rs @@ -252,7 +252,7 @@ impl WebdavClient { if (status == 429 || status == 503) && attempt < BACKOFF_MS.len() { let wait = BACKOFF_MS[attempt]; crate::logger::log_warn( - "notes", + "editor", &format!("WebDAV 返回 {status},{wait}ms 后重试(第 {} 次)", attempt + 1), ); std::thread::sleep(Duration::from_millis(wait)); @@ -265,7 +265,7 @@ impl WebdavClient { if attempt < BACKOFF_MS.len() { let wait = BACKOFF_MS[attempt]; crate::logger::log_warn( - "notes", + "editor", &format!("WebDAV 请求失败({e}),{wait}ms 后重试"), ); std::thread::sleep(Duration::from_millis(wait)); @@ -373,7 +373,7 @@ impl WebdavClient { while let Some(dir) = queue.pop() { depth += 1; if depth > 4096 { - crate::logger::log_warn("notes", "远端目录过多,提前结束遍历"); + crate::logger::log_warn("editor", "远端目录过多,提前结束遍历"); break; } let Some(entries) = self.list(&dir)? else { @@ -664,7 +664,7 @@ fn parse_http_date(value: &str) -> Option { /// 该远端路径是否应当排除在同步之外。 /// -/// `.notes/` 是本模块的私有目录(索引 + 同步状态),**必须排除**:把索引同步到 +/// `.editor/` 是本模块的私有目录(索引 + 同步状态),**必须排除**:把索引同步到 /// 远端毫无意义,且它随每次搜索变化,会让每一次同步都变成全量传输。 pub fn should_skip(rel: &str) -> bool { let normalized = rel.replace('\\', "/"); @@ -772,7 +772,7 @@ mod tests { #[test] fn skip_rules_exclude_private_dir() { - assert!(should_skip(".notes/notes.db")); + 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")); diff --git a/src-tauri/src/notes/webdav/mod.rs b/src-tauri/src/editor/webdav/mod.rs similarity index 96% rename from src-tauri/src/notes/webdav/mod.rs rename to src-tauri/src/editor/webdav/mod.rs index 7add611..fd274f4 100644 --- a/src-tauri/src/notes/webdav/mod.rs +++ b/src-tauri/src/editor/webdav/mod.rs @@ -15,11 +15,11 @@ pub mod sync; use serde::{Deserialize, Serialize}; use specta::Type; -use crate::notes::types::WebdavSettings; +use crate::editor::types::WebdavSettings; use client::WebdavClient; /// keyring 里的服务名(与 `secrets.rs` 的约定一致,服务名固定 `"Thing"`)。 -pub const KEYRING_PASSWORD: &str = "notes.webdav.password"; +pub const KEYRING_PASSWORD: &str = "editor.webdav.password"; /// 连接自检结果(设置页展示)。 #[derive(Debug, Clone, Serialize, Deserialize, Type)] diff --git a/src-tauri/src/notes/webdav/sync.rs b/src-tauri/src/editor/webdav/sync.rs similarity index 98% rename from src-tauri/src/notes/webdav/sync.rs rename to src-tauri/src/editor/webdav/sync.rs index f42ac68..9a329ab 100644 --- a/src-tauri/src/notes/webdav/sync.rs +++ b/src-tauri/src/editor/webdav/sync.rs @@ -2,7 +2,7 @@ //! //! # 状态存在哪、为什么不是「靠时间戳猜」 //! -//! `{库根}/.notes/sync.json` 记录**上次成功同步时**每个文件的两侧指纹: +//! `{库根}/.editor/sync.json` 记录**上次成功同步时**每个文件的两侧指纹: //! 本地内容的 hash + 本地 mtime,以及远端的 mtime。有了基线才能回答「谁改的」: //! //! - 本地 hash ≠ 基线 hash → 本地改了; @@ -36,11 +36,11 @@ use tauri::{AppHandle, Emitter}; use super::client::{should_skip, WebdavClient}; use crate::constants::events; -use crate::notes::index::content_hash; -use crate::notes::library; -use crate::notes::types::{ConflictPolicy, SyncDirection, WebdavSettings}; +use crate::editor::index::content_hash; +use crate::editor::library; +use crate::editor::types::{ConflictPolicy, SyncDirection, WebdavSettings}; -/// 同步状态文件名(位于库根 `.notes/` 下,永不参与同步)。 +/// 同步状态文件名(位于库根 `.editor/` 下,永不参与同步)。 const SYNC_STATE_FILE: &str = "sync.json"; /// 状态文件结构版本。 const SYNC_STATE_VERSION: u32 = 1; @@ -73,7 +73,7 @@ pub struct SyncState { impl SyncState { /// 从库根读取状态(缺失/损坏都回退空状态 —— 最坏结果是「下次同步当作首次」)。 pub fn load(root: &Path, remote_root: &str) -> Self { - let path = root.join(".notes").join(SYNC_STATE_FILE); + let path = root.join(".editor").join(SYNC_STATE_FILE); let mut state: SyncState = std::fs::read_to_string(&path) .ok() .and_then(|text| serde_json::from_str(&text).ok()) @@ -91,7 +91,7 @@ impl SyncState { /// 落盘。 pub fn save(&self, root: &Path) -> Result<(), String> { - let dir = root.join(".notes"); + let dir = root.join(".editor"); std::fs::create_dir_all(&dir).map_err(|e| format!("创建索引目录失败: {e}"))?; let text = serde_json::to_string_pretty(self).map_err(|e| format!("序列化同步状态失败: {e}"))?; std::fs::write(dir.join(SYNC_STATE_FILE), text).map_err(|e| format!("写入同步状态失败: {e}")) @@ -546,14 +546,14 @@ impl<'a> SyncRunner<'a> { /// 发进度事件(前端据此画进度条)。 fn progress(&self, done: usize, current: &str, kind: &str) { - let payload = crate::notes::types::SyncProgress { + let payload = crate::editor::types::SyncProgress { done: done as u32, total: self.total as u32, current: current.to_string(), kind: kind.to_string(), message: String::new(), }; - let _ = self.app.emit(events::NOTES_SYNC_PROGRESS, payload); + let _ = self.app.emit(events::EDITOR_SYNC_PROGRESS, payload); } /// 执行整个计划。 @@ -579,7 +579,7 @@ impl<'a> SyncRunner<'a> { if report.failures.len() < MAX_FAILURES { report.failures.push(format!("{}:{e}", item.rel_path)); } - crate::logger::log_warn("notes", &format!("同步 {} 失败: {e}", item.rel_path)); + crate::logger::log_warn("editor", &format!("同步 {} 失败: {e}", item.rel_path)); continue; } match item.kind { @@ -1078,10 +1078,10 @@ mod tests { let root = std::env::temp_dir().join(format!("thing-notes-scan-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(root.join("notes")).unwrap(); - std::fs::create_dir_all(root.join(".notes")).unwrap(); + std::fs::create_dir_all(root.join(".editor")).unwrap(); std::fs::write(root.join("notes/a.md"), "x").unwrap(); std::fs::write(root.join("notes/b.txt"), "x").unwrap(); - std::fs::write(root.join(".notes/notes.db"), "x").unwrap(); + std::fs::write(root.join(".editor/editor.db"), "x").unwrap(); let map = scan_local(&root).unwrap(); let keys: Vec<&String> = map.keys().collect(); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 556f915..b1a0969 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -10,7 +10,7 @@ mod mihomo_manager; mod monitor_kernel; pub mod music; mod network_monitor; -mod notes; +mod editor; mod osd_window; mod process_manager; mod quickpanel; @@ -38,17 +38,20 @@ use download_engine::{ use logger::{ log_clear, log_info_state, log_list, log_message, }; -use notes::{ - notes_add_template, notes_authorize_file, notes_backlinks, notes_backup_now, - notes_create_folder, notes_create_note, notes_daily_note, notes_delete_entry, - notes_export_note, notes_export_snapshot_local, notes_export_zip, notes_get_settings, - notes_import, notes_index_stats, notes_library_info, notes_link_graph, notes_list_backups, - notes_list_notes, notes_list_templates, notes_open_file, notes_read_asset, notes_read_note, - notes_read_template, notes_rebuild_index, notes_rename_entry, notes_restore_backup, - notes_save_note, notes_save_settings, notes_scan_library, notes_search_notes, - notes_set_library_root, notes_set_webdav_password, notes_sync_index, notes_sync_now, - notes_tags, notes_take_pending_file, notes_test_webdav, notes_webdav_status, - notes_write_asset, notes_write_file, +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 mihomo_manager::{ proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy, @@ -138,7 +141,7 @@ use quickpanel::{ 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, @@ -337,18 +340,27 @@ 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, - // notes(39)——与 `run()` 里那份保持一致,否则 bindings.ts 缺类型 - notes_get_settings, notes_save_settings, notes_library_info, notes_set_library_root, - notes_scan_library, notes_read_note, notes_save_note, notes_create_note, - notes_create_folder, notes_rename_entry, notes_delete_entry, - notes_rebuild_index, notes_sync_index, notes_search_notes, notes_list_notes, - notes_tags, notes_index_stats, notes_open_file, notes_write_file, - notes_write_asset, notes_authorize_file, - notes_list_templates, notes_add_template, notes_read_template, notes_daily_note, - notes_import, notes_export_note, notes_export_zip, notes_export_snapshot_local, - notes_webdav_status, notes_set_webdav_password, notes_test_webdav, - notes_sync_now, notes_backup_now, notes_list_backups, notes_restore_backup, - notes_backlinks, notes_link_graph, notes_take_pending_file, notes_read_asset, + // 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, ]) .export(Typescript::default(), "../src/lib/bindings.ts") .expect("failed to export bindings"); @@ -384,11 +396,13 @@ pub fn run() { let _ = window.unminimize(); let _ = window.set_focus(); } - match crate::notes::note_path_from_args(argv.clone()) { - Some(path) => crate::notes::emit_open_file(app, &path), + // 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("notes", "第二个实例无文件参数,仅聚焦主窗口"); + crate::logger::log_info("editor", "第二个实例无文件参数,仅聚焦主窗口"); } } })) @@ -618,6 +632,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, @@ -812,47 +828,62 @@ pub fn run() { dsh_install_log, dsh_log_clear, dsh_open_dir, - // notes(39) - notes_get_settings, - notes_save_settings, - notes_library_info, - notes_set_library_root, - notes_scan_library, - notes_read_note, - notes_save_note, - notes_create_note, - notes_create_folder, - notes_rename_entry, - notes_delete_entry, - notes_rebuild_index, - notes_sync_index, - notes_search_notes, - notes_list_notes, - notes_tags, - notes_index_stats, - notes_open_file, - notes_write_file, - notes_write_asset, - notes_authorize_file, - notes_list_templates, - notes_add_template, - notes_read_template, - notes_daily_note, - notes_import, - notes_export_note, - notes_export_zip, - notes_export_snapshot_local, - notes_webdav_status, - notes_set_webdav_password, - notes_test_webdav, - notes_sync_now, - notes_backup_now, - notes_list_backups, - notes_restore_backup, - notes_backlinks, - notes_link_graph, - notes_take_pending_file, - notes_read_asset + // 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 ]) .setup(setup::init) .on_window_event(|window, event| { diff --git a/src-tauri/src/music/mod.rs b/src-tauri/src/music/mod.rs index aba70f6..3ffdad8 100644 --- a/src-tauri/src/music/mod.rs +++ b/src-tauri/src/music/mod.rs @@ -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::{ diff --git a/src-tauri/src/notes/args.rs b/src-tauri/src/notes/args.rs deleted file mode 100644 index 071a59e..0000000 --- a/src-tauri/src/notes/args.rs +++ /dev/null @@ -1,153 +0,0 @@ -//! 「用 Thing 打开」的参数解析与事件投递。 -//! -//! # 两条入口,同一份逻辑 -//! -//! 1. **冷启动**:安装器注册的文件关联让 Windows 用 `thing.exe <文件路径>` 启动本应用; -//! 2. **热启动**:应用已在运行时双击 `.md`,会起第二个进程,由 -//! `tauri-plugin-single-instance` 把它的命令行参数转交给第一个实例。 -//! -//! 两条路径的输入形态完全一样(都是命令行参数),因此共用 [`note_path_from_args`]。 -//! 解析成功后统一发 [`crate::constants::events::NOTES_OPEN_FILE`],**窗口由前端创建** —— -//! Rust 侧不持有窗口 label 策略,也不该知道「用户是不是想让它在已有窗口里打开」。 - -use std::path::{Path, PathBuf}; -use std::sync::Mutex; - -/// 「启动时命令行指定的文件」缓存。 -/// -/// # 为什么需要缓存而不是启动时直接 `emit` -/// -/// 冷启动的顺序是:`setup` 跑完 → 创建主窗口 → WebView 加载前端 → 前端注册监听。 -/// 在 `setup` 里 `emit` 时前端还没开始监听,事件**直接丢掉**了 —— 表现是 -/// 「双击 .md 打开了应用,但笔记没打开」。 -/// -/// 因此这里把路径存下来,由前端在注册完监听后**主动取一次** -/// (`notes_take_pending_file`)。取走即清空,避免下次打开窗口时又被翻出来。 -static PENDING: std::sync::OnceLock>> = std::sync::OnceLock::new(); - -fn pending_slot() -> &'static Mutex> { - PENDING.get_or_init(|| Mutex::new(None)) -} - -/// 记下「启动时想打开的文件」(由 `setup` 调用)。 -pub fn remember_pending_file(path: PathBuf) { - if let Ok(mut slot) = pending_slot().lock() { - *slot = Some(path); - } -} - -/// 取出并清空待打开文件(由 `notes_take_pending_file` 命令调用)。 -pub fn take_pending_file() -> Option { - pending_slot() - .lock() - .ok() - .and_then(|mut slot| slot.take()) -} - -/// 从一组命令行参数里挑出「看起来是笔记文件」的那个路径。 -/// -/// # 为什么需要挑而不是直接用 `args[1]` -/// -/// 关联启动时命令行长这样:`thing.exe D:\笔记\会议.md`; -/// 但从「开始菜单 → 打开」启动时可能有别的开关参数;开发模式下还有 `cargo run --`。 -/// 这里只认「**存在**的文件 + 笔记类扩展名」,其余一律忽略 —— -/// 宁可漏开一个窗口,也不要因为一个参数把主窗口的启动逻辑搞乱。 -/// -/// 认的扩展名比「只有 .md」宽一点:`.markdown` / `.mdx` 也常见,且编辑器都能处理 -/// (打开后走「库外文件」路径,不影响库内笔记的 `.md` 约定)。 -/// -/// # 为什么要 `.is_file()` -/// -/// 参数里出现 `foo.md` 但那个文件其实不存在(用户删了、路径编码错了)时, -/// 让前端去报「文件不存在」不如在这里就静默忽略 —— 前端那条路径会开一个空窗口。 -pub fn note_path_from_args>(args: I) -> Option { - 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_file(app: &tauri::AppHandle, path: &Path) { - use tauri::Emitter; - let payload = serde_json::json!({ "path": path.to_string_lossy() }); - if let Err(e) = app.emit(crate::constants::events::NOTES_OPEN_FILE, payload) { - crate::logger::log_warn("notes", &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()); - } -} diff --git a/src-tauri/src/setup.rs b/src-tauri/src/setup.rs index b699ac5..46ad737 100644 --- a/src-tauri/src/setup.rs +++ b/src-tauri/src/setup.rs @@ -21,7 +21,7 @@ use crate::mihomo_manager::MihomoManager; use crate::monitor_kernel::{MonitorKernel, check_and_relaunch_if_needed}; use crate::music::MusicManager; use crate::network_monitor::NetworkMonitor; -use crate::notes::NotesManager; +use crate::editor::EditorManager; use crate::process_manager::{ProcessManager, start_monitoring_thread}; use crate::terminal::TerminalManager; use crate::translate::TranslateManager; @@ -84,19 +84,19 @@ pub fn init(app: &mut App) -> Result<(), Box> { let dsh = crate::dsh::DshManager::new(app_data_dir.clone()); app.manage(dsh); - // ===== 笔记模块:NotesManager ===== + // ===== 笔记模块:EditorManager ===== // 仅注册状态:库扫描与读写都在命令调用时按需触发,启动阶段只创建目录结构。 - let notes = NotesManager::new(app_data_dir.clone()); + 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 还没加载、前端还没注册监听,事件会丢掉。 - // 前端注册完监听后会主动调 `notes_take_pending_file` 取走(见 notes/args.rs)。 - if let Some(path) = crate::notes::note_path_from_args(std::env::args().skip(1)) { - crate::logger::log_info("notes", &format!("命令行指定打开: {}", path.display())); - crate::notes::remember_pending_file(path); + // 前端注册完监听后会主动调 `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); } // ===== 翻译模块:TranslateManager ===== diff --git a/src-tauri/src/tray_menu.rs b/src-tauri/src/tray_menu.rs index be8d044..eeeb74c 100644 --- a/src-tauri/src/tray_menu.rs +++ b/src-tauri/src/tray_menu.rs @@ -27,6 +27,7 @@ static LAST_MENU_LAYOUT: Mutex> = 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,34 @@ pub struct TrayMenuState { pub proxy_current: Option, } +/// 托盘音乐控制条状态。 +/// +/// 曲目信息取自 [`SmtcMetaCache`](前端推给 SMTC 的元数据回填), +/// 播放态取自 [`AudioEngine`]:两者都在 Rust 侧,托盘菜单只需一次拉取。 +#[derive(Serialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct MusicState { + pub playing: bool, + pub title: String, + pub artist: String, +} + +fn get_music_state(app: &AppHandle) -> MusicState { + let playing = app + .try_state::() + .map(|e| e.state().playing) + .unwrap_or(false); + let (title, artist) = app + .try_state::() + .and_then(|c| c.0.lock().ok().map(|g| (g.title.clone(), g.artist.clone()))) + .unwrap_or_default(); + MusicState { + playing, + title, + artist, + } +} + // ===== 状态查询 ===== fn is_proxy_running(app: &AppHandle) -> bool { @@ -420,14 +449,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 +496,37 @@ 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`)执行—— +/// 队列、洗牌、单曲循环等播放语义都在前端,托盘只负责转发,不重复实现。 +/// `action`:`toggle` | `play` | `pause` | `next` | `prev`。 +#[tauri::command] +pub fn tray_music_control(app: AppHandle, action: String) -> Result<(), 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", + other => return Err(format!("未知的音乐控制动作: {other}")), + }; + app.emit(SMTC_BUTTON_EVENT, name).map_err(|e| e.to_string()) +} + /// 前端测量内容高度后调用:调整窗口大小、精确定位、然后显示。 /// 这样窗口从一开始就是正确尺寸和位置,不会出现间隙。 #[tauri::command] @@ -502,6 +566,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(); diff --git a/src-tauri/src/win32_util.rs b/src-tauri/src/win32_util.rs index e5c6440..8c0485f 100644 --- a/src-tauri/src/win32_util.rs +++ b/src-tauri/src/win32_util.rs @@ -233,6 +233,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 +327,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 } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index dc85bca..f08ef65 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -41,8 +41,8 @@ "fileAssociations": [ { "ext": ["md", "markdown", "mdx"], - "name": "Markdown 笔记", - "description": "用 Thing 打开 Markdown 笔记", + "name": "Markdown 文档", + "description": "用 Thing 编辑器打开 Markdown 文档", "role": "Editor" } ], diff --git a/src/App.vue b/src/App.vue index abdfe47..5da7ae8 100644 --- a/src/App.vue +++ b/src/App.vue @@ -14,10 +14,12 @@ 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 { 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 { EVENTS, STORAGE_KEYS, WINDOWS } from '@/lib/constants' import { commands } from '@/lib/bindings' @@ -27,6 +29,7 @@ const screenshotStore = useScreenshotStore() const quickpanelStore = useQuickPanelStore() const monitorStore = useMonitorStore() const processStore = useProcessStore() +const dshStore = useDshStore() /** 侧边栏 / 标题栏需要的模块信息(id + name + icon) */ interface NavModule { @@ -244,15 +247,24 @@ 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)) + }) + ) + // 托盘「dsh」:就绪则直接开界面,否则先开启动进度窗口并同步拉起服务 + trayUnlisteners.push( + await listen(EVENTS.trayOpenDsh, () => { + void dshStore.openFromTray().catch(e => console.error('[tray] 打开 dsh 失败:', e)) }) ) // 浏览器扩展新增下载:为该任务创建一个专属的一次性下载窗口(不打断主界面)。 @@ -263,11 +275,6 @@ onMounted(async () => { void openDownloadWindow(e.payload.id) }) ) - trayUnlisteners.push( - await listen(EVENTS.trayOpenSettings, () => { - handleModuleChange('settings') - }) - ) // 截图导出监听(应用级常驻,确保任何来源的截图都记录到历史) screenshotStore.initExportListener().catch(e => console.error('[screenshot] 导出监听初始化失败:', e)) // 滚动截图完成 → 进编辑器(应用级常驻) diff --git a/src/lib/bindings.ts b/src/lib/bindings.ts index 9b6210a..b8f0398 100644 --- a/src/lib/bindings.ts +++ b/src/lib/bindings.ts @@ -921,53 +921,68 @@ export const commands = { /** 在资源管理器中打开 dsh 模块目录。 */ dshOpenDir: () => __TAURI_INVOKE("dsh_open_dir"), /** 读取笔记模块设置。 */ - notesGetSettings: () => __TAURI_INVOKE("notes_get_settings"), + editorGetSettings: () => __TAURI_INVOKE("editor_get_settings"), /** 保存笔记模块设置(自愈后落盘,并广播给各窗口)。 */ - notesSaveSettings: (settings: NoteSettings) => __TAURI_INVOKE("notes_save_settings", { settings }), + editorSaveSettings: (settings: EditorSettings) => __TAURI_INVOKE("editor_save_settings", { settings }), /** 当前库状态概览(库根 / 是否自定义 / 笔记数)。 */ - notesLibraryInfo: () => __TAURI_INVOKE("notes_library_info"), + editorLibraryInfo: () => __TAURI_INVOKE("editor_library_info"), /** 设置库根(`None` 或空串 = 恢复默认库根)。 */ - notesSetLibraryRoot: (root: string | null) => __TAURI_INVOKE("notes_set_library_root", { root }), + editorSetLibraryRoot: (root: string | null) => __TAURI_INVOKE("editor_set_library_root", { root }), /** 扫描库,返回扁平条目列表(前端组树)。 */ - notesScanLibrary: () => __TAURI_INVOKE("notes_scan_library"), + editorScanLibrary: () => __TAURI_INVOKE("editor_scan_library"), /** 读取一篇笔记。 */ - notesReadNote: (relPath: string) => __TAURI_INVOKE("notes_read_note", { relPath }), + editorReadNote: (relPath: string) => __TAURI_INVOKE("editor_read_note", { relPath }), /** 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。 */ - notesSaveNote: (relPath: string, content: string) => __TAURI_INVOKE("notes_save_note", { relPath, content }), + editorSaveNote: (relPath: string, content: string) => __TAURI_INVOKE("editor_save_note", { relPath, content }), /** * 新建笔记(自动补 `.md`、重名加序号),返回新文档。 * * `template_id` 为空时用默认模板;找不到该模板时同样回退默认模板(不报错 —— * 模板文件被删掉不该让「新建笔记」这个核心动作失败)。 */ - notesCreateNote: (dirRel: string, name: string, templateId: string | null) => __TAURI_INVOKE("notes_create_note", { dirRel, name, templateId }), + editorCreateNote: (dirRel: string, name: string, templateId: string | null) => __TAURI_INVOKE("editor_create_note", { dirRel, name, templateId }), /** 新建文件夹。 */ - notesCreateFolder: (dirRel: string, name: string) => __TAURI_INVOKE("notes_create_folder", { dirRel, name }), + editorCreateFolder: (dirRel: string, name: string) => __TAURI_INVOKE("editor_create_folder", { dirRel, name }), /** 重命名条目,返回新相对路径。 */ - notesRenameEntry: (relPath: string, newName: string) => __TAURI_INVOKE("notes_rename_entry", { relPath, newName }), + editorRenameEntry: (relPath: string, newName: string) => __TAURI_INVOKE("editor_rename_entry", { relPath, newName }), /** 删除条目(目录递归删除)。 */ - notesDeleteEntry: (relPath: string) => __TAURI_INVOKE("notes_delete_entry", { relPath }), + editorDeleteEntry: (relPath: string) => __TAURI_INVOKE("editor_delete_entry", { relPath }), /** 全量重建索引(设置页「重建索引」)。文件不受影响。 */ - notesRebuildIndex: () => __TAURI_INVOKE("notes_rebuild_index"), + editorRebuildIndex: () => __TAURI_INVOKE("editor_rebuild_index"), /** 增量同步索引(打开编辑器 / 手动刷新时调用)。 */ - notesSyncIndex: () => __TAURI_INVOKE("notes_sync_index"), + editorSyncIndex: () => __TAURI_INVOKE("editor_sync_index"), /** 全文检索 / 按标签 / 按目录筛选。 */ - notesSearchNotes: (query: NoteSearchQuery) => __TAURI_INVOKE("notes_search_notes", { query }), + editorSearchNotes: (query: NoteSearchQuery) => __TAURI_INVOKE("editor_search_notes", { query }), /** 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。 */ - notesListNotes: (limit: number | null) => __TAURI_INVOKE("notes_list_notes", { limit }), + editorListNotes: (limit: number | null) => __TAURI_INVOKE("editor_list_notes", { limit }), /** 标签及计数。 */ - notesTags: () => __TAURI_INVOKE("notes_tags"), + editorTags: () => __TAURI_INVOKE("editor_tags"), /** 索引状态(设置页展示:索引数 / 文件数 / 标签数 / 索引文件路径)。 */ - notesIndexStats: () => __TAURI_INVOKE("notes_index_stats"), + editorIndexStats: () => __TAURI_INVOKE("editor_index_stats"), /** * 打开(读取)库外任意文件。 * * 读取本身不要求预先授权(用户可能刚通过系统对话框选完,也可能带命令行参数), * 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。 */ - notesOpenFile: (path: string) => __TAURI_INVOKE("notes_open_file", { path }), + editorOpenFile: (path: string) => __TAURI_INVOKE("editor_open_file", { path }), /** 保存库外任意文件(按前端回传的编码与换行写回)。 */ - notesWriteFile: (path: string, content: string, encoding: string, eol: string) => __TAURI_INVOKE("notes_write_file", { path, content, encoding, eol }), + editorWriteFile: (path: string, content: string, encoding: string, eol: string) => __TAURI_INVOKE("editor_write_file", { path, content, encoding, eol }), + /** + * 临时草稿文件的存放目录(`{app_data_dir}/editor/scratch`),不存在则创建,返回绝对路径。 + * + * 「新建临时文件(草稿)」用它:**不随应用退出删除** —— 用户可能还没决定存哪儿, + * 收尾交给「关闭该文件时选择保存 / 删除」。 + * + * # 为什么不放在**安装目录** + * + * 安装目录(`Program Files` 之类)对普通用户通常不可写,装到系统盘就必然失败; + * 而 `app_data_dir` 本来就是本模块放设置与默认库的地方,是「应用自己的可写目录」的 + * 标准位置,且卸载时随程序数据一起清理。 + */ + editorScratchDir: () => __TAURI_INVOKE("editor_scratch_dir"), + /** 以指定编码重新解码磁盘字节(切换编码用;不写回,只换一种解释方式)。 */ + editorRedecodeFile: (path: string, encoding: string) => __TAURI_INVOKE("editor_redecode_file", { path, encoding }), /** * 把 base64 图片写进库根的 `assets/`,返回可插入 Markdown 的相对路径。 * @@ -975,21 +990,21 @@ export const commands = { * 前端拿到的本来就是 Blob/DataURL;转一次 base64 比让前端拿到「任意写权限」 * 安全得多(写的位置由后端决定,且只落在 `assets/`)。 */ - notesWriteAsset: (fileName: string, ext: string, dataBase64: string) => __TAURI_INVOKE("notes_write_asset", { fileName, ext, dataBase64 }), + editorWriteAsset: (fileName: string, ext: string, dataBase64: string) => __TAURI_INVOKE("editor_write_asset", { fileName, ext, dataBase64 }), /** * 显式登记一个路径为「可写」。 * - * 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `notes_open_file`, + * 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `editor_open_file`, * 但用户确实是用系统对话框选的,属于「用户显式选择」)。 */ - notesAuthorizeFile: (path: string) => __TAURI_INVOKE("notes_authorize_file", { path }), + editorAuthorizeFile: (path: string) => __TAURI_INVOKE("editor_authorize_file", { path }), /** * 列出可用模板(用户模板优先,同名覆盖内置)。 * * 顺带确保库内 `templates/` 目录存在 —— 这样界面上「新建模板」按钮第一次点击 * 就能直接写文件,不需要用户先去资源管理器建目录。 */ - notesListTemplates: () => __TAURI_INVOKE("notes_list_templates"), + editorListTemplates: () => __TAURI_INVOKE("editor_list_templates"), /** * 把内置模板导出到库内 `templates/`(已存在的不覆盖),返回新写入的名字。 * @@ -997,61 +1012,111 @@ export const commands = { * - 都不传:把全部内置模板导出到 `templates/`(用户想改内置模板时的起点); * - 传 `name` + `body`:新建一个自定义模板。 */ - notesAddTemplate: (name: string | null, body: string | null) => __TAURI_INVOKE("notes_add_template", { name, body }), + editorAddTemplate: (name: string | null, body: string | null) => __TAURI_INVOKE("editor_add_template", { name, body }), /** * 读取一个模板的正文(界面上「查看 / 编辑模板」用)。 * * 内置模板也返回正文(便于「另存为自定义模板」),但 `path` 为 `None` —— * 内置模板没有对应的库内文件,前端据此禁掉「直接编辑」。 */ - notesReadTemplate: (templateId: string) => __TAURI_INVOKE("notes_read_template", { templateId }), + editorReadTemplate: (templateId: string) => __TAURI_INVOKE("editor_read_template", { templateId }), /** 打开(或创建)今天的日记:`日记/YYYY-MM-DD.md`。 */ - notesDailyNote: () => __TAURI_INVOKE("notes_daily_note"), + editorDailyNote: () => __TAURI_INVOKE("editor_daily_note"), /** 从磁盘路径导入(文件 / 目录 / zip 自动判别)。 */ - notesImport: (source: string, destDir: string) => __TAURI_INVOKE("notes_import", { source, destDir }), + editorImport: (source: string, destDir: string) => __TAURI_INVOKE("editor_import", { source, destDir }), /** * 把一篇笔记导出为独立 HTML 文件,返回落盘路径。 * * HTML 的渲染在**前端**(`markdown-it` + `DOMPurify` 都在前端),这里只负责把 * 已经渲染好的字符串写到用户选定的位置 —— 即「后端不碰渲染逻辑,前端不碰文件系统」。 */ - notesExportNote: (relPath: string, html: string, dest: string) => __TAURI_INVOKE("notes_export_note", { relPath, html, dest }), + editorExportNote: (relPath: string, html: string, dest: string) => __TAURI_INVOKE("editor_export_note", { relPath, html, dest }), /** 把整库(或某个目录)打包成 zip,返回落盘路径。 */ - notesExportZip: (dest: string, dirRel: string | null) => __TAURI_INVOKE("notes_export_zip", { dest, dirRel }), + editorExportZip: (dest: string, dirRel: string | null) => __TAURI_INVOKE("editor_export_zip", { dest, dirRel }), /** * 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。 * - * 与 [`notes_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」, + * 与 [`editor_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」, * 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为 * 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。 */ - notesExportSnapshotLocal: (dest: string | null) => __TAURI_INVOKE("notes_export_snapshot_local", { dest }), + editorExportSnapshotLocal: (dest: string | null) => __TAURI_INVOKE("editor_export_snapshot_local", { dest }), /** 当前 WebDAV 配置状态(设置页展示;**密码只回传「是否已保存」**)。 */ - notesWebdavStatus: () => __TAURI_INVOKE("notes_webdav_status"), + editorWebdavStatus: () => __TAURI_INVOKE("editor_webdav_status"), /** 保存 WebDAV 密码到系统凭据管理器(传空串 = 删除)。 */ - notesSetWebdavPassword: (password: string) => __TAURI_INVOKE("notes_set_webdav_password", { password }), + editorSetWebdavPassword: (password: string) => __TAURI_INVOKE("editor_set_webdav_password", { password }), /** 连接自检(建目录 + 列远端)。 */ - notesTestWebdav: () => __TAURI_INVOKE("notes_test_webdav"), + editorTestWebdav: () => __TAURI_INVOKE("editor_test_webdav"), /** 立即同步(并按设置决定是否追加一次快照备份)。 */ - notesSyncNow: () => __TAURI_INVOKE("notes_sync_now"), + editorSyncNow: () => __TAURI_INVOKE("editor_sync_now"), /** 只做一次 zip 快照备份(不上传增量)。 */ - notesBackupNow: () => __TAURI_INVOKE("notes_backup_now"), + editorBackupNow: () => __TAURI_INVOKE("editor_backup_now"), /** 列出远端已有快照。 */ - notesListBackups: () => __TAURI_INVOKE("notes_list_backups"), + editorListBackups: () => __TAURI_INVOKE("editor_list_backups"), /** 从远端快照恢复(不覆盖本地已有文件)。 */ - notesRestoreBackup: (name: string) => __TAURI_INVOKE("notes_restore_backup", { name }), + editorRestoreBackup: (name: string) => __TAURI_INVOKE("editor_restore_backup", { name }), /** 一篇笔记的链接关系(出链 + 入链)。 */ - notesBacklinks: (relPath: string) => __TAURI_INVOKE("notes_backlinks", { relPath }), + editorBacklinks: (relPath: string) => __TAURI_INVOKE("editor_backlinks", { relPath }), /** 全库链接图(已解析的内部链接边)。 */ - notesLinkGraph: () => __TAURI_INVOKE("notes_link_graph"), + editorLinkGraph: () => __TAURI_INVOKE("editor_link_graph"), /** * 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。 * * 前端在注册完事件监听后调用。**不能靠启动时 `emit`** —— 那时 WebView 还没加载完, - * 事件会直接丢掉(见 `notes/args.rs` 的 `PENDING` 注释)。 + * 事件会直接丢掉(见 `editor/args.rs` 的 `PENDING` 注释)。 */ - notesTakePendingFile: () => __TAURI_INVOKE("notes_take_pending_file"), - notesReadAsset: (relPath: string) => __TAURI_INVOKE("notes_read_asset", { relPath }), + editorTakePendingFile: () => __TAURI_INVOKE<{ + /** 绝对路径 */ + path: string, + /** `"file"` | `"folder"` */ + kind: string, +} | null>("editor_take_pending_file"), + editorReadAsset: (relPath: string) => __TAURI_INVOKE("editor_read_asset", { relPath }), + /** 列举本地目录(`path` 为空 = 用户主目录)。 */ + editorReadDir: (path: string) => __TAURI_INVOKE("editor_read_dir", { path }), + /** 在 `dir` 下新建一个空文本文件。重名报错(不自动加序号)。 */ + editorCreateFile: (dir: string, name: string) => __TAURI_INVOKE("editor_create_file", { dir, name }), + /** + * 在 `dir` 下新建一个文件夹。重名报错(不自动加序号)。 + * + * 命名用 `editor_create_dir` 而不是 `editor_create_folder`:后者已被**库内**建文件夹 + * 的命令占用(`editor_create_folder(dir_rel, name)`,走库根沙箱)—— 两者操作对象不同 + * (真实文件系统 vs 库内),必须能同时在命令表里存在。 + */ + editorCreateDir: (dir: string, name: string) => __TAURI_INVOKE("editor_create_dir", { dir, name }), + /** 同目录内重命名。目标存在则报错。 */ + editorRenamePath: (path: string, newName: string) => __TAURI_INVOKE("editor_rename_path", { path, newName }), + /** + * 删除若干本地项(**走系统回收站**,不是永久删除)。 + * + * 单个失败不中断其余项:用户选中的 10 个文件里有一个正被占用,另外 9 个仍应删掉。 + */ + editorDeletePath: (paths: string[]) => __TAURI_INVOKE("editor_delete_path", { paths }), + /** + * 把一个文件 / 文件夹移动到目标目录下(同盘移动;重名报错)。 + * + * 不允许把文件夹移动到自身或其子目录下 —— 那会把目录搬进自己里面,属数据事故。 + */ + editorMovePath: (path: string, destDir: string) => __TAURI_INVOKE("editor_move_path", { path, destDir }), + /** + * 「在路径中查找」命令。 + * + * 走 `spawn_blocking`:一次目录扫描是同步阻塞 IO,放在 Tauri 命令线程上会占住它 + * (范式同 `editor_delete_path` / `editor_sync_now`)。 + */ + editorSearchInPath: (query: PathSearchQuery) => __TAURI_INVOKE("editor_search_in_path", { query }), + /** + * 「在路径中替换」命令。 + * + * 与查找同理走 `spawn_blocking`(整棵树的重写是同步阻塞 IO)。 + */ + editorReplaceInPath: (query: PathReplaceQuery) => __TAURI_INVOKE("editor_replace_in_path", { query }), + /** 读取当前状态。 */ + editorContextMenuStatus: () => __TAURI_INVOKE("editor_context_menu_status"), + /** 注册右键菜单(写 HKCU)。 */ + editorRegisterContextMenu: () => __TAURI_INVOKE("editor_register_context_menu"), + /** 卸载右键菜单(删 HKCU 对应项)。 */ + editorUnregisterContextMenu: () => __TAURI_INVOKE("editor_unregister_context_menu"), }; /* Types */ @@ -1509,6 +1574,16 @@ export type ConflictPolicy = /** 两侧都留(本地改名成 `*.sync-conflict-<时间>.md`,再把远端那份下载到原路径) */ "keepBoth"; +/** 右键菜单状态(回传设置页展示)。 */ +export type ContextMenuStatus = { + /** 是否已注册(以 `*` 键为准) */ + registered: boolean, + /** 当前可执行文件绝对路径(注册表里写入的就是它) */ + exePath: string, + /** 是否开发模式(exe 路径不稳定,UI 需给出提示) */ + isDev: boolean, +}; + /** 自定义命令 */ export type CustomCommand = { id: string, @@ -1517,6 +1592,14 @@ export type CustomCommand = { args?: string[], }; +/** 批量删除结果(回传前端展示「成功 N 项、失败明细」)。 */ +export type DeleteReport = { + /** 成功移入回收站的项数 */ + removed: number, + /** 失败明细(路径 + 原因) */ + failed: string[], +}; + /** 批量删除单个条目的结果。 */ export type DeleteResult = { name: string, @@ -1736,6 +1819,73 @@ export type DuplicateKind = /** 磁盘文件已存在 */ "fileExists"; +/** + * 笔记 / 编辑器设置根结构。 + * + * 字段取值必须与前端 `src/modules/notes/editor/themes.ts` 的 key 保持一致, + * 否则用户选了主题却回落默认(静默失效,终端模块踩过这个坑)。 + */ +export type EditorSettings = { + /** 结构版本号 */ + version?: number, + /** 自定义库根(`None` = 用默认 `{app_data_dir}/editor/library`) */ + libraryRoot?: string | null, + /** 编辑器配色方案 key(`"system"` / `"vscode-dark"` / `"vscode-light"` / …) */ + editorTheme?: string, + /** 编辑器配色是否跟随应用深浅(`editor_theme` 仅作取色基准) */ + followAppTheme?: boolean, + /** 编辑器字体族(空串 = 用内置等宽字体栈) */ + fontFamily?: string, + /** 字号(px) */ + fontSize?: number, + /** 行高倍数 */ + lineHeight?: number | null, + /** 是否启用字体连字(ligatures) */ + ligatures?: boolean, + /** Tab 宽度(空格数) */ + tabSize?: number, + /** 是否启用「所见即所得」Live Preview(关闭则纯 Markdown 源码 + 高亮) */ + livePreview?: boolean, + /** 自动保存防抖(毫秒;0 = 关闭自动保存,仅手动 Ctrl+S) */ + autosaveMs?: number, + /** 默认视图:"wysiwyg" | "source" */ + defaultView?: string, + /** 是否显示行号 */ + showLineNumbers?: boolean, + /** 是否显示大纲侧栏(P1) */ + showOutline?: boolean, + /** 是否启用代码自动补全 / 括号闭合(P1;大文件会强制关闭) */ + autocomplete?: boolean, + /** + * 单文件大小上限(MB)。超过则编辑器降级为「纯高亮 + 行号」, + * 关闭 Live Preview / 折叠 / 补全等重扩展(见 §7 R2)。 + */ + maxFileSizeMb?: number, + /** 是否识别 `[[wikilink]]`(P1,仅影响高亮与后续反链) */ + wikilink?: boolean, + /** 多窗口是否复用同一文档的窗口(P1;关闭则每次新建窗口) */ + reuseWindow?: boolean, + /** WebDAV 备份 / 同步设置(P2) */ + webdav?: WebdavSettings, + /** 新建笔记时是否弹出模板选择(P2) */ + showTemplatePicker?: boolean, + /** 导出 HTML 时是否内联代码高亮样式(P2;关闭则用打印友好的纯黑白) */ + exportHighlight?: boolean, + /** + * 全局快捷键:新建笔记(空串 = 不注册)。 + * + * 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译同一套), + * 触发时只发 `editor-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。 + */ + newNoteShortcut?: string, + /** 全局快捷键:打开编辑器窗口(空串 = 不注册) */ + openEditorShortcut?: string, + /** 最近打开的文件(与笔记库解耦;上限 [`RECENT_LIMIT`]) */ + recentFiles?: RecentEntry[], + /** 最近打开的文件夹(与笔记库解耦;上限 [`RECENT_LIMIT`]) */ + recentFolders?: RecentEntry[], +}; + /** * 引擎连通性自检结果。 * @@ -1856,6 +2006,8 @@ export type FileDoc = { large: boolean, /** 行数(前端状态栏显示;大文件也只需要扫一遍换行,成本可忽略) */ lines: number, + /** 是否只读(打开时探测写权限失败;前端据此拦截保存并给出原因) */ + readonly: boolean, }; export type FileEntry = { @@ -2118,7 +2270,7 @@ export type LibraryEntry = { export type LibraryInfo = { /** 当前生效的库根绝对路径 */ root: string, - /** 是否为用户自定义库根(false = 默认 `{app_data_dir}/notes/library`) */ + /** 是否为用户自定义库根(false = 默认 `{app_data_dir}/editor/library`) */ isCustom: boolean, /** `.md` 笔记数量(不含目录) */ noteCount: number, @@ -2133,6 +2285,30 @@ export type LinkEdge = { to: string, }; +/** 目录列举结果。 */ +export type LocalDir = { + /** 规范化之后的目录(`canonicalize` 结果,已去掉 Windows 的 `\\?\` 前缀) */ + cwd: string, + /** 父目录;已是盘符根时为 None(前端据此禁用「上一级」) */ + parent: string | null, + entries: LocalEntry[], +}; + +/** 一个本地目录项(回传前端渲染)。 */ +export type LocalEntry = { + name: string, + /** 完整路径(本地形态,Windows 下用 `\` 分隔) */ + path: string, + /** "dir" | "file" | "other"(符号链接返回**目标**的类型,见模块注释) */ + kind: string, + /** 字节数;目录为 0(前端显示为「—」) */ + size: number, + /** 修改时间(Unix 毫秒;系统未提供时为 None) */ + modifiedAt: number | null, + /** 符号链接的目标(非链接为 None) */ + linkTarget: string | null, +}; + /** 环境状态(返回前端,设置页「环境检查」面板展示) */ export type MusicEnvStatus = { /** 系统 Python 版本(如 "3.14.5"),无则 None */ @@ -2348,69 +2524,6 @@ export type NoteSearchQuery = { limit?: number, }; -/** - * 笔记 / 编辑器设置根结构。 - * - * 字段取值必须与前端 `src/modules/notes/editor/themes.ts` 的 key 保持一致, - * 否则用户选了主题却回落默认(静默失效,终端模块踩过这个坑)。 - */ -export type NoteSettings = { - /** 结构版本号 */ - version?: number, - /** 自定义库根(`None` = 用默认 `{app_data_dir}/notes/library`) */ - libraryRoot?: string | null, - /** 编辑器配色方案 key(`"system"` / `"vscode-dark"` / `"vscode-light"` / …) */ - editorTheme?: string, - /** 编辑器配色是否跟随应用深浅(`editor_theme` 仅作取色基准) */ - followAppTheme?: boolean, - /** 编辑器字体族(空串 = 用内置等宽字体栈) */ - fontFamily?: string, - /** 字号(px) */ - fontSize?: number, - /** 行高倍数 */ - lineHeight?: number | null, - /** 是否启用字体连字(ligatures) */ - ligatures?: boolean, - /** Tab 宽度(空格数) */ - tabSize?: number, - /** 是否启用「所见即所得」Live Preview(关闭则纯 Markdown 源码 + 高亮) */ - livePreview?: boolean, - /** 自动保存防抖(毫秒;0 = 关闭自动保存,仅手动 Ctrl+S) */ - autosaveMs?: number, - /** 默认视图:"wysiwyg" | "source" */ - defaultView?: string, - /** 是否显示行号 */ - showLineNumbers?: boolean, - /** 是否显示大纲侧栏(P1) */ - showOutline?: boolean, - /** 是否启用代码自动补全 / 括号闭合(P1;大文件会强制关闭) */ - autocomplete?: boolean, - /** - * 单文件大小上限(MB)。超过则编辑器降级为「纯高亮 + 行号」, - * 关闭 Live Preview / 折叠 / 补全等重扩展(见 §7 R2)。 - */ - maxFileSizeMb?: number, - /** 是否识别 `[[wikilink]]`(P1,仅影响高亮与后续反链) */ - wikilink?: boolean, - /** 多窗口是否复用同一文档的窗口(P1;关闭则每次新建窗口) */ - reuseWindow?: boolean, - /** WebDAV 备份 / 同步设置(P2) */ - webdav?: WebdavSettings, - /** 新建笔记时是否弹出模板选择(P2) */ - showTemplatePicker?: boolean, - /** 导出 HTML 时是否内联代码高亮样式(P2;关闭则用打印友好的纯黑白) */ - exportHighlight?: boolean, - /** - * 全局快捷键:新建笔记(空串 = 不注册)。 - * - * 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译同一套), - * 触发时只发 `notes-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。 - */ - newNoteShortcut?: string, - /** 全局快捷键:打开编辑器窗口(空串 = 不注册) */ - openEditorShortcut?: string, -}; - /** 标签及其笔记数。 */ export type NoteTagCount = { tag: string, @@ -2431,6 +2544,122 @@ export type NoteTemplate = { body: string, }; +/** 回传给前端的待打开目标。 */ +export type OpenTargetPayload = { + /** 绝对路径 */ + path: string, + /** `"file"` | `"folder"` */ + kind: string, +}; + +/** 一个被修改的文件。 */ +export type PathReplaceFileResult = { + path: string, + name: string, + replacements: number, +}; + +/** 替换请求(`dir` 为绝对路径:当前目录或笔记库根)。 */ +export type PathReplaceQuery = { + /** 检索根目录(绝对路径) */ + dir: string, + /** 关键词(`regex` 为真时按正则解释) */ + pattern: string, + /** 替换串(`regex` 关闭时按**字面量**写入,不做 `$1` 展开) */ + replacement: string, + /** 区分大小写(默认关) */ + caseSensitive: boolean, + /** 全词匹配 */ + wholeWord: boolean, + /** 按正则解释关键词 */ + regex: boolean, + /** 替换总数上限(缺省 1000,夹在 1..=5000) */ + limit: number | null, + /** 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件) */ + fileTypes: string | null, + /** 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单) */ + skipDirs: string | null, +}; + +/** 一次「在路径中替换」的结果。 */ +export type PathReplaceResult = { + /** 实际被改写的文件(含各自的替换处数) */ + files: PathReplaceFileResult[], + filesChanged: number, + replacements: number, + /** 达到上限提前停止:此时**只改了前面一部分文件** */ + truncated: boolean, + skipped: PathReplaceSkipped[], +}; + +/** 被跳过的文件(非 UTF-8 / 写不进去)。 */ +export type PathReplaceSkipped = { + path: string, + reason: string, +}; + +/** 一个文件内的全部命中。 */ +export type PathSearchFileHits = { + /** 文件绝对路径 */ + path: string, + /** 文件名(结果列表展示) */ + name: string, + /** 该文件内**全部**命中行数(`matches` 可能因回传上限只含前一部分) */ + totalInFile: number, + matches: PathSearchMatch[], +}; + +/** 一处命中(以「行」为单位)。 */ +export type PathSearchMatch = { + /** 行号(1 起) */ + line: number, + /** 行内字符列(1 起,指向首个匹配) */ + column: number, + /** 该行预览(超长时围绕命中开窗,两端以 `…` 标记) */ + preview: string, + /** 命中在 `preview` 中的起始字符下标(前端高亮用) */ + matchStart: number, + /** 命中在 `preview` 中的结束字符下标(不含) */ + matchEnd: number, +}; + +/** 查找请求(`dir` 为绝对路径:当前目录或笔记库根)。 */ +export type PathSearchQuery = { + /** 检索根目录(绝对路径) */ + dir: string, + /** 关键词(`regex` 为真时按正则解释) */ + pattern: string, + /** 区分大小写(默认关:与 CM6 搜索一致) */ + caseSensitive: boolean, + /** 全词匹配 */ + wholeWord: boolean, + /** 按正则解释关键词 */ + regex: boolean, + /** + * 回传预览条数上限(缺省 1000,夹在 1..=5000)。总数不受它影响 —— + * 超过上限的命中只计数不构建预览,由前端分页展示回传的部分 + */ + limit: number | null, + /** 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件) */ + fileTypes: string | null, + /** 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单) */ + skipDirs: string | null, +}; + +/** 一次「在路径中查找」的结果。 */ +export type PathSearchResult = { + /** 按文件分组的命中(文件按遍历顺序;超出回传上限的文件不在此列) */ + files: PathSearchFileHits[], + /** 全树命中行总数(统计完整,不受 `limit` 影响) */ + total: number, + /** 全树至少命中一行的文件总数(≥ `files.len()`) */ + totalFiles: number, + /** 实际回传的预览条数(`files` 里 `matches` 长度之和,≤ `total`) */ + returned: number, + /** `total > returned`:还有命中未回传预览 */ + truncated: boolean, +}; + /** 划词结果悬浮窗外观(P1 生效)。 */ export type PopupSettings = { /** 正文字号(逻辑像素) */ @@ -2560,6 +2789,23 @@ export type QuickPanelSettings = { customCommands?: CustomCommand[], }; +/** + * 最近打开的一个文件 / 文件夹。 + * + * `exists` 在每次读取设置时刷新(不依赖前端探测),供 UI 灰显失效项。 + * 与笔记库**解耦**:库可以换 / 删,历史不该跟着丢(规划 §3.5)。 + */ +export type RecentEntry = { + /** 绝对路径(文件或文件夹) */ + path?: string, + /** 显示名(文件名 / 文件夹名) */ + name?: string, + /** 最近打开时间(Unix 毫秒) */ + openedAt?: number, + /** 该路径当前是否仍存在(读取设置时刷新) */ + exists?: boolean, +}; + /** 远程配置(§5.1 命令 `remote_get_config` / `remote_set_enabled`)。 */ export type RemoteConfig = { /** 开关(持久化) */ diff --git a/src/lib/constants.ts b/src/lib/constants.ts index f8c8348..271da31 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -27,8 +27,13 @@ export const WINDOWS = { * 时,webview 仍可正常加载与交互,只是拿不到 IPC)。 */ dshWeb: 'dsh-web', - /** 笔记独立窗口前缀,实际 label = `${notesWindow}-`(可多开) */ - notesWindow: 'notes-window', + /** 编辑器独立窗口前缀,实际 label = `${editorWindow}-`(可多开) */ + editorWindow: 'editor-window', + /** + * dsh「启动进度」独立窗口(单例)。 + * 服务就绪后由主窗口打开真正的 {@link dshWeb} 窗口并关闭它。 + */ + dshWindow: 'dsh-window', } as const /** Tauri 事件名(前端 emit / listen 与 Rust constants::events 对应) */ @@ -37,8 +42,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', @@ -150,19 +159,21 @@ export const EVENTS = { /** 全局快捷键按下:打开 dsh 独立窗口(无负载) */ dshOpenWindow: 'dsh-open-window', /** 笔记:设置已保存(无负载)。各窗口据此重读设置,实现跨窗口同步 */ - notesSettings: 'notes-settings', + editorSettings: 'editor-settings', /** 笔记:库内容已变更(新建/保存/重命名/删除/切换库根,无负载) */ - notesLibraryChanged: 'notes-library-changed', - /** 笔记:库内文件在应用外被改动(负载见 src/types/notes.ts 的 NoteFileEvent) */ - notesFileChanged: 'notes-file-changed', - /** 笔记:WebDAV 同步进度(负载见 src/types/notes.ts 的 SyncProgress) */ - notesSyncProgress: 'notes-sync-progress', + editorLibraryChanged: 'editor-library-changed', + /** 笔记:库内文件在应用外被改动(负载见 src/types/editor.ts 的 NoteFileEvent) */ + editorFileChanged: 'editor-file-changed', + /** 笔记:WebDAV 同步进度(负载见 src/types/editor.ts 的 SyncProgress) */ + editorSyncProgress: 'editor-sync-progress', /** 笔记:全局快捷键「新建笔记」被按下(无负载;主窗口据此打开新建对话框) */ - notesNewNote: 'notes-new-note', + editorNewNote: 'editor-new-note', /** 笔记:全局快捷键「打开编辑器」被按下(无负载) */ - notesOpenEditor: 'notes-open-editor', + editorOpenEditor: 'editor-open-editor', /** 笔记:需要打开一个磁盘文件(负载 `{ path }`;来自文件关联 / 命令行) */ - notesOpenFile: 'notes-open-file', + editorOpenFile: 'editor-open-file', + /** 编辑器:需要打开一个文件夹(负载 `{ path }`;来自资源管理器右键) */ + editorOpenFolder: 'editor-open-folder', } as const /** localStorage 存储键 */ @@ -188,6 +199,4 @@ export const STORAGE_KEYS = { monitorOverviewCards: 'thing_monitor_overview_cards', screenshotHistory: 'thing_screenshot_history', screenshotPinIndex: 'thing_screenshot_pin_index', - /** 笔记模块:最近打开(`{ relPath, name, at }[]`) */ - notesRecent: 'thing_notes_recent', } as const diff --git a/src/main.ts b/src/main.ts index fbfaafd..b81f870 100644 --- a/src/main.ts +++ b/src/main.ts @@ -43,13 +43,14 @@ 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')], - ['#notes-window', '笔记窗口', () => import('./modules/notes/NotesWindow.vue')], + ['#editor-window', '编辑器窗口', () => import('./modules/editor/EditorWindow.vue')], + ['#dsh-window', 'dsh 启动窗口', () => import('./modules/dsh/DshWindow.vue')], ] const winHash = window.location.hash // #screenshot-overlay 带窗口号参数(多屏)、#download-window 带 ?task= 参数, -// #terminal-window 带 /{session_id} 路径参数、#notes-window 带 ?file=(库内笔记) +// #terminal-window 带 /{session_id} 路径参数、#editor-window 带 ?file=(库内笔记) // 或 ?path=(库外文件)参数,均按前缀匹配;其余精确匹配 const matched = standaloneWindowApps.find(([hash]) => { if ( @@ -57,7 +58,7 @@ const matched = standaloneWindowApps.find(([hash]) => { hash === '#screenshot-scroll' || hash === '#download-window' || hash === '#terminal-window' || - hash === '#notes-window' + hash === '#editor-window' ) return winHash.startsWith(hash) return winHash === hash diff --git a/src/modules/dsh/DshWindow.vue b/src/modules/dsh/DshWindow.vue new file mode 100644 index 0000000..73c8617 --- /dev/null +++ b/src/modules/dsh/DshWindow.vue @@ -0,0 +1,212 @@ + + + \ No newline at end of file diff --git a/src/modules/notes/NotesModule.vue b/src/modules/editor/EditorModule.vue similarity index 69% rename from src/modules/notes/NotesModule.vue rename to src/modules/editor/EditorModule.vue index b767e48..fdf1bf6 100644 --- a/src/modules/notes/NotesModule.vue +++ b/src/modules/editor/EditorModule.vue @@ -2,7 +2,7 @@ /** * 笔记模块主页面 —— **只做设置与管理,不做编辑**。 * - * 编辑发生在独立窗口(`openNotesWindow()`),本页负责:库状态与入口、库根管理、 + * 编辑发生在独立窗口(`openEditorWindow()`),本页负责:库状态与入口、库根管理、 * 编辑器偏好。所有设置**即时生效、无保存按钮**。 * * 版式遵循 `UI_DESIGN_SYSTEM.md`: @@ -23,12 +23,14 @@ import { ExternalLink, Eye, FolderOpen, + FolderPlus, Keyboard, Library, NotebookPen, Palette, RefreshCw, - Tags + Tags, + Wrench } from '@lucide/vue' import { toast } from 'vue-sonner' import { Tabs, TabsContent } from '@/components/ui/tabs' @@ -46,34 +48,35 @@ import { import { ConfirmDialog, SettingRow, StateBlock } from '@/components/common' import { useModuleTabs } from '@/lib/use-module-tabs' import { WINDOWS } from '@/lib/constants' -import { useNotesStore } from '@/stores/notesStore' -import { openNotesWindow } from './openWindow' -import { notesClient } from './notesClient' +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 { NoteSettings } from '@/types/notes' +import type { ContextMenuStatus, EditorSettings } from '@/types/editor' -const store = useNotesStore() +const store = useEditorStore() const activeTab = ref('overview') -// Tab 结构(规划 §8-Q5):概览 / 库 / 编辑器 / 同步。 -// 「关于」并入概览(模块信息量不足以独占一页),设置项按主题归入对应页。 +// Tab 结构(规划 §6.1):概览 / 库 / 编辑器 / 集成。 +// 「同步」并入「库」(同步是库的属性);「集成」放文件关联 / 右键菜单 / 单实例。 useModuleTabs( - 'notes', + 'editor', activeTab, [ { value: 'overview', label: '概览' }, { value: 'library', label: '库' }, { value: 'editor', label: '编辑器' }, - { value: 'sync', label: '同步' } + { value: 'integration', label: '集成' } ], { alwaysVisible: true } ) onMounted(() => { void store.init() + void loadContextMenu() }) onBeforeUnmount(() => { store.disposeListeners() @@ -98,25 +101,26 @@ watch( /** * 冷启动的「用 Thing 打开」:命令行留下的文件路径取到后,直接开一个笔记窗口。 * - * **只在主窗口做**:笔记窗口内部也会渲染本模块(`#notes-window` 是独立入口, - * 不走这里),但它的 hash 里已经带了 `?path=`,由 `NotesWindow` 自己打开 —— + * **只在主窗口做**:笔记窗口内部也会渲染本模块(`#editor-window` 是独立入口, + * 不走这里),但它的 hash 里已经带了 `?path=`,由 `EditorWindow` 自己打开 —— * 这里再响应一次就会开第二个窗口。 */ watch( - () => store.pendingOpenPath, - path => { - if (!path || isNotesWindow()) return - void openNotesWindow({ path }).catch(e => toast.error(`打开文件失败:${String(e)}`)) + () => 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 形如 `#notes-window?...`)。 */ -function isNotesWindow(): boolean { - return window.location.hash.startsWith(`#${WINDOWS.notesWindow}`) +/** 当前是否运行在编辑器独立窗口里(hash 形如 `#editor-window?...`)。 */ +function isEditorWindow(): boolean { + return window.location.hash.startsWith(`#${WINDOWS.editorWindow}`) } // ===== 设置写入(即时生效) ===== -function commit(patch: Partial): void { +function commit(patch: Partial): void { void store.patchSettings(patch) } @@ -126,7 +130,7 @@ function onNumber( ) { const value = Number((event.target as HTMLInputElement).value) if (!Number.isFinite(value)) return - commit({ [patchKey]: value } as Partial) + commit({ [patchKey]: value } as Partial) } // ===== 库根 ===== @@ -175,7 +179,7 @@ async function copyRoot(): Promise { async function openEditor(): Promise { try { - await openNotesWindow() + await openEditorWindow() } catch (e) { toast.error(`打开编辑器失败:${String(e)}`) } @@ -190,13 +194,80 @@ async function openExternalFile(): Promise { title: '打开文件' }) if (typeof selected !== 'string') return - await notesClient.authorizeFile(selected) - await openNotesWindow({ path: selected }) + await editorClient.authorizeFile(selected) + await openEditorWindow({ path: selected }) } catch (e) { toast.error(`打开文件失败:${String(e)}`) } } +/** 在编辑器窗口里打开一个本地文件夹(目录面板)。 */ +async function openFolder(): Promise { + 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 { + 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 { + await openEditorWindow({ folder: entry.path }) +} + +// ===== 系统集成(P4-4) ===== +const contextMenu = ref(null) +const contextBusy = ref(false) + +async function loadContextMenu(): Promise { + try { + contextMenu.value = await editorClient.contextMenuStatus() + } catch (e) { + toast.error(`读取集成状态失败:${String(e)}`) + } +} + +async function registerContextMenu(): Promise { + 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 { + 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 { @@ -216,7 +287,7 @@ async function rebuildIndex(): Promise { async function openDailyNote(): Promise { try { await store.openDailyNote() - await openNotesWindow({ relPath: store.currentRelPath }) + await openEditorWindow({ relPath: store.currentRelPath }) } catch (e) { toast.error(`打开日记失败:${String(e)}`) } @@ -290,6 +361,9 @@ const indexSummary = computed(() => { + @@ -297,7 +371,7 @@ const indexSummary = computed(() => { - + @@ -307,28 +381,58 @@ const indexSummary = computed(() => { -
- +
+
+

最近文件

+
+ +
+
+ +
+

最近文件夹

+
+ +
+
@@ -393,7 +497,7 @@ const indexSummary = computed(() => {

- 全文检索与标签依赖一份 SQLite 索引(存放在库内 .notes/)。 + 全文检索与标签依赖一份 SQLite 索引(存放在库内 .editor/)。 它只是加速层:删掉也能从 Markdown 文件完整重建,不影响笔记本身。

@@ -441,6 +545,9 @@ const indexSummary = computed(() => { + + +
@@ -523,7 +630,7 @@ const indexSummary = computed(() => { {
- - + +
- + + + + + 系统集成 + + + +

+ 让编辑器融入系统:双击文档打开、资源管理器右键、全局快捷键。所有注册都走用户级 + (免管理员);开发模式下 exe 路径不稳定,因此右键菜单默认不自动注册。 +

+
+ + + 已启用 + + + + + + 已启用 + + + + +
+ + 已注册 + + + +
+
+ + + + 开发模式 + + 安装目录 + + + + 见「编辑器」页 + +
+
+
diff --git a/src/modules/editor/EditorWindow.vue b/src/modules/editor/EditorWindow.vue new file mode 100644 index 0000000..8a68fe7 --- /dev/null +++ b/src/modules/editor/EditorWindow.vue @@ -0,0 +1,1000 @@ + + + + + diff --git a/src/modules/notes/components/BacklinksPanel.vue b/src/modules/editor/components/BacklinksPanel.vue similarity index 96% rename from src/modules/notes/components/BacklinksPanel.vue rename to src/modules/editor/components/BacklinksPanel.vue index faa361b..994af07 100644 --- a/src/modules/notes/components/BacklinksPanel.vue +++ b/src/modules/editor/components/BacklinksPanel.vue @@ -5,7 +5,7 @@ * # 数据从哪来 * * 全部来自 SQLite 索引的 `links` 表(写入索引时已把 `[[名字]]` 按 Obsidian 语义 - * 「全库按名解析」成库内相对路径)。因此这里不需要扫全库 —— 一次 `notes_backlinks` + * 「全库按名解析」成库内相对路径)。因此这里不需要扫全库 —— 一次 `editor_backlinks` * 调用就把两侧都取回。 * * # 未解析链接为什么值得显示 @@ -18,9 +18,9 @@ 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 { useNotesStore } from '@/stores/notesStore' -import { notesClient } from '../notesClient' -import type { NoteBacklinks, NoteLink } from '@/types/notes' +import { useEditorStore } from '@/stores/editorStore' +import { editorClient } from '../editorClient' +import type { NoteBacklinks, NoteLink } from '@/types/editor' const props = defineProps<{ /** 当前笔记的库内相对路径(空串 = 没有笔记,面板显示空态) */ @@ -34,7 +34,7 @@ const emit = defineEmits<{ create: [name: string] }>() -const store = useNotesStore() +const store = useEditorStore() const data = ref(null) const loading = ref(false) @@ -58,7 +58,7 @@ async function load(): Promise { } loading.value = true try { - data.value = await notesClient.backlinks(props.relPath) + data.value = await editorClient.backlinks(props.relPath) } catch (e) { // 索引还没建立时这里会失败:不是错误,只是「暂时没有数据」 data.value = null diff --git a/src/modules/editor/components/DirectoryPanel.vue b/src/modules/editor/components/DirectoryPanel.vue new file mode 100644 index 0000000..15559c8 --- /dev/null +++ b/src/modules/editor/components/DirectoryPanel.vue @@ -0,0 +1,823 @@ + + + diff --git a/src/modules/editor/components/DrawerPanel.vue b/src/modules/editor/components/DrawerPanel.vue new file mode 100644 index 0000000..2cc7b1e --- /dev/null +++ b/src/modules/editor/components/DrawerPanel.vue @@ -0,0 +1,73 @@ + + + \ No newline at end of file diff --git a/src/modules/notes/components/EditorHost.vue b/src/modules/editor/components/EditorHost.vue similarity index 66% rename from src/modules/notes/components/EditorHost.vue rename to src/modules/editor/components/EditorHost.vue index 932a6c5..9f605d2 100644 --- a/src/modules/notes/components/EditorHost.vue +++ b/src/modules/editor/components/EditorHost.vue @@ -23,9 +23,9 @@ * `store.language`(一个 thunk),拿到后就地 `setLanguageExtension`; * 旧语言的过期结果由 store 里的令牌机制丢弃,这里不需要再判一次。 */ -import { onBeforeUnmount, onMounted, ref, watch } from 'vue' +import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { EditorView } from '@codemirror/view' -import { useNotesStore } from '@/stores/notesStore' +import { useEditorStore } from '@/stores/editorStore' import { createEditorState, jumpToPosition, @@ -34,10 +34,11 @@ import { setLanguageExtension, type EditorConfig } from '../editor/core' +import { editorBackground } from '../editor/themes' import { createLogger } from '@/lib/logger' import type { Extension } from '@codemirror/state' -const logger = createLogger('notes') +const logger = createLogger('editor') const props = defineProps<{ /** 应用当前是否深色(跟随应用主题时用于取深/浅变体) */ @@ -53,9 +54,19 @@ const emit = defineEmits<{ 'wikilink': [target: string] }>() -const store = useNotesStore() +const store = useEditorStore() const hostRef = ref(null) +/** + * 编辑器外壳底色:跟随当前**实际生效**的主题。 + * + * 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 | null = null /** 程序化替换文档期间抑制「变更 → 置脏」 */ @@ -158,8 +169,17 @@ watch( } if (appliedRevision === store.docRevision) return appliedRevision = store.docRevision + // 目标光标行要在 replaceDoc **之前**取:替换会派发 selection 变化, + // updateListener 随即把 store.cursorLine 覆盖成 1,之后再读就只剩第 1 行了。 + const restoreLine = store.cursorLine applyingDoc = true replaceDoc(view, store.content) + // 标签切换 / 会话恢复:按 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 }) + } applyingDoc = false void applyLanguage(++languageSeq) } @@ -218,28 +238,80 @@ defineExpose({ /** 大纲点击跳转 */ 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() } }) diff --git a/src/modules/editor/components/EditorSearch.vue b/src/modules/editor/components/EditorSearch.vue new file mode 100644 index 0000000..7b37f17 --- /dev/null +++ b/src/modules/editor/components/EditorSearch.vue @@ -0,0 +1,879 @@ + + + diff --git a/src/modules/editor/components/EditorTabs.vue b/src/modules/editor/components/EditorTabs.vue new file mode 100644 index 0000000..356f2f8 --- /dev/null +++ b/src/modules/editor/components/EditorTabs.vue @@ -0,0 +1,45 @@ + + + \ No newline at end of file diff --git a/src/modules/editor/components/EditorToolbar.vue b/src/modules/editor/components/EditorToolbar.vue new file mode 100644 index 0000000..8a8f9a6 --- /dev/null +++ b/src/modules/editor/components/EditorToolbar.vue @@ -0,0 +1,282 @@ + + + \ No newline at end of file diff --git a/src/modules/notes/components/ImportExportPanel.vue b/src/modules/editor/components/ImportExportPanel.vue similarity index 96% rename from src/modules/notes/components/ImportExportPanel.vue rename to src/modules/editor/components/ImportExportPanel.vue index 9f584e3..5d404c4 100644 --- a/src/modules/notes/components/ImportExportPanel.vue +++ b/src/modules/editor/components/ImportExportPanel.vue @@ -37,10 +37,10 @@ import { SelectValue } from '@/components/ui/select' import { SettingRow } from '@/components/common' -import { useNotesStore } from '@/stores/notesStore' -import { notesClient } from '../notesClient' +import { useEditorStore } from '@/stores/editorStore' +import { editorClient } from '../editorClient' -const store = useNotesStore() +const store = useEditorStore() const busy = ref<'import' | 'export' | 'zip' | null>(null) @@ -101,7 +101,7 @@ async function doImport(kind: 'file' | 'dir'): Promise { ) if (typeof selected !== 'string') return busy.value = 'import' - const report = await notesClient.import(selected, '') + const report = await editorClient.import(selected, '') await store.refreshLibrary() await store.syncIndex() const renamed = report.renamed ? `,${report.renamed} 篇重名已加序号` : '' @@ -126,7 +126,7 @@ async function doExportHtml(): Promise { return } try { - const doc = await notesClient.readNote(relPath) + const doc = await editorClient.readNote(relPath) // **动态引入**:`markdownExport` 会拉进 markdown-it + DOMPurify + highlight.js // (实测约 1MB),而导出是低频动作。静态引入会让「笔记」模块页一打开就下载 // 这三个包(chunk 从 ~130kB 涨到 1.1MB),把首屏拖垮。 @@ -146,7 +146,7 @@ async function doExportHtml(): Promise { }) if (typeof dest !== 'string') return busy.value = 'export' - const saved = await notesClient.exportNote(relPath, html, dest) + const saved = await editorClient.exportNote(relPath, html, dest) toast.success(`已导出:${saved}`, { action: { label: '打开', onClick: () => void openPath(saved) } }) @@ -170,7 +170,7 @@ async function doExportZip(): Promise { }) if (typeof dest !== 'string') return busy.value = 'zip' - const saved = await notesClient.exportZip(dest, scope || undefined) + const saved = await editorClient.exportZip(dest, scope || undefined) toast.success(`已导出:${saved}`, { action: { label: '打开目录', onClick: () => void openPath(saved.replace(/[\\/][^\\/]+$/, '')) } }) @@ -270,7 +270,7 @@ async function exportTemplates(): Promise { - +