Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fcbcf07b87 | ||
|
|
063718f86d | ||
|
|
6cfa74c901 | ||
|
|
c9e61f38c5 | ||
|
|
ad987111a3 | ||
|
|
7e65825d3e | ||
|
|
ff1d5cd517 | ||
|
|
9e6d73e191 | ||
|
|
79bded1cd2 | ||
|
|
bccd21fde5 | ||
|
|
b018abd922 | ||
|
|
f6c1cc250e | ||
|
|
79c43d5340 | ||
|
|
8f853f7ef3 | ||
|
|
4f574cb5fa | ||
|
|
10a95ddeea | ||
|
|
069aa58c9f | ||
|
|
8e940f164b | ||
|
|
272246fb61 | ||
|
|
78d272859c | ||
|
|
70d2d4e1d0 | ||
|
|
706b32e1f2 | ||
|
|
3664120808 | ||
|
|
ffa410b399 | ||
|
|
d702ed0d31 | ||
|
|
27ad5d89a5 | ||
|
|
6b9f71da08 | ||
|
|
28e0c4664a | ||
|
|
d21649c60e | ||
|
|
4dd60f42a1 | ||
|
|
0a19b4b38a | ||
|
|
7d49a7395f | ||
|
|
d0705b1ffe | ||
|
|
6c7897bf47 | ||
|
|
2f20161010 | ||
|
|
d09599fa95 |
No files matched your search
@@ -7,6 +7,15 @@ yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
.trae
|
||||
.workbuddy
|
||||
.npm-cache
|
||||
.bun-tmp
|
||||
.uploads
|
||||
temp/
|
||||
release_stage/
|
||||
musicdl_outputs/
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
|
||||
@@ -1,618 +0,0 @@
|
||||
# 模块开发指南
|
||||
|
||||
本文档详细说明 Thing 应用的模块系统架构,帮助开发者快速理解并创建新模块。
|
||||
|
||||
## 架构概述
|
||||
|
||||
Thing 采用**统一模块注册机制**,每个模块通过 `index.ts` 自描述其全部配置(名称、图标、组件、搜索项、进程配置、生命周期钩子等),由中央注册表 `moduleRegistry` 统一管理。
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ main.ts │
|
||||
│ import './modules' (触发注册) │
|
||||
└──────────────────────┬──────────────────────────────┘
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ src/modules/index.ts │
|
||||
│ 聚合入口:导入所有模块配置并注册 │
|
||||
└──────────────────────┬──────────────────────────────┘
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ src/modules/registry.ts │
|
||||
│ ModuleRegistry 单例:注册 / 查询 / 组件懒加载 │
|
||||
└──────┬───────────────┬───────────────┬──────────────┘
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
App.vue Sidebar.vue GeneralSettings
|
||||
(组件加载) (侧边栏导航) (模块开关管理)
|
||||
```
|
||||
|
||||
## 核心文件说明
|
||||
|
||||
| 文件 | 职责 |
|
||||
|------|------|
|
||||
| `src/types/module.ts` | 模块配置类型定义 |
|
||||
| `src/modules/registry.ts` | 注册表单例:注册、查询、组件懒加载缓存 |
|
||||
| `src/modules/index.ts` | 聚合入口:导入并注册所有模块 |
|
||||
| `src/modules/icons.ts` | 模块图标映射表 |
|
||||
| `src/modules/<name>/index.ts` | 各模块的配置声明 |
|
||||
| `src/modules/<name>/*.vue` | 模块前端组件 |
|
||||
|
||||
## 模块配置类型
|
||||
|
||||
```typescript
|
||||
// src/types/module.ts
|
||||
|
||||
interface ModuleConfig {
|
||||
/** 模块唯一标识(如 'proxy'、'clipboard') */
|
||||
id: string
|
||||
/** 显示名称 */
|
||||
name: string
|
||||
/** 图标标识(对应 icons.ts 中的 key) */
|
||||
icon: string
|
||||
/** 模块描述(显示在设置界面的模块管理中) */
|
||||
description: string
|
||||
/** 模块分类 */
|
||||
category: 'network' | 'tool' | 'system' | 'media'
|
||||
/** 默认是否启用(默认 true) */
|
||||
defaultEnabled?: boolean
|
||||
/** 是否为内置模块(不可禁用,如设置模块) */
|
||||
builtin?: boolean
|
||||
/** 懒加载组件的 loader 函数(推荐) */
|
||||
loader?: () => Promise<{ default: Component }>
|
||||
/** 直接组件引用(内置模块可用,无需懒加载) */
|
||||
component?: Component
|
||||
/** 全局搜索项 */
|
||||
searchItems?: SearchIndexItem[]
|
||||
/** 进程配置(需要管理子进程的模块填写) */
|
||||
process?: ModuleProcessConfig
|
||||
/** 生命周期钩子 */
|
||||
lifecycle?: ModuleLifecycle
|
||||
/** 排序权重(数值越小越靠前,默认 100) */
|
||||
order?: number
|
||||
}
|
||||
```
|
||||
|
||||
## 创建新模块
|
||||
|
||||
### 第 1 步:创建模块目录
|
||||
|
||||
```
|
||||
src/modules/my-module/
|
||||
├── index.ts # 模块配置
|
||||
└── MyModule.vue # 前端组件
|
||||
```
|
||||
|
||||
### 第 2 步:编写模块配置
|
||||
|
||||
```typescript
|
||||
// src/modules/my-module/index.ts
|
||||
import type { ModuleConfig } from '@/types/module'
|
||||
|
||||
export const moduleConfig: ModuleConfig = {
|
||||
id: 'my-module',
|
||||
name: '我的模块',
|
||||
icon: 'my-module', // 需在 icons.ts 中添加映射
|
||||
description: '模块功能描述',
|
||||
category: 'tool',
|
||||
defaultEnabled: true,
|
||||
loader: () => import('./MyModule.vue'),
|
||||
searchItems: [
|
||||
{
|
||||
title: '功能名称',
|
||||
description: '功能描述',
|
||||
keywords: ['关键词1', '关键词2', 'keyword']
|
||||
}
|
||||
],
|
||||
order: 70
|
||||
}
|
||||
```
|
||||
|
||||
### 第 3 步:注册模块
|
||||
|
||||
在 `src/modules/index.ts` 中添加导入:
|
||||
|
||||
```typescript
|
||||
import { moduleConfig as myModule } from './my-module'
|
||||
|
||||
const allModules: ModuleConfig[] = [
|
||||
// ... 已有模块
|
||||
myModule
|
||||
]
|
||||
|
||||
moduleRegistry.registerAll(allModules)
|
||||
```
|
||||
|
||||
### 第 4 步:添加图标映射
|
||||
|
||||
在 `src/modules/icons.ts` 中添加:
|
||||
|
||||
```typescript
|
||||
import { Wrench } from '@lucide/vue' // 选择合适的图标
|
||||
|
||||
export const moduleIconMap: Record<string, Component> = {
|
||||
// ... 已有映射
|
||||
'my-module': Wrench
|
||||
}
|
||||
```
|
||||
|
||||
### 第 5 步(可选):添加 Rust 后端命令
|
||||
|
||||
如果模块需要 Rust 后端支持,在 `src-tauri/src/` 中创建命令模块,并在 `lib.rs` 的 `invoke_handler` 中注册。
|
||||
|
||||
## 进程管理
|
||||
|
||||
需要管理外部子进程的模块(如 mihomo)通过 `ModuleProcessConfig` 声明进程配置。下载器模块使用进程内自建下载引擎,不涉及外部子进程管理。
|
||||
|
||||
### 配置示例
|
||||
|
||||
```typescript
|
||||
// src/modules/proxy/index.ts
|
||||
export const moduleConfig: ModuleConfig = {
|
||||
// ...
|
||||
process: {
|
||||
name: 'mihomo', // 进程标识
|
||||
executable: '', // 可执行文件路径(运行时确定)
|
||||
args: ['-f', 'config.yaml'], // 启动参数
|
||||
autoStart: false, // 模块启用时是否自动启动
|
||||
restartOnCrash: true, // 崩溃后自动重启
|
||||
maxRestarts: 3 // 最大重启次数(0 = 不限制)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 前端 API
|
||||
|
||||
```typescript
|
||||
import { useProcessStore } from '@/stores/processStore'
|
||||
|
||||
const processStore = useProcessStore()
|
||||
|
||||
// 通过模块 ID 启动进程(自动读取模块配置)
|
||||
await processStore.startByModule('proxy')
|
||||
|
||||
// 停止进程
|
||||
await processStore.stopByModule('proxy')
|
||||
|
||||
// 获取进程状态(从缓存读取)
|
||||
const status = processStore.getProcessStatus('proxy')
|
||||
// status.status: 'running' | 'stopped' | 'crashed' | 'starting'
|
||||
|
||||
// 刷新所有进程状态
|
||||
await processStore.refreshAll()
|
||||
```
|
||||
|
||||
### 自动化行为
|
||||
|
||||
模块启用/禁用时,`appStore.toggleModule` 会自动处理:
|
||||
|
||||
| 操作 | 禁用模块 | 启用模块 |
|
||||
|------|----------|----------|
|
||||
| 进程 | 停止运行中的进程 | 若 `autoStart` 为 true,启动进程 |
|
||||
| 搜索项 | 移除该模块的搜索项 | 恢复该模块的搜索项 |
|
||||
| 组件缓存 | 清除组件缓存,释放内存 | 下次访问时重新懒加载 |
|
||||
| 生命周期 | 调用 `onDisable` 钩子 | 调用 `onEnable` 钩子 |
|
||||
| 侧边栏 | 从侧边栏隐藏 | 在侧边栏显示 |
|
||||
| Toast 通知 | 显示"已禁用 {模块名}" | 显示"已启用 {模块名}" |
|
||||
|
||||
## 生命周期钩子
|
||||
|
||||
```typescript
|
||||
interface ModuleLifecycle {
|
||||
/** 模块首次加载时调用 */
|
||||
onInit?: () => void | Promise<void>
|
||||
/** 模块组件挂载时调用(切换到该模块) */
|
||||
onActivate?: () => void | Promise<void>
|
||||
/** 模块组件卸载时调用(切换离开该模块) */
|
||||
onDeactivate?: () => void | Promise<void>
|
||||
/** 模块被禁用时调用 */
|
||||
onDisable?: () => void | Promise<void>
|
||||
/** 模块被启用时调用 */
|
||||
onEnable?: () => void | Promise<void>
|
||||
}
|
||||
```
|
||||
|
||||
使用示例:
|
||||
|
||||
```typescript
|
||||
export const moduleConfig: ModuleConfig = {
|
||||
// ...
|
||||
lifecycle: {
|
||||
onEnable: async () => {
|
||||
console.log('模块已启用')
|
||||
// 初始化资源、建立连接等
|
||||
},
|
||||
onDisable: async () => {
|
||||
console.log('模块已禁用')
|
||||
// 释放资源、关闭连接等
|
||||
},
|
||||
onActivate: () => {
|
||||
console.log('用户切换到本模块')
|
||||
// 开始实时数据更新等
|
||||
},
|
||||
onDeactivate: () => {
|
||||
console.log('用户离开本模块')
|
||||
// 暂停实时更新以节省资源
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 全局搜索
|
||||
|
||||
模块通过 `searchItems` 声明可被全局搜索的功能项。用户在标题栏搜索框输入关键词时,匹配的搜索项会显示在结果列表中。
|
||||
|
||||
```typescript
|
||||
searchItems: [
|
||||
{
|
||||
title: '代理设置', // 显示标题
|
||||
description: '配置网络代理', // 显示描述
|
||||
keywords: ['代理', 'proxy', '网络'] // 匹配关键词
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
如果搜索项需要执行特定操作(如跳转到子页面、触发命令),在模块组件挂载时通过 `searchStore.registerAction` 注册:
|
||||
|
||||
```typescript
|
||||
import { useSearchStore } from '@/stores/searchStore'
|
||||
|
||||
const searchStore = useSearchStore()
|
||||
|
||||
onMounted(() => {
|
||||
// 注册第 0 个搜索项的 action
|
||||
searchStore.registerAction('my-module', 0, () => {
|
||||
// 跳转到特定子页面或执行操作
|
||||
activeTab.value = 'settings'
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## 模块分类
|
||||
|
||||
| 分类 | 说明 | 适用场景 |
|
||||
|------|------|----------|
|
||||
| `network` | 网络相关 | 代理、下载器、网络工具 |
|
||||
| `tool` | 实用工具 | 剪贴板、文件搜索、文本处理 |
|
||||
| `system` | 系统相关 | 硬件监控、系统设置 |
|
||||
| `media` | 媒体相关 | 截图、录屏、图片处理 |
|
||||
|
||||
分类目前用于元信息标记,未来可用于设置界面的分组展示。
|
||||
|
||||
## 模块禁用机制详解
|
||||
|
||||
当用户在设置页面切换模块开关时:
|
||||
|
||||
```
|
||||
用户点击开关
|
||||
│
|
||||
▼
|
||||
appStore.toggleModule(moduleId, enabled)
|
||||
│
|
||||
├─ 禁用时:
|
||||
│ ├─ searchStore.unregisterModule(moduleId) // 移除搜索项
|
||||
│ ├─ processStore.stopByModule(moduleId) // 停止进程
|
||||
│ ├─ config.lifecycle?.onDisable?.() // 生命周期钩子
|
||||
│ ├─ moduleRegistry.clearComponentCache(id) // 清除组件缓存
|
||||
│ ├─ modules[id].enabled = false // 更新状态
|
||||
│ └─ toast.success('已禁用 {模块名}') // 通知用户
|
||||
│
|
||||
└─ 启用时:
|
||||
├─ modules[id].enabled = true // 更新状态
|
||||
├─ config.lifecycle?.onEnable?.() // 生命周期钩子
|
||||
├─ searchStore.registerItem(...) // 恢复搜索项
|
||||
├─ processStore.startByModule(moduleId) // 启动进程(若 autoStart)
|
||||
└─ toast.success('已启用 {模块名}') // 通知用户
|
||||
```
|
||||
|
||||
禁用后的效果:
|
||||
- 模块从侧边栏导航中隐藏
|
||||
- 模块的搜索项从全局搜索中移除
|
||||
- 模块的后台进程被停止
|
||||
- 模块的组件缓存被清除,释放内存
|
||||
- 如果当前正在查看被禁用的模块,自动切换到第一个可用模块
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **模块 ID 必须唯一**:重复注册会被忽略并输出警告
|
||||
2. **图标必须映射**:模块配置中的 `icon` 字符串必须在 `icons.ts` 中有对应映射,否则回退到 Settings 图标
|
||||
3. **懒加载优先**:使用 `loader` 而非 `component`,避免首屏加载所有模块代码
|
||||
4. **避免循环依赖**:模块的 `index.ts` 只导出配置,不导入其他模块的 store
|
||||
5. **进程配置的 executable**:通常留空,由模块组件在运行时根据用户设置确定实际路径
|
||||
6. **内置模块**:设置 `builtin: true` 的模块不可被用户禁用,开关处于禁用状态
|
||||
|
||||
## 跨模块开发经验(代理模块沉淀)
|
||||
|
||||
以下要点来自代理模块开发,对后续涉及子进程管理、外部 API 交互、shadcn-vue 组件使用的模块同样适用。
|
||||
|
||||
### Tauri 命令与主线程
|
||||
|
||||
- **同步命令(`pub fn`)会阻塞主线程**:Tauri 的同步命令在主线程执行,其内部的 `std::thread::sleep`、磁盘 I/O、网络请求会阻塞所有 async 命令的调度。涉及等待/阻塞操作的命令必须声明为 `pub async fn`,并用 `tauri::async_runtime::spawn_blocking(|| { std::thread::sleep(...) }).await` 将阻塞操作放到线程池。
|
||||
- **Windows 端口释放有延迟**:`child.kill()` + `child.wait()` 后 TCP 端口不会立即可用,需等待约 800ms 再重新绑定。重启类命令应预留此延迟。
|
||||
- **`Mutex` 持锁期间禁止 sleep**:`ProcessManager::check_and_cleanup` 等持锁函数中不要执行长时间 sleep,否则会阻塞所有需要该锁的命令(如状态查询)。应先释放锁再 sleep,或移出临界区。
|
||||
- **进程监控线程**:`start_monitoring_thread` 每 3 秒检查一次进程状态,崩溃时自动重启(可配置 `maxRestarts`)。前端通过监听 `process-status-changed` 事件更新 UI。
|
||||
|
||||
### 外部 API 交互
|
||||
|
||||
- **API 就绪轮询**:子进程 spawn 后 API 不会立即可用(需初始化配置、加载 geo 文件等)。前端应在请求前轮询健康检查接口(如 `/version`),500ms 间隔、10s 超时。
|
||||
- **缓存配置避免频繁读盘**:后端 Manager 每次方法调用都从磁盘读 settings 会拖慢批量操作。建议在 Manager 内维护内存缓存,`save_settings` 时同步更新。
|
||||
- **并发请求限流**:批量测速等场景不要一次性 `Promise.all` 全部请求,应分批(如每批 20 个),避免压垮子进程。
|
||||
|
||||
### shadcn-vue / reka-ui 注意事项
|
||||
|
||||
- **Select 禁止空字符串 value**:`<SelectItem value="">` 会触发警告并失效。使用哨兵值(如 `__default__`、`__all__`)替代空字符串,在 `@update:model-value` 回调中转回空值。
|
||||
- **Select 双击问题**:reka-ui Select 的 DismissableLayer + closeAutoFocus 会导致连续点击两个 Select 时第一次点击仅关闭上一个、需第二次点击才打开下一个。当前未完美解决,建议同一界面避免放置过多相邻 Select。
|
||||
- **Switch 使用 `model-value` / `update:model-value`**:reka-ui v2+ 的 Switch 不再使用 `checked` / `update:checked`。
|
||||
- **Sonner toast 不可见**:通常是缺少 `vue-sonner/lib/index.css` 导入,而非 z-index 问题。确保在入口处导入该 CSS。
|
||||
- **AlertDialog 替代 confirm()**:原生 `confirm()` 在 Tauri WebView 中样式不一致,使用 shadcn-vue AlertDialog 封装 Promise 化的 `showConfirm()` 函数,支持 destructive 样式。
|
||||
|
||||
### 数据一致性与自愈
|
||||
|
||||
- **配置文件与磁盘 reconcile**:settings.json 中的列表(如订阅 profiles)可能与磁盘文件不同步(用户手动删除、反序列化失败被 default 覆盖)。每次 `load_settings` 时应扫描磁盘补全缺失条目,并在 `currentProfile` 为 null 时自动指向第一个。
|
||||
- **操作顺序防重复**:导入文件后写入 settings 时,若先写文件再 load_settings(含 reconcile 扫盘),reconcile 会扫到新文件添加一次,随后 push 又添加一次。应先 load_settings → 写文件 → push(加去重保护)。
|
||||
- **子进程崩溃循环防护**:子进程因依赖文件损坏(如 geo 数据库)崩溃时,`restart_on_crash` 会反复重启。需配置备用下载源(如 jsdelivr 镜像)避免无代理时 GitHub 超时。
|
||||
|
||||
### UI 细节
|
||||
|
||||
- **瀑布流布局避免卡片等高撑开**:使用 `columns-1 md:columns-2 gap-4 [&>*]:mb-4 [&>*]:break-inside-avoid` 替代 `grid`,让卡片按内容高度自然排列。
|
||||
- **模块禁用清理系统状态**:模块 `onDisable` 钩子应清理系统级副作用(如系统代理注册表项),避免模块停用后遗留导致系统异常。
|
||||
- **应用退出清理**:在 `lib.rs` 的 `quit_app` 命令和托盘退出事件中都要调用 `cleanup_on_exit` + `stop_all`,确保任何退出路径都清理干净。
|
||||
|
||||
## 近期重要变更(影响其他模块开发)
|
||||
|
||||
以下是最近几次改动中确立的约定和模式,开发新模块时需遵循。
|
||||
|
||||
### 后端:子进程启动必须隐藏控制台窗口
|
||||
|
||||
`process_manager.rs` 暴露了公共函数 `setup_creation_flags(cmd: &mut Command)`,Windows 上会设置 `CREATE_NO_WINDOW` 标志。
|
||||
|
||||
**所有用 `std::process::Command` 启动外部程序的地方都必须调用它**,否则会弹出黑色控制台窗口(即使程序是后台运行)。包括:
|
||||
|
||||
- `ProcessManager::start()` 启动 mihomo 等内核
|
||||
- `ProcessManager::check_and_cleanup()` 崩溃重启
|
||||
- 任何调用 `mihomo.exe -v` 等查询版本的场景
|
||||
|
||||
跨平台:非 Windows 平台该函数为空实现,无需条件编译。
|
||||
|
||||
```rust
|
||||
use crate::process_manager::setup_creation_flags;
|
||||
|
||||
let mut cmd = std::process::Command::new(&path);
|
||||
cmd.arg("-v");
|
||||
setup_creation_flags(&mut cmd); // 必须调用
|
||||
cmd.stdout(Stdio::piped()).stderr(Stdio::null()).stdin(Stdio::null());
|
||||
```
|
||||
|
||||
### 后端:长时间 wait() 不要阻塞主线程
|
||||
|
||||
`ProcessManager::stop()` 中 `child.kill()` 是快速的,但 `child.wait()` 可能阻塞几十到几百毫秒。**wait() 已移到后台线程**:
|
||||
|
||||
```rust
|
||||
thread::spawn(move || {
|
||||
let _ = entry.child.wait();
|
||||
});
|
||||
```
|
||||
|
||||
新模块若有类似的"终止外部进程"逻辑,也应遵循此模式,避免 Tauri 命令阻塞导致前端卡顿。
|
||||
|
||||
### 后端:内核/二进制下载用流式 + 事件推送
|
||||
|
||||
`mihomo_manager/` 目录(`kernel.rs`)的 `install_kernel` 确立了"下载二进制资源"的标准模式,未来若有其他模块需要下载外部内核时应复用:
|
||||
|
||||
- **流式下载**:`reqwest::Response::bytes_stream()` + `futures_util::StreamExt`,避免大文件一次性读入内存
|
||||
- **进度事件**:通过 `app.emit("xxx-install-progress", progress)` 推送,事件载荷结构参考 `InstallProgress`
|
||||
- **事件节流**:仅在百分比变化 ≥1% 时 emit,避免事件轰炸
|
||||
- **zip 解压**:用 `zip` crate(纯 Rust),不要用 PowerShell `Expand-Archive`(有执行策略问题)
|
||||
- **文件名匹配**:解压后用 `find_exe_in_dir` 查找 `.exe`(zip 内文件名可能含版本号,不是固定名字),找到后重命名为标准名
|
||||
|
||||
### 后端:GitHub API rate limit 规避
|
||||
|
||||
`check_kernel_update` 采用 **API 优先 + 重定向回退** 策略:
|
||||
|
||||
1. 先调 `api.github.com/.../releases/latest`(能拿完整资产列表,命名变化时更健壮)
|
||||
2. 失败(403 rate limit / 网络错误)时回退到访问 `github.com/.../releases/latest`,从 302 重定向的最终 URL 提取版本号,按稳定命名规则构造下载 URL
|
||||
|
||||
**新模块若需要查 GitHub 最新版本,应复用此模式**,不要直接调 API(未认证 60次/小时/IP 极易超限)。
|
||||
|
||||
### 后端:资产命名规则适配
|
||||
|
||||
mihomo v1.19+ 改了 Windows 资产命名,按 CPU 微架构分级:
|
||||
|
||||
- 旧:`mihomo-windows-amd64-vX.X.X.zip`(已废弃)
|
||||
- 新:`mihomo-windows-amd64-v3-vX.X.X.zip`(v1/v2/v3 对应 CPU level)
|
||||
|
||||
`fetch_latest_via_api` 中的匹配优先级:v3 标准 > v3-go124 > v3-go123 > v3 其他 > v2 > v1 > 旧命名。若未来其他内核也有类似分级,参考此优先级策略。
|
||||
|
||||
### 前端:Transition 内的 v-if/v-else 必须加 key
|
||||
|
||||
**这是 dev 模式的坑**。`<Transition mode="out-in">` 内的 `v-if`/`v-else` 分支如果缺 `:key`,Vue 3.5.x dev 模式下会触发 `__vnode` 写入竞态,导致:
|
||||
|
||||
- 控制台报错 `Cannot set properties of null (setting '__vnode')`
|
||||
- vnode 树损坏,所有事件派发失效(按钮点击没反应)
|
||||
- **build 模式不报错**(生产构建剥除了 `__vnode` instrumentation),容易漏掉
|
||||
|
||||
**约定**:`<Transition>` 内所有分支(v-if/v-else-if/v-else)都必须加 `:key`,即使是原生 div 也要加。
|
||||
|
||||
```vue
|
||||
<Transition name="fade" mode="out-in">
|
||||
<ComponentA v-if="cond" key="a" />
|
||||
<div v-else key="empty">占位</div>
|
||||
</Transition>
|
||||
```
|
||||
|
||||
`ModuleContainer.vue` 和 `ProxyModule.vue` 的 Progress 区块已修复,新模块开发时注意。
|
||||
|
||||
### 前端:模块内 Tabs 顶部固定模式
|
||||
|
||||
模块根容器用 `h-full overflow-hidden flex flex-col`,Tabs 用 `flex-1 min-h-0 flex flex-col`,TabsList 加 `shrink-0`,TabsContent 加 `flex-1 min-h-0 overflow-y-auto`:
|
||||
|
||||
```vue
|
||||
<div class="h-full p-6 overflow-hidden flex flex-col">
|
||||
<Tabs v-model="tab" class="flex-1 min-h-0 flex flex-col">
|
||||
<TabsList class="shrink-0">...</TabsList>
|
||||
<TabsContent value="x" class="flex-1 min-h-0 overflow-y-auto">...</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
```
|
||||
|
||||
这样 TabsList 固定在顶部,只有 TabsContent 滚动。`min-h-0` 是 flex 子元素 overflow 生效的关键,不能省。
|
||||
|
||||
### 前端:Tauri 事件监听需在 store 中管理生命周期
|
||||
|
||||
`proxyStore.ts` 的 `installKernel` 确立了模式:
|
||||
|
||||
- 监听在方法调用时注册,`finally` 块中取消
|
||||
- 用模块级变量保存 `UnlistenFn`,避免重复注册
|
||||
- 错误事件由后端保证 emit(前端不重复弹 toast,统一由 watch 处理)
|
||||
|
||||
```typescript
|
||||
let progressUnlisten: UnlistenFn | null = null
|
||||
const installKernel = async () => {
|
||||
if (!progressUnlisten) {
|
||||
progressUnlisten = await listen<Progress>('xxx-progress', (e) => {
|
||||
progress.value = e.payload
|
||||
})
|
||||
}
|
||||
try {
|
||||
await invoke('xxx_command')
|
||||
} finally {
|
||||
if (progressUnlisten) {
|
||||
progressUnlisten()
|
||||
progressUnlisten = null
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 前端:窗口隐藏前 blur 焦点
|
||||
|
||||
TitleBar 的关闭按钮实际是 `hide()` 到托盘。webview 快速隐藏时浏览器 `mouseleave` 可能不触发,导致从托盘恢复后按钮仍显示 hover 高亮。
|
||||
|
||||
**修复**:`hide()` 前调用 `document.activeElement.blur()`,并监听 `onFocusChanged` 在窗口重新获得焦点时再 blur 一次。新模块若有类似的"隐藏窗口"操作(如全局快捷键隐藏),同样需要 blur。
|
||||
|
||||
### 前端:浮动标签切换器(TabsList 滚动遮挡时在 TitleBar 显示)
|
||||
|
||||
模块详情页内容滚动时,顶部 `TabsList` 会被 `TitleBar` 遮挡,导致用户必须滚回顶部才能切换 Tab。已抽取通用 composable `src/lib/use-module-tabs.ts` 自动处理。
|
||||
|
||||
**接入方式**(任何使用 Tabs 的模块都可用,代理/下载器模块已接入):
|
||||
|
||||
```ts
|
||||
// 模块 <script setup> 顶部
|
||||
import { useModuleTabs } from '@/lib/use-module-tabs'
|
||||
|
||||
const activeTab = ref('overview')
|
||||
const tabsListRef = useModuleTabs(activeTab, [
|
||||
{ value: 'overview', label: '概览' },
|
||||
{ value: 'settings', label: '设置' }
|
||||
])
|
||||
```
|
||||
|
||||
```vue
|
||||
<!-- 模板中给 TabsList 包一层带 ref 的 div -->
|
||||
<Tabs v-model="activeTab">
|
||||
<div ref="tabsListRef">
|
||||
<TabsList>...</TabsList>
|
||||
</div>
|
||||
<TabsContent .../>
|
||||
</Tabs>
|
||||
```
|
||||
|
||||
**工作原理**:
|
||||
- composable 内部在 `onMounted` 时注册标签到 `moduleTabsStore`,`onUnmounted` 时注销
|
||||
- 用 `IntersectionObserver`(`rootMargin: '-44px 0px 0px 0px'` 裁剪 TitleBar 高度)监听 TabsList 可见性
|
||||
- 滚动遮挡时 `TitleBar` 中"Thing"标题右侧自动显示浮动切换按钮(带淡入+左滑动画)
|
||||
- 双向 watch 同步本地 `activeTab` 与 store,用户点击 TitleBar 浮动按钮也能切换模块内 Tab
|
||||
|
||||
**约束**:TitleBar 高度固定 40px(h-10),composable 已用 44px 裁剪(含 4px 缓冲);store 是单例,一个模块同一时间只能注册一组标签。
|
||||
|
||||
### 前端:内核路径用 %APPDATA% 简化显示
|
||||
|
||||
内核路径较长(如 `C:\Users\xxx\AppData\Roaming\thing.lfeng.me\proxy\cores\mihomo.exe`),展示时用 `%APPDATA%` 替换前缀,并提供复制完整路径 / 在文件夹中显示两个按钮。代理和下载器模块的内核管理区块已采用此模式。
|
||||
|
||||
```ts
|
||||
import { appDataDir } from '@tauri-apps/api/path'
|
||||
|
||||
const appDataPath = ref('')
|
||||
onMounted(async () => {
|
||||
try { appDataPath.value = await appDataDir() } catch {}
|
||||
})
|
||||
|
||||
const pathDisplay = computed(() => {
|
||||
const p = store.kernel?.path
|
||||
if (!p) return ''
|
||||
if (appDataPath.value && p.toLowerCase().startsWith(appDataPath.value.toLowerCase())) {
|
||||
return '%APPDATA%' + p.slice(appDataPath.value.length)
|
||||
}
|
||||
return p
|
||||
})
|
||||
```
|
||||
|
||||
`<title>` 放完整路径,显示文本用 `pathDisplay`,复制时复制完整路径。
|
||||
|
||||
### 前端:任务历史持久化(下载器模块模式)
|
||||
|
||||
下载引擎在进程内运行,状态通过 `engine_state.json` 持久化到磁盘。前端 store 的做法:
|
||||
|
||||
- `onMounted` 时调用 `store.init()`,一次性加载 status/settings/extensionInfo/tasks
|
||||
- 通过 Tauri 事件 `download-progress`、`download-complete`、`download-added` 实时更新任务状态
|
||||
- 引擎在 `Storage::new` 时自动创建数据目录,`save` 时兜底重建父目录,避免路径不存在错误
|
||||
|
||||
此模式适用于任何"引擎在进程内运行、状态需持久化"的场景。
|
||||
|
||||
### 前端:轻量设置 Dialog(替代独立 Tab)
|
||||
|
||||
模块设置项较多时,传统做法是单独开一个"设置"Tab。但任务页工具栏需要快速调整少量核心设置(如下载目录、并发数),切到设置 Tab 再切回来体验割裂。
|
||||
|
||||
**模式**:在任务工具栏放一个"下载设置"按钮,点击弹出 Dialog,包含核心设置项(与设置页共用 `store.settings`),保存时调用 `handleSaveSettings`(引擎立即应用新配置,无需重启)并自动关闭弹窗。完整设置仍保留在"设置"Tab。
|
||||
|
||||
适用场景:需要在任务页快速调整的少量高频设置;若设置项不多,可完全用 Dialog 替代设置 Tab。
|
||||
|
||||
### 后端:opener 插件 scope 限制与绕过
|
||||
|
||||
`tauri-plugin-opener` 的 `opener:allow-open-path` 权限默认 **无 scope**,IPC `open_path` 命令会拒绝任何路径并报错 `Not allowed to open path`。
|
||||
|
||||
**解决方案**:在 Rust 端写一个自定义命令,用 `OpenerExt::opener().open_path()` 直接调用(绕过 IPC scope 检查):
|
||||
|
||||
```rust
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn my_open_dir(app: AppHandle, path: String) -> Result<(), String> {
|
||||
let p = std::path::Path::new(&path);
|
||||
if !p.exists() {
|
||||
return Err(format!("路径不存在: {}", path));
|
||||
}
|
||||
app.opener().open_path(path, None::<&str>).map_err(|e| e.to_string())
|
||||
}
|
||||
```
|
||||
|
||||
在 `lib.rs` 的 `invoke_handler` 中注册,前端通过 `invoke('my_open_dir', { path })` 调用。下载器模块的"打开下载目录"已采用此方案。
|
||||
|
||||
### 前端:剩余时间(ETA)可读化
|
||||
|
||||
下载卡片直接显示 `(total-completed)/speed` 会得到 `17.217666215634114 B` 这种难懂的字节数。应格式化为时间:
|
||||
|
||||
```ts
|
||||
const formatEta = (seconds: number): string => {
|
||||
if (!isFinite(seconds) || seconds <= 0) return ''
|
||||
if (seconds < 60) return `剩余 ${Math.ceil(seconds)} 秒`
|
||||
if (seconds < 3600) {
|
||||
const m = Math.floor(seconds / 60)
|
||||
const s = Math.ceil(seconds % 60)
|
||||
return `剩余 ${m} 分 ${s} 秒`
|
||||
}
|
||||
const h = Math.floor(seconds / 3600)
|
||||
const m = Math.ceil((seconds % 3600) / 60)
|
||||
return `剩余 ${h} 小时 ${m} 分`
|
||||
}
|
||||
```
|
||||
|
||||
`getEta(task) = (totalLength - completedLength) / downloadSpeed`,speed≤0 时返回 0(不显示)。
|
||||
|
||||
### 前端:状态统计用 Badge 替代纯文本
|
||||
|
||||
下载任务工具栏的速度/活跃/等待/已完成数量,以及代理概览页的内核状态/版本,从纯文本改为 `Badge variant="secondary"` 或带颜色的 `Badge`(绿色已安装/红色未安装),视觉更醒目。新模块的状态展示建议统一用 Badge。
|
||||
|
||||
### 后端:应用退出清理(单一出口)
|
||||
|
||||
退出清理已收敛到 `lib.rs` 的 `RunEvent::ExitRequested` 分支(P0-1/V7):`quit_app` 命令与托盘退出项都只触发 `app.exit(0)`,清理逻辑(`cleanup_on_exit` + `stop_all`)只在该分支执行一次。新增管理子进程的模块时,在 `ExitRequested` 分支注册自己的 `cleanup_on_exit` 即可,不要在命令或托盘路径重复清理。
|
||||
@@ -100,7 +100,7 @@ Thing/
|
||||
#### 📸 截图
|
||||
- [x] 截图及相关
|
||||
- [ ] 滚动截图(后续支持)
|
||||
- [ ] 贴图(后续支持)
|
||||
- [x] 贴图
|
||||
|
||||
#### 📊 硬件监控
|
||||
- [x] 悬浮窗显示
|
||||
@@ -111,7 +111,7 @@ Thing/
|
||||
- [x] 自建进程内下载引擎(多线程 HTTP/HTTPS,无需外部内核)
|
||||
- [x] 接管浏览器下载,浏览器扩展(Thing Extension)
|
||||
- [x] HTTP 下载支持
|
||||
- [ ] BT/磁力链接支持(后续支持)
|
||||
- [x] BT/磁力链接支持(后续支持)
|
||||
- [x] 下载任务管理(历史)
|
||||
- [x] 速度限制
|
||||
- [x] 断点续传
|
||||
@@ -124,11 +124,11 @@ Thing/
|
||||
|
||||
### 第三阶段:优化与完善
|
||||
|
||||
- [x] 性能优化(P1/P2:轮询随窗口可见性暂停、批量测速限并发、渲染 memo 化等,见 MODULE_REVIEW.md)
|
||||
- [x] 错误处理与日志完善(B5 进程级全局日志器、异常兜底)
|
||||
- [x] 性能优化(见 MODULE_REVIEW.md)
|
||||
- [x] 错误处理与日志完善(全局日志器、异常兜底)
|
||||
- [x] 用户体验优化(混合 DPI 定位、rAF 节流、UI 细节)
|
||||
- [ ] 自动更新机制
|
||||
- [ ] 打包发布
|
||||
- [x] 自动更新机制
|
||||
- [x] 打包发布
|
||||
|
||||
## 模块管理架构
|
||||
|
||||
|
||||
@@ -66,6 +66,8 @@ internal sealed class KernelStatus
|
||||
{
|
||||
public bool Ready { get; set; }
|
||||
public bool IsAdmin { get; set; }
|
||||
/// <summary>PawnIO 驱动是否已安装(ring0 传感器读取依赖它或 WinRing0,缺失时温度/频率通常无法读取)</summary>
|
||||
public bool PawnIoInstalled { get; set; }
|
||||
public double UptimeMs { get; set; }
|
||||
public int GroupCount { get; set; }
|
||||
public int SensorCount { get; set; }
|
||||
|
||||
+45
-11
@@ -24,6 +24,9 @@ internal sealed class HardwareManager : IDisposable
|
||||
private readonly bool _isAdmin;
|
||||
private readonly double _coldStartMs;
|
||||
private readonly Stopwatch _startupSw;
|
||||
// 传感器 ID 缓存:避免每秒为每个传感器重复拼接字符串(减少 GC 压力)
|
||||
private readonly Dictionary<ISensor, string> _sensorIdCache = new();
|
||||
private bool _coldStartSent;
|
||||
private bool _ready;
|
||||
private bool _closed;
|
||||
private HardwareConfig _config;
|
||||
@@ -84,7 +87,7 @@ internal sealed class HardwareManager : IDisposable
|
||||
|
||||
/// <summary>
|
||||
/// 全量 Update 所有硬件。
|
||||
/// 由 SamplingScheduler 按通道分频调用。
|
||||
/// 仅用于构造函数首轮填充,运行期由调度器分频调用 UpdateFastOnly/UpdateSlowOnly。
|
||||
/// </summary>
|
||||
public void UpdateAll()
|
||||
{
|
||||
@@ -94,9 +97,24 @@ internal sealed class HardwareManager : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 仅 Update 快通道硬件(CPU/GPU/Memory/Network 等)。
|
||||
/// 由调度器快通道 tick 高频调用,避免 SMART 等重查询拖慢采样节奏。
|
||||
/// </summary>
|
||||
public void UpdateFastOnly()
|
||||
{
|
||||
foreach (var hw in _visitor.AllHardware)
|
||||
{
|
||||
if (!IsSlowHardware(hw.HardwareType))
|
||||
{
|
||||
try { hw.Update(); } catch { /* 单个硬件 Update 失败不影响整体 */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 仅 Update 慢通道硬件(Storage/PSU/Battery 等)。
|
||||
/// 快通道硬件(CPU/GPU/Memory/Network)由调度器更高频调用 UpdateAll。
|
||||
/// 快通道硬件(CPU/GPU/Memory/Network)由调度器更高频调用 UpdateFastOnly。
|
||||
/// </summary>
|
||||
public void UpdateSlowOnly()
|
||||
{
|
||||
@@ -123,10 +141,11 @@ internal sealed class HardwareManager : IDisposable
|
||||
Ready = _ready,
|
||||
};
|
||||
|
||||
// 首个快照带上冷启动耗时,后续为 0
|
||||
if (_coldStartMs > 0 && snap.Timestamp > 0)
|
||||
// 首个快照带上冷启动耗时,后续为 0(修复:此前每个快照都携带 ColdStartMs)
|
||||
if (_coldStartMs > 0 && !_coldStartSent)
|
||||
{
|
||||
snap.ColdStartMs = Math.Round(_coldStartMs, 1);
|
||||
_coldStartSent = true;
|
||||
}
|
||||
|
||||
// 重新遍历以读取最新传感器值(visitor 缓存的是 hardware 引用,sensor 值实时)
|
||||
@@ -156,7 +175,7 @@ internal sealed class HardwareManager : IDisposable
|
||||
|
||||
g.Sensors.Add(new SensorEntry
|
||||
{
|
||||
Id = $"{groupId}/{hw.Name}/{s.SensorType}/{s.Name}".Replace(' ', '_').ToLowerInvariant(),
|
||||
Id = GetSensorId(s, groupId, hw.Name),
|
||||
Name = s.Name,
|
||||
Type = sensorType,
|
||||
Value = s.Value,
|
||||
@@ -169,6 +188,21 @@ internal sealed class HardwareManager : IDisposable
|
||||
return snap;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取传感器稳定 ID(带缓存)。
|
||||
/// ID 格式:{groupId}/{hwName}/{sensorType}/{sensorName},空格转下划线、小写化。
|
||||
/// 缓存命中直接返回,未命中(新传感器)计算后入缓存。
|
||||
/// </summary>
|
||||
private string GetSensorId(ISensor s, string groupId, string hwName)
|
||||
{
|
||||
if (!_sensorIdCache.TryGetValue(s, out var id))
|
||||
{
|
||||
id = $"{groupId}/{hwName}/{s.SensorType}/{s.Name}".Replace(' ', '_').ToLowerInvariant();
|
||||
_sensorIdCache[s] = id;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为已启用但 LHB 未枚举到的硬件类型预创建空分组。
|
||||
/// 场景:用户在设置中勾选了主板/电池/电源等,但 LHB 在当前权限或机型下检测不到对应硬件,
|
||||
@@ -243,7 +277,7 @@ internal sealed class HardwareManager : IDisposable
|
||||
_ => "",
|
||||
};
|
||||
|
||||
private static bool IsRunningAsAdmin()
|
||||
internal static bool IsRunningAsAdmin()
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -290,14 +324,14 @@ internal sealed class SnapshotVisitor : IVisitor
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 采样调度器:按快/慢通道分频驱动 HardwareManager.UpdateAll。
|
||||
/// 采样调度器:按快/慢通道分频驱动 HardwareManager 的分层 Update。
|
||||
/// 使用 Channel 向 SSE 推送层广播快照(解耦:调度器不关心有几个订阅者)。
|
||||
///
|
||||
/// 调度策略:
|
||||
/// - 快通道 tick:UpdateAll(含慢通道硬件,因 UpdateAll 成本主要在 SMART,已通过慢通道分频减少调用频率)
|
||||
/// 实际优化:快通道 tick 只 Update 快通道硬件(UpdateFastOnly),慢通道单独按慢节奏 Update
|
||||
/// - 快通道 tick:UpdateFastOnly(仅 CPU/GPU/Memory/Network 等轻量硬件),
|
||||
/// 避免 SMART 等重查询每秒执行拖慢采样节奏
|
||||
/// - 慢通道 tick:UpdateSlowOnly(仅 Storage/PSU/Motherboard 等)
|
||||
/// - 每个 tick 结束后构建快照并广播
|
||||
/// - 快通道每个 tick 结束后构建快照并广播(慢通道更新后的值随下一帧带出)
|
||||
/// </summary>
|
||||
internal sealed class SamplingScheduler : IDisposable
|
||||
{
|
||||
@@ -352,7 +386,7 @@ internal sealed class SamplingScheduler : IDisposable
|
||||
{
|
||||
try
|
||||
{
|
||||
_hw.UpdateAll();
|
||||
_hw.UpdateFastOnly();
|
||||
var snap = _hw.BuildSnapshot();
|
||||
_cache.Update(snap);
|
||||
_broadcast.Writer.TryWrite(snap);
|
||||
|
||||
@@ -44,6 +44,7 @@ internal static class HttpEndpoints
|
||||
{
|
||||
Ready = hw?.Ready ?? false,
|
||||
IsAdmin = hw?.IsAdmin ?? false,
|
||||
PawnIoInstalled = PawnIoSupport.IsServiceInstalled(),
|
||||
UptimeMs = kernel.Uptime.Elapsed.TotalMilliseconds,
|
||||
GroupCount = snap?.Groups.Count ?? 0,
|
||||
SensorCount = kernel.Scheduler.Cache.SensorCount,
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.Diagnostics;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace ThingHK;
|
||||
|
||||
/// <summary>
|
||||
/// PawnIO 驱动支持:检测 + 静默安装。
|
||||
///
|
||||
/// 背景:LHM 读取 CPU 温度/频率等 ring0 数据依赖内核驱动,回退用的 WinRing0 被
|
||||
/// 微软"易受攻击的驱动程序阻止列表"和部分杀软(如火绒)拦截,导致传感器缺失。
|
||||
/// PawnIO 是正规签名的替代驱动(不在阻止列表、兼容 HVCI/安全启动),
|
||||
/// LHM 0.9.5+ 检测到已安装时优先使用,无需任何代码开关。
|
||||
///
|
||||
/// 安装器约定:PawnIO_setup.exe 与 ThingHK.exe 同目录
|
||||
/// (由 Tauri 侧 prepare_kernel 从资源目录随内核一起复制到 {app_data}/monitor/cores/)。
|
||||
///
|
||||
/// 静默参数:-install -silent(官方 CLI 参数,见 namazso/PawnIO.Setup)。
|
||||
/// 退出码:0=成功;3010=成功但需重启(ERROR_SUCCESS_REBOOT_REQUIRED)。
|
||||
///
|
||||
/// 策略:仅在内核已提权时安装。两种提权模式(Thing 提权继承 / 仅提权 ThingHK)
|
||||
/// 都只有一次 UAC,内核拿到权限后自行静默安装,避免二次弹窗。
|
||||
/// serve 模式调用;scan 诊断模式不安装,保持被动。
|
||||
/// </summary>
|
||||
internal static class PawnIoSupport
|
||||
{
|
||||
/// <summary>驱动服务注册表键:存在即认为已安装</summary>
|
||||
private const string ServiceKeyName = @"SYSTEM\CurrentControlSet\Services\PawnIO";
|
||||
|
||||
private const string SetupFileName = "PawnIO_setup.exe";
|
||||
|
||||
/// <summary>3010 = ERROR_SUCCESS_REBOOT_REQUIRED(安装成功但需重启生效)</summary>
|
||||
private const int ExitCodeRebootRequired = 3010;
|
||||
|
||||
/// <summary>驱动安装通常数秒内完成,留足余量防止卡死启动流程</summary>
|
||||
private const int InstallTimeoutMs = 90_000;
|
||||
|
||||
/// <summary>检测 PawnIO 驱动服务是否已注册</summary>
|
||||
public static bool IsServiceInstalled()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.LocalMachine.OpenSubKey(ServiceKeyName);
|
||||
return key != null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 确保 PawnIO 就绪:已安装直接返回;未安装且当前已提权时静默安装。
|
||||
/// 返回描述性结果(写入 stderr 日志 + /status 诊断)。
|
||||
/// </summary>
|
||||
public static string EnsureInstalled()
|
||||
{
|
||||
if (IsServiceInstalled())
|
||||
return "already-installed";
|
||||
|
||||
if (!HardwareManager.IsRunningAsAdmin())
|
||||
return "skipped: not elevated (温度/频率等传感器需要提权运行)";
|
||||
|
||||
string setupPath = Path.Combine(AppContext.BaseDirectory, SetupFileName);
|
||||
if (!File.Exists(setupPath))
|
||||
return $"skipped: {SetupFileName} 未找到(应随内核一起部署,见 prepare_kernel)";
|
||||
|
||||
try
|
||||
{
|
||||
using var process = Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = setupPath,
|
||||
Arguments = "-install -silent",
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
});
|
||||
if (process == null)
|
||||
return "failed: Process.Start 返回 null";
|
||||
|
||||
if (!process.WaitForExit(InstallTimeoutMs))
|
||||
{
|
||||
try { process.Kill(); } catch { /* 超时后进程可能已自行退出 */ }
|
||||
return "failed: 安装超时";
|
||||
}
|
||||
|
||||
int code = process.ExitCode;
|
||||
if (code == ExitCodeRebootRequired)
|
||||
return "installed: 需重启后生效";
|
||||
|
||||
if (code != 0)
|
||||
return $"failed: 安装器退出码 {code}";
|
||||
|
||||
return IsServiceInstalled()
|
||||
? "installed"
|
||||
: "failed: 安装器返回 0 但服务未注册";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return $"failed: {ex.Message}";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,11 @@ internal static class Program
|
||||
|
||||
Console.Error.WriteLine($"[ThingHK] serve 模式: port={port} config={configPath ?? "(默认)"} fast={fastMs}ms slow={slowMs}ms");
|
||||
|
||||
// PawnIO:ring0 传感器读取的首选驱动(未安装且已提权时静默安装,
|
||||
// 避开 WinRing0 被系统阻止列表/杀软拦截导致的温度/频率缺失)
|
||||
string pawnIoResult = PawnIoSupport.EnsureInstalled();
|
||||
Console.Error.WriteLine($"[ThingHK] PawnIO: {pawnIoResult}");
|
||||
|
||||
using var kernel = new KernelHost();
|
||||
await kernel.StartAsync(configPath, fastMs, slowMs);
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="LibreHardwareMonitorLib" Version="0.9.7-pre716" />
|
||||
<PackageReference Include="LibreHardwareMonitorLib" Version="0.9.7-pre729" />
|
||||
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -386,6 +386,7 @@ LibreHardwareMonitor 访问 CPU MSR(温度/时钟)、存储 SMART、SMBus、
|
||||
采用 **ShellExecuteW "runas"** 弹 UAC 提权启动 Kernel,架构上与普通模式分离:
|
||||
|
||||
- **启动**:[monitor_kernel.rs](file:///d:/Atie/Gitea/Thing/src-tauri/src/monitor_kernel.rs) `start_elevated` → 停止当前 Kernel → `ShellExecuteW "runas"` 启动管理员 Kernel(隐藏控制台窗口)→ 等待 ready → 重新订阅 SSE
|
||||
- **提权偏好(持久化)**:提权成功后会写入 `{app_data_dir}/monitor/settings.json` 的 `elevateOnStart=true`。此后 `start_with_subscription` 检测到该偏好且 Thing 非管理员时,改走 `start_elevated`,因此**应用重启后的自动启动路径也会提权**(仍会弹一次 UAC 确认)。前端「监控设置」提供同名开关可随时关闭(关闭后内核启动回到普通权限)。
|
||||
- **停止**:调用 Kernel 的 `POST /shutdown` 接口(普通权限无法 `TerminateProcess` 管理员进程)
|
||||
- **状态查询**:通过 HTTP `/status` 判断运行状态(pid 不可用,返回 None)
|
||||
|
||||
@@ -397,7 +398,7 @@ LibreHardwareMonitor 访问 CPU MSR(温度/时钟)、存储 SMART、SMBus、
|
||||
| 崩溃重启 | 3s 巡检 + 自动重启 | 不支持(需手动重新提权) |
|
||||
| 停止方式 | `ProcessManager.stop`(kill) | `POST /shutdown`(优雅退出) |
|
||||
| PID 查询 | 可用 | 不可用(返回 None) |
|
||||
| UAC 弹窗 | 无 | 每次启动需确认 |
|
||||
| UAC 弹窗 | 无 | 每次启动需确认(提权偏好开启时,应用重启后的自动启动同样弹一次) |
|
||||
|
||||
### 7.4 C# Kernel /shutdown 接口
|
||||
|
||||
|
||||
@@ -5,18 +5,62 @@
|
||||
"": {
|
||||
"name": "thing",
|
||||
"dependencies": {
|
||||
"@lucide/vue": "^1.28.0",
|
||||
"@codemirror/autocomplete": "^6.20.3",
|
||||
"@codemirror/commands": "^6.11.1",
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
"@codemirror/lang-go": "^6.0.1",
|
||||
"@codemirror/lang-html": "^6.4.12",
|
||||
"@codemirror/lang-java": "^6.0.2",
|
||||
"@codemirror/lang-javascript": "^6.2.5",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/lang-less": "^6.0.2",
|
||||
"@codemirror/lang-markdown": "^6.5.2",
|
||||
"@codemirror/lang-php": "^6.0.2",
|
||||
"@codemirror/lang-python": "^6.2.1",
|
||||
"@codemirror/lang-rust": "^6.0.2",
|
||||
"@codemirror/lang-sass": "^6.0.2",
|
||||
"@codemirror/lang-sql": "^6.10.0",
|
||||
"@codemirror/lang-vue": "^0.1.3",
|
||||
"@codemirror/lang-xml": "^6.1.0",
|
||||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/language": "^6.12.4",
|
||||
"@codemirror/language-data": "^6.5.2",
|
||||
"@codemirror/legacy-modes": "^6.5.4",
|
||||
"@codemirror/merge": "^6.12.2",
|
||||
"@codemirror/search": "^6.7.2",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@codemirror/view": "^6.43.13",
|
||||
"@lucide/vue": "^1.48.0",
|
||||
"@replit/codemirror-lang-csharp": "^6.2.0",
|
||||
"@replit/codemirror-lang-svelte": "^6.0.0",
|
||||
"@tailwindcss/vite": "^4.3.2",
|
||||
"@tauri-apps/api": "^2",
|
||||
"@tauri-apps/plugin-autostart": "~2",
|
||||
"@tauri-apps/plugin-dialog": "^2",
|
||||
"@tauri-apps/plugin-global-shortcut": "^2",
|
||||
"@tauri-apps/plugin-opener": "^2",
|
||||
"@tauri-apps/api": "^2.12.0",
|
||||
"@tauri-apps/plugin-autostart": "~2.6.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.0",
|
||||
"@tauri-apps/plugin-global-shortcut": "^2.4.0",
|
||||
"@tauri-apps/plugin-opener": "^2.7.0",
|
||||
"@uiw/codemirror-themes": "^4.25.12",
|
||||
"@vueuse/core": "^14.4.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-search": "^0.16.0",
|
||||
"@xterm/addon-serialize": "^0.14.0",
|
||||
"@xterm/addon-unicode11": "^0.9.0",
|
||||
"@xterm/addon-web-links": "^0.12.0",
|
||||
"@xterm/addon-webgl": "^0.19.0",
|
||||
"@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",
|
||||
"reka-ui": "^2.10.1",
|
||||
"pinyin-pro": "^3.28.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"reka-ui": "^2.10.5",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tailwindcss": "^4.3.2",
|
||||
"vue": "^3.5.13",
|
||||
@@ -24,9 +68,14 @@
|
||||
"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",
|
||||
"@vue/eslint-config-typescript": "^14.9.0",
|
||||
"eslint": "^10.11.0",
|
||||
"eslint-plugin-vue": "^10.11.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "~5.6.2",
|
||||
"vite": "^6.0.3",
|
||||
@@ -43,6 +92,74 @@
|
||||
|
||||
"@babel/types": ["@babel/types@7.29.7", "https://registry.npmmirror.com/@babel/types/-/types-7.29.7.tgz", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="],
|
||||
|
||||
"@cacheable/memory": ["@cacheable/memory@2.2.0", "https://registry.npmmirror.com/@cacheable/memory/-/memory-2.2.0.tgz", { "dependencies": { "@cacheable/utils": "^2.5.0", "@keyv/bigmap": "^1.3.1", "hookified": "^1.15.1", "keyv": "^5.6.0" } }, "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ=="],
|
||||
|
||||
"@cacheable/utils": ["@cacheable/utils@2.5.0", "https://registry.npmmirror.com/@cacheable/utils/-/utils-2.5.0.tgz", { "dependencies": { "hashery": "^1.5.1", "keyv": "^5.6.0" } }, "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA=="],
|
||||
|
||||
"@codemirror/autocomplete": ["@codemirror/autocomplete@6.20.3", "https://registry.npmmirror.com/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0" } }, "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g=="],
|
||||
|
||||
"@codemirror/commands": ["@codemirror/commands@6.11.1", "https://registry.npmmirror.com/@codemirror/commands/-/commands-6.11.1.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.7.0", "@codemirror/view": "^6.27.0", "@lezer/common": "^1.1.0" } }, "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg=="],
|
||||
|
||||
"@codemirror/lang-angular": ["@codemirror/lang-angular@0.1.4", "https://registry.npmmirror.com/@codemirror/lang-angular/-/lang-angular-0.1.4.tgz", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-javascript": "^6.1.2", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.3" } }, "sha512-oap+gsltb/fzdlTQWD6BFF4bSLKcDnlxDsLdePiJpCVNKWXSTAbiiQeYI3UmES+BLAdkmIC1WjyztC1pi/bX4g=="],
|
||||
|
||||
"@codemirror/lang-cpp": ["@codemirror/lang-cpp@6.0.3", "https://registry.npmmirror.com/@codemirror/lang-cpp/-/lang-cpp-6.0.3.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/cpp": "^1.0.0" } }, "sha512-URM26M3vunFFn9/sm6rzqrBzDgfWuDixp85uTY49wKudToc2jTHUrKIGGKs+QWND+YLofNNZpxcNGRynFJfvgA=="],
|
||||
|
||||
"@codemirror/lang-css": ["@codemirror/lang-css@6.3.1", "https://registry.npmmirror.com/@codemirror/lang-css/-/lang-css-6.3.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.2", "@lezer/css": "^1.1.7" } }, "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg=="],
|
||||
|
||||
"@codemirror/lang-go": ["@codemirror/lang-go@6.0.1", "https://registry.npmmirror.com/@codemirror/lang-go/-/lang-go-6.0.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.6.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/go": "^1.0.0" } }, "sha512-7fNvbyNylvqCphW9HD6WFnRpcDjr+KXX/FgqXy5H5ZS0eC5edDljukm/yNgYkwTsgp2busdod50AOTIy6Jikfg=="],
|
||||
|
||||
"@codemirror/lang-html": ["@codemirror/lang-html@6.4.12", "https://registry.npmmirror.com/@codemirror/lang-html/-/lang-html-6.4.12.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/css": "^1.1.0", "@lezer/html": "^1.3.12" } }, "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w=="],
|
||||
|
||||
"@codemirror/lang-java": ["@codemirror/lang-java@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-java/-/lang-java-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/java": "^1.0.0" } }, "sha512-m5Nt1mQ/cznJY7tMfQTJchmrjdjQ71IDs+55d1GAa8DGaB8JXWsVCkVT284C3RTASaY43YknrK2X3hPO/J3MOQ=="],
|
||||
|
||||
"@codemirror/lang-javascript": ["@codemirror/lang-javascript@6.2.5", "https://registry.npmmirror.com/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.6.0", "@codemirror/lint": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/javascript": "^1.0.0" } }, "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A=="],
|
||||
|
||||
"@codemirror/lang-jinja": ["@codemirror/lang-jinja@6.0.1", "https://registry.npmmirror.com/@codemirror/lang-jinja/-/lang-jinja-6.0.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.4.0" } }, "sha512-P5kyHLObzjtbGj16h+hyvZTxJhSjBEeSx4wMjbnAf3b0uwTy2+F0zGjMZL4PQOm/mh2eGZ5xUDVZXgwP783Nsw=="],
|
||||
|
||||
"@codemirror/lang-json": ["@codemirror/lang-json@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-json/-/lang-json-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/json": "^1.0.0" } }, "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ=="],
|
||||
|
||||
"@codemirror/lang-less": ["@codemirror/lang-less@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-less/-/lang-less-6.0.2.tgz", { "dependencies": { "@codemirror/lang-css": "^6.2.0", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-EYdQTG22V+KUUk8Qq582g7FMnCZeEHsyuOJisHRft/mQ+ZSZ2w51NupvDUHiqtsOy7It5cHLPGfHQLpMh9bqpQ=="],
|
||||
|
||||
"@codemirror/lang-liquid": ["@codemirror/lang-liquid@6.3.2", "https://registry.npmmirror.com/@codemirror/lang-liquid/-/lang-liquid-6.3.2.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.1" } }, "sha512-6PDVU3ZnfeYyz1at1E/ttorErZvZFXXt1OPhtfe1EZJ2V2iDFa0CwPqPgG5F7NXN0yONGoBogKmFAafKTqlwIw=="],
|
||||
|
||||
"@codemirror/lang-markdown": ["@codemirror/lang-markdown@6.5.2", "https://registry.npmmirror.com/@codemirror/lang-markdown/-/lang-markdown-6.5.2.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.7.1", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.3.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.2.1", "@lezer/markdown": "^1.0.0" } }, "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw=="],
|
||||
|
||||
"@codemirror/lang-php": ["@codemirror/lang-php@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-php/-/lang-php-6.0.2.tgz", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/php": "^1.0.0" } }, "sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA=="],
|
||||
|
||||
"@codemirror/lang-python": ["@codemirror/lang-python@6.2.1", "https://registry.npmmirror.com/@codemirror/lang-python/-/lang-python-6.2.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.3.2", "@codemirror/language": "^6.8.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.1", "@lezer/python": "^1.1.4" } }, "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw=="],
|
||||
|
||||
"@codemirror/lang-rust": ["@codemirror/lang-rust@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-rust/-/lang-rust-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/rust": "^1.0.0" } }, "sha512-EZaGjCUegtiU7kSMvOfEZpaCReowEf3yNidYu7+vfuGTm9ow4mthAparY5hisJqOHmJowVH3Upu+eJlUji6qqA=="],
|
||||
|
||||
"@codemirror/lang-sass": ["@codemirror/lang-sass@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-sass/-/lang-sass-6.0.2.tgz", { "dependencies": { "@codemirror/lang-css": "^6.2.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.2", "@lezer/sass": "^1.0.0" } }, "sha512-l/bdzIABvnTo1nzdY6U+kPAC51czYQcOErfzQ9zSm9D8GmNPD0WTW8st/CJwBTPLO8jlrbyvlSEcN20dc4iL0Q=="],
|
||||
|
||||
"@codemirror/lang-sql": ["@codemirror/lang-sql@6.10.0", "https://registry.npmmirror.com/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-6ayPkEd/yRw0XKBx5uAiToSgGECo/GY2NoJIHXIIQh1EVwLuKoU8BP/qK0qH5NLXAbtJRLuT73hx7P9X34iO4w=="],
|
||||
|
||||
"@codemirror/lang-vue": ["@codemirror/lang-vue@0.1.3", "https://registry.npmmirror.com/@codemirror/lang-vue/-/lang-vue-0.1.3.tgz", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-javascript": "^6.1.2", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.1" } }, "sha512-QSKdtYTDRhEHCfo5zOShzxCmqKJvgGrZwDQSdbvCRJ5pRLWBS7pD/8e/tH44aVQT6FKm0t6RVNoSUWHOI5vNug=="],
|
||||
|
||||
"@codemirror/lang-wast": ["@codemirror/lang-wast@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-wast/-/lang-wast-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-Imi2KTpVGm7TKuUkqyJ5NRmeFWF7aMpNiwHnLQe0x9kmrxElndyH0K6H/gXtWwY6UshMRAhpENsgfpSwsgmC6Q=="],
|
||||
|
||||
"@codemirror/lang-xml": ["@codemirror/lang-xml@6.1.0", "https://registry.npmmirror.com/@codemirror/lang-xml/-/lang-xml-6.1.0.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/xml": "^1.0.0" } }, "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg=="],
|
||||
|
||||
"@codemirror/lang-yaml": ["@codemirror/lang-yaml@6.1.3", "https://registry.npmmirror.com/@codemirror/lang-yaml/-/lang-yaml-6.1.3.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.0.0", "@lezer/yaml": "^1.0.0" } }, "sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ=="],
|
||||
|
||||
"@codemirror/language": ["@codemirror/language@6.12.4", "https://registry.npmmirror.com/@codemirror/language/-/language-6.12.4.tgz", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0", "style-mod": "^4.0.0" } }, "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A=="],
|
||||
|
||||
"@codemirror/language-data": ["@codemirror/language-data@6.5.2", "https://registry.npmmirror.com/@codemirror/language-data/-/language-data-6.5.2.tgz", { "dependencies": { "@codemirror/lang-angular": "^0.1.0", "@codemirror/lang-cpp": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-go": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-java": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/lang-jinja": "^6.0.0", "@codemirror/lang-json": "^6.0.0", "@codemirror/lang-less": "^6.0.0", "@codemirror/lang-liquid": "^6.0.0", "@codemirror/lang-markdown": "^6.0.0", "@codemirror/lang-php": "^6.0.0", "@codemirror/lang-python": "^6.0.0", "@codemirror/lang-rust": "^6.0.0", "@codemirror/lang-sass": "^6.0.0", "@codemirror/lang-sql": "^6.0.0", "@codemirror/lang-vue": "^0.1.1", "@codemirror/lang-wast": "^6.0.0", "@codemirror/lang-xml": "^6.0.0", "@codemirror/lang-yaml": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/legacy-modes": "^6.4.0" } }, "sha512-CPkWBKrNS8stYbEU5kwBwTf3JB1kghlbh4FSAwzGW2TEscdeHHH4FGysREW86Mqnj3Qn09s0/6Ea/TutmoTobg=="],
|
||||
|
||||
"@codemirror/legacy-modes": ["@codemirror/legacy-modes@6.5.4", "https://registry.npmmirror.com/@codemirror/legacy-modes/-/legacy-modes-6.5.4.tgz", { "dependencies": { "@codemirror/language": "^6.0.0" } }, "sha512-/cZr6qZyl08iYNLGsJ862CXXNI51LryRFRE40ejgoIjXZz0C1rGkD3/Ek5jM/8w1ceRjqtt4qx/KLMh4zBTgew=="],
|
||||
|
||||
"@codemirror/lint": ["@codemirror/lint@6.9.7", "https://registry.npmmirror.com/@codemirror/lint/-/lint-6.9.7.tgz", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.42.0", "crelt": "^1.0.5" } }, "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg=="],
|
||||
|
||||
"@codemirror/merge": ["@codemirror/merge@6.12.2", "https://registry.npmmirror.com/@codemirror/merge/-/merge-6.12.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/highlight": "^1.0.0", "style-mod": "^4.1.0" } }, "sha512-V8JvyAPjHbPupqP7BeMcsdsYCbyPij74jxIbaIJDORI+VZzW44zFmon8bF+oxGWvOKhcRmkiUMXd8MxHr3YA2w=="],
|
||||
|
||||
"@codemirror/search": ["@codemirror/search@6.7.2", "https://registry.npmmirror.com/@codemirror/search/-/search-6.7.2.tgz", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.37.0", "crelt": "^1.0.5" } }, "sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA=="],
|
||||
|
||||
"@codemirror/state": ["@codemirror/state@6.7.6", "https://registry.npmmirror.com/@codemirror/state/-/state-6.7.6.tgz", { "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } }, "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w=="],
|
||||
|
||||
"@codemirror/theme-one-dark": ["@codemirror/theme-one-dark@6.1.3", "https://registry.npmmirror.com/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/highlight": "^1.0.0" } }, "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA=="],
|
||||
|
||||
"@codemirror/view": ["@codemirror/view@6.43.13", "https://registry.npmmirror.com/@codemirror/view/-/view-6.43.13.tgz", { "dependencies": { "@codemirror/state": "^6.7.0", "crelt": "^1.0.6", "style-mod": "^4.1.0", "w3c-keyname": "^2.2.4" } }, "sha512-sihaFrUzAsYBQsL9J2t69y8nfMQGwcYmggAZsk+kjPbjYZMyuf2hU8tUNTZ+P+isb6XRr8JE22TZlJxBoVdH1A=="],
|
||||
|
||||
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="],
|
||||
|
||||
"@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.25.12.tgz", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="],
|
||||
@@ -95,6 +212,20 @@
|
||||
|
||||
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "https://registry.npmmirror.com/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="],
|
||||
|
||||
"@eslint-community/eslint-utils": ["@eslint-community/eslint-utils@4.10.1", "https://registry.npmmirror.com/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", { "dependencies": { "eslint-visitor-keys": "^3.4.3" }, "peerDependencies": { "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg=="],
|
||||
|
||||
"@eslint-community/regexpp": ["@eslint-community/regexpp@4.12.2", "https://registry.npmmirror.com/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", {}, "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew=="],
|
||||
|
||||
"@eslint/config-array": ["@eslint/config-array@0.23.5", "https://registry.npmmirror.com/@eslint/config-array/-/config-array-0.23.5.tgz", { "dependencies": { "@eslint/object-schema": "^3.0.5", "debug": "^4.3.1", "minimatch": "^10.2.4" } }, "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA=="],
|
||||
|
||||
"@eslint/config-helpers": ["@eslint/config-helpers@0.7.0", "https://registry.npmmirror.com/@eslint/config-helpers/-/config-helpers-0.7.0.tgz", { "dependencies": { "@eslint/core": "^1.2.1" } }, "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw=="],
|
||||
|
||||
"@eslint/core": ["@eslint/core@1.2.1", "https://registry.npmmirror.com/@eslint/core/-/core-1.2.1.tgz", { "dependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ=="],
|
||||
|
||||
"@eslint/object-schema": ["@eslint/object-schema@3.0.5", "https://registry.npmmirror.com/@eslint/object-schema/-/object-schema-3.0.5.tgz", {}, "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw=="],
|
||||
|
||||
"@eslint/plugin-kit": ["@eslint/plugin-kit@0.7.3", "https://registry.npmmirror.com/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz", { "dependencies": { "@eslint/core": "^1.2.1", "levn": "^0.4.1" } }, "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q=="],
|
||||
|
||||
"@floating-ui/core": ["@floating-ui/core@1.8.0", "https://registry.npmmirror.com/@floating-ui/core/-/core-1.8.0.tgz", { "dependencies": { "@floating-ui/utils": "^0.2.12" } }, "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ=="],
|
||||
|
||||
"@floating-ui/dom": ["@floating-ui/dom@1.8.0", "https://registry.npmmirror.com/@floating-ui/dom/-/dom-1.8.0.tgz", { "dependencies": { "@floating-ui/core": "^1.8.0", "@floating-ui/utils": "^0.2.12" } }, "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg=="],
|
||||
@@ -103,6 +234,16 @@
|
||||
|
||||
"@floating-ui/vue": ["@floating-ui/vue@1.1.11", "https://registry.npmmirror.com/@floating-ui/vue/-/vue-1.1.11.tgz", { "dependencies": { "@floating-ui/dom": "^1.7.6", "@floating-ui/utils": "^0.2.11", "vue-demi": ">=0.13.0" } }, "sha512-HzHKCNVxnGS35r9fCHBc3+uCnjw9IWIlCPL683cGgM9Kgj2BiAl8x1mS7vtvP6F9S/e/q4O6MApwSHj8hNLGfw=="],
|
||||
|
||||
"@humanfs/core": ["@humanfs/core@0.19.2", "https://registry.npmmirror.com/@humanfs/core/-/core-0.19.2.tgz", { "dependencies": { "@humanfs/types": "^0.15.0" } }, "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA=="],
|
||||
|
||||
"@humanfs/node": ["@humanfs/node@0.16.8", "https://registry.npmmirror.com/@humanfs/node/-/node-0.16.8.tgz", { "dependencies": { "@humanfs/core": "^0.19.2", "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ=="],
|
||||
|
||||
"@humanfs/types": ["@humanfs/types@0.15.0", "https://registry.npmmirror.com/@humanfs/types/-/types-0.15.0.tgz", {}, "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q=="],
|
||||
|
||||
"@humanwhocodes/module-importer": ["@humanwhocodes/module-importer@1.0.1", "https://registry.npmmirror.com/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", {}, "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA=="],
|
||||
|
||||
"@humanwhocodes/retry": ["@humanwhocodes/retry@0.4.3", "https://registry.npmmirror.com/@humanwhocodes/retry/-/retry-0.4.3.tgz", {}, "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ=="],
|
||||
|
||||
"@internationalized/date": ["@internationalized/date@3.12.2", "https://registry.npmmirror.com/@internationalized/date/-/date-3.12.2.tgz", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-FY1Y+H64NDs+HAF6omlnWxm3mEpfgaCSWtL5l551ZZfImA+kGjPFgrnJrGjH6lfmLL0g8Z/mBu1R3kufeCp6Jw=="],
|
||||
|
||||
"@internationalized/number": ["@internationalized/number@3.6.7", "https://registry.npmmirror.com/@internationalized/number/-/number-3.6.7.tgz", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-3ji1fcrT+FPAK86UqEhB/psHixYo6niWPJtt7+qRaYFynt/BaJG8GhAPimtWUpEiVSTq8ZM8L5psMxGquiB/Vg=="],
|
||||
@@ -117,7 +258,57 @@
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
|
||||
|
||||
"@lucide/vue": ["@lucide/vue@1.28.0", "https://registry.npmmirror.com/@lucide/vue/-/vue-1.28.0.tgz", { "peerDependencies": { "vue": ">=3.0.1" } }, "sha512-cO89UyNM/0i2Srdi04nFWeEOQkqzDZlM2ehtWyBhcMpRTJDKpMZPCGAVlmVBgBgr5HaeL5L6FsU8RHsOdwXtKw=="],
|
||||
"@keyv/bigmap": ["@keyv/bigmap@1.3.1", "https://registry.npmmirror.com/@keyv/bigmap/-/bigmap-1.3.1.tgz", { "dependencies": { "hashery": "^1.4.0", "hookified": "^1.15.0" }, "peerDependencies": { "keyv": "^5.6.0" } }, "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ=="],
|
||||
|
||||
"@keyv/serialize": ["@keyv/serialize@1.1.1", "https://registry.npmmirror.com/@keyv/serialize/-/serialize-1.1.1.tgz", {}, "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA=="],
|
||||
|
||||
"@lezer/common": ["@lezer/common@1.5.3", "https://registry.npmmirror.com/@lezer/common/-/common-1.5.3.tgz", {}, "sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q=="],
|
||||
|
||||
"@lezer/cpp": ["@lezer/cpp@1.1.6", "https://registry.npmmirror.com/@lezer/cpp/-/cpp-1.1.6.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA=="],
|
||||
|
||||
"@lezer/css": ["@lezer/css@1.3.8", "https://registry.npmmirror.com/@lezer/css/-/css-1.3.8.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-EJn1zcL9qoDptief6ipWKZKLiOpXkxSe0+t8CH9oiMVcZlq7NBWrjCqnc/41EIjeo/ITj1gFFiATdTkaJDL+Og=="],
|
||||
|
||||
"@lezer/go": ["@lezer/go@1.0.1", "https://registry.npmmirror.com/@lezer/go/-/go-1.0.1.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-xToRsYxwsgJNHTgNdStpcvmbVuKxTapV0dM0wey1geMMRc9aggoVyKgzYp41D2/vVOx+Ii4hmE206kvxIXBVXQ=="],
|
||||
|
||||
"@lezer/highlight": ["@lezer/highlight@1.2.5", "https://registry.npmmirror.com/@lezer/highlight/-/highlight-1.2.5.tgz", { "dependencies": { "@lezer/common": "^1.3.0" } }, "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w=="],
|
||||
|
||||
"@lezer/html": ["@lezer/html@1.3.13", "https://registry.npmmirror.com/@lezer/html/-/html-1.3.13.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg=="],
|
||||
|
||||
"@lezer/java": ["@lezer/java@1.1.4", "https://registry.npmmirror.com/@lezer/java/-/java-1.1.4.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-gQylJ2xHV2xXsVqtnAcJrcROvLZJaQiC0tR//+q0k961BxqvyYttusPkJ8d9T1fPDJKHJW2etUH8XbIn9jhVUg=="],
|
||||
|
||||
"@lezer/javascript": ["@lezer/javascript@1.5.5", "https://registry.npmmirror.com/@lezer/javascript/-/javascript-1.5.5.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.1.3", "@lezer/lr": "^1.3.0" } }, "sha512-sWg4yX1J6XW67AaAynVt0iwF0M5c+np36TEu+P2ifAJ8haRYvHnWDV28r1jdwnJehWCwXECutAUy56K4RBZIyg=="],
|
||||
|
||||
"@lezer/json": ["@lezer/json@1.0.3", "https://registry.npmmirror.com/@lezer/json/-/json-1.0.3.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ=="],
|
||||
|
||||
"@lezer/lr": ["@lezer/lr@1.4.10", "https://registry.npmmirror.com/@lezer/lr/-/lr-1.4.10.tgz", { "dependencies": { "@lezer/common": "^1.0.0" } }, "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A=="],
|
||||
|
||||
"@lezer/markdown": ["@lezer/markdown@1.7.2", "https://registry.npmmirror.com/@lezer/markdown/-/markdown-1.7.2.tgz", { "dependencies": { "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0" } }, "sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ=="],
|
||||
|
||||
"@lezer/php": ["@lezer/php@1.0.6", "https://registry.npmmirror.com/@lezer/php/-/php-1.0.6.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.1.0" } }, "sha512-QJ2xNXPmsm/Z3IpThq8fnJrEIVpxhsIoj6GZBW0JYEd/l9zxpJZW216X4fzqQY4vgpdGIumypvI4uQjd4tnYtw=="],
|
||||
|
||||
"@lezer/python": ["@lezer/python@1.1.19", "https://registry.npmmirror.com/@lezer/python/-/python-1.1.19.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ=="],
|
||||
|
||||
"@lezer/rust": ["@lezer/rust@1.0.3", "https://registry.npmmirror.com/@lezer/rust/-/rust-1.0.3.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-XxErOjZzQ7yJt1agUT4fu9qQvESZ3acgoxpPaPTPOiUx+duCjaVAtZGFIgphkHxlN05djdVAIOy/wItShMEjqQ=="],
|
||||
|
||||
"@lezer/sass": ["@lezer/sass@1.1.0", "https://registry.npmmirror.com/@lezer/sass/-/sass-1.1.0.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-3mMGdCTUZ/84ArHOuXWQr37pnf7f+Nw9ycPUeKX+wu19b7pSMcZGLbaXwvD2APMBDOGxPmpK/O6S1v1EvLoqgQ=="],
|
||||
|
||||
"@lezer/xml": ["@lezer/xml@1.0.6", "https://registry.npmmirror.com/@lezer/xml/-/xml-1.0.6.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww=="],
|
||||
|
||||
"@lezer/yaml": ["@lezer/yaml@1.0.4", "https://registry.npmmirror.com/@lezer/yaml/-/yaml-1.0.4.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.4.0" } }, "sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw=="],
|
||||
|
||||
"@lucide/vue": ["@lucide/vue@1.49.0", "https://registry.npmmirror.com/@lucide/vue/-/vue-1.49.0.tgz", { "peerDependencies": { "vue": ">=3.0.1" } }, "sha512-7xS5gYnLoIx0jlmlRE3Rb71fIHaNqhVBiKMpOlqrYt6nMPy3C/62HJHo5XNsV3HTK+9l3M0hXICrIA7S5v6y5Q=="],
|
||||
|
||||
"@marijn/find-cluster-break": ["@marijn/find-cluster-break@1.0.4", "https://registry.npmmirror.com/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", {}, "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ=="],
|
||||
|
||||
"@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "https://registry.npmmirror.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="],
|
||||
|
||||
"@nodelib/fs.stat": ["@nodelib/fs.stat@2.0.5", "https://registry.npmmirror.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", {}, "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A=="],
|
||||
|
||||
"@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=="],
|
||||
|
||||
@@ -205,48 +396,84 @@
|
||||
|
||||
"@tanstack/vue-virtual": ["@tanstack/vue-virtual@3.13.32", "https://registry.npmmirror.com/@tanstack/vue-virtual/-/vue-virtual-3.13.32.tgz", { "dependencies": { "@tanstack/virtual-core": "3.17.4" }, "peerDependencies": { "vue": "^2.7.0 || ^3.0.0" } }, "sha512-E8OCutx7QnwZdvpJijz0Q2PHsYDWBWjnGr3TvgWiqxTU35jB1kVhtkd93scRV7tTFuId2tg3x2iFiw+IE4evjQ=="],
|
||||
|
||||
"@tauri-apps/api": ["@tauri-apps/api@2.11.1", "https://registry.npmmirror.com/@tauri-apps/api/-/api-2.11.1.tgz", {}, "sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA=="],
|
||||
"@tauri-apps/api": ["@tauri-apps/api@2.12.0", "https://registry.npmmirror.com/@tauri-apps/api/-/api-2.12.0.tgz", {}, "sha512-fUSxFX8VABYe9W9K5ROdEaKVkNUFRcMSRofjruvaxztXA+I0XnQHcYHF8m/a6iExRUxsUf0HsFWhPBuH9IgzJw=="],
|
||||
|
||||
"@tauri-apps/cli": ["@tauri-apps/cli@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli/-/cli-2.11.4.tgz", { "optionalDependencies": { "@tauri-apps/cli-darwin-arm64": "2.11.4", "@tauri-apps/cli-darwin-x64": "2.11.4", "@tauri-apps/cli-linux-arm-gnueabihf": "2.11.4", "@tauri-apps/cli-linux-arm64-gnu": "2.11.4", "@tauri-apps/cli-linux-arm64-musl": "2.11.4", "@tauri-apps/cli-linux-riscv64-gnu": "2.11.4", "@tauri-apps/cli-linux-x64-gnu": "2.11.4", "@tauri-apps/cli-linux-x64-musl": "2.11.4", "@tauri-apps/cli-win32-arm64-msvc": "2.11.4", "@tauri-apps/cli-win32-ia32-msvc": "2.11.4", "@tauri-apps/cli-win32-x64-msvc": "2.11.4" }, "bin": { "tauri": "tauri.js" } }, "sha512-R8xGtMpwyetawSqm9kYOuMmEqkhUbvcUy8n0aNXIxollKBLESUu5f4Fx+64hgASYm1H+jSWq6jCW6zqTnH6hqQ=="],
|
||||
"@tauri-apps/cli": ["@tauri-apps/cli@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli/-/cli-2.12.0.tgz", { "optionalDependencies": { "@tauri-apps/cli-darwin-arm64": "2.12.0", "@tauri-apps/cli-darwin-x64": "2.12.0", "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.0", "@tauri-apps/cli-linux-arm64-gnu": "2.12.0", "@tauri-apps/cli-linux-arm64-musl": "2.12.0", "@tauri-apps/cli-linux-riscv64-gnu": "2.12.0", "@tauri-apps/cli-linux-x64-gnu": "2.12.0", "@tauri-apps/cli-linux-x64-musl": "2.12.0", "@tauri-apps/cli-win32-arm64-msvc": "2.12.0", "@tauri-apps/cli-win32-ia32-msvc": "2.12.0", "@tauri-apps/cli-win32-x64-msvc": "2.12.0" }, "bin": { "tauri": "tauri.js" } }, "sha512-GIShnAR4C16kSTA8NO02fo8fOw/I5z5sAUEB5S2HlPHFnBkbihL4c9a/MpkxOm1+q5S+tFd3X4QUjHWxfyGzpQ=="],
|
||||
|
||||
"@tauri-apps/cli-darwin-arm64": ["@tauri-apps/cli-darwin-arm64@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.11.4.tgz", { "os": "darwin", "cpu": "arm64" }, "sha512-1ryOF3ZhpZ/nemHV5zVwBQBz9jDGKmKPvWPADOhc83ig0P4bMc2iER4NbC6r9sjeIZ6RVQ4g3RZIYvezhcl4TQ=="],
|
||||
"@tauri-apps/cli-darwin-arm64": ["@tauri-apps/cli-darwin-arm64@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.0.tgz", { "os": "darwin", "cpu": "arm64" }, "sha512-v5J+jISihLGtih1+3yWagbsL+5dbLZORu4vaSI0vhY0Heb+MAW+T/1s1RyKxrQrwEPGBG5kqwfDDTnSbmVkuqA=="],
|
||||
|
||||
"@tauri-apps/cli-darwin-x64": ["@tauri-apps/cli-darwin-x64@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.11.4.tgz", { "os": "darwin", "cpu": "x64" }, "sha512-uFsGQAAfuyz1k/yGLmkWfkBlgKAqZfxqlHmLWx81QU27RJWfmbNHCIq8T8w1e+VClleIuZUjpHWfoE4E3DLo3A=="],
|
||||
"@tauri-apps/cli-darwin-x64": ["@tauri-apps/cli-darwin-x64@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.0.tgz", { "os": "darwin", "cpu": "x64" }, "sha512-g27I07pfW/dMS8vcNqB9lamgKF0TqLlcy8e7t9qDGsB1iaeyjJWb2TgBF4tM9ZwLqPAZUXbsz28oXljO12WC4g=="],
|
||||
|
||||
"@tauri-apps/cli-linux-arm-gnueabihf": ["@tauri-apps/cli-linux-arm-gnueabihf@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.11.4.tgz", { "os": "linux", "cpu": "arm" }, "sha512-IaHZn5CdBL21oUmjiVOS1ctw6Ip1O0pjp70FwOWmYz1myWe0SY96ZIj2FYf7pT0m8bI2h/hrs5ZbEXXh44/MkQ=="],
|
||||
"@tauri-apps/cli-linux-arm-gnueabihf": ["@tauri-apps/cli-linux-arm-gnueabihf@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.0.tgz", { "os": "linux", "cpu": "arm" }, "sha512-gXyQ710fNc99YuxFxNyeX9PLSrIpbtgBBj7GQo9tSeRT6fIK40q3/gm7X5jqZo7mWLR2m0R/2ALd3vAWo0Z32Q=="],
|
||||
|
||||
"@tauri-apps/cli-linux-arm64-gnu": ["@tauri-apps/cli-linux-arm64-gnu@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.11.4.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-N41/ukTRVe6XSuUTESuFdGeOW2i7k62tK+6gHK5Kd5/q5RPvvi19GaWAVPPb9u95HSGmTChSolBfzynUsssFaA=="],
|
||||
"@tauri-apps/cli-linux-arm64-gnu": ["@tauri-apps/cli-linux-arm64-gnu@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.0.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-H9cyXuq9WgxoHh2NZ+R+oN+W78x5UwaBDEp0/fmqUUkaBoioCuOZErM9xKiIV6bpNAhmw1RoWZ49u37q/vaiAg=="],
|
||||
|
||||
"@tauri-apps/cli-linux-arm64-musl": ["@tauri-apps/cli-linux-arm64-musl@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.11.4.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-v277UnT/fB64xAfSroL5N3Km3tLmvATWqJJw/wRI+g6o+HkeD0slyE7gOhNs1MbjE41R7bQOTxMVoL3aomUJmw=="],
|
||||
"@tauri-apps/cli-linux-arm64-musl": ["@tauri-apps/cli-linux-arm64-musl@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.0.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-5tFuk3JKMBa1M/iN4gN32OYlSfhY3aqb5PO3zCugxaT+sfecyMKpc3EM9VDbhmwWBE9QD4Tfj7wGhlqx2yy2pQ=="],
|
||||
|
||||
"@tauri-apps/cli-linux-riscv64-gnu": ["@tauri-apps/cli-linux-riscv64-gnu@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.11.4.tgz", { "os": "linux", "cpu": "none" }, "sha512-qqgNkQ2u1yZHxjhxsZaxUtRDW8dIqIYm33rx/mzwQv0SfY9x1B+iraj8vWeFiXjjSVVhEMepXSOts1TqPzvXNQ=="],
|
||||
"@tauri-apps/cli-linux-riscv64-gnu": ["@tauri-apps/cli-linux-riscv64-gnu@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.0.tgz", { "os": "linux", "cpu": "none" }, "sha512-LOrMyV+nb7pKq8P0BZtTBQuyzm1ORjn16R9MlupmxuT5LqxtuYJlw3VMwbaeXCToJ8jbP5u9JnkfmbqDlvETXw=="],
|
||||
|
||||
"@tauri-apps/cli-linux-x64-gnu": ["@tauri-apps/cli-linux-x64-gnu@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.11.4.tgz", { "os": "linux", "cpu": "x64" }, "sha512-2VRNWl84FOH0m2giiDkO2h0QXlcMJeX+zJDpI5kDIQAx6s+geF3v48F4DXfJez4GS/FdoDGnPnw1C2iYGbQ7bQ=="],
|
||||
"@tauri-apps/cli-linux-x64-gnu": ["@tauri-apps/cli-linux-x64-gnu@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.0.tgz", { "os": "linux", "cpu": "x64" }, "sha512-aMIkI+X9qvD2+k80QZB3tuOYT41/cEheikC510CwAIZ31KLXORsRASYYzM4mi1/58ICmtzSLFhCC08keir7COw=="],
|
||||
|
||||
"@tauri-apps/cli-linux-x64-musl": ["@tauri-apps/cli-linux-x64-musl@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.11.4.tgz", { "os": "linux", "cpu": "x64" }, "sha512-o9GyhYor/nc7xarmwDE3ka2szuW3uuZzXjHWh64Q8YX5AtSgxdQkFWzrY4O8KiGtVNvFBI14H3Q49Qj5TOIP/A=="],
|
||||
"@tauri-apps/cli-linux-x64-musl": ["@tauri-apps/cli-linux-x64-musl@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.0.tgz", { "os": "linux", "cpu": "x64" }, "sha512-9gl3NhUbfuGhSKjeGCypKSdtoezOQRcDUrkhTWtLQEjnajets6peO6NadgI2DF0OzbiiFOzrnnIGMwBS+Ap6Iw=="],
|
||||
|
||||
"@tauri-apps/cli-win32-arm64-msvc": ["@tauri-apps/cli-win32-arm64-msvc@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.11.4.tgz", { "os": "win32", "cpu": "arm64" }, "sha512-ld5Ehb598m0VkYyylRPNeCFsBe/km0jxis6KgMpl3IGY6I/i1RwQXO05I1AsXUXO2WC6AvB/Lw4qTf/asiuEiQ=="],
|
||||
"@tauri-apps/cli-win32-arm64-msvc": ["@tauri-apps/cli-win32-arm64-msvc@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.0.tgz", { "os": "win32", "cpu": "arm64" }, "sha512-1W+v86wsYLuyBDN0iDessD4CD9o+yNyO0m8Dp3+/vfjiZrJ/v7R7/aTRBeikaq2tLGgxeag0gxnFggBNBGw91A=="],
|
||||
|
||||
"@tauri-apps/cli-win32-ia32-msvc": ["@tauri-apps/cli-win32-ia32-msvc@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.11.4.tgz", { "os": "win32", "cpu": "ia32" }, "sha512-12Hxi0XX/H5VFxO/bGgHkFWhml9VMgEOu9CidjeCeTNQ1l6fpUlbiGgSP7CLI3PFtW9/FfbeHieZ+kyWK5H7CA=="],
|
||||
"@tauri-apps/cli-win32-ia32-msvc": ["@tauri-apps/cli-win32-ia32-msvc@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.0.tgz", { "os": "win32", "cpu": "ia32" }, "sha512-SsBjvq4f7YaBGqcWoE3cycoItPf0SrQeqFqWWgfxoeZWAIz01E31LDSeZ2p/etJiIY0R9oi045chkFfb0O7WGw=="],
|
||||
|
||||
"@tauri-apps/cli-win32-x64-msvc": ["@tauri-apps/cli-win32-x64-msvc@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.11.4.tgz", { "os": "win32", "cpu": "x64" }, "sha512-+vDiqBIU5dMISg/wNvX3sF+ZHfgJGJ5T0AcO+EHNXV9GGAG+P5fzodlDXD3QdKCRgZxMoCm5PPvj3BqLNjBthw=="],
|
||||
"@tauri-apps/cli-win32-x64-msvc": ["@tauri-apps/cli-win32-x64-msvc@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.0.tgz", { "os": "win32", "cpu": "x64" }, "sha512-9zzDKYUH4TKKBgRdDdVQX8fiRO5gJ8hD1nGsHU9DOHG5Jpm3arjbu9Xg1frR20EusG3Sl8X0dppoO/4EoUXUGg=="],
|
||||
|
||||
"@tauri-apps/plugin-autostart": ["@tauri-apps/plugin-autostart@2.5.1", "https://registry.npmmirror.com/@tauri-apps/plugin-autostart/-/plugin-autostart-2.5.1.tgz", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-zS/xx7yzveCcotkA+8TqkI2lysmG2wvQXv2HGAVExITmnFfHAdj1arGsbbfs3o6EktRHf6l34pJxc3YGG2mg7w=="],
|
||||
"@tauri-apps/plugin-autostart": ["@tauri-apps/plugin-autostart@2.6.0", "https://registry.npmmirror.com/@tauri-apps/plugin-autostart/-/plugin-autostart-2.6.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-myppl3C/dygGbn7Inmm3LqsAQ7SSsT3KtNpSt/e+fA5J7xeCIf8H+LMiE1tkS7mKzTfChCutfZCt0FQkrL/YdA=="],
|
||||
|
||||
"@tauri-apps/plugin-dialog": ["@tauri-apps/plugin-dialog@2.7.2", "https://registry.npmmirror.com/@tauri-apps/plugin-dialog/-/plugin-dialog-2.7.2.tgz", { "dependencies": { "@tauri-apps/api": "^2.11.0" } }, "sha512-pX0IGm1I3I6wc+zeKYcq1GSqogK6okCNX5fOdaNU5ab1AjGS6l1E5wFNjEb7meg7ZFSp0JUs+0jQGQNyOvLrsg=="],
|
||||
"@tauri-apps/plugin-dialog": ["@tauri-apps/plugin-dialog@2.8.0", "https://registry.npmmirror.com/@tauri-apps/plugin-dialog/-/plugin-dialog-2.8.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-HSSD5C8UFE9ijD1wue84F7jjaIReFmj8AAPtS+xyjYRltJafIc4BiWHY7SJ6vbbew6u+YljEJHfyNfy5VwywXg=="],
|
||||
|
||||
"@tauri-apps/plugin-global-shortcut": ["@tauri-apps/plugin-global-shortcut@2.3.2", "https://registry.npmmirror.com/@tauri-apps/plugin-global-shortcut/-/plugin-global-shortcut-2.3.2.tgz", { "dependencies": { "@tauri-apps/api": "^2.11.0" } }, "sha512-UReHNXrLvpEjylE4jb4oCYiy96uRykPUthoCQCmRXYrd5hs5X9DrW+qOn7GLW57EJN4tdK8bgK5twBTz2NOxzA=="],
|
||||
"@tauri-apps/plugin-global-shortcut": ["@tauri-apps/plugin-global-shortcut@2.4.0", "https://registry.npmmirror.com/@tauri-apps/plugin-global-shortcut/-/plugin-global-shortcut-2.4.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-XBA4PcRjRdJBp/jwFxc5YZ/yKhZuslpOG/pGaNfhnRDVGMQfoXEKMv/6A6vjzfKLUxr8ml3ay8o2W8Rk6mHICA=="],
|
||||
|
||||
"@tauri-apps/plugin-opener": ["@tauri-apps/plugin-opener@2.5.4", "https://registry.npmmirror.com/@tauri-apps/plugin-opener/-/plugin-opener-2.5.4.tgz", { "dependencies": { "@tauri-apps/api": "^2.11.0" } }, "sha512-1HnPkb+AmgO29HBazm4uPLKB+r7zzcTBW1d0fyYp1uP+jwtpoiNDGKMMzz58SFp49nOIrxdE3aUJtT57lfO9CQ=="],
|
||||
"@tauri-apps/plugin-opener": ["@tauri-apps/plugin-opener@2.7.0", "https://registry.npmmirror.com/@tauri-apps/plugin-opener/-/plugin-opener-2.7.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-mBorYfVKh9Lt7s4ZFtKbMUTxBw+Y/sVmSlKCtkkoBgMTC/DIbt/kaPm67L/2djAUqDI1wbixy5OHHVmipjuGMw=="],
|
||||
|
||||
"@types/esrecurse": ["@types/esrecurse@4.3.1", "https://registry.npmmirror.com/@types/esrecurse/-/esrecurse-4.3.1.tgz", {}, "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="],
|
||||
|
||||
"@types/estree": ["@types/estree@1.0.9", "https://registry.npmmirror.com/@types/estree/-/estree-1.0.9.tgz", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],
|
||||
|
||||
"@types/json-schema": ["@types/json-schema@7.0.15", "https://registry.npmmirror.com/@types/json-schema/-/json-schema-7.0.15.tgz", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
|
||||
|
||||
"@types/linkify-it": ["@types/linkify-it@5.0.0", "https://registry.npmmirror.com/@types/linkify-it/-/linkify-it-5.0.0.tgz", {}, "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q=="],
|
||||
|
||||
"@types/markdown-it": ["@types/markdown-it@14.2.0", "https://registry.npmmirror.com/@types/markdown-it/-/markdown-it-14.2.0.tgz", { "dependencies": { "@types/linkify-it": "^5", "@types/mdurl": "^2" } }, "sha512-NoQ2yGlLWj4wpxMs+TYmRKk3thDrQ97agr7sFqfLsAlvoS8SNQuTrlObhFqG9iugdTtgOE9jpJ6FNM4ZGsa5xQ=="],
|
||||
|
||||
"@types/mdurl": ["@types/mdurl@2.0.0", "https://registry.npmmirror.com/@types/mdurl/-/mdurl-2.0.0.tgz", {}, "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg=="],
|
||||
|
||||
"@types/node": ["@types/node@26.1.1", "https://registry.npmmirror.com/@types/node/-/node-26.1.1.tgz", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="],
|
||||
|
||||
"@types/qrcode": ["@types/qrcode@1.5.6", "https://registry.npmmirror.com/@types/qrcode/-/qrcode-1.5.6.tgz", { "dependencies": { "@types/node": "*" } }, "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw=="],
|
||||
|
||||
"@types/sortablejs": ["@types/sortablejs@1.15.9", "https://registry.npmmirror.com/@types/sortablejs/-/sortablejs-1.15.9.tgz", {}, "sha512-7HP+rZGE2p886PKV9c9OJzLBI6BBJu1O7lJGYnPyG3fS4/duUCcngkNCjsLwIMV+WMqANe3tt4irrXHSIe68OQ=="],
|
||||
|
||||
"@types/trusted-types": ["@types/trusted-types@2.0.7", "https://registry.npmmirror.com/@types/trusted-types/-/trusted-types-2.0.7.tgz", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="],
|
||||
|
||||
"@types/web-bluetooth": ["@types/web-bluetooth@0.0.21", "https://registry.npmmirror.com/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", {}, "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA=="],
|
||||
|
||||
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.70.0.tgz", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.70.0", "@typescript-eslint/type-utils": "8.70.0", "@typescript-eslint/utils": "8.70.0", "@typescript-eslint/visitor-keys": "8.70.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.70.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-/v8HZt6RlyIZxB3ntehELOcUcfxKPVGWXnQdJuHRmzrqgF8nQypcC/oxGW+Ot4VGKDq81XugPKxx0n5PBtf9PA=="],
|
||||
|
||||
"@typescript-eslint/parser": ["@typescript-eslint/parser@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/parser/-/parser-8.70.0.tgz", { "dependencies": { "@typescript-eslint/scope-manager": "8.70.0", "@typescript-eslint/types": "8.70.0", "@typescript-eslint/typescript-estree": "8.70.0", "@typescript-eslint/visitor-keys": "8.70.0", "debug": "^4.4.3" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-zYvrmj9Yxd63UGaXw+kdt6A0F0s0qveJyuatIM77bYC2DE4pgmg7a50u8LR7PRtXd0x+h+Tl3eXabGm06SWd3Q=="],
|
||||
|
||||
"@typescript-eslint/project-service": ["@typescript-eslint/project-service@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/project-service/-/project-service-8.70.0.tgz", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.70.0", "@typescript-eslint/types": "^8.70.0", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-hFHbTNqhU9G+2eKFXCBVb1tjFT/LceiJ4+HfLO4pTpDI0KHi6iajpcFFkaSQ9gXmCh7n82A0PthaayEdN6mspQ=="],
|
||||
|
||||
"@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/scope-manager/-/scope-manager-8.70.0.tgz", { "dependencies": { "@typescript-eslint/types": "8.70.0", "@typescript-eslint/visitor-keys": "8.70.0" } }, "sha512-8nP3Kwh5hlgZ4FicGvmznAmJe8UL4sdU8tLukrPaMuQmDuk4Y8xYfzu/aYZW4xT2JCgc7H/TpDI5cGlxcWJSqQ=="],
|
||||
|
||||
"@typescript-eslint/tsconfig-utils": ["@typescript-eslint/tsconfig-utils@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.70.0.tgz", { "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-adnkeeNq9Sq1sUf4+FRVc0KdgYghzsgFpZSQVZVvY0LCuUuN0FnQgyGzCJeC4fW1cdXseBAjU2EOqUIjbNcZUw=="],
|
||||
|
||||
"@typescript-eslint/type-utils": ["@typescript-eslint/type-utils@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/type-utils/-/type-utils-8.70.0.tgz", { "dependencies": { "@typescript-eslint/types": "8.70.0", "@typescript-eslint/typescript-estree": "8.70.0", "@typescript-eslint/utils": "8.70.0", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-NUMKIhYVaVIVLnRL9CRt+VVcuLgSHUCpXn4/+K8wql+vdInUzvx8BjUO1oJ7cG9shjFJKtF8F8Hh2kCh3/KBVw=="],
|
||||
|
||||
"@typescript-eslint/types": ["@typescript-eslint/types@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/types/-/types-8.70.0.tgz", {}, "sha512-asTOIYhDg4zdzOScCyaytrsV3cR6B4ecPQlXw/dJIm7J/MZTtCtfVII9JD8Geh4jTCrK/Xe6cg5UevoleMcoJQ=="],
|
||||
|
||||
"@typescript-eslint/typescript-estree": ["@typescript-eslint/typescript-estree@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/typescript-estree/-/typescript-estree-8.70.0.tgz", { "dependencies": { "@typescript-eslint/project-service": "8.70.0", "@typescript-eslint/tsconfig-utils": "8.70.0", "@typescript-eslint/types": "8.70.0", "@typescript-eslint/visitor-keys": "8.70.0", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-d9NmHMPEKQ7QCLLm1jI3zmoQBwT5KwFYjXBJ9ymZfKCUU+5rmTRykKAFvH5Qn/ZCds3CEAFS9OC9M/jkl0X2bA=="],
|
||||
|
||||
"@typescript-eslint/utils": ["@typescript-eslint/utils@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/utils/-/utils-8.70.0.tgz", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.70.0", "@typescript-eslint/types": "8.70.0", "@typescript-eslint/typescript-estree": "8.70.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-oZmtKJz/4fufZ2p3+Cn3ijEojcdfR+1zYDH2xKYrEly0dR/Q/1xUPRCOlKGxod78nWlU2UnDe09GZ3TaknBFGA=="],
|
||||
|
||||
"@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.70.0.tgz", { "dependencies": { "@typescript-eslint/types": "8.70.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-BoC8PiO4Hkdo0TVJh9Ntxr5MxPDI7/oFsrygN5ADelFSeXG/qgNuucIGA+L5Z6JpPTE/uRfcTWtscjbUaufepQ=="],
|
||||
|
||||
"@uiw/codemirror-themes": ["@uiw/codemirror-themes@4.25.12", "https://registry.npmmirror.com/@uiw/codemirror-themes/-/codemirror-themes-4.25.12.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0" } }, "sha512-3bLX6C+gstr82SmY2FAj2TfHXnl2SnC+whRZJmRsv82wMhG8RZlZVy+o0rLuGRIPD9acuY0gpouHVRNUnzBj3g=="],
|
||||
|
||||
"@vitejs/plugin-vue": ["@vitejs/plugin-vue@5.2.4", "https://registry.npmmirror.com/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz", { "peerDependencies": { "vite": "^5.0.0 || ^6.0.0", "vue": "^3.2.25" } }, "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA=="],
|
||||
|
||||
"@volar/language-core": ["@volar/language-core@2.4.15", "https://registry.npmmirror.com/@volar/language-core/-/language-core-2.4.15.tgz", { "dependencies": { "@volar/source-map": "2.4.15" } }, "sha512-3VHw+QZU0ZG9IuQmzT68IyN4hZNd9GchGPhbD9+pa8CVv7rnoOZwo7T8weIbrRmihqy3ATpdfXFnqRrfPVK6CA=="],
|
||||
@@ -271,6 +498,8 @@
|
||||
|
||||
"@vue/devtools-shared": ["@vue/devtools-shared@7.7.10", "https://registry.npmmirror.com/@vue/devtools-shared/-/devtools-shared-7.7.10.tgz", { "dependencies": { "rfdc": "^1.4.1" } }, "sha512-wOPslzB8vTvpxwdaOcR2qAbwmuSP0L+rhpoC6Cf56V3Jip+HWb7PQQXOUPgBNQARpXsbQX/+mvi8kKucmBGRwQ=="],
|
||||
|
||||
"@vue/eslint-config-typescript": ["@vue/eslint-config-typescript@14.9.0", "https://registry.npmmirror.com/@vue/eslint-config-typescript/-/eslint-config-typescript-14.9.0.tgz", { "dependencies": { "@typescript-eslint/utils": "^8.60.0", "fast-glob": "^3.3.3", "typescript-eslint": "^8.60.0", "vue-eslint-parser": "^10.4.0" }, "peerDependencies": { "eslint": "^9.10.0 || ^10.0.0", "eslint-plugin-vue": "^9.28.0 || ^10.0.0", "typescript": ">=4.8.4" }, "optionalPeers": ["typescript"], "bin": { "vue-eslint-config-typescript": "./dist/bin.js" } }, "sha512-E3j9hDlfVf10F30MRcLTPY2IIhWIx1nsvkVukk14kTcuA+oBVot9zsP1hzsO+PAMDxV3Fd9FimBJtUBNBL5KFA=="],
|
||||
|
||||
"@vue/language-core": ["@vue/language-core@2.2.12", "https://registry.npmmirror.com/@vue/language-core/-/language-core-2.2.12.tgz", { "dependencies": { "@volar/language-core": "2.4.15", "@vue/compiler-dom": "^3.5.0", "@vue/compiler-vue2": "^2.7.16", "@vue/shared": "^3.5.0", "alien-signals": "^1.0.3", "minimatch": "^9.0.3", "muggle-string": "^0.4.1", "path-browserify": "^1.0.1" }, "peerDependencies": { "typescript": "*" }, "optionalPeers": ["typescript"] }, "sha512-IsGljWbKGU1MZpBPN+BvPAdr55YPkj2nB/TBNGNC32Vy2qLG25DYu/NBN2vNtZqdRbTRjaoYrahLrToim2NanA=="],
|
||||
|
||||
"@vue/reactivity": ["@vue/reactivity@3.5.39", "https://registry.npmmirror.com/@vue/reactivity/-/reactivity-3.5.39.tgz", { "dependencies": { "@vue/shared": "3.5.39" } }, "sha512-TpsuBJ9gGlZa5d23XcM2y8EXanz9dZeVDQBXRwzy46ItgvM+rWpzs+UVM0wcRLxGvcav0HE5jz2gNL53xlRAog=="],
|
||||
@@ -289,52 +518,188 @@
|
||||
|
||||
"@vueuse/shared": ["@vueuse/shared@14.4.0", "https://registry.npmmirror.com/@vueuse/shared/-/shared-14.4.0.tgz", { "peerDependencies": { "vue": "^3.5.0" } }, "sha512-JRgY90Sz8DDtPMsaDflvPMp9xYk69JZAmbuDvAquUVXKr2gEjqtzGNTTthLfckH0BzBqvnu31gb4a8TGLRe79g=="],
|
||||
|
||||
"@xterm/addon-fit": ["@xterm/addon-fit@0.11.0", "https://registry.npmmirror.com/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", {}, "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g=="],
|
||||
|
||||
"@xterm/addon-search": ["@xterm/addon-search@0.16.0", "https://registry.npmmirror.com/@xterm/addon-search/-/addon-search-0.16.0.tgz", {}, "sha512-9OeuBFu0/uZJPu+9AHKY6g/w0Czyb/Ut0A5t79I4ULoU4IfU5BEpPFVGQxP4zTTMdfZEYkVIRYbHBX1xWwjeSA=="],
|
||||
|
||||
"@xterm/addon-serialize": ["@xterm/addon-serialize@0.14.0", "https://registry.npmmirror.com/@xterm/addon-serialize/-/addon-serialize-0.14.0.tgz", {}, "sha512-uteyTU1EkrQa2Ux6P/uFl2fzmXI46jy5uoQMKEOM0fKTyiW7cSn0WrFenHm5vO5uEXX/GpwW/FgILvv3r0WbkA=="],
|
||||
|
||||
"@xterm/addon-unicode11": ["@xterm/addon-unicode11@0.9.0", "https://registry.npmmirror.com/@xterm/addon-unicode11/-/addon-unicode11-0.9.0.tgz", {}, "sha512-FxDnYcyuXhNl+XSqGZL/t0U9eiNb/q3EWT5rYkQT/zuig8Gz/VagnQANKHdDWFM2lTMk9ly0EFQxxxtZUoRetw=="],
|
||||
|
||||
"@xterm/addon-web-links": ["@xterm/addon-web-links@0.12.0", "https://registry.npmmirror.com/@xterm/addon-web-links/-/addon-web-links-0.12.0.tgz", {}, "sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw=="],
|
||||
|
||||
"@xterm/addon-webgl": ["@xterm/addon-webgl@0.19.0", "https://registry.npmmirror.com/@xterm/addon-webgl/-/addon-webgl-0.19.0.tgz", {}, "sha512-b3fMOsyLVuCeNJWxolACEUED0vm7qC0cy4wRvf3oURSzDTYVQiGPhTnhWZwIHdvC48Y+oLhvYXnY4XDXPoJo6A=="],
|
||||
|
||||
"@xterm/xterm": ["@xterm/xterm@6.0.0", "https://registry.npmmirror.com/@xterm/xterm/-/xterm-6.0.0.tgz", {}, "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg=="],
|
||||
|
||||
"acorn": ["acorn@8.18.0", "https://registry.npmmirror.com/acorn/-/acorn-8.18.0.tgz", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="],
|
||||
|
||||
"acorn-jsx": ["acorn-jsx@5.3.2", "https://registry.npmmirror.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="],
|
||||
|
||||
"ajv": ["ajv@6.15.0", "https://registry.npmmirror.com/ajv/-/ajv-6.15.0.tgz", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="],
|
||||
|
||||
"alien-signals": ["alien-signals@1.0.13", "https://registry.npmmirror.com/alien-signals/-/alien-signals-1.0.13.tgz", {}, "sha512-OGj9yyTnJEttvzhTUWuscOvtqxq5vrhF7vL9oS0xJ2mK0ItPYP1/y+vCFebfxoEyAz0++1AIwJ5CMr+Fk3nDmg=="],
|
||||
|
||||
"ansi-regex": ["ansi-regex@5.0.1", "https://registry.npmmirror.com/ansi-regex/-/ansi-regex-5.0.1.tgz", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
|
||||
|
||||
"ansi-styles": ["ansi-styles@4.3.0", "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
|
||||
|
||||
"argparse": ["argparse@3.0.2", "https://registry.npmmirror.com/argparse/-/argparse-3.0.2.tgz", {}, "sha512-mFdDM6WqWKraGLsVb+C9CahPnzTXOefAOLq3jYcca2YZ8bEWpr++Tzj+zSaKW9+X9L5uSxcm1AZ3Y6aZJ09OhQ=="],
|
||||
|
||||
"aria-hidden": ["aria-hidden@1.2.6", "https://registry.npmmirror.com/aria-hidden/-/aria-hidden-1.2.6.tgz", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
|
||||
|
||||
"balanced-match": ["balanced-match@1.0.2", "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
|
||||
"balanced-match": ["balanced-match@4.0.4", "https://registry.npmmirror.com/balanced-match/-/balanced-match-4.0.4.tgz", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
|
||||
|
||||
"birpc": ["birpc@2.9.0", "https://registry.npmmirror.com/birpc/-/birpc-2.9.0.tgz", {}, "sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw=="],
|
||||
|
||||
"brace-expansion": ["brace-expansion@2.1.2", "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-2.1.2.tgz", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA=="],
|
||||
"boolbase": ["boolbase@1.0.0", "https://registry.npmmirror.com/boolbase/-/boolbase-1.0.0.tgz", {}, "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww=="],
|
||||
|
||||
"brace-expansion": ["brace-expansion@5.0.12", "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-5.0.12.tgz", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="],
|
||||
|
||||
"braces": ["braces@3.0.3", "https://registry.npmmirror.com/braces/-/braces-3.0.3.tgz", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
|
||||
|
||||
"cacheable": ["cacheable@2.5.0", "https://registry.npmmirror.com/cacheable/-/cacheable-2.5.0.tgz", { "dependencies": { "@cacheable/memory": "^2.2.0", "@cacheable/utils": "^2.5.0", "hookified": "^1.15.0", "keyv": "^5.6.0", "qified": "^0.10.1" } }, "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g=="],
|
||||
|
||||
"camelcase": ["camelcase@5.3.1", "https://registry.npmmirror.com/camelcase/-/camelcase-5.3.1.tgz", {}, "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg=="],
|
||||
|
||||
"class-variance-authority": ["class-variance-authority@0.7.1", "https://registry.npmmirror.com/class-variance-authority/-/class-variance-authority-0.7.1.tgz", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
|
||||
|
||||
"cliui": ["cliui@6.0.0", "https://registry.npmmirror.com/cliui/-/cliui-6.0.0.tgz", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^6.2.0" } }, "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ=="],
|
||||
|
||||
"clsx": ["clsx@2.1.1", "https://registry.npmmirror.com/clsx/-/clsx-2.1.1.tgz", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
|
||||
|
||||
"codemirror-lang-elixir": ["codemirror-lang-elixir@4.0.1", "https://registry.npmmirror.com/codemirror-lang-elixir/-/codemirror-lang-elixir-4.0.1.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "lezer-elixir": "^1.0.0" } }, "sha512-z6W/XB4b7TZrp9EZYBGVq93vQfvKbff+1iM8YZaVErL0dguBAeLmVRlEv1NuDZHOP1qjJ3NwyibkUkNWn7q9VQ=="],
|
||||
|
||||
"codemirror-lang-makefile": ["codemirror-lang-makefile@0.1.1", "https://registry.npmmirror.com/codemirror-lang-makefile/-/codemirror-lang-makefile-0.1.1.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-aCmX0TIj88pQDFeBLmfhiE1ZYmLcWf2c9hk0pscbshCk1x1JO1314q67fbpSaPWm86fl8+wZ2gFuNPlVJ2iFzw=="],
|
||||
|
||||
"color-convert": ["color-convert@2.0.1", "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
|
||||
|
||||
"color-name": ["color-name@1.1.4", "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
|
||||
|
||||
"copy-anything": ["copy-anything@4.0.5", "https://registry.npmmirror.com/copy-anything/-/copy-anything-4.0.5.tgz", { "dependencies": { "is-what": "^5.2.0" } }, "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA=="],
|
||||
|
||||
"crelt": ["crelt@1.0.7", "https://registry.npmmirror.com/crelt/-/crelt-1.0.7.tgz", {}, "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA=="],
|
||||
|
||||
"cross-spawn": ["cross-spawn@7.0.6", "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.6.tgz", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
|
||||
|
||||
"cssesc": ["cssesc@3.0.0", "https://registry.npmmirror.com/cssesc/-/cssesc-3.0.0.tgz", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="],
|
||||
|
||||
"csstype": ["csstype@3.2.3", "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
|
||||
|
||||
"de-indent": ["de-indent@1.0.2", "https://registry.npmmirror.com/de-indent/-/de-indent-1.0.2.tgz", {}, "sha512-e/1zu3xH5MQryN2zdVaF0OrdNLUbvWxzMbi+iNA6Bky7l1RoP8a2fIbRocyHclXt/arDrrR6lL3TqFD9pMQTsg=="],
|
||||
|
||||
"debug": ["debug@4.4.3", "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
|
||||
|
||||
"decamelize": ["decamelize@1.2.0", "https://registry.npmmirror.com/decamelize/-/decamelize-1.2.0.tgz", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="],
|
||||
|
||||
"deep-is": ["deep-is@0.1.4", "https://registry.npmmirror.com/deep-is/-/deep-is-0.1.4.tgz", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="],
|
||||
|
||||
"defu": ["defu@6.1.7", "https://registry.npmmirror.com/defu/-/defu-6.1.7.tgz", {}, "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ=="],
|
||||
|
||||
"detect-libc": ["detect-libc@2.1.2", "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
|
||||
|
||||
"dijkstrajs": ["dijkstrajs@1.0.3", "https://registry.npmmirror.com/dijkstrajs/-/dijkstrajs-1.0.3.tgz", {}, "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA=="],
|
||||
|
||||
"dompurify": ["dompurify@3.4.16", "https://registry.npmmirror.com/dompurify/-/dompurify-3.4.16.tgz", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ=="],
|
||||
|
||||
"emoji-regex": ["emoji-regex@8.0.0", "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-8.0.0.tgz", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
|
||||
|
||||
"enhanced-resolve": ["enhanced-resolve@5.21.6", "https://registry.npmmirror.com/enhanced-resolve/-/enhanced-resolve-5.21.6.tgz", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-aNnGCvbJ/RIyWo1IuhNdVjnNF+EjH9wpzpNHt+ci/m9He9LJvUN8wrCcXjp9cWsGNAuvSpVFTx/vraAFQ8qGjQ=="],
|
||||
|
||||
"entities": ["entities@7.0.1", "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
"entities": ["entities@8.1.0", "https://registry.npmmirror.com/entities/-/entities-8.1.0.tgz", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="],
|
||||
|
||||
"esbuild": ["esbuild@0.25.12", "https://registry.npmmirror.com/esbuild/-/esbuild-0.25.12.tgz", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="],
|
||||
|
||||
"escape-string-regexp": ["escape-string-regexp@4.0.0", "https://registry.npmmirror.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
|
||||
|
||||
"eslint": ["eslint@10.11.0", "https://registry.npmmirror.com/eslint/-/eslint-10.11.0.tgz", { "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.2", "@eslint/config-array": "^0.23.5", "@eslint/config-helpers": "^0.7.0", "@eslint/core": "^1.2.1", "@eslint/plugin-kit": "^0.7.3", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", "ajv": "^6.14.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", "eslint-scope": "^9.1.2", "eslint-visitor-keys": "^5.0.1", "espree": "^11.2.0", "esquery": "^1.7.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "11.1.5 || >11.1.6 <12", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", "minimatch": "^10.2.5", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, "peerDependencies": { "jiti": "*" }, "optionalPeers": ["jiti"], "bin": { "eslint": "bin/eslint.js" } }, "sha512-P7a6UEEqb9G95MYAtqkmsTbVXIYyzIfl6NGOIJk162PaahFxFyeGcrlXYFSiagECg4sEm8IseJdZBKR3rx6MsQ=="],
|
||||
|
||||
"eslint-plugin-vue": ["eslint-plugin-vue@10.11.0", "https://registry.npmmirror.com/eslint-plugin-vue/-/eslint-plugin-vue-10.11.0.tgz", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "natural-compare": "^1.4.0", "nth-check": "^2.1.1", "postcss-selector-parser": "^7.1.4", "semver": "^7.8.5", "xml-name-validator": "^5.0.0" }, "peerDependencies": { "@stylistic/eslint-plugin": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", "@typescript-eslint/parser": "^7.0.0 || ^8.0.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "vue-eslint-parser": "^10.3.0" }, "optionalPeers": ["@stylistic/eslint-plugin", "@typescript-eslint/parser"] }, "sha512-fGt38SsaPCZ2FmA3bX/3vOW2qdsPNx0/9x+7Aab6NMX++PhynMtK4LWC4vzXgfQBCqpUAler18H38GA+NBAd0Q=="],
|
||||
|
||||
"eslint-scope": ["eslint-scope@9.1.2", "https://registry.npmmirror.com/eslint-scope/-/eslint-scope-9.1.2.tgz", { "dependencies": { "@types/esrecurse": "^4.3.1", "@types/estree": "^1.0.8", "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ=="],
|
||||
|
||||
"eslint-visitor-keys": ["eslint-visitor-keys@5.0.1", "https://registry.npmmirror.com/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="],
|
||||
|
||||
"espree": ["espree@11.2.0", "https://registry.npmmirror.com/espree/-/espree-11.2.0.tgz", { "dependencies": { "acorn": "^8.16.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^5.0.1" } }, "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw=="],
|
||||
|
||||
"esquery": ["esquery@1.7.0", "https://registry.npmmirror.com/esquery/-/esquery-1.7.0.tgz", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g=="],
|
||||
|
||||
"esrecurse": ["esrecurse@4.3.0", "https://registry.npmmirror.com/esrecurse/-/esrecurse-4.3.0.tgz", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="],
|
||||
|
||||
"estraverse": ["estraverse@5.3.0", "https://registry.npmmirror.com/estraverse/-/estraverse-5.3.0.tgz", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],
|
||||
|
||||
"estree-walker": ["estree-walker@2.0.2", "https://registry.npmmirror.com/estree-walker/-/estree-walker-2.0.2.tgz", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],
|
||||
|
||||
"esutils": ["esutils@2.0.3", "https://registry.npmmirror.com/esutils/-/esutils-2.0.3.tgz", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="],
|
||||
|
||||
"fast-deep-equal": ["fast-deep-equal@3.1.3", "https://registry.npmmirror.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
|
||||
|
||||
"fast-glob": ["fast-glob@3.3.3", "https://registry.npmmirror.com/fast-glob/-/fast-glob-3.3.3.tgz", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="],
|
||||
|
||||
"fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "https://registry.npmmirror.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="],
|
||||
|
||||
"fast-levenshtein": ["fast-levenshtein@2.0.6", "https://registry.npmmirror.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="],
|
||||
|
||||
"fastq": ["fastq@1.20.3", "https://registry.npmmirror.com/fastq/-/fastq-1.20.3.tgz", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw=="],
|
||||
|
||||
"fdir": ["fdir@6.5.0", "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
|
||||
|
||||
"file-entry-cache": ["file-entry-cache@11.1.5", "https://registry.npmmirror.com/file-entry-cache/-/file-entry-cache-11.1.5.tgz", { "dependencies": { "flat-cache": "^6.1.23" } }, "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q=="],
|
||||
|
||||
"fill-range": ["fill-range@7.1.1", "https://registry.npmmirror.com/fill-range/-/fill-range-7.1.1.tgz", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
|
||||
|
||||
"find-up": ["find-up@5.0.0", "https://registry.npmmirror.com/find-up/-/find-up-5.0.0.tgz", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="],
|
||||
|
||||
"flat-cache": ["flat-cache@6.1.23", "https://registry.npmmirror.com/flat-cache/-/flat-cache-6.1.23.tgz", { "dependencies": { "cacheable": "^2.5.0", "flatted": "^3.4.2", "hookified": "^1.15.0" } }, "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA=="],
|
||||
|
||||
"flatted": ["flatted@3.4.4", "https://registry.npmmirror.com/flatted/-/flatted-3.4.4.tgz", {}, "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q=="],
|
||||
|
||||
"fsevents": ["fsevents@2.3.3", "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"get-caller-file": ["get-caller-file@2.0.5", "https://registry.npmmirror.com/get-caller-file/-/get-caller-file-2.0.5.tgz", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
|
||||
|
||||
"glob-parent": ["glob-parent@6.0.2", "https://registry.npmmirror.com/glob-parent/-/glob-parent-6.0.2.tgz", { "dependencies": { "is-glob": "^4.0.3" } }, "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A=="],
|
||||
|
||||
"graceful-fs": ["graceful-fs@4.2.11", "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.11.tgz", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
|
||||
|
||||
"hashery": ["hashery@1.5.1", "https://registry.npmmirror.com/hashery/-/hashery-1.5.1.tgz", { "dependencies": { "hookified": "^1.15.0" } }, "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ=="],
|
||||
|
||||
"he": ["he@1.2.0", "https://registry.npmmirror.com/he/-/he-1.2.0.tgz", { "bin": { "he": "bin/he" } }, "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw=="],
|
||||
|
||||
"highlight.js": ["highlight.js@11.12.0", "https://registry.npmmirror.com/highlight.js/-/highlight.js-11.12.0.tgz", {}, "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg=="],
|
||||
|
||||
"hookable": ["hookable@5.5.3", "https://registry.npmmirror.com/hookable/-/hookable-5.5.3.tgz", {}, "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ=="],
|
||||
|
||||
"hookified": ["hookified@1.15.1", "https://registry.npmmirror.com/hookified/-/hookified-1.15.1.tgz", {}, "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg=="],
|
||||
|
||||
"ignore": ["ignore@5.3.2", "https://registry.npmmirror.com/ignore/-/ignore-5.3.2.tgz", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
|
||||
|
||||
"imurmurhash": ["imurmurhash@0.1.4", "https://registry.npmmirror.com/imurmurhash/-/imurmurhash-0.1.4.tgz", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="],
|
||||
|
||||
"is-extglob": ["is-extglob@2.1.1", "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
|
||||
|
||||
"is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "https://registry.npmmirror.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
|
||||
|
||||
"is-glob": ["is-glob@4.0.3", "https://registry.npmmirror.com/is-glob/-/is-glob-4.0.3.tgz", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="],
|
||||
|
||||
"is-number": ["is-number@7.0.0", "https://registry.npmmirror.com/is-number/-/is-number-7.0.0.tgz", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="],
|
||||
|
||||
"is-what": ["is-what@5.5.0", "https://registry.npmmirror.com/is-what/-/is-what-5.5.0.tgz", {}, "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw=="],
|
||||
|
||||
"isexe": ["isexe@2.0.0", "https://registry.npmmirror.com/isexe/-/isexe-2.0.0.tgz", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
|
||||
|
||||
"jiti": ["jiti@2.7.0", "https://registry.npmmirror.com/jiti/-/jiti-2.7.0.tgz", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="],
|
||||
|
||||
"json-schema-traverse": ["json-schema-traverse@0.4.1", "https://registry.npmmirror.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
|
||||
|
||||
"json-stable-stringify-without-jsonify": ["json-stable-stringify-without-jsonify@1.0.1", "https://registry.npmmirror.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", {}, "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw=="],
|
||||
|
||||
"keyv": ["keyv@5.6.0", "https://registry.npmmirror.com/keyv/-/keyv-5.6.0.tgz", { "dependencies": { "@keyv/serialize": "^1.1.1" } }, "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw=="],
|
||||
|
||||
"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=="],
|
||||
@@ -359,20 +724,50 @@
|
||||
|
||||
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "https://registry.npmmirror.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
|
||||
|
||||
"linkify-it": ["linkify-it@6.1.0", "https://registry.npmmirror.com/linkify-it/-/linkify-it-6.1.0.tgz", { "dependencies": { "uc.micro": "^3.0.0" } }, "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw=="],
|
||||
|
||||
"locate-path": ["locate-path@6.0.0", "https://registry.npmmirror.com/locate-path/-/locate-path-6.0.0.tgz", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="],
|
||||
|
||||
"magic-string": ["magic-string@0.30.21", "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
|
||||
"minimatch": ["minimatch@9.0.9", "https://registry.npmmirror.com/minimatch/-/minimatch-9.0.9.tgz", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="],
|
||||
"markdown-it": ["markdown-it@15.0.2", "https://registry.npmmirror.com/markdown-it/-/markdown-it-15.0.2.tgz", { "dependencies": { "argparse": "^3.0.0", "entities": "^8.0.0", "linkify-it": "^6.0.0", "mdurl": "^2.1.0", "punycode.js": "^2.3.1", "uc.micro": "^3.0.0" }, "bin": { "markdown-it": "bin/markdown-it.mjs" } }, "sha512-q4IGxMv56jCqT4OCRCADBoDP3LO4MhmTXjFbphHPXs4g3j9Xg5RDnxqN8IF/3vIWEU+VCnUq+7JUg/cfy2E6Qw=="],
|
||||
|
||||
"mdurl": ["mdurl@2.1.0", "https://registry.npmmirror.com/mdurl/-/mdurl-2.1.0.tgz", {}, "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg=="],
|
||||
|
||||
"merge2": ["merge2@1.4.1", "https://registry.npmmirror.com/merge2/-/merge2-1.4.1.tgz", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="],
|
||||
|
||||
"micromatch": ["micromatch@4.0.8", "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.8.tgz", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
|
||||
|
||||
"minimatch": ["minimatch@10.2.6", "https://registry.npmmirror.com/minimatch/-/minimatch-10.2.6.tgz", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="],
|
||||
|
||||
"mitt": ["mitt@3.0.1", "https://registry.npmmirror.com/mitt/-/mitt-3.0.1.tgz", {}, "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw=="],
|
||||
|
||||
"ms": ["ms@2.1.3", "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"muggle-string": ["muggle-string@0.4.1", "https://registry.npmmirror.com/muggle-string/-/muggle-string-0.4.1.tgz", {}, "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ=="],
|
||||
|
||||
"nanoid": ["nanoid@3.3.16", "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.16.tgz", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q=="],
|
||||
|
||||
"natural-compare": ["natural-compare@1.4.0", "https://registry.npmmirror.com/natural-compare/-/natural-compare-1.4.0.tgz", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="],
|
||||
|
||||
"nth-check": ["nth-check@2.1.1", "https://registry.npmmirror.com/nth-check/-/nth-check-2.1.1.tgz", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="],
|
||||
|
||||
"ohash": ["ohash@2.0.11", "https://registry.npmmirror.com/ohash/-/ohash-2.0.11.tgz", {}, "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ=="],
|
||||
|
||||
"optionator": ["optionator@0.9.4", "https://registry.npmmirror.com/optionator/-/optionator-0.9.4.tgz", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="],
|
||||
|
||||
"p-limit": ["p-limit@3.1.0", "https://registry.npmmirror.com/p-limit/-/p-limit-3.1.0.tgz", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="],
|
||||
|
||||
"p-locate": ["p-locate@5.0.0", "https://registry.npmmirror.com/p-locate/-/p-locate-5.0.0.tgz", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="],
|
||||
|
||||
"p-try": ["p-try@2.2.0", "https://registry.npmmirror.com/p-try/-/p-try-2.2.0.tgz", {}, "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ=="],
|
||||
|
||||
"path-browserify": ["path-browserify@1.0.1", "https://registry.npmmirror.com/path-browserify/-/path-browserify-1.0.1.tgz", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="],
|
||||
|
||||
"path-exists": ["path-exists@4.0.0", "https://registry.npmmirror.com/path-exists/-/path-exists-4.0.0.tgz", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
|
||||
|
||||
"path-key": ["path-key@3.1.1", "https://registry.npmmirror.com/path-key/-/path-key-3.1.1.tgz", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
|
||||
|
||||
"perfect-debounce": ["perfect-debounce@1.0.0", "https://registry.npmmirror.com/perfect-debounce/-/perfect-debounce-1.0.0.tgz", {}, "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA=="],
|
||||
|
||||
"picocolors": ["picocolors@1.1.1", "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
|
||||
@@ -381,18 +776,58 @@
|
||||
|
||||
"pinia": ["pinia@3.0.4", "https://registry.npmmirror.com/pinia/-/pinia-3.0.4.tgz", { "dependencies": { "@vue/devtools-api": "^7.7.7" }, "peerDependencies": { "typescript": ">=4.5.0", "vue": "^3.5.11" }, "optionalPeers": ["typescript"] }, "sha512-l7pqLUFTI/+ESXn6k3nu30ZIzW5E2WZF/LaHJEpoq6ElcLD+wduZoB2kBN19du6K/4FDpPMazY2wJr+IndBtQw=="],
|
||||
|
||||
"pinyin-pro": ["pinyin-pro@3.29.4", "https://registry.npmmirror.com/pinyin-pro/-/pinyin-pro-3.29.4.tgz", {}, "sha512-SPXpDT2cHEy+d26V1RXYMlVzXN42hotFAak1fzyWPi4o2dKXb61UqD4pzxDJHwk6gbv8vQ6EfErd+hYX0Qhzug=="],
|
||||
|
||||
"pngjs": ["pngjs@5.0.0", "https://registry.npmmirror.com/pngjs/-/pngjs-5.0.0.tgz", {}, "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw=="],
|
||||
|
||||
"postcss": ["postcss@8.5.19", "https://registry.npmmirror.com/postcss/-/postcss-8.5.19.tgz", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-Mz8SaolMd8nB+G13WkORcxQKHZ/NE4xXevtkJHVuG+guo9/wYKlIMTKAqGdEmYOXR2ijPjTYNHssizdaVSUNdQ=="],
|
||||
|
||||
"reka-ui": ["reka-ui@2.10.1", "https://registry.npmmirror.com/reka-ui/-/reka-ui-2.10.1.tgz", { "dependencies": { "@floating-ui/dom": "^1.6.13", "@floating-ui/vue": "^1.1.6", "@internationalized/date": "^3.5.0", "@internationalized/number": "^3.5.0", "@tanstack/vue-virtual": "^3.12.0", "@vueuse/core": "^14.1.0", "@vueuse/shared": "^14.1.0", "aria-hidden": "^1.2.4", "defu": "^6.1.5", "ohash": "^2.0.11" }, "peerDependencies": { "vue": ">= 3.4.0" } }, "sha512-drcOQ4rQtDYAcGCsyQBqQg8QQ+H3B+zDaMJU0h8KPEPMa7g9BHu3zcOi4OB39XJSWizceFoNO0Z9tctSGLOXqg=="],
|
||||
"postcss-selector-parser": ["postcss-selector-parser@7.1.6", "https://registry.npmmirror.com/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw=="],
|
||||
|
||||
"prelude-ls": ["prelude-ls@1.2.1", "https://registry.npmmirror.com/prelude-ls/-/prelude-ls-1.2.1.tgz", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="],
|
||||
|
||||
"punycode": ["punycode@2.3.1", "https://registry.npmmirror.com/punycode/-/punycode-2.3.1.tgz", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
|
||||
|
||||
"punycode.js": ["punycode.js@2.3.1", "https://registry.npmmirror.com/punycode.js/-/punycode.js-2.3.1.tgz", {}, "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA=="],
|
||||
|
||||
"qified": ["qified@0.10.1", "https://registry.npmmirror.com/qified/-/qified-0.10.1.tgz", { "dependencies": { "hookified": "^2.1.1" } }, "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA=="],
|
||||
|
||||
"qrcode": ["qrcode@1.5.4", "https://registry.npmmirror.com/qrcode/-/qrcode-1.5.4.tgz", { "dependencies": { "dijkstrajs": "^1.0.1", "pngjs": "^5.0.0", "yargs": "^15.3.1" }, "bin": { "qrcode": "bin/qrcode" } }, "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg=="],
|
||||
|
||||
"queue-microtask": ["queue-microtask@1.2.3", "https://registry.npmmirror.com/queue-microtask/-/queue-microtask-1.2.3.tgz", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
|
||||
|
||||
"reka-ui": ["reka-ui@2.10.5", "https://registry.npmmirror.com/reka-ui/-/reka-ui-2.10.5.tgz", { "dependencies": { "@floating-ui/dom": "^1.6.13", "@floating-ui/vue": "^1.1.6", "@internationalized/date": "^3.5.0", "@internationalized/number": "^3.5.0", "@tanstack/vue-virtual": "^3.12.0", "@vueuse/core": "^14.1.0", "@vueuse/shared": "^14.1.0", "aria-hidden": "^1.2.4", "defu": "^6.1.5", "ohash": "^2.0.11" }, "peerDependencies": { "vue": ">= 3.4.0" } }, "sha512-/8o0y9BThE0hcHKFg+3770tWcJh3qKdOEFxLOPb9HIajXeFoH/J530cZH62jUJunbqwBgpSBL9v7nB8LJ5pDXA=="],
|
||||
|
||||
"require-directory": ["require-directory@2.1.1", "https://registry.npmmirror.com/require-directory/-/require-directory-2.1.1.tgz", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
|
||||
|
||||
"require-main-filename": ["require-main-filename@2.0.0", "https://registry.npmmirror.com/require-main-filename/-/require-main-filename-2.0.0.tgz", {}, "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg=="],
|
||||
|
||||
"reusify": ["reusify@1.1.0", "https://registry.npmmirror.com/reusify/-/reusify-1.1.0.tgz", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="],
|
||||
|
||||
"rfdc": ["rfdc@1.4.1", "https://registry.npmmirror.com/rfdc/-/rfdc-1.4.1.tgz", {}, "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA=="],
|
||||
|
||||
"rollup": ["rollup@4.62.2", "https://registry.npmmirror.com/rollup/-/rollup-4.62.2.tgz", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.62.2", "@rollup/rollup-android-arm64": "4.62.2", "@rollup/rollup-darwin-arm64": "4.62.2", "@rollup/rollup-darwin-x64": "4.62.2", "@rollup/rollup-freebsd-arm64": "4.62.2", "@rollup/rollup-freebsd-x64": "4.62.2", "@rollup/rollup-linux-arm-gnueabihf": "4.62.2", "@rollup/rollup-linux-arm-musleabihf": "4.62.2", "@rollup/rollup-linux-arm64-gnu": "4.62.2", "@rollup/rollup-linux-arm64-musl": "4.62.2", "@rollup/rollup-linux-loong64-gnu": "4.62.2", "@rollup/rollup-linux-loong64-musl": "4.62.2", "@rollup/rollup-linux-ppc64-gnu": "4.62.2", "@rollup/rollup-linux-ppc64-musl": "4.62.2", "@rollup/rollup-linux-riscv64-gnu": "4.62.2", "@rollup/rollup-linux-riscv64-musl": "4.62.2", "@rollup/rollup-linux-s390x-gnu": "4.62.2", "@rollup/rollup-linux-x64-gnu": "4.62.2", "@rollup/rollup-linux-x64-musl": "4.62.2", "@rollup/rollup-openbsd-x64": "4.62.2", "@rollup/rollup-openharmony-arm64": "4.62.2", "@rollup/rollup-win32-arm64-msvc": "4.62.2", "@rollup/rollup-win32-ia32-msvc": "4.62.2", "@rollup/rollup-win32-x64-gnu": "4.62.2", "@rollup/rollup-win32-x64-msvc": "4.62.2", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA=="],
|
||||
|
||||
"run-parallel": ["run-parallel@1.2.0", "https://registry.npmmirror.com/run-parallel/-/run-parallel-1.2.0.tgz", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="],
|
||||
|
||||
"semver": ["semver@7.8.5", "https://registry.npmmirror.com/semver/-/semver-7.8.5.tgz", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
|
||||
|
||||
"set-blocking": ["set-blocking@2.0.0", "https://registry.npmmirror.com/set-blocking/-/set-blocking-2.0.0.tgz", {}, "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="],
|
||||
|
||||
"shebang-command": ["shebang-command@2.0.0", "https://registry.npmmirror.com/shebang-command/-/shebang-command-2.0.0.tgz", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
|
||||
|
||||
"shebang-regex": ["shebang-regex@3.0.0", "https://registry.npmmirror.com/shebang-regex/-/shebang-regex-3.0.0.tgz", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
||||
|
||||
"source-map-js": ["source-map-js@1.2.1", "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
|
||||
"speakingurl": ["speakingurl@14.0.1", "https://registry.npmmirror.com/speakingurl/-/speakingurl-14.0.1.tgz", {}, "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ=="],
|
||||
|
||||
"string-width": ["string-width@4.2.3", "https://registry.npmmirror.com/string-width/-/string-width-4.2.3.tgz", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
|
||||
|
||||
"strip-ansi": ["strip-ansi@6.0.1", "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
|
||||
|
||||
"style-mod": ["style-mod@4.1.4", "https://registry.npmmirror.com/style-mod/-/style-mod-4.1.4.tgz", {}, "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw=="],
|
||||
|
||||
"superjson": ["superjson@2.2.6", "https://registry.npmmirror.com/superjson/-/superjson-2.2.6.tgz", { "dependencies": { "copy-anything": "^4" } }, "sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA=="],
|
||||
|
||||
"tailwind-merge": ["tailwind-merge@3.6.0", "https://registry.npmmirror.com/tailwind-merge/-/tailwind-merge-3.6.0.tgz", {}, "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w=="],
|
||||
@@ -403,14 +838,28 @@
|
||||
|
||||
"tinyglobby": ["tinyglobby@0.2.17", "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
|
||||
|
||||
"to-regex-range": ["to-regex-range@5.0.1", "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
|
||||
|
||||
"ts-api-utils": ["ts-api-utils@2.5.0", "https://registry.npmmirror.com/ts-api-utils/-/ts-api-utils-2.5.0.tgz", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA=="],
|
||||
|
||||
"tslib": ["tslib@2.8.1", "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
|
||||
|
||||
"tw-animate-css": ["tw-animate-css@1.4.0", "https://registry.npmmirror.com/tw-animate-css/-/tw-animate-css-1.4.0.tgz", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="],
|
||||
|
||||
"type-check": ["type-check@0.4.0", "https://registry.npmmirror.com/type-check/-/type-check-0.4.0.tgz", { "dependencies": { "prelude-ls": "^1.2.1" } }, "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="],
|
||||
|
||||
"typescript": ["typescript@5.6.3", "https://registry.npmmirror.com/typescript/-/typescript-5.6.3.tgz", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw=="],
|
||||
|
||||
"typescript-eslint": ["typescript-eslint@8.70.0", "https://registry.npmmirror.com/typescript-eslint/-/typescript-eslint-8.70.0.tgz", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.70.0", "@typescript-eslint/parser": "8.70.0", "@typescript-eslint/typescript-estree": "8.70.0", "@typescript-eslint/utils": "8.70.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-P/W5cz70/cQAuKfY3xwQMWWTV7BvJ0mAQmi+9mBcsVPaBUpd6Ohpa+fECv9rBFrQcig86jAiNBFNWUqnTjr4pw=="],
|
||||
|
||||
"uc.micro": ["uc.micro@3.0.0", "https://registry.npmmirror.com/uc.micro/-/uc.micro-3.0.0.tgz", {}, "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw=="],
|
||||
|
||||
"undici-types": ["undici-types@8.3.0", "https://registry.npmmirror.com/undici-types/-/undici-types-8.3.0.tgz", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
|
||||
|
||||
"uri-js": ["uri-js@4.4.1", "https://registry.npmmirror.com/uri-js/-/uri-js-4.4.1.tgz", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
|
||||
|
||||
"util-deprecate": ["util-deprecate@1.0.2", "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
|
||||
|
||||
"vite": ["vite@6.4.3", "https://registry.npmmirror.com/vite/-/vite-6.4.3.tgz", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A=="],
|
||||
|
||||
"vscode-uri": ["vscode-uri@3.1.0", "https://registry.npmmirror.com/vscode-uri/-/vscode-uri-3.1.0.tgz", {}, "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ=="],
|
||||
@@ -421,10 +870,34 @@
|
||||
|
||||
"vue-draggable-plus": ["vue-draggable-plus@0.6.1", "https://registry.npmmirror.com/vue-draggable-plus/-/vue-draggable-plus-0.6.1.tgz", { "dependencies": { "@types/sortablejs": "^1.15.8" }, "peerDependencies": { "@vue/composition-api": "*" }, "optionalPeers": ["@vue/composition-api"] }, "sha512-FbtQ/fuoixiOfTZzG3yoPl4JAo9HJXRHmBQZFB9x2NYCh6pq0TomHf7g5MUmpaDYv+LU2n6BPq2YN9sBO+FbIg=="],
|
||||
|
||||
"vue-eslint-parser": ["vue-eslint-parser@10.4.1", "https://registry.npmmirror.com/vue-eslint-parser/-/vue-eslint-parser-10.4.1.tgz", { "dependencies": { "debug": "^4.4.0", "eslint-scope": "^8.2.0 || ^9.0.0", "eslint-visitor-keys": "^4.2.0 || ^5.0.0", "espree": "^10.3.0 || ^11.0.0", "esquery": "^1.6.0", "semver": "^7.6.3" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0" } }, "sha512-Gk6gRDj0n/fkRa3C3l0bBheoBckUq/Rs0F/TvMWIS6nzzx67amAViMe9CkNgsP2tXyQONvGiHQESHwFtZ3aYDA=="],
|
||||
|
||||
"vue-sonner": ["vue-sonner@2.0.9", "https://registry.npmmirror.com/vue-sonner/-/vue-sonner-2.0.9.tgz", { "peerDependencies": { "@nuxt/kit": "^4.0.3", "@nuxt/schema": "^4.0.3", "nuxt": "^4.0.3" }, "optionalPeers": ["@nuxt/kit", "@nuxt/schema", "nuxt"] }, "sha512-i6BokNlNDL93fpzNxN/LZSn6D6MzlO+i3qXt6iVZne3x1k7R46d5HlFB4P8tYydhgqOrRbIZEsnRd3kG7qGXyw=="],
|
||||
|
||||
"vue-tsc": ["vue-tsc@2.2.12", "https://registry.npmmirror.com/vue-tsc/-/vue-tsc-2.2.12.tgz", { "dependencies": { "@volar/typescript": "2.4.15", "@vue/language-core": "2.2.12" }, "peerDependencies": { "typescript": ">=5.0.0" }, "bin": { "vue-tsc": "./bin/vue-tsc.js" } }, "sha512-P7OP77b2h/Pmk+lZdJ0YWs+5tJ6J2+uOQPo7tlBnY44QqQSPYvS0qVT4wqDJgwrZaLe47etJLLQRFia71GYITw=="],
|
||||
|
||||
"w3c-keyname": ["w3c-keyname@2.2.8", "https://registry.npmmirror.com/w3c-keyname/-/w3c-keyname-2.2.8.tgz", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="],
|
||||
|
||||
"which": ["which@2.0.2", "https://registry.npmmirror.com/which/-/which-2.0.2.tgz", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||
|
||||
"which-module": ["which-module@2.0.1", "https://registry.npmmirror.com/which-module/-/which-module-2.0.1.tgz", {}, "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ=="],
|
||||
|
||||
"word-wrap": ["word-wrap@1.2.5", "https://registry.npmmirror.com/word-wrap/-/word-wrap-1.2.5.tgz", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],
|
||||
|
||||
"wrap-ansi": ["wrap-ansi@6.2.0", "https://registry.npmmirror.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA=="],
|
||||
|
||||
"xml-name-validator": ["xml-name-validator@5.0.0", "https://registry.npmmirror.com/xml-name-validator/-/xml-name-validator-5.0.0.tgz", {}, "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg=="],
|
||||
|
||||
"y18n": ["y18n@4.0.3", "https://registry.npmmirror.com/y18n/-/y18n-4.0.3.tgz", {}, "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ=="],
|
||||
|
||||
"yargs": ["yargs@15.4.1", "https://registry.npmmirror.com/yargs/-/yargs-15.4.1.tgz", { "dependencies": { "cliui": "^6.0.0", "decamelize": "^1.2.0", "find-up": "^4.1.0", "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", "string-width": "^4.2.0", "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^18.1.2" } }, "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A=="],
|
||||
|
||||
"yargs-parser": ["yargs-parser@18.1.3", "https://registry.npmmirror.com/yargs-parser/-/yargs-parser-18.1.3.tgz", { "dependencies": { "camelcase": "^5.0.0", "decamelize": "^1.2.0" } }, "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ=="],
|
||||
|
||||
"yocto-queue": ["yocto-queue@0.1.0", "https://registry.npmmirror.com/yocto-queue/-/yocto-queue-0.1.0.tgz", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],
|
||||
|
||||
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "https://registry.npmmirror.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
|
||||
|
||||
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.2", "https://registry.npmmirror.com/@emnapi/core/-/core-1.11.2.tgz", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" }, "bundled": true }, "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA=="],
|
||||
|
||||
"@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.2", "https://registry.npmmirror.com/@emnapi/runtime/-/runtime-1.11.2.tgz", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA=="],
|
||||
@@ -437,10 +910,28 @@
|
||||
|
||||
"@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
|
||||
|
||||
"reka-ui/@vueuse/core": ["@vueuse/core@14.3.0", "https://registry.npmmirror.com/@vueuse/core/-/core-14.3.0.tgz", { "dependencies": { "@types/web-bluetooth": "^0.0.21", "@vueuse/metadata": "14.3.0", "@vueuse/shared": "14.3.0" }, "peerDependencies": { "vue": "^3.5.0" } }, "sha512-aHfz47g0ZhMtTVHmIzMVpJy8ePhhOy68GY5bv110+5DVtZ+W7BsOx+m61UNQqfrWyPztIHIanWa3E2tib3NFIw=="],
|
||||
"@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.9", "https://registry.npmmirror.com/ignore/-/ignore-7.0.9.tgz", {}, "sha512-brTTsvFRt5C1gGHtPst/281UjPD5t9fBqbgoMPlVWy11ZLTPfu7HxK4ZYqO9H7o/yC9rSTCI85EaQ4OoY12qYw=="],
|
||||
|
||||
"reka-ui/@vueuse/shared": ["@vueuse/shared@14.3.0", "https://registry.npmmirror.com/@vueuse/shared/-/shared-14.3.0.tgz", { "peerDependencies": { "vue": "^3.5.0" } }, "sha512-bZpge9eSXwa4ToSiqJ7j6KRwhAsneMFoSz3LMWKQDkqimm3D/tbFlrklrs/IOqC8tEcYmXQZJ6N0UrjhBirVCg=="],
|
||||
"@vue/compiler-core/entities": ["entities@7.0.1", "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
|
||||
"reka-ui/@vueuse/core/@vueuse/metadata": ["@vueuse/metadata@14.3.0", "https://registry.npmmirror.com/@vueuse/metadata/-/metadata-14.3.0.tgz", {}, "sha512-BwxmbAzwAVF50+MW57GXOUEV61nFBGnlBvrTqj49PqWJu3uw7hdu72ztXeZ33RdZtDY6kO+bfCAE1PCn88Tktw=="],
|
||||
"@vue/language-core/minimatch": ["minimatch@9.0.9", "https://registry.npmmirror.com/minimatch/-/minimatch-9.0.9.tgz", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="],
|
||||
|
||||
"fast-glob/glob-parent": ["glob-parent@5.1.2", "https://registry.npmmirror.com/glob-parent/-/glob-parent-5.1.2.tgz", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
|
||||
"micromatch/picomatch": ["picomatch@2.3.2", "https://registry.npmmirror.com/picomatch/-/picomatch-2.3.2.tgz", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
|
||||
|
||||
"qified/hookified": ["hookified@2.2.0", "https://registry.npmmirror.com/hookified/-/hookified-2.2.0.tgz", {}, "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA=="],
|
||||
|
||||
"yargs/find-up": ["find-up@4.1.0", "https://registry.npmmirror.com/find-up/-/find-up-4.1.0.tgz", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="],
|
||||
|
||||
"@vue/language-core/minimatch/brace-expansion": ["brace-expansion@2.1.2", "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-2.1.2.tgz", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA=="],
|
||||
|
||||
"yargs/find-up/locate-path": ["locate-path@5.0.0", "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],
|
||||
|
||||
"@vue/language-core/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
|
||||
|
||||
"yargs/find-up/locate-path/p-locate": ["p-locate@4.1.0", "https://registry.npmmirror.com/p-locate/-/p-locate-4.1.0.tgz", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="],
|
||||
|
||||
"yargs/find-up/locate-path/p-locate/p-limit": ["p-limit@2.3.0", "https://registry.npmmirror.com/p-limit/-/p-limit-2.3.0.tgz", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="],
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,349 @@
|
||||
# 对比工具模块规划(Diff Module Plan)
|
||||
|
||||
> 状态:**P4 已落地**(选项卡 / 左右双树 / 下钻 / 快捷键 / 中间列快速替换)
|
||||
> 本轮决策(2026-10-13,用户已拍板):**移除 devtools 的文本对比工具**(并入本模块)· **目录对比暂不做写回**(只读浏览)· **需要拖入支持**
|
||||
> P4 决策(用户提出,2026-10-13):**选项卡式会话**(标题 `左 ↔ 右`)· **目录对比改为左右两棵结构树**(两侧路径可自由输入 + 图标按钮)· **点树里的文件新开文件选项卡** · **全局快捷键 Alt+C** · **中间列差异 + 快速替换**(参考 Beyond Compare)
|
||||
> 定位:Thing 工具集的第 14 个模块,`id = diff`,`category = 'tool'`
|
||||
> 作者:砚 | 日期:2026-10-13
|
||||
> 关联文档:`AI_DEV_GUIDE.md`(模块注册 / IPC / 独立窗口范式)、`UI_DESIGN_SYSTEM.md`(页面框架 / 组件规范)、`EDITOR_MODULE_PLAN.md`(CM6 装配 / 编码探测 / 独立窗口 / 任务栏身份范式)、`TERMINAL_MODULE_PLAN.md`(拖放补注入范式)
|
||||
|
||||
> 阅读顺序:§9 开工清单(执行入口)→ §0 结论 → §4 技术选型 → §6 文件清单 → §8 分期。
|
||||
|
||||
---
|
||||
|
||||
## 0. 结论先行
|
||||
|
||||
六个关键判断。
|
||||
|
||||
1. **可行,且仓库里已有大半基础设施。** 编辑器模块已经把「CM6 + 主题系统 + 多语言高亮」「带编码探测的文件读取」「递归遍历(`walkdir` 已在依赖树)」「独立窗口 + 任务栏身份 + 拖放补注入」四块能力做完了。本模块的主要工作是**组装**,而不是造轮子。
|
||||
|
||||
2. **做成独立模块 + 独立窗口,不塞进编辑器。** 编辑器模块的中心对象是「一篇文档的生命周期」(标签、自动保存、光标、会话恢复);对比工具是「两个只读视图 + 一棵目录树」,没有自动保存、没有文档标签。混进去会让本已很大的 `EditorWindow.vue`(1500 行)与 `editorStore.ts` 继续膨胀,也会让 `editor-window-*` 这个 capability 的语义变模糊。模块体系是现成的(`moduleConfig` + 一行注册 + 图标表 + 搜索索引 + 启用开关),独立成模块成本很低。
|
||||
|
||||
3. **渲染层用 `@codemirror/merge`(CM6 官方 MergeView),计算层留在 Rust。** MergeView 天然给出并排 / 统一视图、块级高亮、chunk 跳转、接受/拒绝,并且**直接吃项目现有的 CM6 主题**(编辑器那九套配色自动跟随,无需为对比工具再维护一套配色)。Rust 只负责目录级扫描与分类:`walkdir` 递归 + size/mtime 快速路径 + 按需内容比对。这样目录对比的每一项都能「点一下」下钻到 MergeView 的文件级对比 —— 正是 Beyond Compare 的交互主线。
|
||||
|
||||
4. **三层能力按「易 → 难」分期,P1 只做文本对比。** 文本对比(粘贴两段)→ 文件对比(两个路径,含编码探测)→ 文件夹对比(递归树 + 三态分类 + 下钻)。P1 的价值不只是功能,更是**验证 `@codemirror/merge` 与项目现有 CM6 版本的兼容性**(见 §10),风险最低、最快闭环。
|
||||
|
||||
5. **目录对比这一期只读,不做写回。** 「浏览差异」与「同步目录」是两个量级的工程:后者要处理冲突策略、部分失败回滚、覆盖确认、二进制文件、只读属性与长路径。这一期给出只读的三态树 + 下钻即可,写回(复制 / 镜像 / 双向同步)留待单独评估。
|
||||
|
||||
6. **拖入支持从 P2 起生效。** 文本对比没有文件路径,用不上拖放;P2 起需要把「拖文件进窗口」纳入。既有实现是编辑器专用的 `editor/drag_drop.rs`(不通用:它按 editor 窗口的 label 前缀做注入),因此本模块**另建一份同构实现**或把它**泛化成按 label 前缀参数化**(见 §7.1,倾向后者)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 定位与边界
|
||||
|
||||
| 维度 | 说明 |
|
||||
|---|---|
|
||||
| 一句话 | 一个 Beyond Compare 式的对比工具:文本 / 文件 / 文件夹三层,左右双栏 |
|
||||
| 中心对象 | **两个被比较的目标**(一段文本、一个文件、一棵目录树),而不是某篇文档 |
|
||||
| 首要入口 | 模块页「新建对比」+ 独立窗口(可拖入文件/文件夹) |
|
||||
| 与编辑器模块的关系 | 复用它的 CM6 装配、主题与语言包、Rust 文件读取;但**不共享窗口、不共享 store** |
|
||||
| 明确不做 | 不做三路合并(3-way merge)· 不做 Git 集成 · 本期不做目录写回/同步 · 不做二进制语义对比(只报「二进制不同」) |
|
||||
|
||||
---
|
||||
|
||||
## 2. 需求解构
|
||||
|
||||
| 用户原话 | 解构为 | 落点 |
|
||||
|---|---|---|
|
||||
| 「能够进行文本,文件,文件夹对比」 | 三种对比目标,同一条渲染管线 | §3.1 / §3.2 / §3.3 |
|
||||
| 「左右两个窗口对比,参考 beyond compare」 | 并排双栏 + 块级高亮 + 差异导航 + 三态目录树 | §3.1 / §3.3 |
|
||||
| 「调整…对比工具…做到编辑器里面还是单独做模块」 | 架构决策 → 独立模块 | §5 |
|
||||
| 「去除 devtools 里的 diff」 | 删除 `DiffTools.vue` 及其注册项,能力并入本模块 | §8 开工清单 |
|
||||
| 「目录对比暂时不用写回」 | P3 只读三态树,不做复制/同步 | §3.3 / §9 |
|
||||
| 「需要拖入支持」 | 拖文件/文件夹进窗口即作为某一侧目标 | §7.1 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 能力规格
|
||||
|
||||
### 3.1 文本对比(P1)
|
||||
|
||||
- 左右两个**可编辑**的 CM6 视图,构成一个 MergeView;任一侧输入即重算差异。
|
||||
- 差异呈现:行内块级高亮(左边「被删/被改」、右边「新增/被改」),行号槽标注变化。
|
||||
- 差异导航:上一个 / 下一个差异(工具栏按钮;到两端即停,不做循环跳转)。
|
||||
- 顶部工具栏:粘贴到某一侧(从剪贴板)、交换左右、差异导航、清空两侧。并排是**唯一**的视图形态(统一视图需要另一套渲染路径,留待后续评估)。
|
||||
- 状态栏:`差异 N 处 · +A 行 · -R 行 · 左侧 X 行 / 右侧 Y 行`。
|
||||
- 大文本保护:**不做「超过 N 行就不算」的硬阈值**,改用 MergeView 内置的 `diffConfig.scanLimit`(默认 500)—— 它在差异过大时放弃精确比对、退回快速(不精确)算法,从而避开二次方耗时,同时**仍然给出结果**(比「停算并提示」更可用)。已知代价:极端输入下差异块可能不够精确(`Chunk.precise` 为 false)。
|
||||
|
||||
### 3.2 文件对比(P2)
|
||||
|
||||
- 两个路径(任意磁盘文件,不限于笔记库),来源:文件对话框 / 拖入 / 命令行 / 编辑器「与…对比」。
|
||||
- **编码感知**:复用 `editor::files::read_file`(BOM → 严格 UTF-8 → chardetng 探测 → GB18030 兜底),状态栏显示两侧各自探测到的编码,不一致时给出提示(「左边 GBK / 右边 UTF-8」这类差异往往就是用户要找的问题)。
|
||||
- 二进制文件:不渲染 diff,只报「二进制文件,大小 X vs Y,内容不同/相同」。
|
||||
- 只读打开 + 可切换为可编辑;保存回写**仅作用于被显式编辑的一侧**(这一条属于 P2,不等同于 P3 的目录同步)。
|
||||
- 拖入:拖文件到左半区 = 设为左侧目标,右半区 = 右侧目标。
|
||||
|
||||
### 3.3 文件夹对比(P3,只读)
|
||||
|
||||
- 递归遍历两侧,按**相对路径**对齐(根目录不同名也要对齐)。
|
||||
- 每个条目三态 + 细分:
|
||||
| 状态 | 判据 |
|
||||
|---|---|
|
||||
| 仅左侧有 | 右侧无同相对路径 |
|
||||
| 仅右侧有 | 左侧无同相对路径 |
|
||||
| 两侧都有 · 相同 | size 相同 → mtime 相同 →(必要时)内容一致 |
|
||||
| 两侧都有 · 不同 | size 不同,或 size 相同但内容不同 |
|
||||
| 目标类型不同 | 一侧是文件、另一侧是同名目录 |
|
||||
- 树形展开 + 过滤(只看有差异 / 只看某一侧有)+ 「展开到下一个差异」。
|
||||
- 目录级汇总:`N 项不同 · M 项仅左 · K 项仅右`,可折叠跳过相同项。
|
||||
- 点击「不同」的文件行 → 在**同一个窗口**下钻到 §3.2 的文件对比视图(带返回上一级)。
|
||||
- 忽略规则(可选,P3 后期):`node_modules` / `.git` 等常见目录的默认忽略清单。
|
||||
|
||||
### 3.4 不做(本期明确划界)
|
||||
|
||||
- 目录写回 / 镜像 / 双向同步(用户已拍板暂不做)。
|
||||
- 三路合并与冲突解决。
|
||||
- 二进制内容级对比(只判「相同/不同」与大小)。
|
||||
- 大文件(> 阈值)的完整 diff —— 降级为只报状态,不做行级对齐。
|
||||
|
||||
---
|
||||
|
||||
## 4. 技术选型
|
||||
|
||||
### 4.1 渲染层:`@codemirror/merge`(已安装 6.12.2)
|
||||
|
||||
| 方案 | 结论 | 理由 |
|
||||
|---|---|---|
|
||||
| **`@codemirror/merge`** | **采用** | CM6 官方 MergeView:并排/统一、块级高亮、chunk 导航、接受/拒绝、行号 gutter 全部现成;与已装的 `@codemirror/state 6.7.6` / `view 6.43.x` 同源;主题直接复用 `editor/editor/themes.ts` 的九套配色 |
|
||||
| Rust `similar` crate | 暂不引入 | 计算快、可单测,但并排对齐 UI 要自己写;P1/P2 用不到,等 P3 目录级需要「批量算文件差异摘要」时再评估 |
|
||||
| 手写 LCS(原 devtools 实现) | 弃用 | O(n·m) DP 会卡死 UI,且没有对齐/高亮,已随 `DiffTools.vue` 一并移除 |
|
||||
|
||||
### 4.2 计算层:Rust 只做目录级
|
||||
|
||||
- `walkdir` 已在依赖树([Cargo.toml](../src-tauri/Cargo.toml)),递归扫描零新增成本。
|
||||
- 文件内容比对优先用 **size → mtime → 内容** 三级快速路径,避免几万文件目录下全量读盘。
|
||||
- 需要内容级判定时可选 `similar` 或 SHA-256(`sha2` 已在依赖树)。
|
||||
|
||||
### 4.3 主题:复用编辑器配色,不新建一套
|
||||
|
||||
对比窗口必须与编辑器窗口「同深同浅、同配色」,否则用户从编辑器跳到对比会感到割裂。做法:直接调用 `resolveEditorTheme` / `editorTypography` / `editorBackground`,并沿用编辑器窗口那套「跟随主应用主题 / 配色方案」的深浅推导(`EditorWindow.windowIsDark` 的逻辑)。**不需要在本模块重复维护配色表。**
|
||||
|
||||
---
|
||||
|
||||
## 5. 模块化决策(编辑器内 vs 独立模块)
|
||||
|
||||
| 维度 | 放进编辑器 | **独立 `diff` 模块(采纳)** |
|
||||
|---|---|---|
|
||||
| 中心对象 | 一篇文档的生命周期 | 两个被比较的目标 |
|
||||
| 窗口形态 | 编辑器标签栏 + 编辑区 | 双栏 + 目录树(布局不兼容) |
|
||||
| 状态 | 自动保存 / 脏标记 / 会话恢复 / 光标 | 无自动保存;目标是只读或被显式编辑 |
|
||||
| capability 语义 | 「编辑笔记」 | 「对比」(授权范围各自清晰) |
|
||||
| 代码影响面 | 继续膨胀 `EditorWindow.vue` / `editorStore.ts` | 新增独立目录,互不干扰 |
|
||||
| 复用方式 | —— | 复用 CM6 装配 / 主题 / 语言包 / Rust 文件读取,**不共享窗口与 store** |
|
||||
|
||||
补充两条:
|
||||
|
||||
- **不做成 devtools 里的小工具**:devtools 是「主窗口内的单页聚合」,双栏 + 目录树装不进那个壳,也没有空间与拖拽入口。
|
||||
- **交叉入口(可选,P2 之后再评估)**:编辑器窗口加「与…对比」,把当前文档发给 diff 窗口。它只是锦上添花,不影响主体结构。
|
||||
|
||||
---
|
||||
|
||||
## 6. 架构与文件清单
|
||||
|
||||
```
|
||||
主模块页(入口 / 进度) 独立窗口(双栏差异视图 / 目录三态树)
|
||||
↓ Tauri IPC ↓
|
||||
src-tauri/src/diff/ 命令层
|
||||
↓
|
||||
commands.rs 单文件读取 / 写回 / 路径类型探测 / 目录对比入口
|
||||
scan.rs 目录对比:递归遍历 + 三态分类(三层判据,见 §7.3)
|
||||
types.rs 回传前端的 DTO(与前端 types.ts 对齐)
|
||||
↓
|
||||
editor::files 文件读取与编码探测(**复用**,提升为 pub(crate))
|
||||
|
||||
src-tauri/src/drag_drop.rs 拖放补注入(**通用**,编辑器与对比窗口共用)
|
||||
|
||||
前端:
|
||||
src/modules/diff/
|
||||
index.ts moduleConfig(icon: 'diff',order 50)
|
||||
DiffModule.vue 主模块页:入口 + 三层能力进度
|
||||
DiffWindow.vue 独立窗口外壳:模式切换(文件 / 文本 ↔ 文件夹)+ 文件对比界面
|
||||
openWindow.ts diff-window 创建入口(单例,隐藏创建 + 拖放补注入)
|
||||
diffClient.ts 命令名唯一落点(照抄 editorClient.ts 范式)
|
||||
types.ts 与 Rust DTO 对齐的类型(DiffStats / DiffFileDoc / DirDiffEntry / DirDiffReport / DiffSide)
|
||||
components/
|
||||
TextMergeView.vue MergeView 封装(P1;P2 增补 setTexts / getText / doc-changed)
|
||||
DirDiffView.vue 目录对比视图(P3:工具行 / 根路径 / 过滤 / 三态树 / 汇总)
|
||||
|
||||
登记点:
|
||||
src/modules/index.ts 注册 moduleConfig
|
||||
src/modules/icons.ts 图标映射(diff → Diff)
|
||||
src/main.ts 独立窗口路由表加一行 '#diff-window'(按前缀匹配,支持 ?path=)
|
||||
src/lib/constants.ts WINDOWS.diffWindow
|
||||
src-tauri/src/taskbar_identity.rs 新增 'diff' 窗口类型(AUMID + 组合图标)
|
||||
src-tauri/capabilities/diff-window.json windows: ["diff-window"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 关键实现细节
|
||||
|
||||
### 7.1 拖入支持(用户点名需要)
|
||||
|
||||
既有实现原先在 `src-tauri/src/editor/drag_drop.rs`,**已泛化**为 `src-tauri/src/drag_drop.rs` 的 `window_attach_drag_drop`(按传入 label 生效,日志标记为 `drag-drop`),编辑器窗口与对比窗口共用同一份实现 —— 泛化而非复制,避免第二份同构实现各自腐坏。
|
||||
|
||||
要点(两条实现路径的取舍已定:**泛化**):
|
||||
|
||||
| 事项 | 结论 |
|
||||
|---|---|
|
||||
| 命令 | `window_attach_drag_drop(label)`,模块位于 crate 根部(不再属于 editor) |
|
||||
| 调用时机 | 窗口创建后**立即** fire-and-forget 调用(不能等 `tauri://created`:窗口创建过快时该事件可能早于监听注册而永远等不到)。Rust 侧自行重试等待子窗口就位 |
|
||||
| 窗口配置 | `dragDropEnabled: true` |
|
||||
| 落点分侧 | 前端按 drop 坐标分左右半边。坐标是**物理像素**,需除以 `devicePixelRatio` 再与 CSS 宽度比较 |
|
||||
| 目录 | `diff_read_file` 会拒绝目录并提示「目录对比尚未开放」——不让用户拖了没反应 |
|
||||
|
||||
### 7.2 编码与二进制(P2)
|
||||
|
||||
- 读取复用 `editor::files::read_file(path, max_mb)`:BOM → 严格 UTF-8 → chardetng 探测 → GB18030 兜底,并把「读到的编码 + 换行」成对记下来供写回原样还原。为此把 `editor::files` 提升为 `pub(crate)`(跨模块复用,范式同 `terminal::local_fs`)。
|
||||
- **二进制由对比模块自己判定**(`editor::files` 只负责解码,没有二进制概念):按**头部 8KB 含 NUL** 判定,与 `editor::grep` 的跳过判据完全一致 —— 否则会出现「搜索跳过了、对比工具却显示一堆乱码」这种自相矛盾的行为。判定为二进制后**不读内容**,只回元信息(避免把无意义字节解码成一大段乱码再走 IPC)。
|
||||
- 两侧编码分别在各自头部以 chip 显示;**编码不一致要在状态栏显式提示**(这是真实场景里最常见的「看起来全是乱码差异」根因)。
|
||||
- 尺寸两级:软阈值 5MB(置 `large`,供前端降级)、硬上限 16MB(直接拒绝)。硬上限比编辑器的每篇上限更严,因为对比窗口**同时**持有两侧内容。
|
||||
- 大文件降级:`large` 已回传,前端目前只在 `TextMergeView` 里靠 MergeView 的 `scanLimit` 兜底(见 §7.4),更细的降级(关折叠 / 不做行级对齐)留待后续。
|
||||
|
||||
### 7.3 目录扫描性能与判据(P3)
|
||||
|
||||
三层判据(代价递增,能不打盘就不打盘):
|
||||
|
||||
1. **size 不同** → 直接判「不同」(大小都不同,内容不可能相同);
|
||||
2. **size 相同且 mtime 相同** → 判「相同」;
|
||||
3. **size 相同但 mtime 不同** → 才读内容逐字节比对。
|
||||
|
||||
第 3 步有预算:[`MAX_CONTENT_COMPARES`] = 2000 条、单文件 ≤ 4MB。超出后不再读盘,按
|
||||
时间戳归入「不同」并把 `content_compared` 置 false —— 结论仍是「不同」,但界面会显式
|
||||
标注「未比对内容」,不与已确认的差异用同一种语气呈现(不能把「按元数据的推测」包装成
|
||||
「读过的结论」)。
|
||||
|
||||
其余边界:
|
||||
|
||||
- **条目上限** 8000(`truncated` 标记 + 界面提示):再大就让用户缩小范围,
|
||||
而不是把几十 MB 的 JSON 塞过 IPC。
|
||||
- **不跟随符号链接**(`walkdir` 默认):跟随会让「链接成的环」把遍历变成死循环。
|
||||
- **跳过清单由前端给出**(目录名、大小写不敏感、命中即整棵子树不遍历),默认清单与
|
||||
`editor` 模块的默认跳过清单一致,另有开关可关。后端只按清单执行 —— 同 `editor::grep`
|
||||
把默认清单留在前端的取舍。
|
||||
- 扫描是**同步命令 + 前端异步等待**(一次返回整棵树),不做进度事件:实测量级下
|
||||
(几万条目)耗时在百毫秒到数秒,做进度事件的复杂度不值当。若将来真的出现分钟级扫描,
|
||||
再改成分批回传。
|
||||
- 返回**扁平列表**(不是树):递归类型在 specta 下会生成无穷展开的 TS 类型(同
|
||||
`editor::types::LibraryEntry` 的坑);树的组装、剪枝、排序都在前端。
|
||||
|
||||
### 7.4 大文本保护(P1)
|
||||
|
||||
旧的 devtools 实现是 3000 行、LCS O(n·m)、超限直接停算。P1 **不设硬阈值**:MergeView 的 `diffConfig.scanLimit`(默认 500)会在差异过大时放弃精确比对、退回快速但不精确的算法,避开二次方耗时且仍然给出结果。真要做「超大文件不做行级对齐」的降级,留到 P2/P3 与文件读取的 `large` 标记一并处理 —— 那时才有「一个真实的大文件」这个输入,而不是用户粘贴的文本。
|
||||
|
||||
### 7.5 窗口与任务栏身份
|
||||
|
||||
沿用编辑器窗口的范式:**隐藏创建**(避免深色主题下闪白)→ 应用主题与窗口效果 → `window_set_taskbar_identity`(独立任务栏按钮 + 组合图标)→ `show()`。任务栏身份**必须在 show() 之前**设置。
|
||||
|
||||
---
|
||||
|
||||
## 8. 分期路线图
|
||||
|
||||
### P1 · 文本对比(**已落地**)
|
||||
|
||||
**目标**:双栏 MergeView 跑通,验证 `@codemirror/merge` 与项目 CM6 版本的兼容性。
|
||||
|
||||
已交付:
|
||||
|
||||
1. `src/modules/diff/`:`index.ts`(moduleConfig)+ `DiffModule.vue`(主模块页)+ `DiffWindow.vue`(独立窗口)+ `openWindow.ts` + `components/TextMergeView.vue` + `types.ts`。
|
||||
2. `src/modules/icons.ts` 加 `diff` 图标映射;`src/modules/index.ts` 注册模块;`src/main.ts` 加 `#diff-window` 路由。
|
||||
3. `src-tauri/capabilities/diff-window.json`(glob `diff-window-*` 同源权限集)。
|
||||
4. `src-tauri/src/taskbar_identity.rs` 新增 `diff` 类型(独立 AUMID + 双栏图形组合图标)。
|
||||
5. `src/lib/constants.ts` 加 `WINDOWS.diffWindow`。
|
||||
6. 删除 devtools 的文本对比工具:`DiffTools.vue` 已删,`tools/index.ts` 去掉元数据 / 图标 / 组件映射,`devtools/index.ts` 计数 20 → 19。
|
||||
7. 依赖:`@codemirror/merge ^6.12.2`(`@codemirror/state 6.7.6` 未变,`view 6.43.x` 补丁级同步)。
|
||||
8. 校验:`vue-tsc --noEmit`、`eslint`、`vite build`、`cargo check` 全部通过。
|
||||
|
||||
**尚未验证**:窗口在真实 Tauri 运行时的观感(滚动联动、mica 底色下的对比度、任务栏图标)需要跑一次 `tauri dev` 目视确认。
|
||||
|
||||
### P2 · 文件对比(**已落地**)
|
||||
|
||||
已交付:
|
||||
|
||||
1. Rust `src-tauri/src/diff/`:`mod.rs` / `types.rs`(`DiffFileDoc`)/ `commands.rs`(`diff_read_file`、`diff_write_file`)。读取复用 `editor::files::read_file`(编码探测 / 换行归一 / 只读探测),读取即登记授权(于是「打开过就能保存」成立)。为此把 `editor::files` 提升为 `pub(crate)`。
|
||||
2. 尺寸与二进制策略:软阈值 5MB(置 `large`)、硬上限 16MB(直接拒绝,对比窗口天生要同时持有两侧)、二进制按「头部 8KB 含 NUL」判定(与 `editor::grep` 同一判据),二进制**不读内容**只回元信息。
|
||||
3. 拖放泛化:`editor/drag_drop.rs` → `src-tauri/src/drag_drop.rs`,命令改名 `window_attach_drag_drop`,编辑器与对比窗口共用;`diff/openWindow.ts` 创建后立即补注入。
|
||||
4. `diffClient.ts`(命令名唯一落点)+ `types.ts` 扩展(`DiffFileDoc` / `DiffSide`)。
|
||||
5. `TextMergeView` 增补 `setTexts` / `getText` 与 `doc-changed` 事件(程序化装载期间抑制,避免把装载记成用户编辑)。
|
||||
6. `DiffWindow.vue`:两侧头部(打开文件 / 保存 / 编码 chip / 只读 chip / 脏标记)、拖入分侧高亮、编码不一致提示、二进制概览面板(只比大小,不断言「内容相同」)、`Ctrl+S` 单侧写回、关闭前三选一确认。
|
||||
7. `DiffModule.vue` 主模块页把「文件对比」标为可用。
|
||||
8. 校验:`cargo check`、`vue-tsc --noEmit`、`eslint`、`vite build` 全部通过。
|
||||
|
||||
**已知取舍**:
|
||||
|
||||
- `bindings.ts` 是 `run()` 里 `export_bindings()` 在 debug 构建时生成的,本次未跑 `tauri dev`,因此其中仍留着旧的 `editorAttachDragDrop` 声明(**无任何调用点**);下次 debug 运行会自动重建。
|
||||
- 脏标记是布尔(改过即脏),「改了又撤销回原样」仍显示为脏 —— 方向安全(至多多一次关闭确认),换来的是每次按键不必把整篇文档 `toString()` 出来比对。
|
||||
- 单侧写回**不检查另一侧是否也改了同一个文件**(两侧选中同一路径时后保存的覆盖先保存的)。仍是未解决的边界 —— P3 的目录模式是只读的,不会走到这条路径。
|
||||
|
||||
### P3 · 文件夹对比(**已落地**,只读)
|
||||
|
||||
已交付:
|
||||
|
||||
1. Rust `diff/scan.rs`:递归遍历(`walkdir`,不跟随符号链接)+ 三态分类 + 三层判据(见 §7.3)+ 跳过清单 + 条目上限。
|
||||
2. `diff/commands.rs` 增补 `diff_compare_dirs` 与 `diff_path_kind`(后者用于「拖入 / `?path=` 传进来的路径是文件还是目录」)。
|
||||
3. 前端 `diffClient.compareDirs` / `pathKind`,`types.ts` 增补 `DirDiffEntry` / `DirDiffReport` / `DirDiffStatus`。
|
||||
4. `components/DirDiffView.vue`:选两侧文件夹、跳过构建目录 / 比对内容两个开关、过滤(仅差异 / 全部 / 仅左侧 / 仅右侧)、树(目录在前、同名排序、可折叠、展开/折叠全部)、按子树剪枝、汇总栏(不同 / 仅左 / 仅右 / 相同 / 类型不一致 / 跳过目录数 / 耗时 / 截断提示)。
|
||||
5. `DiffWindow.vue` 增加模式切换(文件 / 文本 ↔ 文件夹,各自记住自己的目标)、拖入按模式分派(目录模式取该侧根;拖文件取父目录)、点差异行下钻到文件对比 + 「返回目录对比」。
|
||||
6. 校验:`cargo check`、`vue-tsc --noEmit`、`eslint`、`vite build` 全部通过(并核对 `h-6.5` 这类分数间距类确实被 Tailwind v4 生成)。
|
||||
|
||||
**关键取舍(都在实现里写了理由)**:
|
||||
|
||||
- **切模式不能丢改动**:目录模式下 `TextMergeView` 被卸载,用户刚敲的内容只存在于 CM6 实例里。离开文件模式前先 `snapshotEdits()` 把脏侧的内容取进 `contentA/B`,切回来时再灌回去(`setTexts` 抑制 `doc-changed`,脏标记原样保留)。
|
||||
- **保存必须先确保文件模式已挂载**:`saveSide` 在取不到内容时直接返回 false 而**不是**写空串;`Ctrl+S` / 「保存并关闭」走 `saveAllDirtyEnsuringFiles`,会先切回文件模式再保存 —— 否则目录模式下保存会把文件写空。
|
||||
- **目录的「相同 / 不同」由子树决定**:Rust 一律给目录标 `identical`,前端按子树是否含差异决定目录行的颜色与是否显示。
|
||||
- **只读**:本期不做任何写回 / 同步(用户已拍板)。
|
||||
|
||||
**尚未验证**:与 P1/P2 一样,真实 Tauri 运行时下的观感与拖放行为需要跑一次 `tauri dev` 目视确认。
|
||||
|
||||
### P4 · 交互层补全(**已落地**,参考 Beyond Compare)
|
||||
|
||||
用户提出的五项调整,逐项落地情况:
|
||||
|
||||
| # | 需求 | 实现 |
|
||||
|---|---|---|
|
||||
| 1 | 选项卡,标题 `xxx ↔ xxx` | `DiffWindow` 改为**会话(session)**架构:一个选项卡 = 一对目标。标题取两侧显示名(文件用文件名、目录用末段目录名)。窗口标题同步为 `对比 — 左 ↔ 右`,任务栏悬停可见 |
|
||||
| 2 | 目录对比改左右两个界面,都用结构树;两侧可自由输入与选择,选择改图标按钮 | `DirDiffView` 重写为**左右两棵结构树**:同一份并集行渲染两遍(行数/顺序一致、共用折叠状态),每侧只显示该侧真实存在的文件(缺失侧显示「—」并压暗名字);每侧顶部是**可编辑路径输入框 + 文件夹图标按钮**;列头对齐 Beyond Compare 的「名称 / 大小 / 已修改」 |
|
||||
| 3 | 点一侧文件 → 新开文件对比选项卡 | 行点击 → `open-file` → 新开文件选项卡(记录 `fromDirTabId`,工具栏出现「返回目录对比」)。**只在一侧存在的文件也能开**(另一侧留空,整篇为新增/删除) |
|
||||
| 4 | 快捷键唤出对比窗口,默认 Alt+C,参考编辑器机制 | Rust 侧新增 `DiffSettings` + `DiffManager`(`{app_data_dir}/diff/settings.json`),`init_on_launch` 用 `shortcut.rs` 注册(原子注册 + 应用内冲突检测),触发只发 `diff-open-window` 事件;`App.vue` **应用级**监听后调 `openDiffWindow()`。模块页可改快捷键(保存后就地重注册) |
|
||||
| 5 | 中间列显示差异、快速替换等 BC 细节 | 文件对比启用 MergeView 的 `revertControls`:**中间列**按差异块渲染 ⇜ / ⇝ 按钮,点一下即把该块替换到另一侧(替换后该侧变脏)。MergeView 一次只能渲染一个方向,因此工具栏给出「右 → 左 / 左 → 右」方向切换(`reconfigure` 热切换,不重建视图) |
|
||||
|
||||
**P4 关键取舍**:
|
||||
|
||||
- **切选项卡不能丢改动**:`TextMergeView` 只有一个实例,内容只在 CM6 里是最新的。切走前 `snapshotEdits()` 把脏侧内容取回会话,切回来再灌进去(`setTexts` 抑制 `doc-changed`,脏标记保留)。
|
||||
- **关闭选项卡的判据是「脏」而不是「编辑器是否挂载」**:非激活选项卡的编辑内容已快照在会话里,静默丢弃同样是丢改动 —— 因此脏就弹确认,确认后先激活它再保存(激活那一刻才能拿到最新内容)。
|
||||
- **会话状态里的大对象要 `markRaw`**:扫描报告可达数千条目,进响应式系统会逐条生成 Proxy。内容字符串是原始值,不进 Proxy,可以放心放会话里。
|
||||
- **`v-model:session` 而不是普通 prop**:`DirDiffView` 要直接改会话字段(8 个字段几乎都双向改),而 `vue/no-mutating-props` 禁止改 prop;`defineModel` 是 Vue 为这种场景给的正解。
|
||||
|
||||
---
|
||||
|
||||
## 9. 已拍板决策表
|
||||
|
||||
| # | 问题 | 决策 | 影响 |
|
||||
|---|---|---|---|
|
||||
| 1 | devtools 里的文本对比工具 | **移除**,能力并入本模块 | 避免仓库里存在两套 diff 引擎;顺带解决它的 3000 行上限 |
|
||||
| 2 | 目录对比是否写回 | **暂不做**(P3 只读) | P3 工程量显著下降;写回留待单独评估 |
|
||||
| 3 | 是否需要拖入 | **需要** | 已落地:P2 起拖入文件按落点装入左 / 右半区 |
|
||||
| 4 | 做进编辑器还是独立模块 | **独立模块 + 独立窗口** | 复用编辑器能力但不共享窗口/store |
|
||||
| 5 | 渲染层选型 | **`@codemirror/merge`** | 已有 6.12.2 安装;主题复用编辑器配色 |
|
||||
| 6 | 本期是否引入 Rust `similar` | **不引入**(P1/P2 不需要) | P3 目录级若需批量摘要再评估 |
|
||||
| 7 | 拖放补注入的实现路径 | **泛化既有实现**(不复制第二份) | `drag_drop.rs` 移到 crate 根部、命令改名 `window_attach_drag_drop`;编辑器调用点随之一并更新 |
|
||||
| 8 | 单文件读取的尺寸策略 | 软阈值 **5MB** / 硬上限 **16MB** | 硬上限比编辑器更严:对比窗口同时持有两侧内容 |
|
||||
| 9 | 目录对比的判据 | size → mtime → 内容(三层) | 内容比对有预算(2000 条 / 4MB):超出按时间戳判定,并在界面标注「未比对内容」 |
|
||||
| 10 | 目录树结构 | Rust 返回**扁平列表**,前端组装 | 避开 specta 递归类型的坑(同 `LibraryEntry`);剪枝 / 排序 / 过滤都在前端 |
|
||||
| 11 | 本期是否做目录写回 | **不做**(只读) | 用户已拍板;冲突策略等留待单独评估 |
|
||||
| 12 | 窗口内是否有选项卡 | **有**(P4):一选项卡 = 一对目标 | 状态按会话组织;目录下钻新开选项卡而不是替换 |
|
||||
| 13 | 目录对比的界面形态 | **左右两棵结构树**(P4,原为一棵并集树) | 同一份并集行渲染两遍,共用折叠状态保证不错行 |
|
||||
| 14 | 打开对比窗口的快捷键 | **Alt+C**(P4,可在模块页改) | 走 `shortcut.rs`;触发只发事件,窗口由前端创建 |
|
||||
| 15 | 中间列快速替换 | **启用**(P4):⇜/⇝ 单方向 + 工具栏切换 | MergeView 一次只能一个方向;双方向要自绘中间列,暂不做 |
|
||||
|
||||
---
|
||||
|
||||
## 10. 风险与待验证
|
||||
|
||||
| 风险 / 未知 | 说明 | 应对 |
|
||||
|---|---|---|
|
||||
| `@codemirror/merge` 与项目版本兼容 | 已确认安装 `6.12.2`,`@codemirror/state 6.7.6` 未变,`view` 由 `6.43.13` 升到 `6.43.14`(补丁级) | 已通过安装验证;P1 构建与运行再复核一次 |
|
||||
| MergeView 的块级高亮配色与自建主题的融合 | MergeView 提供的是结构类名/默认色,需按项目语义色覆盖(新增/删除/修改) | P1 里显式覆盖 `.cm-changedLine` 等规则,对齐 `--success-soft` / `--danger-soft` |
|
||||
| 目录扫描在大目录上的耗时 | 几十万文件递归 + 内容比对可能秒级到十几秒 | §7.3 快速路径 + 忽略清单 +(必要时)进度事件分批 |
|
||||
| 拖放注入射程 | 现实现是编辑器专用的,泛化会触及编辑器路径 | §7.1 二选一;若选泛化,回归编辑器窗口的拖入 |
|
||||
| 二进制与超长行文本在 MergeView 下的表现 | 极长单行(如压缩后的 JSON)会让对齐与渲染变慢 | 阈值降级 + 明确提示,不做静默失败 |
|
||||
@@ -0,0 +1,533 @@
|
||||
# 编辑器模块规划(Editor Module Plan)
|
||||
|
||||
> 状态:**方案已确认,待开工**(v1 已落地;v2 定位修订与本轮 10 项决策已定稿)
|
||||
> 本轮决策(2026-09-30,用户已拍板):**不引入工作区**(Q2=a)· **目录树不纳入索引**(Q3=a)· **标签页放 P4**(Q4=a)· **模块显示名 = 编辑器**(Q1=a)
|
||||
> v1 现状(原「笔记模块」,已全部落地):CM6 内核 + Live Preview + 本地笔记库 + 独立窗口 + 检索/索引 + WebDAV + 导入导出 + 模板 + 双链 + 图片预览 + 全局快捷键 + 文件关联
|
||||
> v2 修订方向:模块核心从「笔记」改为「**编辑器**」——一个 notepad++ 式的通用文本/代码编辑器;**笔记库与本地目录探查退化为它的两个并列导航能力**,不再是模块的中心
|
||||
> 已确认决策:所见即所得 = **Live Preview**(非块编辑);WebDAV = **备份 / 同步目标**(不做远端直连读写);编码 = **可探测、可切换、原样写回**
|
||||
> 定位:Thing 工具集的第 13 个模块,`id = editor`(原 `notes`),`category = 'tool'`
|
||||
> 作者:砚 | 日期:2026-09-30
|
||||
> 关联文档:`AI_DEV_GUIDE.md`(模块注册 / IPC / 进程管理范式)、`UI_DESIGN_SYSTEM.md`(页面框架 / 组件规范)、`TERMINAL_MODULE_PLAN.md`(独立窗口 / 跨窗口设置同步范式)
|
||||
>
|
||||
> 阅读顺序:**§11 开工清单(先读,它是执行入口)** → §0 结论 → §1 定位修订 → §3 功能规格 → §5 编码 → §7 缺口 → §8 路线图。
|
||||
> **§9 是 v1 的压缩实施记录**,只保留「为什么这么做」的结论与踩过的坑;**§10 是已拍板的决策表**(不再是待定项)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 结论先行
|
||||
|
||||
八个关键判断。
|
||||
|
||||
1. **模块改名 `notes` → `editor`,但一次到位、不留双命名。** `id` / 窗口 label / 事件名 / Rust 命令前缀 / 目录名 / 存储键全部统一。半改不改(模块叫 editor、命令还叫 `notes_*`)比不改更糟:读代码的人要同时维护两套心智。改名是机械工作(约 400 处标识符),风险集中在「漏改一处」,用脚本核对(§9.6)。
|
||||
|
||||
2. **「笔记」不是被删掉,而是被降级为一种能力。** 编辑器的最小模型是「路径 + 字节 + 编码」,笔记库是加在它之上的一层(库根沙箱 + front-matter + 索引 + 双链)。因此**文件是真相层,笔记库是视图层**——这条和 v1 的「文件即真相」并不冲突,只是把「库」从中心挪到了并列位置。
|
||||
|
||||
3. **左侧导航 = 两个并列的树 + 三块辅助能力。** 两个树:**笔记库**(沙箱、有索引、有双链)与**本地目录**(任意路径、无索引、无 front-matter 语义)。三块辅助:**文件名/内容搜索**、**最近打开(文件夹与文件分开记)**、**定位到资源管理器**。
|
||||
|
||||
4. **多编码是这一版的新增硬需求,且必须「可切换」。** 探测链:BOM → 严格 UTF-8 → GB18030(中文存量主力)→ 用户手动指定。写回**默认按读取时的编码**。切换编码的语义是「**换一种方式解释磁盘字节**」而不是「重新解释缓冲区文本」——因此切换动作会**从磁盘按新编码重新解码**(有未保存改动时先让用户三选一,见 §5.3)。
|
||||
|
||||
5. **系统集成走用户级注册表,不需要管理员权限。** 文件关联(双击打开)走 Tauri `fileAssociations`;**资源管理器右键菜单**(文件/文件夹)走 `HKCU\Software\Classes\*\shell\*` 与 `Directory\shell\*`,用**已在依赖树里的 `winreg`** 写(项目已有 `system_proxy.rs` / `glsmtc.rs` 两处先例)。**注册动作放在设置页按钮里、默认不自动写注册表**——开发模式下的 exe 路径是 `target\debug\thing.exe`,自动注册会留下指向临时产物的僵尸菜单项。
|
||||
|
||||
6. **默认全局快捷键 `Alt+E` 打开编辑器。** 走既有 `shortcut.rs`(原子注册 + 冲突检测),设置页可改。
|
||||
|
||||
7. **不引入「工作区」概念(已拍板)。** 用户要的是「右键文件夹 → 在这里打开」,用**当前目录根**这一个状态就够了(可切换 + 有历史)。引入 workspace 会连带出「多根 / 会话恢复 / 每根独立状态」三个复杂度,而收益(同时开两个目录树)在 notepad++ 式用法里很低。因此侧栏只有一个「目录」面板,根是单值。
|
||||
|
||||
8. **不做的事**(明确划界,避免无限扩张):不做 IDE 能力(调试器、终端内嵌、LSP 补全、Git 集成);不做块编辑器;不做远端工作区(WebDAV 只做备份/同步目标)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 定位修订(v1 → v2)
|
||||
|
||||
| 维度 | v1(笔记模块) | v2(编辑器模块) |
|
||||
|---|---|---|
|
||||
| 一句话 | 一个 Markdown 笔记库,带所见即所得编辑 | 一个通用文本/代码编辑器,**顺带**能管一个笔记库 |
|
||||
| 中心对象 | 笔记(库内 `.md`) | 文件(任意路径的任意文本) |
|
||||
| 首要入口 | 库树 → 选一篇笔记 | 打开文件 / 最近文件 / 目录树 → 选一个文件 |
|
||||
| 笔记库的角色 | 模块的**全部** | 两个导航根之一 + 一层语义(front-matter / 双链 / 索引) |
|
||||
| 编码 | 「尽量别写坏」(读时记、写回原样) | **一级功能**:探测 + 状态栏显示 + 可切换 |
|
||||
| 系统集成 | 无(P2 曾因依赖代价搁置) | 文件关联 + 资源管理器右键 + `Alt+E` |
|
||||
| 索引 | FTS5 全文检索(笔记的核心) | 保留,但只服务笔记库;目录树只做文件名匹配 |
|
||||
| markdown Live Preview | 默认视图 | **按文件类型自动选择**:`.md` 用 Live Preview,其余用纯高亮 |
|
||||
|
||||
> 一句话总结这次修订:**把「库」从产品中心降为两个导航能力之一,把「文件 + 编码 + 系统集成」提到中心。**
|
||||
|
||||
---
|
||||
|
||||
## 2. 需求解构
|
||||
|
||||
| 用户原话 | 解构为 | 落点 |
|
||||
|---|---|---|
|
||||
| 「核心改为 Editer,标题和其他都改」 | 模块改名 + 重定位 + 主页面/窗口标题/文案全面改口径 | §1 / §7 / §9.6 |
|
||||
| 「笔记作为编辑器模块的一个核心功能」 | 笔记库降为并列能力,但保留全部既有实现 | §1 / §3.3 |
|
||||
| 「左边导航栏有两个功能:笔记库 / 本地目录结构」 | 侧栏两个并列根:库根(沙箱 + 索引)与当前目录(任意) | §3.3 / §6 |
|
||||
| 「导航栏需要定位打开文件位置、搜索文件名(参考 idea)」 | 「在资源管理器中显示」+ 两级过滤(文件名 LIKE / 库内 FTS) | §3.4 |
|
||||
| 「核心只是普通编辑器,类似 notepad++」 | 不引入 IDE 能力;以「打开快、编码稳、快捷键全」为质量目标 | §0.8 / §3.1 |
|
||||
| 「快捷键直接打开编辑器,默认 alt+e」 | 全局快捷键,默认 `Alt+E`,设置页可改 | §3.7 |
|
||||
| 「文件管理器右键菜单,用 Thing Editer 打开」 | HKCU 注册 `*\shell\ThingEditor` 与 `Directory\shell\ThingEditor` | §3.6 |
|
||||
| 「历史打开的文件夹/文件记录」 | 最近文件 + 最近文件夹两份列表(分组显示、可清空) | §3.5 |
|
||||
| 「多编码,识别 + 支持切换编码」 | 探测链 + 状态栏编码菜单 + 重解码 + 按新编码重写 | §5 |
|
||||
| 「优化结构和功能完整性」 | 补齐:编码切换、目录树、最近记录、右键菜单、大文件策略、只读打开 | §3 / §4 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 功能规格
|
||||
|
||||
### 3.1 编辑器核心
|
||||
|
||||
- **打开方式**:最近文件 / 目录树 / 笔记库树 / 系统对话框 / 命令行 / 文件关联 / 资源管理器右键。
|
||||
- **视图按类型自动选**:`.md`/`.markdown`/`.mdx` 默认 Markdown(Live Preview,可在状态栏切到源码);其余按扩展名加载语言高亮(`@codemirror/lang-*` 按需 `import()`)。
|
||||
- **基础编辑**:行号、折叠、括号匹配、多光标、矩形选择、搜索替换(CM6 原生 `searchKeymap`)、转到行(`Alt+G`)、撤销栈、Tab 缩进。
|
||||
- **快捷键**(窗口内,CM6 `keymap` 优先于全局):`Ctrl+S` 保存、`Ctrl+Shift+S` 另存为、`Ctrl+O` 打开、`Ctrl+P` 快速打开、`Ctrl+W` 关闭当前文档、`Ctrl+Tab` 文档间切换、`Ctrl+E` 切换编码、`Ctrl+Shift+M` 切换 Live Preview/源码。
|
||||
- **多文档**:同一窗口内多标签(**新增**,见 §8-P1)。`Ctrl+W` 关闭标签,关闭前若有未保存改动则二次确认。
|
||||
- **大文件策略**:超过阈值(默认 5MB,可配)时关闭 Live Preview / 折叠 / 补全 / 装饰,只保留高亮 + 行号;并在状态栏给出可点击的降级说明。
|
||||
- **只读打开**:检测到文件不可写时以只读模式打开(替代「打开成功但保存失败」)。
|
||||
|
||||
### 3.2 笔记模式(`.md` 在库内)
|
||||
|
||||
保持 v1 全部能力:Live Preview(标题/强调/行内代码/列表/任务/引用/代码块/分隔线/表格/图片内联)、`[[wikilink]]` 点击跳转与一键新建、front-matter 属性面板、大纲、双链面板、字数/行数统计。
|
||||
|
||||
### 3.3 左侧导航(两个并列根)
|
||||
|
||||
| 面板 | 根 | 能力 | 数据来源 |
|
||||
|---|---|---|---|
|
||||
| **笔记库** | 库根(可切换,默认 `{appData}/editor/library`) | 树 / 新建 / 重命名 / 删除 / 标签 / 双链 / FTS 全文检索 | SQLite 索引(`notes.db` → `editor.db`) |
|
||||
| **本地目录** | 当前目录根(可切换,有历史) | 树 / 文件名过滤 / 打开文件 / 新建文件/文件夹 / 重命名 / 删除 / 在资源管理器中显示 / 复制路径 | 直接 `fs` 读目录(**不进索引**) |
|
||||
|
||||
两个面板都在**同一个侧栏**里用分段导航切换(v1 已有 4 段:文件/检索/大纲/双链;v2 扩为:**库 / 目录 / 检索 / 最近**,大纲与双链改为编辑区右侧的**抽屉**,因为它们跟「当前文档」绑定而不是跟「导航」绑定)。
|
||||
|
||||
> 为什么把大纲/双链挪到右侧抽屉:它们描述的是**当前文档**,而侧栏描述的是**去哪找文件**。混在一起会让侧栏在「导航」与「文档信息」两种语义之间摇摆(v1 已经能感到这个别扭)。
|
||||
|
||||
### 3.4 搜索与定位
|
||||
|
||||
- **文件名过滤**:侧栏顶部输入框,对当前树做不区分大小写的子串匹配,命中项的**祖先自动展开**(v1 已有)。
|
||||
- **快速打开 `Ctrl+P`**:跨「库 + 最近 + 当前目录」的文件名跳转,本地模糊排序(连续匹配 > 前缀 > 词首 > 位置),零网络、零后端。
|
||||
- **库内全文检索 `Ctrl+Shift+F`**:FTS5(trigram),标题权重高于正文,命中片段高亮(定界符方案,不注入 HTML)。目录树**不做**全文检索(不在索引里,也不该为此扫盘)。
|
||||
- **定位打开文件位置**:`revealItemInDir`(`opener` 插件,能力已授权)。三处入口:标签右键、侧栏行右键、状态栏路径点击。
|
||||
- **搜索文件名作用域切换**:输入框旁边一个「当前树 / 全库 / 当前目录」的小切换(idea 的 `Ctrl+Shift+N` 体验,但不引入独立对话框)。
|
||||
|
||||
### 3.5 历史记录
|
||||
|
||||
- **最近文件**:路径 + 显示名 + 时间 + 是否仍存在(失效项灰显、可一键清理)。
|
||||
- **最近文件夹**:同理,用于「右键文件夹 → 在这里打开」与侧栏目录面板的快速切换。
|
||||
- 存储:`editor/settings.json` 的 `recentFiles` / `recentFolders`(**与笔记库解耦** —— 库可以换/删,历史不该跟着丢)。各自上限 20 条,超出淘汰最旧。
|
||||
- 两份列表**分开存**:文件与文件夹的用途不同,混在一起会让「最近文件夹」被文件挤掉。
|
||||
|
||||
### 3.6 系统集成
|
||||
|
||||
| 集成 | 机制 | 权限 |
|
||||
|---|---|---|
|
||||
| 双击 `.md`/`.markdown`/`.mdx` 打开 | `bundle.fileAssociations`(安装器写 `OpenWithProgids`) | 安装器 |
|
||||
| 「用 Thing 编辑器打开」(文件) | `HKCU\Software\Classes\*\shell\ThingEditor` | 用户级,免管理员 |
|
||||
| 「用 Thing 编辑器打开」(文件夹) | `HKCU\Software\Classes\Directory\shell\ThingEditor` | 同上 |
|
||||
| 「用 Thing 编辑器打开」(目录背景) | `HKCU\Software\Classes\Directory\Background\shell\ThingEditor` | 同上 |
|
||||
| 菜单图标 | 菜单项 `Icon` 值指向 exe(用 exe 自带图标) | — |
|
||||
| 已运行时的二次启动 | `tauri-plugin-single-instance` 转交 argv 给已有实例 | 已落地 |
|
||||
| 免注册表运行 | 设置页提供「注册 / 卸载右键菜单」按钮,并显示当前 exe 路径 | — |
|
||||
|
||||
**关键约束**:注册表条目里写的是**绝对 exe 路径**。
|
||||
- 打包安装后:指向安装目录的 exe,稳定;
|
||||
- `tauri dev` 下:指向 `target\debug\thing.exe`,一旦清理 target 就变成死链。
|
||||
→ 因此**默认不注册**,且注册时校验 exe 存在;设置页在 dev 环境下给出明确提示。
|
||||
|
||||
### 3.7 全局快捷键
|
||||
|
||||
| 快捷键 | 动作 | 默认 |
|
||||
|---|---|---|
|
||||
| `Alt+E` | 打开编辑器窗口(无参数 = 上次的文档/最近文件) | **本版新增默认值** |
|
||||
| `Ctrl+Shift+N` | 新建笔记(直接落库根) | 空(v1 已有实现,改为可配) |
|
||||
|
||||
两者都走 `shortcut.rs`,触发时只发事件、窗口由前端创建(v1 已确立的姿态)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 存储、索引与目录树
|
||||
|
||||
```
|
||||
{appData}/editor/ # 模块自身(与库解耦)
|
||||
├── settings.json # 设置 + 最近文件/文件夹
|
||||
├── editor.db # 笔记库索引(可重建)
|
||||
└── library/ # 默认库根
|
||||
├── notes/ assets/ templates/
|
||||
└── .editor/ # 库内私有:同步基线 sync.json
|
||||
```
|
||||
|
||||
- **配置文件全量走 `settings.json`**(v1 已如此),新增 `recentFiles` / `recentFolders` / `defaultEncoding` / `largeFileMb` / `contextMenuEnabled`。
|
||||
- **索引服务架构不变**(单线程 worker 独占 `rusqlite` 连接 + 通道排队 + notify 监听),只改名。
|
||||
- **目录树不进索引**:它是「看盘」而不是「管库」。目录树节点按需 `read_dir`(带缓存与手动刷新),深度上限与库树一致(24)。
|
||||
- **配置改动只在用户显式操作下发生**:目录树上的新建/重命名/删除都是显式动作,且删除走系统回收站(复用 `quickpanel` 的回收站实现,`terminal/local_fs.rs` 已有先例)。**目录树自身不做任何隐式写入**(不生成索引、不生成元数据文件、不自动整理)。
|
||||
|
||||
---
|
||||
|
||||
## 5. 编码:探测、显示、切换
|
||||
|
||||
### 5.1 探测链(按优先级)
|
||||
|
||||
| 顺序 | 判据 | 结论 | 说明 |
|
||||
|---|---|---|---|
|
||||
| 1 | `EF BB BF` / `FF FE` / `FE FF` | `utf-8-bom` / `utf-16le` / `utf-16be` | BOM 是无歧义事实,直接采信 |
|
||||
| 2 | `std::str::from_utf8` 通过 | `utf-8` | 结构性校验,不是统计猜测 |
|
||||
| 3 | 以上失败 | `gb18030` | 中文存量主力(GBK 超集),比「猜 Big5/Shift_JIS」安全 |
|
||||
| 4 | 用户手动指定 | 用户值 | 前三级都可能错,必须留人工兜底 |
|
||||
|
||||
**刻意不做**:字符频率统计 + 多编码自信度比较(chardet 式)。理由是它在短文本上比规则更不可靠,而本项目的主要场景(代码/配置/中文笔记)恰好都是「UTF-8 或 GB18030」二选一。真错了有第 4 级兜底,代价可控。
|
||||
|
||||
### 5.2 读取与状态
|
||||
|
||||
读文件时一次性回传:`content`(已解码 UTF-8 字符串 + 换行归一为 `\n`)、`encoding`(探测结果)、`eol`(`lf`/`crlf`)、`size`、`large`、`readonly`。
|
||||
|
||||
- 状态栏显示:`UTF-8` / `GB18030` / `UTF-8 BOM` + `CRLF` / `LF` + 只读标记。
|
||||
- `readonly`:打开时用 `OpenOptions::new().write(true).open()` 探一次写权限(**不实际写入**),失败则置只读。这比「打开成功但保存时才报错」体验好得多。
|
||||
- 编码名一律用 `terminal/encoding.rs` 的 `normalize()` 规范形态(`utf-8` / `gbk` / `gb18030` / `big5` / `shift_jis` / `euc-kr` / `latin1`),双端取值同源,避免「状态栏写 GBK、设置里叫 cp936」这种不一致。
|
||||
|
||||
### 5.3 切换编码(关键设计)
|
||||
|
||||
**核心约束:切换编码不是「重新解释缓冲区文本」,而是「换一种方式去解释磁盘字节」。**
|
||||
|
||||
- **切换时**:以磁盘当前字节(而非缓冲区文本)按新编码重新解码 → 替换缓冲区内容。
|
||||
- 若此时有未保存改动:弹确认框给出三个选项——①**丢弃我的改动并按新编码重读**(默认,语义最清晰);②**先保存再重读**(用旧编码落盘,再按新编码读回——用户能立刻看出旧编码是否选错);③取消。
|
||||
- **保存时**:按当前 `encoding` 编码写回。若目标编码无法表示缓冲区里的某些字符(例如把含 emoji 的文本存成 GBK),**保存前报错并列出无法表示的字符位置**,而不是静默替换成 `?`(静默替换 = 不可逆数据损坏)。
|
||||
- **状态栏编码下拉**:`UTF-8` / `UTF-8 BOM` / `GB18030` / `GBK` / `Big5` / `Shift_JIS` / `EUC-KR` / `Latin-1` + 「重新载入为…」(不改变写回编码,仅重新解释)。
|
||||
- **换行切换**:`LF` / `CRLF` 独立于编码(v1 已按读取值写回),状态栏可切换。
|
||||
|
||||
### 5.4 与终端模块的编码复用
|
||||
|
||||
`terminal/encoding.rs` 提供 `decode` / `encode` / `normalize` / `SUPPORTED` / `is_supported`(v1 已直接复用,未提取为公共模块 —— 它们是纯函数,无业务耦合;若将来第三个模块要用再提取)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 界面结构
|
||||
|
||||
### 6.1 主模块页(设置与管理,不编辑)
|
||||
|
||||
Tab 收敛为 **概览 / 库 / 编辑器 / 集成**(把 v1 的「同步」并入「库」,因为同步是库的属性):
|
||||
|
||||
| Tab | 内容 |
|
||||
|---|---|
|
||||
| 概览 | 库状态横幅(路径/笔记数/索引)、最近文件与文件夹、快捷入口(打开编辑器 / 打开文件 / 打开文件夹 / 今日日记) |
|
||||
| 库 | 库根切换、重建索引、导入导出、WebDAV(连接/方向/冲突/快照) |
|
||||
| 编辑器 | 主题(含 JetBrains 三套)、字体字号行高连字、Live Preview 开关、默认编码、大文件阈值、自动保存、快捷键 |
|
||||
| 集成 | 文件关联状态、**右键菜单注册/卸载**、exe 路径、单实例说明 |
|
||||
|
||||
### 6.2 编辑器窗口
|
||||
|
||||
```
|
||||
┌─ 标题栏(自绘:文档名 + 未保存点 + 窗口按钮)────────────────────────┐
|
||||
├─ 工具栏:保存 另存 打开 快速打开 | 格式化(.md 时) | 编码 换行 主题 ─┤
|
||||
├────────────┬──────────────────────────────────────────┬─────────────┤
|
||||
│ 侧栏 │ 标签栏:doc1 × | doc2 × | … │ 抽屉(可选) │
|
||||
│ [库|目录| ├──────────────────────────────────────────┤ 大纲 / 双链 │
|
||||
│ 检索|最近] │ 编辑器(CM6) │ │
|
||||
│ │ │ │
|
||||
│ 树 / 结果 │ │ │
|
||||
├────────────┴──────────────────────────────────────────┴─────────────┤
|
||||
│ 状态栏:保存态 · 字数/行数 · 行列 · 语言 · 编码 · 换行 · 路径 │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**并排分屏**(标签右键 → 并排分屏)把编辑页平分为左右两列,各占一半宽:
|
||||
|
||||
```
|
||||
├─ 工具栏(整行,不参与分屏)──────────────────────────────────────────┤
|
||||
│ 标签栏:doc1 × | doc2 × │ 副文档名 × │
|
||||
├──────────────────────────────┼──────────────────────────────────────┤
|
||||
│ 编辑器(CM6)· 主文档 │ 编辑器(CM6)· 副文档 │
|
||||
└──────────────────────────────┴──────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 「标签栏 + 编辑栏」整体是**左半列**,副文档是**右半列**(自带 8px 标题行与关闭按钮),
|
||||
两列等宽、各自独立滚动 —— 副文档是并排的一列,**不是嵌在编辑栏内部的一块**。
|
||||
从前的做法把副面板塞在编辑栏(标签栏下方)内部,看起来像"同一栏里又开了个窗口"。
|
||||
- 不分屏时标签栏回到顶部、横跨整列宽度(即左半列占满),行为与基础形态一致。
|
||||
- 侧栏可整体折叠(腾出宽度给长行代码)。
|
||||
- 抽屉默认关闭,`Ctrl+Shift+O` 切大纲、`Ctrl+Shift+B` 切双链。**这两个键位在实现时由 `keymap.ts` 统一声明并做冲突检测**:若与 CM6 默认键位冲突,以 CM6 默认键位优先,本功能改用 `Alt+O` / `Alt+B`(冲突检测方式沿用 v1 的 `shortcut.rs` 思路,编辑器内用 CM6 的 keymap 优先级)。
|
||||
|
||||
### 6.3 目录面板的命令面(P3-5 实现依据)
|
||||
|
||||
| 命令 | 入参 | 说明 |
|
||||
|---|---|---|
|
||||
| `editor_read_dir` | `path: String`(空 = 用户主目录) | 返回 `cwd` / `parent` / `entries`(名字/路径/是否目录/大小/mtime) |
|
||||
| `editor_create_file` | `dir: String`, `name: String` | 重名报错(**不自动加序号**:目录树是用户的真实文件系统,静默改名会让人找不到刚建的文件) |
|
||||
| `editor_create_folder` | `dir: String`, `name: String` | 同上 |
|
||||
| `editor_rename_path` | `path: String`, `newName: String` | 同目录改名;目标存在则报错 |
|
||||
| `editor_delete_path` | `paths: Vec<String>` | **走系统回收站**(复用 `quickpanel::commands::delete_file_impl`),返回 `(成功数, 失败明细)`;拒绝盘符根 |
|
||||
| `editor_reveal_path` | `path: String` | 在资源管理器中选中(`opener` 的 `reveal_item_in_dir`) |
|
||||
|
||||
**安全边界**:目录树操作的是**用户真实文件系统**(不是沙箱),因此
|
||||
- 不设「必须在本目录根下」的限制(那是本地文件管理器,限制根目录只会挡住用户自己);
|
||||
- 但**拒绝删除盘符根**(`Path::new(p).parent().is_none()`)—— 这是唯一不可恢复的事故;
|
||||
- 删除一律走回收站,不用 `remove_file`;
|
||||
- 路径来自用户自己的浏览/输入,与 `terminal/local_fs.rs` 同一姿态(该模块已有 `list_dir` / `delete` 的成熟实现,**优先复用而不是重写**)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 缺口清单(v1 已有 → v2 要做)
|
||||
|
||||
| # | 缺口 | 严重度 | 落点 |
|
||||
|---|---|---|---|
|
||||
| G1 | 模块仍叫 notes(id / 命令 / 事件 / 目录 / 存储键) | 高(结构性) | §9.6 |
|
||||
| G2 | 没有「本地目录」导航根(只有笔记库) | 高 | §3.3 |
|
||||
| G3 | 编码只能探测不能切换;无状态栏显示 | 高 | §5 |
|
||||
| G4 | 没有最近文件夹记录(只有最近笔记,且存在 localStorage) | 中 | §3.5 |
|
||||
| G5 | 没有资源管理器右键菜单 | 中 | §3.6 |
|
||||
| G6 | 默认全局快捷键为空(`Alt+E` 未设) | 低 | §3.7 |
|
||||
| G7 | 单窗口单文档(无标签页) | 中 | §3.1 |
|
||||
| G8 | 大纲/双链挤在导航侧栏里,语义混杂 | 中 | §3.3 |
|
||||
| G9 | 大文件降级没有「只读打开」与显式提示 | 低 | §3.1 / §5.2 |
|
||||
| G10 | 主模块页 Tab 结构未随定位调整(同步应并入库) | 低 | §6.1 |
|
||||
| G11 | 语言包缺 `.sh`/`.ps1`/`.toml`/`.ini`/`.scss`(legacy-modes 未接) | 低 | §8-P5.1 |
|
||||
| G12 | Markdown 内嵌代码块高亮未做(`codeLanguages` 异步问题) | 低 | §8-P5.3 |
|
||||
| G13 | `FileDoc` 无 `readonly` 字段(只读文件要等保存时才报错) | 中 | §5.2 / P4-1 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 分期路线图
|
||||
|
||||
> v1 的 P0/P1/P2 已全部落地(见 §9)。以下是从 **P3 起**的新路线图。
|
||||
|
||||
### P3 — 编辑器化改造(结构)
|
||||
|
||||
1. **改名**:`notes` → `editor`(id / 窗口 label / 事件 / 命令前缀 / 目录 / 存储键 / Rust 模块名),脚本核对无残留(§9.6)。
|
||||
2. **库内目录改名**:`<库根>/.notes/` → `<库根>/.editor/`(含 `sync.json`),首次打开时惰性迁移;索引可重建,丢了无损。
|
||||
3. **侧栏重构**:`库 / 目录 / 检索 / 最近` 四段;大纲与双链移到编辑区右侧抽屉。
|
||||
4. **本地目录树**:打开文件夹(对话框 / 右键菜单 / 最近文件夹)、树浏览、文件名过滤、打开文件、在资源管理器中显示、复制路径、手动刷新。
|
||||
5. **最近记录**:最近文件 + 最近文件夹(落 `settings.json`,分组显示、可清空、失效项灰显)。
|
||||
6. **主模块页 Tab 调整**:概览 / 库 / 编辑器 / 集成。
|
||||
|
||||
### P4 — 编码与系统集成(这一版的核心价值)
|
||||
|
||||
1. **编码探测链**(§5.1)+ 状态栏显示编码/换行/只读。
|
||||
2. **切换编码**(§5.3):重解码对话框三选项、保存时不可表示字符报错、换行独立切换。
|
||||
3. **系统集成**:`Alt+E` 默认值;HKCU 右键菜单注册/卸载(文件 + 文件夹 + 目录背景),设置页按钮 + exe 路径显示 + dev 环境提示。
|
||||
4. **只读打开**与大文件降级提示。
|
||||
5. **标签页**(多文档):`Ctrl+W` / `Ctrl+Tab`、每标签独立编码与视图模式、关闭确认。
|
||||
|
||||
### P5 — 完善(本轮不做,按体感排后续优先级)
|
||||
|
||||
1. 语言包补齐:`.sh` / `.ps1` / `.toml` / `.ini` / `.dockerfile` 走 `legacy-modes`;`.scss` / `.less` 引入 `@codemirror/lang-sass`。
|
||||
2. 目录树上的文件操作完善:拖拽移动、在新窗口打开、批量重命名。
|
||||
3. Markdown 内嵌代码块高亮(`codeLanguages`,需解决 language-data 异步 vs `markdown()` 同步)。
|
||||
4. 双链图谱(数据已就绪:`editor_link_graph` 命令可用,仅缺可视化)。
|
||||
5. 会话恢复:关窗后重开恢复文档与光标位置。
|
||||
|
||||
---
|
||||
|
||||
## 9. v1 实施记录(压缩归档)
|
||||
|
||||
> 完整细节已在 v1 文档中,此处只留**结论**与**坑**——它们对 v2 仍然成立。
|
||||
|
||||
> **本节的文件名一律是 v2 目标名**。v1 代码里对应的真实路径是:
|
||||
> `src-tauri/src/notes/*.rs`、`src/modules/notes/**`、`src/stores/notesStore.ts`、
|
||||
> `src/types/notes.ts`,命令为 `notes_*`。
|
||||
|
||||
### 9.1 交付总览(v1,均已落地)
|
||||
|
||||
| 层 | 关键文件 |
|
||||
|---|---|
|
||||
| Rust 文件 IO | `editor/files.rs`(编码/换行探测、授权白名单、附件落盘) |
|
||||
| Rust 库 | `editor/library.rs`(`safe_join` 路径沙箱、扫描、增删改移) |
|
||||
| Rust 模板 | `editor/templates.rs`(4 个内置模板 + 库内覆盖 + `{{title}}`/`{{date}}`) |
|
||||
| Rust 导入导出 | `editor/import.rs`(文件/目录/zip,重名加序号、绝不覆盖)、`editor/export.rs`(整库/单目录 zip) |
|
||||
| Rust 索引 | `editor/index.rs`(SQLite + FTS5 trigram:front-matter、标签、双链、检索、片段)、`editor/index_service.rs`(单线程 worker + notify) |
|
||||
| Rust WebDAV | `editor/webdav/{client,sync}.rs`(PROPFIND/MKCOL/PUT/GET/DELETE/MOVE + 三方比对 + 冲突策略 + 改名识别)、`editor/backup.rs`(zip 快照 + 轮转 + 恢复) |
|
||||
| Rust 参数 | `editor/args.rs`(文件关联/命令行参数解析 + 待打开文件缓存) |
|
||||
| 前端内核 | `editor/core.ts`(Compartment 热重配置)、`markdownLivePreview.ts`、`languages.ts`、`themes.ts`、`keymap.ts`、`outline.ts`、`wikilink.ts`、`images.ts`、`markdownExport.ts` |
|
||||
| 前端组件 | `LibrarySidebar.vue`、`SearchPanel.vue`、`QuickOpen.vue`、`MarkdownOutline.vue`、`BacklinksPanel.vue`、`WebdavPanel.vue`、`ImportExportPanel.vue`、`NewNoteDialog.vue`、`EditorHost.vue`、`EditorToolbar.vue` |
|
||||
| 前端状态 | `stores/editorStore.ts`、`modules/editor/editorClient.ts`、`types/editor.ts` |
|
||||
| 命令 | 40 条(`notes_*` → 将统一改名为 `editor_*`) |
|
||||
|
||||
### 9.2 关键决策(v2 继续沿用)
|
||||
|
||||
- **真相是文件,索引可丢**:删掉 `editor.db` 的唯一后果是下次搜索前做一次全量扫描。
|
||||
- **索引由单线程 worker 独占**:`rusqlite::Connection` 非共享对象,而搜索命令(Tauri 线程池)、保存后的增量更新、notify 回调会并发进来;通道排队 + 专职线程换来「慢操作只排队不堵搜索」。
|
||||
- **FTS5 用 trigram**:默认 `unicode61` 把连续汉字切成一个词元,「会议」搜不到「周会议纪要」。代价是查询词 <3 字符静默返回空 → 回退 `LIKE` + Rust 侧自建片段。
|
||||
- **WebDAV 同步基线存两侧指纹**,不比 mtime(跨机时钟偏差会让「本地比远端新」两边都成立)。删除传播保守优先;同步有失败不推进基线。
|
||||
- **冲突「两侧都留」用远端 `MOVE`** 保留历史,而不是覆盖。
|
||||
- **同步/网络类命令一律 `async` + `spawn_blocking`**:`reqwest::blocking` 在 tokio 运行时线程上会 panic。
|
||||
- **HTML 导出零外链、失败关闭**:样式内联;DOMPurify 不可用时返回**空串**而不是原文。
|
||||
- **渲染链路按需 `import()`**:`markdownExport`(markdown-it + DOMPurify + highlight.js)约 1.1MB,静态引入会让模块 chunk 从 40kB 涨到 1.2MB。
|
||||
- **库外文件的路径授权白名单**:库内走 `safe_join`(根目录沙箱),库外走「用户显式打开过的绝对路径集合」。读宽松(读时登记),写严格。
|
||||
- **`from`(大纲)一律是行首偏移**:指向正文起点会让空标题没有合法取值。
|
||||
- **Live Preview 是装饰不是渲染**:只对 `view.visibleRanges` 计算(性能红线);光标行「显形」为可编辑源码。
|
||||
|
||||
### 9.3 验证状态(v1 收尾时)
|
||||
|
||||
```
|
||||
cargo check 0 warning
|
||||
cargo build 整包通过
|
||||
cargo test --lib 58 passed / 0 failed
|
||||
node --test 74 passed / 0 failed / 1 skipped(Node 无 DOM 的 XSS 断言)
|
||||
vue-tsc / eslint 通过
|
||||
vite build NotesModule 41kB(gzip 12.5) / NotesWindow 98kB(gzip 32.6)
|
||||
/ markdownExport 1.12MB(gzip 371) 按需加载
|
||||
接线核对 命令 定义=导出=注册 40/40/40,无差集
|
||||
事件 Rust 8 = TS 8,无差集
|
||||
类型 18 个结构字段名双端一一对应
|
||||
```
|
||||
|
||||
### 9.4 坑记录(跨版本有效)
|
||||
|
||||
1. **`<SelectItem>` 不能用空串 `value`**:reka-ui 把空串保留给 placeholder,会直接抛异常。用显式哨兵值(`'__all__'` / `'__current__'`)在调用点翻译。报错栈指向 `SelectItem.vue` 而不是调用方 —— 先搜 `value: ''`。
|
||||
2. **`cargo add <tauri 插件>` 会连带升级整个 tauri 依赖树**(wry / tray-icon / window-vibrancy),而 dev 启动会校验 JS 包与 crate 的 minor 是否一致。**改一边必须同时看另一边**。
|
||||
3. **不要把 `package.json` 交给 PowerShell 的 `Set-Content -Encoding UTF8`**(PS 5.1 写入 BOM),带 BOM 会让 Vite 读 PostCSS 配置直接失败。用 `node -e` 或 `UTF8Encoding($false)`。
|
||||
4. **CRLF 下反推行首偏移一律偏 1**:必须预先算 `lineStarts` 表,不要在循环里「减回去」。
|
||||
5. **front-matter 用状态机而不是布尔量**:首行 `---` 是*开头*,布尔量会在第 0 行就关掉状态,导致第 2 行的闭合 `---` 把上一行元数据提升成 Setext 标题。
|
||||
6. **`let plan = plan(...)` 会遮蔽函数名**,第二个测试起报 `E0618` 且位置离成因很远。函数名避开返回值名。
|
||||
7. **`enum` 不能出现在 `node --test` 直接跑的文件里**(Node 的 TS 支持是 strip-only)。用 `const X = {...} as const` + 类型别名。
|
||||
8. **quick-xml 0.42 的 `QName::as_ref()` 返回 `&str`**(旧版 `&[u8]`),`BytesText` 无 `decode()`;升级时只 `cargo update -p quick-xml`,避免动到 wry 链。
|
||||
9. **冷启动的文件关联事件会丢**:`setup` 里 `emit` 时 WebView 还没加载。改为存 `OnceLock<Mutex<Option<PathBuf>>>`,前端注册完监听后主动取走。
|
||||
10. **FTS5 的 `snippet()` 对「走 LIKE 回退的短词」什么都不产出**;列索引用 `-1`(让 FTS 挑最佳列)。
|
||||
|
||||
### 9.5 与 v1 规划不一致之处(保留结论)
|
||||
|
||||
| 规划 | 实际 | 原因 |
|
||||
|---|---|---|
|
||||
| 语言支持走 `language-data` 一处入口 | 手写扩展名映射表 + 逐语言 `import()` | `matchFilename` 覆盖不到 `.vue`/`.toml`/`.ps1`;手写表行为可预期 |
|
||||
| Markdown 内嵌代码块高亮 | 未做 | language-data 清单异步 vs `markdown()` 同步(见 G12) |
|
||||
| `.scss` / `.less` | 未做 | `@codemirror/lang-css` 只导出 `css()` |
|
||||
| 表格渲染 / 图片内联 | **已做**(图片走 data URL,非 asset 协议) | asset 协议要求把用户自选库根加进白名单,等于给 WebView 开任意读文件的口子 |
|
||||
| 提取 `terminal/encoding.rs` 为公共模块 | 未提取,直接复用 | 纯函数无耦合;第三个模块要用时再提取 |
|
||||
| 系统关联 | 已做文件关联;**右键菜单本轮补** | §3.6 |
|
||||
| 双链图谱 / 托盘入口 / Mermaid | 未做 | §8-P5 / §0.8 |
|
||||
|
||||
### 9.6 改名清单(P3 的执行依据)
|
||||
|
||||
| 面 | v1 | v2 | 规模 |
|
||||
|---|---|---|---|
|
||||
| 模块 id / 目录 | `notes` / `src/modules/notes/` | `editor` / `src/modules/editor/` | 10 处 |
|
||||
| 窗口 hash / label 前缀 | `#notes-window` / `notes-window-*` | `#editor-window` / `editor-window-*` | 16 处 + capability 文件名 |
|
||||
| 事件名 | `notes-settings` 等 8 个 | `editor-*` | 4 处(双端一致) |
|
||||
| Rust 命令前缀 | `notes_*`(40 条) | `editor_*` | 246 行 |
|
||||
| Rust 模块目录 | `src-tauri/src/notes/` | `src-tauri/src/editor/` | 18 处 |
|
||||
| store / client / types | `notesStore` / `notesClient` / `types/notes.ts` | `editorStore` / `editorClient` / `types/editor.ts` | 77 处 |
|
||||
| localStorage 键 | `thing_notes_recent` | 改为落 `settings.json`(不再用 localStorage) | 1 处 |
|
||||
| capability 文件 | `notes-window.json` | `editor-window.json` | 1 文件 |
|
||||
| 默认库目录 | `{appData}/notes/library` | `{appData}/editor/library` | 需迁移逻辑(见下) |
|
||||
|
||||
**迁移策略**:`{appData}/notes/` 若存在且 `{appData}/editor/` 不存在 → 启动时整目录重命名并记日志;否则各自独立。库内 `.notes/`(索引 + 同步基线)同理改 `.editor/`,并在首次打开时惰性迁移(索引可重建,丢了也无损)。
|
||||
|
||||
---
|
||||
|
||||
## 10. 决策表(已拍板,开工时按此执行)
|
||||
|
||||
> Q1–Q4 由用户于 2026-09-30 明确拍板;Q5–Q10 由本规划给出建议并**一并视为生效**(若要改,改这一行即可,不影响其它章节)。
|
||||
|
||||
| # | 决策点 | 结论 | 影响面 |
|
||||
|---|---|---|---|
|
||||
| Q1 | 模块显示名与英文 id | **`id = editor`,显示名「编辑器」**(一词式,与「终端」「下载」一致) | 模块注册、窗口标题、搜索项、改名清单 §9.6 |
|
||||
| Q2 | 是否引入「工作区」 | **不引入**。只有「笔记库根」与「当前目录根」两个单值 + 各自历史 | §3.3 侧栏只有一个目录面板;ST-4 无需 workspace 状态 |
|
||||
| Q3 | 目录树是否纳入索引 | **不纳入**。目录树只做文件名过滤;全文检索仅对笔记库可用(FTS5) | §3.4 / §4;`editor_index_*` 只处理库内 `.md` |
|
||||
| Q4 | 标签页放哪一期 | **P4**(与编码、系统集成同期) | §8-P4.5;`EditorHost` 需支持多 view 实例 |
|
||||
| Q5 | 右键菜单注册时机 | **设置页手动按钮**,默认不写注册表 | §3.6;dev 环境 exe 路径不稳定 |
|
||||
| Q6 | 目录树删除语义 | **走系统回收站**(复用 `quickpanel` 实现) | §4;与 `terminal/local_fs.rs` 同口径 |
|
||||
| Q7 | 默认编码兜底 | **`GB18030`**(探测链第 3 级) | §5.1;第 4 级人工指定兜底 |
|
||||
| Q8 | 「笔记库」这一叫法 | **保留**(库内文件仍是笔记,用户已理解该词) | §3.3 面板名「笔记库」 |
|
||||
| Q9 | 主模块页是否给「打开文件夹」入口 | **给** | §6.1 概览页行动区 |
|
||||
| Q10 | 大文件阈值 | **5MB 默认,可配**,且状态栏显式提示降级 | §3.1;`largeFileMb` 进设置 |
|
||||
|
||||
---
|
||||
|
||||
## 11. 开工清单(执行入口)
|
||||
|
||||
> 本节是「照做即可」的清单。**P3 与 P4 之间没有依赖倒置**:P3 是结构改造(改名 + 侧栏 + 目录树 + 最近记录),P4 是能力新增(编码 + 系统集成 + 标签页)。建议**严格 P3 → P4**:改名会碰到 P4 要改的每一个文件,同时做会让 diff 无法 review。
|
||||
|
||||
### 11.1 定稿参数(实现时直接用这些值,不要再另起炉灶)
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 模块 id / 显示名 / 图标 key | `editor` / `编辑器` / `editor`(`icons.ts` 映射到 `FileCode2` 或 `NotebookPen`,见下) |
|
||||
| 模块排序 `order` | **45**(沿用,排在终端 40 之后) |
|
||||
| 窗口 hash / label 前缀 | `#editor-window` / `editor-window-` |
|
||||
| 窗口查询参数 | `?file=<绝对路径>` / `?note=<库内相对路径>` / `?folder=<绝对路径>` |
|
||||
| Tauri 命令前缀 | `editor_`(40 条现有命令全部平移,P4 新增约 12 条) |
|
||||
| 事件名(8 个) | `editor-settings` / `editor-library-changed` / `editor-file-changed` / `editor-sync-progress` / `editor-new-note` / `editor-open-editor` / `editor-open-file` / `editor-open-folder`(最后一个是 P4 新增) |
|
||||
| Rust 模块目录 | `src-tauri/src/editor/` |
|
||||
| 前端目录 | `src/modules/editor/` |
|
||||
| store / client / types | `useEditorStore` / `src/modules/editor/editorClient.ts` / `src/types/editor.ts` |
|
||||
| 模块自身目录 | `{appData}/editor/`(settings.json / editor.db / library/) |
|
||||
| 库内私有目录 | `<库根>/.editor/`(`sync.json`) |
|
||||
| keyring 键 | `editor.webdav.password` |
|
||||
| 默认全局快捷键 | 打开编辑器 = **`Alt+E`**;新建笔记 = 空(可配) |
|
||||
| 默认库根 | `{appData}/editor/library` |
|
||||
| 默认编码 / 大文件阈值 | `UTF-8` 优先探测,兜底 `GB18030`;5MB |
|
||||
| 右键菜单键名 | `HKCU\Software\Classes\{*,Directory,Directory\Background}\shell\ThingEditor`,显示名 **「用 Thing 编辑器打开」** |
|
||||
| 图标 key / 组件 | key = `editor`;组件 **`FileCode2`**(已确认 `@lucide/vue` 有该图标;备选 `SquarePen` / `FileCode`)。侧栏新面板建议:目录 = `FolderTree`、最近 = `History`、抽屉 = `PanelRight` |
|
||||
|
||||
### 11.2 P3 执行顺序(每步都可独立验证 + 可提交)
|
||||
|
||||
| 步 | 内容 | 验证 |
|
||||
|---|---|---|
|
||||
| **P3-1** | 改名:Rust 侧(模块目录 `notes/` → `editor/`、40 条命令 `notes_*` → `editor_*`、`NoteSettings` → `EditorSettings` 等类型名、事件常量) | `cargo check` 0 warning;`cargo test --lib editor::` 58 passed |
|
||||
| **P3-2** | 改名:前端侧(`src/modules/notes/` → `editor/`、`notesStore` → `editorStore`、`notesClient` → `editorClient`、`types/notes.ts` → `editor.ts`、`STORAGE_KEYS`、`main.ts` 路由、capability 文件名与 `windows` glob、模块注册与图标) | `vue-tsc` / `eslint` / `vite build` 通过;模块列表里显示「编辑器」 |
|
||||
| **P3-3** | 迁移:`{appData}/notes/` → `{appData}/editor/`(启动时整目录 rename,幂等);`<库根>/.notes/` → `.editor/`(惰性,`ensure_schema` 时探测并 rename) | 手工验证:改名前留下的库仍能被打开、索引被重建 |
|
||||
| **P3-4** | 侧栏重构为 `库 / 目录 / 检索 / 最近` 四段;大纲与双链移到右侧抽屉 | 四段可切换;抽屉快捷键生效 |
|
||||
| **P3-5** | 本地目录树:Rust `editor_read_dir` / `editor_create_file` / `editor_create_folder` / `editor_rename_path` / `editor_delete_path`(回收站)+ 前端 `DirectoryPanel.vue` | 能浏览、新建、重命名、删除(进回收站)、在资源管理器中显示 |
|
||||
| **P3-6** | 最近记录:`recentFiles` / `recentFolders` 落 `settings.json`,`RecentPanel.vue`,失效项灰显 + 清空 | 打开文件/文件夹后出现在「最近」,重启后仍在 |
|
||||
| **P3-7** | 主模块页 Tab → 概览 / 库 / 编辑器 / 集成(同步并入库页) | 四页可切换,入口按钮就位 |
|
||||
|
||||
**P3 完成判据**:模块叫「编辑器」、侧栏有库与目录两个根、最近记录可用、`cargo test` 与 `node --test` 全绿、`vite build` 通过且模块 chunk 无异常膨胀。
|
||||
|
||||
### 11.3 P4 执行顺序
|
||||
|
||||
| 步 | 内容 | 验证 |
|
||||
|---|---|---|
|
||||
| **P4-1** | `FileDoc` 增 `readonly`;`files.rs` 增写权限探测(`OpenOptions::new().write(true).open()` 不写入) | 只读文件打开后状态栏显示「只读」,保存被拦并给出原因 |
|
||||
| **P4-2** | 编码探测链按 §5.1 收紧(BOM → 严格 UTF-8 → GB18030);新增 `editor_redecode_file(path, encoding)` | Rust 单测覆盖 BOM/UTF-8/GBK/UTF-16 |
|
||||
| **P4-3** | 状态栏编码与本行下拉 + 切换编码三选项对话框(§5.3)+ 保存时不可表示字符报错 | 手工:GBK 文件切 UTF-8 看到乱码→切回正常;含 emoji 存 GBK 被拦 |
|
||||
| **P4-4** | 系统集成:`Alt+E` 默认值;右键菜单注册/卸载(`winreg`,HKCU)+ 设置页「集成」Tab | 注册后资源管理器右键出现菜单项,点击能打开文件/文件夹 |
|
||||
| **P4-5** | 标签页(多文档):`Ctrl+W` / `Ctrl+Tab`、每标签独立 `encoding`/`eol`/视图模式、关闭确认 | 同时开 3 个不同编码的文件,互不串味 |
|
||||
|
||||
**P4 完成判据**:编码可探测可切换、右键菜单可用、`Alt+E` 生效、多标签可用;§9.3 的全部检查项重新跑一遍通过。
|
||||
|
||||
### 11.4 每个阶段都要跑的验证命令
|
||||
|
||||
```powershell
|
||||
# Rust
|
||||
& "C:\Users\<user>\.cargo\bin\cargo.exe" check --message-format short # 必须 0 warning
|
||||
& "C:\Users\<user>\.cargo\bin\cargo.exe" test --lib editor:: # 单测(P3-1 后模块名变了)
|
||||
# 前端
|
||||
& "C:\Program Files\nodejs\node.exe" node_modules/vue-tsc/bin/vue-tsc.js --noEmit
|
||||
& "C:\Program Files\nodejs\node.exe" node_modules/eslint/bin/eslint.js src
|
||||
& "C:\Program Files\nodejs\node.exe" node_modules/vite/bin/vite.js build
|
||||
& "C:\Program Files\nodejs\node.exe" --test src/modules/quickpanel/engine.test.ts src/lib/calc.test.ts src/lib/theme.test.ts src/modules/editor/editor/outline.test.ts
|
||||
```
|
||||
|
||||
> 注意:本机沙箱禁止直接 spawn 工作区外的可执行文件,必须用**绝对路径**调用
|
||||
> `cargo.exe` / `node.exe`(`node` 在 `C:\Program Files\nodejs\`)。
|
||||
> 新增依赖用 `bun add`,且 `$env:TEMP` 必须指向可写目录(详见 §9.4 的坑记录)。
|
||||
|
||||
### 11.5 改名核对脚本(P3-1/P3-2 完成后跑)
|
||||
|
||||
```powershell
|
||||
# 应无输出(除文档与 §9 的历史记录外)
|
||||
Select-String -Path (Get-ChildItem src,src-tauri/src,src-tauri/capabilities -Recurse -Include *.ts,*.vue,*.rs,*.json |
|
||||
ForEach-Object { $_.FullName }) -Pattern "notes_" | ForEach-Object { "$($_.Path):$($_.LineNumber)" }
|
||||
Select-String -Path (Get-ChildItem src -Recurse -Include *.ts,*.vue |
|
||||
ForEach-Object { $_.FullName }) -Pattern "notesStore|notesClient" | ForEach-Object { "$($_.Path):$($_.LineNumber)" }
|
||||
# 命令三方一致性(应 定义 = 导出 = 注册)
|
||||
# 见 §9.3 的接线核对做法:比对 commands.rs / mod.rs / lib.rs 两处
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:命名规范(v2)
|
||||
|
||||
- 模块 id:`editor`;显示名:`编辑器`;图标 key:`editor`。
|
||||
- 窗口 hash:`#editor-window`(可带 `?file=<abs path>` 或 `?note=<rel path>`);label 前缀:`editor-window`。
|
||||
- 事件名(**8 个**,与 v1 一一对应,最后一个为 P4 新增):`editor-settings` / `editor-library-changed` / `editor-file-changed` / `editor-sync-progress` / `editor-new-note` / `editor-open-editor` / `editor-open-file` / `editor-open-folder`。
|
||||
- 窗口 label 前缀:`editor-window-`(不是事件,列在此处避免与上表混淆)。
|
||||
- 前端组件:`DirectoryPanel.vue` / `RecentPanel.vue` / `EditorTabs.vue`(P4)/ `DrawerPanel.vue`(大纲与双链的容器)为 P3/P4 新增。
|
||||
- Rust 命令前缀:`editor_`;Rust 模块目录:`src-tauri/src/editor/`。
|
||||
- 前端 store:`useEditorStore`;类型文件:`src/types/editor.ts`;IPC 客户端:`src/modules/editor/editorClient.ts`。
|
||||
- 存储:`{appData}/editor/settings.json`;库内私有目录:`<库根>/.editor/`。
|
||||
- keyring 键:`editor.webdav.password`。
|
||||
|
||||
## 附录 B:能力边界(明确不做)
|
||||
|
||||
| 不做 | 理由 |
|
||||
|---|---|
|
||||
| 调试器 / 内嵌终端 / LSP 补全 / Git 集成 | 那是 IDE,与「notepad++ 式编辑器」的定位冲突;本项目终端模块已覆盖终端场景 |
|
||||
| 块编辑器(拖拽块、`/` 菜单) | 与「`.md` 文本是唯一真相」的模型不匹配(v1 已确认) |
|
||||
| 远端直连读写(把 WebDAV 当工作区) | 离线不可用、限流敏感、冲突面大(v1 已确认) |
|
||||
| 目录树全文索引 | 与「打开快」冲突(Q3) |
|
||||
| 字符频率统计式编码探测 | 短文本上比规则更不可靠(§5.1) |
|
||||
| 二进制文件编辑 | 编码/换行模型只对文本成立;识别为二进制时明确拒绝并提示用外部工具 |
|
||||
@@ -0,0 +1,667 @@
|
||||
# 音乐模块 · 本地音乐解密规划(Music Decrypt Plan)
|
||||
|
||||
> 状态:**P0 + P1a + P1c 已实施并完成真机端到端验证**(2026-09-27:网易云解密 + QQ音乐离线解密 + 文件夹批量 + musicex 在线取密钥,用真实 192kHz/24bit `.mflac` 样本跑通全链路;Rust 单测 204 项全库通过)
|
||||
> 定位:音乐模块的「本地解密」子能力,不是独立模块——挂靠 `music` 模块新增「解密」页签,Rust 侧新增 `music/decrypt/` 子模块;`ncm` 与 `qmc` 均为纯 Rust 离线引擎,QQ 按「内嵌 ekey 离线 → musicex 在线取密钥」分层(Frida 降为 P2 兜底)
|
||||
> 日期:2026-09-27(同日修订:QQ 分层重排、ncm 算法细节补全)
|
||||
> 关联文档:`AI_DEV_GUIDE.md`(模块注册 / IPC 范式——注意 specta 绑定见 `lib.rs` 的 `export_bindings()`)、`MUSIC_REMOTE_PLAN.md`(规划文档范式)
|
||||
> 参考项目与**许可分档**:
|
||||
> - `taurusxin/ncmdump`(<https://github.com/taurusxin/ncmdump>,**MIT**)——§3.1 全部算法细节的对照物,**可逐行对照**。
|
||||
> - `QQKWKG-TriMusicDecrypt`(QKKDecrypt,<https://github.com/Acooldog/QQKWKG-TriMusicDecrypt>,**GPLv3**)——只取平台矩阵与坑清单。
|
||||
> - `ownlight6/qmc-decoder`(<https://github.com/ownlight6/qmc-decoder>,**GPLv3**)——只取 QMC/musicex/ekey 的**格式与协议知识**(<https://github.com/ownlight6/qmc-decoder/blob/main/MGG_DECRYPTION_FLOW.md>)。
|
||||
> - GPLv3 两仓:**只读文档与行为,严禁抄代码**。
|
||||
|
||||
---
|
||||
|
||||
## 0. 结论先行
|
||||
|
||||
1. **范围收敛到两平台**(本轮显式指定):网易云 `.ncm` + QQ音乐 QMC 系列。酷狗/酷我明确出栈,不进任何分期。
|
||||
2. **两条技术路线,全部纯 Rust,零新增运行时依赖**:
|
||||
- ncm → **Rust 原生**(`aes 0.8` / `cbc 0.1` / `base64 0.22` 已在依赖;`ecb` crate 不在依赖树,ECB 手写 16 字节块循环,零新增 crate)。
|
||||
- QQ → **Rust 原生三层路由**(详见 §3.2):① 尾部内嵌 ekey 的文件纯离线可解;② musicex 文件读本机凭据调 `GetEVkey` API;③ 前两层都不成立才用 Frida 注入兜底。
|
||||
- **本节原有的「Frida 主链」判断已作废**:它把「需要客户端在跑」与「需要 Frida 注入」绑成了一件事。实际只有第③层需要注入,而前两层覆盖绝大多数真实文件。改分层后**不再需要便携 Python、不再需要 `pip install frida`、不再受杀软与 mangled 符号版本漂移影响**。
|
||||
3. **UI 是音乐模块第 4 个页签「解密」**:`useModuleTabs` 加一项 + `DecryptPanel.vue` + 独立轻量 store,命令与事件挂进现有 music 命令族,完全照抄下载任务的「先回 taskId、进度走事件」范式。
|
||||
4. **许可边界分三档**:`ncmdump` 是 MIT,**可逐行对照**;QKKDecrypt 与 `qmc-decoder` 是 GPLv3 + FFmpeg GPL,**只沉淀格式/协议知识与坑清单,实现逐行重写**。
|
||||
5. **工作量**:P0(网易云 + 页签全链路)约 **2 个工作日**;P1a(QQ 离线 + API,纯 Rust)约 **2~3 个工作日**;P1b(Frida 兜底,按需)另计。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph FE["前端 · 解密页签"]
|
||||
A["DecryptPanel.vue<br/>文件选择 / 任务列表 / 状态卡"]
|
||||
S["decryptStore.ts<br/>任务状态 + 事件监听"]
|
||||
end
|
||||
subgraph R["Rust · music/decrypt/"]
|
||||
C["commands.rs<br/>run / cancel"]
|
||||
N["ncm.rs<br/>网易云离线引擎"]
|
||||
Q["qq.rs<br/>QMC 三层路由(P1)"]
|
||||
end
|
||||
subgraph QQS["QQ 三层(P1)"]
|
||||
L1["① 尾部内嵌 ekey<br/>纯离线"]
|
||||
L2["② musicex → 本机凭据<br/>GetEVkey API"]
|
||||
L3["③ Frida 兜底<br/>(P1b,按需)"]
|
||||
end
|
||||
O["savedir/decrypted/"]
|
||||
A --> S --> C
|
||||
C --> N --> O
|
||||
C --> Q --> L1 --> O
|
||||
Q --> L2 --> O
|
||||
Q -.-> L3 -.-> O
|
||||
Q -.->|"music-decrypt-event"| S
|
||||
N -.-> S
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 1. 需求解构
|
||||
|
||||
| 用户原话 | 解构 | 落点 |
|
||||
|---|---|---|
|
||||
| 在音乐模块添加解密 Tabs | 音乐模块第 4 个页签 | §5.2 |
|
||||
| 解密各平台的加密格式 | 收敛为 QQ音乐 + 网易云(本轮显式指定) | §3 |
|
||||
| 最小路径实现 | 砍掉:转码、元数据回填、封面提取、拖拽、酷狗酷我、并发调优、历史持久化 | §7 P2 清单 |
|
||||
| 可参考 QKKDecrypt | 对齐思路与坑,不搬 GPLv3 代码 | §3.3 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 现状勘察(2026-09-27 从仓库实际读取)
|
||||
|
||||
### 2.1 已具备的基建(直接复用)
|
||||
|
||||
| 能力 | 现有实现 | 复用方式 |
|
||||
|---|---|---|
|
||||
| Tab 体系 | `useModuleTabs`(`MusicModule.vue:78`,alwaysVisible 模式,标题栏浮动切换器自动接管) | 加 `{ value: 'decrypt', label: '解密' }` 一项 |
|
||||
| 任务 + 事件范式 | `music_download` / `music-download-event`(`commands.rs:187`、`constants.rs:107`) | 解密照抄:先回 taskId,进度推事件 |
|
||||
| 便携 Python + pip 镜像 | `runtime.rs`(清华源 `PIP_INDEX_URL`,`mod.rs:77`) | QQ sidecar 的 frida 安装、Python 就绪检查 |
|
||||
| 加密依赖 | `Cargo.toml` 已有 `aes = "0.8"`、`cbc = "0.1"`、`base64 = "0.22"` | ncm 的 AES-128-ECB 手写循环,零新增依赖 |
|
||||
| specta 绑定 | `lib.rs export_bindings()` 两处 `collect_commands!` | 新命令两处同步登记(`lib.rs:300` 注释明确要求) |
|
||||
| 文件选择对话框 | `@tauri-apps/plugin-dialog`(`MusicModule.vue:4` 已 import) | 页签内直接用,不加 Rust 命令 |
|
||||
| 输出目录 | 默认 `savedir`(设置页「本地下载目录」) | 解密默认输出 `savedir/decrypted/` |
|
||||
| 播放引擎 | symphonia(`Cargo.toml:115`) | 解出的 flac/mp3/ogg 可直接进曲库试听 |
|
||||
|
||||
### 2.2 关键缺口(需新增)
|
||||
|
||||
| 缺口 | 说明 |
|
||||
|---|---|
|
||||
| ncm 解密实现 | 纯算法,约 200 行 + 单测 |
|
||||
| QQ 运行期 sidecar | Frida 注入 + `EncAndDesMediaFile` 调用序列,按参考思路重写 |
|
||||
| 解密任务 store | 下载任务在 `musicStore`;解密需独立轻量 store(页签切换会卸载组件,监听器必须挂 store) |
|
||||
| frida 依赖安装 | `pip install frida`(wheel 带原生扩展,走现有镜像),需一条安装命令 + 进度事件 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 技术选型
|
||||
|
||||
### 3.1 网易云 `.ncm`:Rust 原生离线
|
||||
|
||||
**为什么不进 Python**:
|
||||
|
||||
- ncm 是纯文件级算法,不需要任何进程配合;塞进 Python 等于把 200 行算法绑上「必须先装运行时」的前置。
|
||||
- 便携 Python 是按需安装(musicdl 才触发),解密不应被它卡住——Rust 路线开箱即用。
|
||||
- Rust 侧可直接 `cargo test`,对照样本文件做回归。
|
||||
|
||||
**算法要点**(对照 MIT 协议的 `ncmdump`(`src/ncmcrypt.cpp`)逐条独立重写。下面每一条都是**会写错的地方**,不是梗概):
|
||||
|
||||
**① 容器结构**
|
||||
|
||||
```
|
||||
0x00 magic 8B "CTENFDAM"(即 43 54 45 4E 46 44 41 4D)
|
||||
0x08 2B 0x02 0x00 → 跳过
|
||||
0x0A key_len 4B LE
|
||||
0x0E key_data key_len B (XOR 0x64 → AES-128-ECB → 得 RC4 密钥盒种子)
|
||||
... meta_len 4B LE
|
||||
... meta_data meta_len B (XOR 0x63 → 去 22B 前缀 → base64 → AES-128-ECB → 去 6B 前缀 → JSON)
|
||||
... 5B 跳过(CRC32 4B + 图片版本 1B)
|
||||
... cover_len 4B LE
|
||||
... img_len 4B LE
|
||||
... img_data img_len B (内嵌封面:PNG 或 JPEG)
|
||||
... 跳 cover_len - img_len
|
||||
... audio 剩余全部 (改性 RC4)
|
||||
```
|
||||
|
||||
**② 两个 XOR 常量不同**(原文档误合并成一个 `0x64`)
|
||||
|
||||
| 段 | XOR 常量 | 加密方式 | 解密后处理 |
|
||||
|---|---|---|---|
|
||||
| key 段 | `0x64` | AES-128-ECB | **跳过前 17 字节**(`neteasecloudmusic`),其余即 RC4 密钥盒种子 |
|
||||
| meta 段 | `0x63` | AES-128-ECB(先 base64 解码) | 跳过前 6 字节(`music:`),其余为 JSON |
|
||||
|
||||
**③ AES-128-ECB 解密**:**key 段与 meta 段用两个不同的 16 字节密钥**——`sCoreKey` = ASCII `neteasecloudmusi`(即 17 字节前缀 `neteasecloudmusic\0` 的前 16 字节)、`sModifyKey` = ASCII `#14ljk_!\]&0U<'(`。**收尾不是"去前缀",而是 PKCS#7 风格 padding**:逐 16 字节块解密,最后一字节即 padding 长度(`> 16` 时视作 0),去掉 padding 后再手动跳前缀。
|
||||
|
||||
> 易错点:**「AES 密钥」与「要剥掉的前缀」是两个东西**。`neteasecloudmusic` 既是被剥的 17 字节前缀(含结尾 NUL),其前 16 字节又是 key 段的 AES 密钥;meta 段则两者都不同。混用不报错、只会全解错(实现里分别命名为 `CORE_KEY` / `CORE_AES_KEY` / `MODIFY_KEY`)。
|
||||
|
||||
**④ meta 段的两层前缀**:原始数据前 22 字节是字面量 `163 key(Don't modify):`,**先剥掉它**,再对余下部分 base64 解码,才喂给 AES。
|
||||
|
||||
**⑤ 音频段是「改性 RC4」**
|
||||
|
||||
- 密钥盒用参考实现的 KSA:`swap = keybox[i]`;`c = (swap + last_byte + key[key_offset]) & 0xff`,`key_offset` 触 keyLen 归零循环取 key,`keybox[i] = keybox[c]`、`keybox[c] = swap`、`last_byte = c`。**照抄即可,但注意 `last_byte` 在模 256 下是恒等变形(结果与标准 RC4 逐字节相同),它既不是"关键差异",也不能作为验证手段**——见 §6.25。
|
||||
- 明文按 `0x8000` 字节一块循环,块内 `j = (i + 1) & 0xff`,`plain[i] = cipher[i] ^ keybox[(keybox[(keybox[j] + j) & 0xff] + keybox[j]) & 0xff]`。块之间不重置密钥盒、也不额外跳字节——`i` 是块内下标。
|
||||
- **块边界必须由"读满一块"确定**(`read_full`),不能用 `Read::read` 的短读结果,否则相位错位、中途变噪声(§6.24)。
|
||||
- **不存在"每 0x8000 字节后跳过 5 字节间隔"**(原文档此条有误)。`0x8000` 是块大小,`5` 是 §① 里跳过的 CRC32 + 图片版本。
|
||||
|
||||
**⑥ 输出扩展名由音频首帧魔数决定,不是 meta 的 `format` 字段**(原文档此条说反了):首个解密块以 `ID3`(`0x49 0x44 0x33`)开头 → `.mp3`,否则 → `.flac`。meta 的 `format` 只用于另一件事——**判断该不该回填标签/封面时的格式分支**。
|
||||
|
||||
**⑦ 顺手可得的元数据**:meta JSON 含 `musicName` / `artist`(二维数组,取每项第 0 个元素并用 `/` 连接)/ `album` / `bitrate` / `duration`,且封面字节已在上面的 `img_data` 里读出。**P0 已实现封面单独落盘**(`<歌名>.cover.png|jpg`,按魔数定扩展名);**写进音频标签**仍留 P2——那需要 `lofty` 且要按 mp3/flac/m4a 分派容器,属于「增强」而非「能播」。
|
||||
|
||||
**⑧ 失败处理**:魔数不符 / `key_len <= 0` / 块不足 16 字节 → 返回可读错误(`Err(String)`),**per-file 失败不 panic、不中断整批**。
|
||||
|
||||
### 3.2 QQ音乐:Rust 原生三层路由(**本节已重写**)
|
||||
|
||||
**原判断作废的理由**:原文把「需要 QQ 客户端在跑」与「需要 Frida 注入」绑成了一件事。二者其实独立——ekey(解密密钥)有三种存储形态,只有第三种才需要注入。前两层覆盖真实曲库的绝大多数文件,且都是纯 Rust。
|
||||
|
||||
**QMC 加密本体**(与 ncm 同构:字节流密码 + 可选密钥):
|
||||
|
||||
| 方案 | 密钥来源 | 适用 |
|
||||
|---|---|---|
|
||||
| QMC1 | 固定种子,**无需密钥** | 旧版 `.qmc0` / `.qmc3` / `.qmcflac` / `.qmcogg` |
|
||||
| QMC2 | ekey(base64 + TC-TEA 加密),密钥 ≤300B 走 Map XOR,>300B 走改性 RC4 | `.mgg` / `.mflac` 全系 |
|
||||
|
||||
**ekey 的三种存储形态 → 三层路由**:
|
||||
|
||||
| 层 | 形态 | 需要客户端? | 实现方式 |
|
||||
|---|---|---|---|
|
||||
| **①** | **尾部内嵌 ekey**:QTag 格式(ekey + 歌曲 ID + `QTag` 魔术)或 V1 格式(文件末尾 4 字节为 key 长度,key 在其前) | ❌ 不需要 | **纯 Rust 离线**,从文件尾直接提取 |
|
||||
| **②** | **musicex 尾部**(QQ 客户端 ≥ 19.57 / Win 22.x):尾部 192B 只存 song_id + media_mid + filename,**ekey 不落盘** | ✅ 需运行且已登录 | **纯 Rust**:读凭据 → 调 API 取 ekey |
|
||||
| **③** | 客户端内部导出(方案原文所选) | ✅ | Python sidecar + Frida attach `QQMusicCommon.dll` |
|
||||
|
||||
**第②层的完整链路**(全部可在 Rust 内完成,`windows-sys` 只差一个 feature):
|
||||
|
||||
1. 尾部检测:读末 8 字节,为 `"musicex\0"` 即 musicex;再向前读 `footer_size + 8` 解析完整 footer(`0x00` song_id u32LE、`0x0C` media_mid UTF-16LE 60B、`0x48` filename UTF-16LE 68B、`0xC0` footer_size、`0xC8` magic)。
|
||||
2. 取 `uin`:读 `%APPDATA%\Tencent\QQMusic\QQMusicServiceConfig.ini` 的 `[Account] Uin`(明文 INI)。
|
||||
3. 取 `authst`:**`authst` 在 Windows 上不落盘**,仅在运行中的 `QQMusic.exe` 进程内存里。用 `CreateToolhelp32Snapshot` + `Process32FirstW/NextW` 定位进程 → `OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ)` → `VirtualQueryEx` 遍历可读区(只需 `MEM_COMMIT`,跳过 `MEM_MAPPED`)→ `ReadProcessMemory` 按 1MB 分块 → 搜 `"authst":"` 取其后 Base64URL 串。实测约 0.5 秒。
|
||||
4. 调 API:`POST https://u.y.qq.com/cgi-bin/musicu.fcg`,`req_1.module = "music.vkey.GetEVkey"`、`method = "CgiGetEVkey"`;`param.filename` **必须带 `.mgg`/`.mflac` 后缀**、`param.songtype` **必须为 1**(否则返回 `104005`)、`param.platform = "27"`(Windows)。响应取 `req_1.data.midurlinfo[0].ekey`。
|
||||
|
||||
> 三处易错点:`MEMORY_BASIC_INFORMATION` 在 Win10 1803+ 有 2 字节 `PartitionId` 插在 `AllocationProtect` 与 `RegionSize` 之间,**漏掉会导致 `state` 读成 `protect`、所有内存区被跳过**;`filename` 不带扩展名返回空 ekey;`authst` 有效期约 22.3 小时会过期。
|
||||
|
||||
**前置检查与降级出口**(UI 状态卡据此渲染):QQ 未运行或未登录 → 提示"请启动并登录 QQ 音乐后重试";层①②均失败的文件才落到③;Frida 不可用时报可读错误并给排除指引,**不自动拉起 QQ 客户端**。
|
||||
|
||||
**③(P1b,按需)的形态**若将来要做:`qq_decrypt.py` 走 `include_str!` 内置(与 `bridge.rs:17` 的 `BRIDGE_SCRIPT` 同范式),一次进程 attach 一批文件,stdout JSON-Lines 回报进度;导出符号是 mangled name(`?Open@EncAndDesMediaFile@@…`),**按子串 `EncAndDesMediaFile` 模糊匹配,严禁硬编码地址或 RVA**。
|
||||
|
||||
**输出扩展名**(不能按输入扩展名机械映射):`.qmc0`→`.mp3`、`.qmc3`→`.mp3`、`.qmc2`→`.ogg`、`.qmcogg`→`.ogg`、`.qmcflac`→`.flac`、`.mgg`/`.mgg0`/`.mgg1`/`.mggl`→`.ogg`、`.mflac`/`.mflac0`/`.mflach`→`.flac`(均以首帧魔数兜底校验)。**`.mmp4` 的产物容器(m4a 还是 mp4)尚未独立证实,实施 P1 时必须用真机样本确认后再定**。
|
||||
|
||||
### 3.3 许可边界(必须遵守,三档口径)
|
||||
|
||||
- **MIT(可逐行对照)**:`taurusxin/ncmdump`(网易云 ncm 算法本体)。可直接对照 `src/ncmcrypt.cpp` 实现,仅需保留版权声明。
|
||||
- **GPLv3(只读文档与行为,严禁抄代码)**:`QQKWKG-TriMusicDecrypt`(+ FFmpeg GPL)、`ownlight6/qmc-decoder`。**整段搬代码 = 给本仓库引入 GPL 传染。** 允许的是:阅读其调用序列、常量、格式与协议说明后**独立重写**——本文档 §3.1 / §3.2 沉淀的正是这类非代码知识。
|
||||
- **合规口径**(UI 底部放一行):仅处理用户本人拥有合法访问权限的本地文件,不用于批量分发或规避付费授权。
|
||||
|
||||
---
|
||||
|
||||
## 4. 接口契约
|
||||
|
||||
### 4.1 Tauri 命令
|
||||
|
||||
```rust
|
||||
// 任务
|
||||
music_decrypt_run(task_id, files?, folder?, root?, out_dir?, in_place?) -> Result<(), String>
|
||||
music_decrypt_cancel(task_id: String) -> Result<bool, String>
|
||||
// 预览与状态
|
||||
music_decrypt_scan(folder: String, root: Option<String>) -> Result<ScanSummary, String>
|
||||
music_decrypt_qq_status() -> Result<QqOnlineStatus, String> // 只读本机,不发网络请求
|
||||
```
|
||||
|
||||
`QqOnlineStatus` 字段:`{ running, loggedIn, uin, ready, message, steps }`。
|
||||
**`authst` 不下发到前端**——它只活在后端内存里用于调接口。
|
||||
|
||||
- **注册是 3 处,不是 2 处**(实测仓库现状):
|
||||
1. `music/mod.rs` 的 `pub use commands::{...}` re-export(约 `mod.rs:48`);
|
||||
2. `lib.rs` 的 `collect_commands![]`(`export_bindings()` 内,`lib.rs:205`);
|
||||
3. `lib.rs` 的 `generate_handler![]`(`run()` 内,`lib.rs:348`)。
|
||||
漏第 2 处 = 运行时能调但 `bindings.ts` 缺类型;漏第 1、3 处 = 编译失败或调用失败。
|
||||
- 前端沿用本模块既有范式(`musicStore.ts` 全用原生 `invoke` + 手写类型,不用 `commands`),故解密 store 同样用 `invoke`。
|
||||
|
||||
### 4.2 事件 `music-decrypt-event`(登记进 `constants.rs` 音乐分组)
|
||||
|
||||
```typescript
|
||||
type MusicDecryptEvent = // 注意:只有 tag 是 kebab-case,**字段名仍是 snake_case**
|
||||
| { type: 'start'; task_id: string; total: number }
|
||||
| { type: 'file'; task_id: string; index: number; name: string;
|
||||
status: 'ok' | 'error' | 'unsupported';
|
||||
message: string | null; // 失败原因,或成功时的备注(平台 / 密钥形态 / 元数据摘要)
|
||||
output: string | null; // 主产物
|
||||
cover: string | null } // 单独落盘的封面(网易云带内嵌封面时才有)
|
||||
| { type: 'progress'; task_id: string; done: number; total: number;
|
||||
bytes_done: number; bytes_total: number; name: string }
|
||||
| { type: 'finished'; task_id: string; ok: number; failed: number; cancelled: number }
|
||||
```
|
||||
|
||||
> **字段名是 snake_case 而非 camelCase**:`DecryptEvent` 上只有 `#[serde(tag = "type", rename_all = "kebab-case")]`
|
||||
> 作用在 tag 上,变体字段名原样输出。前端 `decryptStore.ts` 的 `RawEvent` 必须照此声明
|
||||
> ——两边不一致时不会编译报错,只会表现为「任务建好了但进度永不动」。
|
||||
> Rust 侧有 `event_json_contract` 单测把形状钉死(§6.23)。
|
||||
>
|
||||
> 结果态没有 `already`:P0 不做「已解密过则跳过」(同一文件重解会产出 `_1` 后缀的新文件),
|
||||
> 语义比"猜哪份产物属于哪次输入"更可预测。
|
||||
|
||||
> 原先的 `deps-install` 事件随 `music_decrypt_install_deps` 一起取消——三层路由后不再需要 `pip install frida`。
|
||||
> 注意前端 `musicStore.ts:419` 是**硬编码事件名字符串**、并未引用前端常量表,故解密 store 同样硬编码,仅 Rust 侧登记常量。
|
||||
|
||||
### 4.3 文件识别(用户不选平台)
|
||||
|
||||
按扩展名路由,魔数校验兜底:
|
||||
|
||||
| 扩展名 | 路线 |
|
||||
|---|---|
|
||||
| `.ncm` | 网易云离线引擎(按内容魔数识别,不依赖后缀) |
|
||||
| `.mgg` / `.mgg0` / `.mgg1` / `.mggl` / `.mflac` / `.mflac0` / `.mflach` / `.mmp4` / `.qmc0` / `.qmc2` / `.qmc3` / `.qmcflac` / `.qmcogg` | QQ 引擎(按尾部形态决定是否联网) |
|
||||
| 其他 | 散选时保留为 `unsupported`;文件夹扫描时直接跳过 |
|
||||
|
||||
> 后缀矩阵原文档只列了 3 个,会**静默漏掉用户曲库里的常见文件**,故过滤列表与路由表**一次写全**。
|
||||
> 实际判定以**内容**为准(§4.5),后缀只用于文件对话框的过滤器。
|
||||
|
||||
### 4.3.1 QQ 音乐:是否需要登录?
|
||||
|
||||
这是使用者最常问的一点,所以结论放在前面:
|
||||
|
||||
| 文件来源 | 扩展名 | 需要 QQ 音乐登录? |
|
||||
|---|---|---|
|
||||
| QQ 客户端 **≤ 19.51** 下载 | `.qmc0` `.qmc3` `.qmcflac` `.qmcogg` | **不需要** |
|
||||
| QQ 客户端较旧版本下载(QTag / V1 尾部) | `.mgg` `.mflac` | **不需要** |
|
||||
| QQ 客户端 **≥ 19.57** 下载(musicex 尾部) | `.mgg` `.mflac` `.mmp4` | **需要**:客户端运行 + 已登录 |
|
||||
| 网易云(任何版本) | `.ncm` | **不需要** |
|
||||
|
||||
**为什么新版必须登录**:从 19.57 起,QQ 音乐不再把解密密钥(ekey)写进文件,
|
||||
只在文件末尾留 192 字节元数据;客户端自己也是在播放/下载时拿本机登录态
|
||||
(`uin` + `authst`)向服务器实时换取密钥。第三方要解开同一个文件,只能复刻这一步。
|
||||
|
||||
**这里的实现方式**:只读本机凭据(INI 里的 `uin` + 运行中 `QQMusic.exe` 内存里的 `authst`),
|
||||
再调官方 `music.vkey.GetEVkey` 接口取密钥——**不注入进程、不改写文件、不做任何反检测**。
|
||||
|
||||
**操作步骤**(与 UI 状态卡里的文案一致):
|
||||
|
||||
1. 在电脑上启动 QQ 音乐客户端(Windows 版)。
|
||||
2. 用它登录你的账号,并**保持客户端开着**(`authst` 只存在于运行期内存)。
|
||||
3. 回到「解密」页点「重新检测」,状态变为「已就绪」即可解密 musicex 文件。
|
||||
4. 若提示未取到登录令牌:先在客户端里**播放任意一首歌**触发一次网络请求,再重新检测。
|
||||
5. 仍失败则试过**以管理员身份运行**本应用(读其他进程内存可能需要更高权限)。
|
||||
6. 登录令牌约 **22.3 小时**过期;过期后重新检测即可,无需重装。
|
||||
|
||||
**UI 呈现**:状态卡显示三态(未运行 / 未登录 / 已就绪)+ QQ 号 + 「重新检测」按钮;
|
||||
未就绪时折叠区里就是上面这 6 条步骤。上方那句"旧版文件与 `.ncm` 本来就不需要登录"
|
||||
也会一并显示,避免用户误以为自己必须登录才能用这个功能。
|
||||
|
||||
### 4.4 输出路径规则
|
||||
|
||||
- **就地模式(`in_place = true`,文件夹批量的默认)**:产物与源文件**同目录同名**,
|
||||
仅按格式改扩展名(`Pop/a.mflac` → `Pop/a.flac`)。符合"就地解出来"的直觉,
|
||||
也天然不会与其他目录的同名文件冲突。此时 `out_dir` 不参与写盘。
|
||||
- **指定输出目录(`in_place = false`)**:默认根目录 `savedir/decrypted/`,
|
||||
并**按 `root` 还原相对目录结构**(`Pop/2026/b.ncm` → `out/Pop/2026/b.flac`)。
|
||||
散选文件没有相对目录,平铺到根目录。
|
||||
- **同名去重**:即使还原了目录结构,同一目录内仍可能撞名(如 `.mgg` 与 `.mgg1` 同基名)。
|
||||
规则:优先用原名,已存在(磁盘上或本批内已占位)则追加 `_1` / `_2`…
|
||||
- **输入输出相交保护**:非就地模式下,若某输入文件已位于输出目录内则剔除,
|
||||
避免"解出来再解"无限膨胀;全被剔除时报错并提示可改用「就地解密」。
|
||||
- 扩展名以**音频首帧魔数**决定(ncm 见 §3.1⑥,QMC 见 §3.2 末),不信任输入扩展名;
|
||||
魔数认不出时才回退到输入后缀映射。
|
||||
|
||||
### 4.5 文件夹批量
|
||||
|
||||
命令参数的关系:
|
||||
|
||||
| 参数 | 含义 |
|
||||
|---|---|
|
||||
| `folder` | **文件夹批量入口**:Rust 侧递归扫描该目录 |
|
||||
| `root` | 计算相对路径的基准(决定输出目录里还原哪几层) |
|
||||
| `files` | 散选文件列表(`folder` 为空时使用) |
|
||||
| `in_place` | 就地解密(默认 `true`,见 §4.4) |
|
||||
| `music_decrypt_scan` | 只扫描不解密,返回 `{ total, ncm, qmc }` 供 UI 预览 |
|
||||
|
||||
**平台判定按内容,不按后缀**(`scan::route`):
|
||||
|
||||
1. 读 8 字节魔数,命中 `CTENFDAM` → 网易云;
|
||||
2. 否则读尾部判 QMC 形态:后缀在 QMC 家族里 → QQ音乐;
|
||||
3. 后缀不认识时,只有**明确**的尾部形态(QTag / V1 / musicex)才认领——
|
||||
否则任何末尾凑巧不是 `QTag` 的文件都会被判成"QMC1",噪声太大。
|
||||
|
||||
理由:同一曲库里 `.ncm` / `.mflac` / `.qmcflac` / `.mgg` 混放是常态,且 QQ 还有
|
||||
`.mgg0` / `.mflac0` 等变体,靠后缀枚举必然漏。代价是**认不出的文件会被跳过**,
|
||||
所以扫描数可能少于用户预期——因此 UI 先调 `music_decrypt_scan` 显示
|
||||
"找到 N 个 · 网易云 x · QQ音乐 y",让用户在开跑前就能判断是否符合预期。
|
||||
|
||||
---
|
||||
|
||||
## 5. 架构与模块设计
|
||||
|
||||
### 5.1 Rust 侧 `src-tauri/src/music/decrypt/`(已实施的实际结构)
|
||||
|
||||
```
|
||||
decrypt/
|
||||
mod.rs // 任务表(Mutex<HashMap<taskId, 取消标志>>)、工作线程 + 节流事件转发、事件契约
|
||||
common.rs // 两引擎公共件:DecryptError、魔数定格式、同名去重、读满一块
|
||||
ncm.rs // 网易云离线引擎(AES-ECB + RC4 变体 + meta/封面)
|
||||
qmc.rs // QQ:QMC1 静态密钥 / QMC2 Map / QMC2 RC4 / tc_tea / 尾部形态 + 流密码
|
||||
qq_footer.rs // musicex 尾部解析(纯,可单测)
|
||||
qq_credentials.rs // 凭据:INI 解析(纯)+ 进程内存取 authst(平台胶水)
|
||||
qq_memscan.rs // Windows 专用:ToolHelp 枚举进程 + VirtualQueryEx/ReadProcessMemory(只读)
|
||||
qq_ekey.rs // GetEVkey 请求组装与响应解析(纯,可单测)
|
||||
qq_online.rs // 编排:musicex → 凭据 → 取密钥 → 解密;probe_status()
|
||||
scan.rs // 文件夹递归扫描 + 内容优先的平台路由
|
||||
commands.rs // run / cancel / scan / qq_status(四条命令)
|
||||
```
|
||||
|
||||
平台判定与密钥来源的**分工**:`scan.rs` 只决定"这文件归哪个引擎";
|
||||
`qmc.rs` 决定"密钥从哪来"(内嵌 / 静态);只有尾部是 musicex 时,
|
||||
调度层才把 `KeyRequired` 交给 `qq_online.rs` 转在线路径——这样离线路径保持零网络依赖。
|
||||
|
||||
`mod.rs` 挂到 `music/mod.rs` 的子模块列表;事件常量加进 `constants.rs` 音乐分组。
|
||||
|
||||
### 5.2 前端
|
||||
|
||||
```
|
||||
src/modules/music/components/DecryptPanel.vue // 页签内容
|
||||
src/stores/decryptStore.ts // 任务列表 + 事件监听(照 musicUploadStore 范式)
|
||||
MusicModule.vue // tabs 加一项 + <TabsContent value="decrypt">
|
||||
index.ts // searchItems 加「音乐解密」(tab: 'decrypt')
|
||||
```
|
||||
|
||||
**P0 / P1a / P1c UI 形态**(已实施):
|
||||
|
||||
- 顶部操作行:**选择文件夹** | 选择文件(dialog 多选,按 §4.3 全后缀过滤)| **就地解密开关** | 取消 / 清空记录
|
||||
- **QQ 音乐在线解密状态卡**:状态点(三态)+ 一句话状态 + QQ 号 + **重新检测** + 折叠的**操作步骤**;
|
||||
未就绪时折叠区里就是 §4.3.1 那 6 条,并附一句"旧版文件与 `.ncm` 本来就不需要登录"
|
||||
- 输出目录行:就地模式下置灰并显示"与源文件同目录"
|
||||
- **文件夹扫描预览条**:显示"找到 N 个 · 网易云 x · QQ音乐 y" + 开始解密按钮
|
||||
- 中部任务表:任务头(文件夹路径 / 进度条 / `bytes_done/bytes_total` / 打开产物目录)|
|
||||
文件行(文件名 | 平台徽标 | 状态徽章 | 打开产物目录 | 打开封面 | 备注或失败原因)
|
||||
- 空态用 `StateBlock variant="empty"`;进度条结构恒定(完成后保留满格,不整块消失)
|
||||
- 底部一行合规说明
|
||||
|
||||
### 5.3 数据流
|
||||
|
||||
与下载链路同构:前端 → `music_decrypt_run` → Rust 建 taskId 即回 → 后台执行 → `music-decrypt-event` → `decryptStore` 更新 → 列表刷新。页签切换组件卸载不影响任务(监听在 store)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 关键实现细节与已知的坑
|
||||
|
||||
**ncm**(编号对应 §3.1 的条目号)
|
||||
|
||||
1. `aes 0.8` 只有块原语、`ecb` crate 不在依赖树:ECB 手写 16 字节块循环(`cipher::BlockDecrypt::decrypt_block`)。**不要**为此引入 `ecb` crate。
|
||||
2. **两段 XOR 常量不同**(`0x64` key / `0x63` meta)。照抄成同一个常量 = 必然失败。
|
||||
3. **PKCS#7 风格 padding**:AES-ECB 收尾取最后一字节为 padding 长度(`> 16` 视作 0),不是“去前缀”。
|
||||
4. **改性 RC4 KSA 的 `last_byte` 累加**(照抄参考实现即可,但别误解它):
|
||||
式子 `c = (swap + last_byte + key[key_offset]) & 0xff` 在模 256 下**恰好化简为标准 RC4**,
|
||||
实测两者密钥盒逐字节相同(256/256)。因此它**不是**"与标准 RC4 的关键差异",
|
||||
也不能靠与标准 RC4 比对来验证实现——验证只能靠固定向量(见 §6.25)。
|
||||
`key_offset` 触 keyLen 归零循环取 key 这一点照抄。
|
||||
5. **音频块之间不跳字节**,`0x8000` 只是块大小;`i` 是块内下标。原文档的"每 0x8000 跳过 5 字节"是错的(那 5 字节在 §① 的头部里,且已单独处理)。**但块边界必须由"读满一块"确定**,不能用 `Read::read` 的短读结果(见 §6.24)。
|
||||
6. **输出扩展名看音频首帧魔数**(`ID3` → `.mp3`,否则 `.flac`),不看 meta 的 `format`。
|
||||
实现比这条更宽一点:还识别 `fLaC` / `OggS` / `RIFF..WAVE` / `ftyp` / `wvpk`,
|
||||
给 P1 的 QQ 产物复用(ncmdump 的兜底同为 flac)。
|
||||
7. meta 段是**两层前缀**:先剥 22 字节 `163 key(Don't modify):`,再 base64,再 AES,再剥 6 字节 `music:`。
|
||||
8. **流式处理**:`0x8000` 块逐块读→解→写,禁止整文件读入内存(`.mmp4` 可能很大)。大文件下需按已处理字节数推 `progress`。
|
||||
9. **单测不依赖真实样本**:真实 FLAC 最小样本进不了仓库。改为对**中间产物**断言——AES-ECB 往返、KSA 密钥盒已知值、padding 剥离、魔数→扩展名判定、以及"自造一个合法 ncm 容器(用同一套算法正向构造)再解回来"的往返测试。真机样本走手动自测。
|
||||
10. 魔数/解析失败走 per-file `Err`,**不 panic、不中断整批**。
|
||||
|
||||
**QQ(P1)**
|
||||
|
||||
11. 第①层(QTag / V1)**完全离线**,不要因为"QQ 文件"就先去连客户端——先用尾部分支判形态再决定要不要读凭据。
|
||||
12. 第②层的 `authst` **只在 `QQMusic.exe` 运行期内存里**,不落盘;`uin` 在 `QQMusicServiceConfig.ini` 可明文读。`MEMORY_BASIC_INFORMATION` 的 2 字节 `PartitionId`(Win10 1803+)**必须包含**,否则 `state` 会读成 `protect`、所有内存区被跳过。
|
||||
13. API 三处必须:`filename` 带 `.mgg`/`.mflac` 后缀、`songtype = 1`、`module = music.vkey.GetEVkey`(不是 `GetVkey`)。否则 `104005` 或 ekey 为空。
|
||||
14. `authst` 约 22.3 小时过期:失败文案要给"重新登录 QQ 音乐"的出口,而不是只报网络错误。
|
||||
15. 第③层(Frida):必须**先启动 QQ 音乐**再 attach,`QQMusicCommon.dll` 打开主界面即加载;导出符号是 mangled name,**按子串 `EncAndDesMediaFile` 模糊匹配,严禁硬编码地址或 RVA**;被杀软拦截只给排除指引,**不做反检测动作**;批量时客户端 UI 可能短暂卡顿,属预期。
|
||||
16. `path_sensitive_mflac` 变体(同名文件不同目录内容不同)P1 不处理:报错带全路径,遇到再迭代。
|
||||
17. `.mmp4` 产物容器未证实,P1 先用真机样本确认再定(见 §3.2 末)。
|
||||
|
||||
**工程**
|
||||
|
||||
18. 新命令登记 **3 处**:`music/mod.rs` re-export、`lib.rs` 的 `collect_commands![]`、`lib.rs` 的 `generate_handler![]`(见 §4.1)。
|
||||
19. `music-decrypt-event` 常量进 `constants.rs` 音乐分组;前端沿用硬编码字符串(与 `musicStore.ts:419` 一致)。
|
||||
20. 解密 store 必须独立于组件生命周期:Tabs 非 active 会卸载内容,事件监听挂 store 不挂组件。
|
||||
21. **输出同名去重 + 输入输出相交保护**(见 §4.4)——原文档缺失,不做会静默覆盖用户文件。
|
||||
22. 三层路由后**不再需要便携 Python 与 frida**,`music_decrypt_install_deps` 命令取消;QQ 未登录的错误出口走状态卡提示。
|
||||
|
||||
**实施中新增确认的坑(2026-09-27 实测)**
|
||||
|
||||
23. **事件字段名是 snake_case**(不是 camelCase)。`#[serde(tag = ..., rename_all = "kebab-case")]`
|
||||
只作用于 tag,变体字段名原样输出。前后端不一致时**不报错**,只表现为进度不动。
|
||||
Rust 侧 `event_json_contract` 单测钉死 JSON 形状。
|
||||
24. **音频块边界必须用"读满一块"而非 `Read::read` 的返回值**。`BufReader::read` 会短读,
|
||||
块边界一漂移,解密式里的「块内偏移 `i`」就与加密侧错位,表现为**文件从中间某处起全是噪声**
|
||||
(实测首个坏字节落在 32418,仍在第一大块内),前半段却完全正常,极难排查。
|
||||
已加 `read_full()` 专门处理。
|
||||
25. **`last_byte` 累加在模 256 下是恒等变形**:`c = swap + last_byte + key` 与标准 RC4 的
|
||||
`j += s[i] + key` 结果**逐字节相同**(已实测 256/256 一致)。所以:
|
||||
- 不能靠"与标准 RC4 比对"来验证密钥盒实现;
|
||||
- 也**不要**以为它是"改性 RC4 的关键差异"而据此改写(本计划早期的 §6.4 表述即由此误导)。
|
||||
真正的验证手段是**固定向量**(`key_box_matches_reference_vectors` /
|
||||
`keystream_matches_reference_vector`)。
|
||||
26. **`MODIFY_KEY` 是 16 字节而非 17**(`aes::Aes128` 的密钥长度就是 16);
|
||||
`CORE_KEY` 的 17 字节是**解密后要剥掉的前缀**,与 AES 密钥不是同一个东西
|
||||
(AES 密钥是它的前 16 字节)。两者混用不会编译报错,只会全解错。
|
||||
27. **合成容器单测的 key 段必须带 `neteasecloudmusic` 前缀**——否则解密端剥前缀后拿到错种子。
|
||||
这个坑一度被"单循环 KSA"的错误实现掩盖(两边同时错、往返仍然自洽)。
|
||||
|
||||
**P1a(QQ 离线)实施中新增确认的坑**
|
||||
|
||||
28. **QMC2 Map 密码的 `scramble` 必须用 `wrapping_shl/shr`**(对移位量取模),
|
||||
不能写成 `u8::rotate_left/rotate_right`——后者会在内部再取一次模,结果**不同**。
|
||||
被 Apache 参考实现的原向量抓到(若不比对向量,会产出"能跑但全错"的解密)。
|
||||
29. **tc_tea 不是 TEA-ECB,而是 TEA 变体 + 自定义 CBC**:块与密钥字都是**大端**、
|
||||
16 轮(非 32)、单轮是 `((v<<4)+k1) ^ (sum+v) ^ ((v>>5)+k2)`,
|
||||
且明文前置 `1+pad+2` 字节头、尾部 7 字节 0 自校验。照 TEA-ECB 写会解出**部分可读的乱码**
|
||||
(表现极具迷惑性:能看到明文碎片)。尾部 0 校验正是"密钥对不对"的权威判据。
|
||||
30. **V1 尾部判定不能只看长度**:任意加密数据末尾都可能凑出 `0<n<=0x400`,
|
||||
只按长度判会把普通 QMC1 文件误判成 V1 并砍掉一大截音频(实测 32871 字节 → 4096)。
|
||||
必须追加"前面那一段像不像 base64 ekey"的校验。
|
||||
31. **`sniff_tail` 的 `audio_len` 必须换算成绝对长度**:它只读了尾部 probe,
|
||||
`detect_tail` 给出的是**相对 probe 起点**的偏移;QMC1(无尾部)必须回落到**整个文件大小**。
|
||||
另外**不要在两个地方各写一遍尾部探测**——当初 `decrypt_file` 自己复制了一遍,
|
||||
修了 `sniff_tail` 却没修它,症状是"探测结果对、实际产物只有 4KB"。
|
||||
32. **QMC1 的掩码分支是 `pos > 0x7FFF`(严格大于)**,不是 `>=`;写成 `>=` 会在回绕点差一字节。
|
||||
|
||||
**P1c(musicex 在线)实施中新增确认的点**
|
||||
|
||||
33. **`MEMORY_BASIC_INFORMATION` 的 `PartitionId`(Win10 1803+)**:直接沿用
|
||||
`windows-sys` 的结构体即可,但**自己手写 `#[repr(C)]` 时千万别漏**——漏了会让
|
||||
`RegionSize`/`State`/`Protect` 全部读错偏移,`VirtualQueryEx` 返回的 `State`
|
||||
读成 `Protect`(如 `0x04` 而非 `0x1000`),于是所有内存区被跳过、永远扫不到 token。
|
||||
34. **`getEVkey` 的三个"必须"**:`filename` 带扩展名、`songtype=1`、
|
||||
`module=music.vkey.GetEVkey`(不是 `GetVkey`)。任一写错都只是"拿不到 ekey",
|
||||
不会报错——所以请求体用纯函数组装并单测锁死(`qq_ekey::build_evkey_request`)。
|
||||
35. **`authst` 会过期(约 22.3 小时)**:失败文案必须给"重新登录 / 重新检测"的出口,
|
||||
否则用户会以为是网络问题。响应里的 `expiration` 已带进产物备注。
|
||||
36. **单元测试不要真的发网络请求**:本机一旦登录成功,测试就会去连 QQ 服务器,
|
||||
导致测试变慢变脆。改为验证"请求体能正确构造"+"`#!Qk` 头守卫"+"尾部能被解析出
|
||||
`media_mid`/`filename`"三段——真实响应留给真机端到端。
|
||||
37. **musicex 音频段要校验 `#!Qk` 头**:尾部像 musicex 不代表内容真是 QMC2 密文;
|
||||
没有这道守卫会把任意文件"解"成垃圾却报告成功。
|
||||
|
||||
**真机端到端验证后修正(2026-09-27)**
|
||||
|
||||
38. **`#!Qk` 不是 QMC2 密文的通用魔术**(推翻第 37 条的做法):真机 musicex 样本
|
||||
(Avicii - Heaven,197MB `.mflac`)的密文头是 **`51 74 03 75`**,按"必须以 `#!Qk`
|
||||
开头"写的守卫会把**完全合法的文件误拒**。
|
||||
正确做法是**用解密结果判定密钥是否正确**:用取到的密钥解出前 16 字节,
|
||||
看是否是已知音频魔术(`fLaC` / `OggS` / `ID3` / `ftyp`…)——密钥错时它是随机噪声,
|
||||
几乎不可能凑巧命中;命中即说明密钥对、文件也对。
|
||||
这也是"内容优先"原则的又一次应用:**不要用猜测的密文特征做判据,要用能验证的结果。**
|
||||
39. **文档给的 musicex 字段偏移在真样本上是对的**:`0x0C` media_mid(60B UTF-16LE)、
|
||||
`0x48` filename(68B UTF-16LE)、`0xC0` footer_size、`0xC8` magic 全部命中,
|
||||
尾部实测 192 字节、padding 区有 13 个非零字节(所以不能假设 padding 全 0)。
|
||||
40. **真机样本的规模提醒**:`.mflac` 可达 197MB / 192kHz / 24bit。
|
||||
`qq_online` 目前把音频段整段读入内存再解密(探针与生产路径都是),
|
||||
在这个量级下可用,但如果将来遇到多 G 的文件,应改成分块解密 + 流式写盘
|
||||
(`qmc` 的流密码本身已支持任意偏移)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 分阶段计划
|
||||
|
||||
### P0 — 网易云 + 解密页签全链路(约 2 天)**✅ 已实施(2026-09-27)**
|
||||
|
||||
- [x] `useModuleTabs` + `TabsContent` 接「解密」页签;`index.ts` 搜索条目
|
||||
- [x] `decrypt/ncm.rs`:§3.1 全部要点 + 单测(**18 项通过**)
|
||||
- [x] `decrypt/mod.rs` + `commands.rs`:run / cancel + 事件发射;**三处**登记;`constants.rs` 事件常量
|
||||
- [x] `decryptStore.ts` + `DecryptPanel.vue`:选文件 → 批量任务 → 进度 → 打开输出目录
|
||||
- [x] 输出同名去重 + 输入输出相交保护(§4.4)
|
||||
- [x] 封面单独落盘(`<歌名>.cover.png|jpg`)——标签回填仍留 P2(`lofty` 需按容器分派)
|
||||
- [ ] **自测:真实 `.ncm` 样本解出**(需人工用真机样本验证;仓库内样本有版权且体积大,故算法靠 §6.9 的中间产物单测 + 合成容器往返覆盖)
|
||||
- **验收**:页签选 10 个 ncm 全部解出、失败有原因、切页签不丢任务、播放器直接可播
|
||||
|
||||
**已交付文件**:
|
||||
|
||||
| 文件 | 内容 |
|
||||
|---|---|
|
||||
| `src-tauri/src/music/decrypt/ncm.rs` | 网易云离线引擎(容器解析 / AES-ECB / 密钥盒 / 流式解密 / 魔数定格式 / 封面 / 同名去重)+ 单测 |
|
||||
| `src-tauri/src/music/decrypt/mod.rs` | 任务表、工作线程 + 节流事件转发、`DecryptEvent` 契约(含 JSON 形状单测) |
|
||||
| `src-tauri/src/music/decrypt/commands.rs` | `music_decrypt_run` / `music_decrypt_cancel` + 输出目录解析与相交保护 |
|
||||
| `src/stores/decryptStore.ts` | 任务状态 + 事件监听(挂 store,不随组件卸载) |
|
||||
| `src/modules/music/components/DecryptPanel.vue` | 页签 UI |
|
||||
| `music/mod.rs` · `lib.rs` · `constants.rs` | 子模块挂载、`MusicManager.decrypt` 字段、三处命令登记、事件常量 |
|
||||
|
||||
### P1a — QQ 离线解密 + 文件夹批量(**✅ 已实施,纯 Rust,无 Python/frida**)
|
||||
|
||||
- [x] `decrypt/qmc.rs`:QMC1 静态密钥表 / QMC2 Map 密码 / QMC2 RC4 变体 / tc_tea(TEA 变体 + 自定义 CBC)
|
||||
- [x] 第①层:QTag 与 V1 尾部 ekey 提取 → **离线解密**
|
||||
- [x] `decrypt/scan.rs`:递归扫描 + 内容优先的平台路由 + 保留相对目录结构
|
||||
- [x] **文件夹批量**:`folder` / `root` / `in_place` 三个参数 + `music_decrypt_scan` 预览命令
|
||||
- [x] `decrypt/common.rs`:两引擎统一的错误类型、魔数定格式、同名去重、读满一块
|
||||
- [x] 单测 **56 项**(模块合计 174 项全库通过),含参考实现的原始测试向量
|
||||
- [ ] 第②层 musicex + `GetEVkey` API(**未实施**,见 P1c)
|
||||
- [ ] 真实 `.mflac/.mgg/.qmcflac` 样本自测(需人工;仓库内不放版权样本)
|
||||
|
||||
**已交付文件(P1a 增量)**:
|
||||
|
||||
| 文件 | 内容 |
|
||||
|---|---|
|
||||
| `src-tauri/src/music/decrypt/qmc.rs` | QMC 全套离线算法 + 尾部形态判定 |
|
||||
| `src-tauri/src/music/decrypt/scan.rs` | 文件夹递归扫描与平台路由 |
|
||||
| `src-tauri/src/music/decrypt/common.rs` | 两引擎公共件 |
|
||||
|
||||
**算法来源(全部宽松许可,均有原始向量锁行为)**:
|
||||
|
||||
| 部分 | 来源 | 许可 |
|
||||
|---|---|---|
|
||||
| QMC1 静态密钥表 + 掩码规则 | `jixunmoe/qmc-decode` | MIT |
|
||||
| QMC2 密钥派生 / Map / RC4 / 尾部形态 | `bczhc/qmc-dec`(`qmc2-crypto`) | Apache-2.0 |
|
||||
| tc_tea | `tc_tea` crate | MIT/Apache-2.0 |
|
||||
|
||||
### P1b — Frida 兜底(按需,不计入本轮)
|
||||
|
||||
- [ ] `qq_decrypt.py`(`include_str!`):attach → `EncAndDesMediaFile` 调用序列 → 批量 → JSON-Lines 进度
|
||||
- [ ] `decrypt/qq_frida.rs`:前置检查、spawn、逐行读转发事件
|
||||
- **触发条件**:仅当 §3.2 的第③层文件在真实用户场景中被确认存在且前两层无法覆盖时才做
|
||||
|
||||
### P1c — musicex 联网取 ekey(**✅ 已实施**)
|
||||
|
||||
- [x] `qq_footer.rs`:musicex 尾部解析(song_id / media_mid / filename)
|
||||
- [x] `qq_credentials.rs`:读 `%APPDATA%\Tencent\QQMusic\QQMusicServiceConfig.ini` 的 `uin` + 扫进程内存取 `authst`
|
||||
- [x] `qq_memscan.rs`(Windows):`CreateToolhelp32Snapshot` + `OpenProcess` + `VirtualQueryEx` + `ReadProcessMemory`(**只读**)
|
||||
- [x] `qq_ekey.rs`:`GetEVkey` 请求组装与响应解析(`filename` 带扩展名 / `songtype=1` / `platform="27"`)
|
||||
- [x] `qq_online.rs`:编排 + `probe_status()` 在线能力探测
|
||||
- [x] `music_decrypt_qq_status` 命令 + UI 状态卡(含**逐步操作说明**)
|
||||
- [x] `windows-sys` 增开 `Win32_System_Diagnostics_ToolHelp` 与 `..._Debug`
|
||||
- [x] **本机实测**:`probe_status()` 返回 `running=true logged_in=true uin=1154027699 ready=true` —— 内存扫描确实取到了 `authst`
|
||||
- [x] **端到端已用真机样本跑通**(2026-09-27,见下)
|
||||
|
||||
#### 真机端到端验证记录(首个 musicex 样本)
|
||||
|
||||
样本:`C:\Users\Administrator\Music\Heaven - Avicii_EM.mflac`(197,104,516 字节,
|
||||
尾部 `musicex\0`,`song_id=233102682`,`media_mid=003iTvi44A6RMs`,
|
||||
`filename=AIM0002ELI6a1wXJDo.mflac`)
|
||||
|
||||
| 环节 | 实测结果 |
|
||||
|---|---|
|
||||
| 尾部解析 | song_id / quality1=2 / quality2=11 / media_mid / filename 全部正确 |
|
||||
| 凭据 | 返回 `running=true logged_in=true uin=1154027699 ready=true` |
|
||||
| `GetEVkey` | **成功**,拿到 704 字符 ekey;`expiration=80400`(22.3 小时,与文档一致) |
|
||||
| ekey → 密钥 | 解密出 **512 字节**原始密钥 → 命中 **RC4 变体**(>300 字节)分支 |
|
||||
| 音频段 | 197,104,324 字节(= 文件大小 − 192 字节尾部,完全吻合) |
|
||||
| 解密结果 | 首帧 `66 4c 61 43` = **`fLaC`** ✅ |
|
||||
| 产物校验(`lofty`) | **277.261 秒 · 192000 Hz · 24 bit · 2 声道 · 5686 kbps** —— 192kHz/24bit Hi-Res 无损 |
|
||||
|
||||
**验证方式**:`examples/decrypt_musicex_probe.rs` 走真实链路(读内存凭据 → 真实
|
||||
HTTP 请求 → 解密),再用 `examples/verify_audio.rs` 交给项目同款解析器确认产物合法。
|
||||
两个 example 都保留,供后续 QQ 改协议时快速定位。
|
||||
|
||||
**这次验证推翻了一个错误假设**:样本的密文头是 `51 74 03 75`,**不是**文档里提到的
|
||||
`#!Qk`。原先按"密文必须以 `#!Qk` 开头"写的守卫会把完全合法的文件误拒——已改为
|
||||
**用解密结果判定**(解出的前 16 字节是否为已知音频魔术),见 §6.38。
|
||||
|
||||
**凭据可用性已知限制**:
|
||||
|
||||
| 维度 | 情况 |
|
||||
|---|---|
|
||||
| `uin` 来源 | INI 明文,稳定 |
|
||||
| `authst` 来源 | 仅运行期内存;**QQ 音乐必须开着且已登录** |
|
||||
| 有效期 | 约 22.3 小时(响应 `expiration` 字段,已带进产物备注) |
|
||||
| 权限 | 读他人进程内存可能需管理员;失败文案已提示 |
|
||||
| 是否注入 | **否**,纯只读——这是它与 Frida 兜底的本质区别 |
|
||||
|
||||
### P2 — 按需增强(不进本轮)
|
||||
|
||||
- **ID3 / FLAC / MP4 标签回填**(用 `lofty`,按容器分派;meta JSON 已在解密时解析出来)
|
||||
- 解密完成 →「加入本地曲库」/ 上传飞牛(复用 `musicUploadStore`)
|
||||
- 拖拽文件进页签、解密历史持久化
|
||||
- 酷狗 / 酷我(除非再次明确要求)
|
||||
- QQ 变体适配(path_sensitive_mflac)
|
||||
|
||||
> **变更**:原计划把「封面提取 / ID3 标签回填」一起从 P2 提前到 P0。**实际只提前了封面提取**——
|
||||
> 封面字节在解析容器时顺手就读出来了,落盘是十几行,且不做就"能播但难用"。
|
||||
> 标签回填仍留 P2:它需要 `lofty` 且要按 mp3/flac/m4a 分派容器,属于增强而非可用性门槛。
|
||||
|
||||
---
|
||||
|
||||
## 8. 风险与开放问题
|
||||
|
||||
| 风险 | 影响 | 对策 |
|
||||
|---|---|---|
|
||||
| QQ 改 musicex 尾部/API 协议 | 第②层失效 | 协议字段集中在 `qq_footer` / `qq_ekey` 两处;错误文案带原始响应码;关注 qmc-decoder issue |
|
||||
| `authst` 提取被安全软件拦截 | 第②层失效 | **只读**内存、不注入;失败给"以管理员身份运行"出口 |
|
||||
| **musicex 端到端** | ~~真实响应字段可能与文档不符~~ **已验证通过**(真机 197MB 样本,产物为合法 192kHz/24bit FLAC) | 保留 `examples/decrypt_musicex_probe.rs` + `verify_audio.rs`,QQ 改协议时可快速定位 |
|
||||
| `authst` 过期(22.3h) | 第②层短期失效 | 错误文案给"重新登录/重新检测"出口;有效期带进产物备注 |
|
||||
| QQ 版本升级改 mangled 导出符号 | 仅第③层(Frida)失效 | 子串模糊匹配;第③层不在实施范围,影响面已缩小 |
|
||||
| 真实样本不足导致算法细节偏差 | 解出错文件 | **已用参考实现的原始测试向量交叉验证**(QMC1 掩码 / Map / RC4 / tc_tea / ekey 端到端) |
|
||||
| GPLv3 边界被无意破坏 | 许可风险 | 三档口径见 §3.3;QMC 只取 MIT / Apache-2.0 两份来源的**代码与数据** |
|
||||
| 网易云改 ncm 格式 | 个别文件失败 | per-file error 不中断整批 |
|
||||
| 同名文件落盘互相覆盖 | **用户文件丢失** | §4.4 同名去重 + 相交保护 |
|
||||
| 文件夹扫描漏文件(内容认不出) | 用户以为解完了 | UI 先出 `music_decrypt_scan` 预览数量 |
|
||||
|
||||
**开放问题**:
|
||||
|
||||
1. 解密输出默认就地(文件夹批量)或 `savedir/decrypted/`(散选);独立设置项留 P2。
|
||||
2. QQ 未运行时是否自动拉起?**离线层与 `.ncm` 完全不需要客户端**;只有 musicex 需要,
|
||||
当前选择"只提示、不自动拉"(客户端要登录,自动拉起也解决不了登录态)。
|
||||
3. `.mmp4` 的产物容器(m4a / mp4)待真机样本确认——当前靠首帧 `ftyp` 魔数判定,认不出时按后缀落 `m4a`。
|
||||
(`.mflac` 已实测确认:产物为 192kHz/24bit 的 `.flac`。)
|
||||
4. ~~musicex 端到端未验证~~ **已解决**(2026-09-27,真机样本跑通,见 P1c 的验证记录)。
|
||||
5. `.mflac0` / `.mgg1` 等变体按 QMC2 处理,但**未用真实样本验证**过其尾部形态与 `.mflac` / `.mgg` 一致。
|
||||
6. 微信登录的 QQ 音乐 (`tmeLoginType=3`):实现上 `authst` 与 QQ 登录通用,
|
||||
但 `login_type` 目前固定发 `1`(QQ 登录实测可用)——若真机发现微信登录取不到 ekey,需按凭据来源推断。
|
||||
7. **大文件内存占用**:`qq_online` 目前整段读入内存解密;197MB 实测可用,
|
||||
但 `.mflac` 可以更大。若遇到多 G 文件,应改流式(`qmc` 的流密码已支持任意偏移)。
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:参考项目对照(只取思路)
|
||||
|
||||
### A.1 QKKDecrypt 实测结论(2026-09-27 深读 `main@938b22d`,来自其源码而非猜测)
|
||||
|
||||
**最重要的一条**:该项目 QQ 路径**完全不解析 QMC 加密格式**——它把原始加密文件整包交给 QQ 自己的 DLL 解密,因此不受 static/map cipher 变体影响。**代价是强依赖四项**:QQ 客户端运行 + `QQMusicCommon.dll` 已加载 + **管理员权限**(`cli.py::_require_admin()`,非管理员直接 `return 2` 并打印"已禁止继续使用")+ mangled 名/编译器版本不变。**这四项与它的"回退"一起,正是我们改走 §3.2 分层路由的原因。**
|
||||
|
||||
| QKKDecrypt 文件 | 可借鉴 | 不可借鉴 |
|
||||
|---|---|---|
|
||||
| `platforms/qq/adapter.py` | `SUPPORTED_SUFFIXES` 仅 `.mflac/.mgg/.mmp4`;前置检查项;ASCII 暂存 |
|
||||
| `qq/runtime/qqmusic_decrypt.py` | `EncAndDesMediaFile` 的 3 组候选 mangled 名、NativeFunction 全 `thiscall` 签名、调用序(`Memory.alloc(0x28)` → ctor → `allocUtf16String` → `Open(..,1,0)` → `GetSize` → `Read` → dtor) | **硬编码**;整文件读入内存;未校验 `Open`/`Read` 返回值 |
|
||||
| `qq/runtime/frida_decrypt_gateway.py` | 进程查找用**子串匹配** `"qqmusic"`;**每批次只 attach 一次**并缓存 session | 无 session 重连(QQ 中途重启即失效) |
|
||||
| `qq/variant_adapter.py` | "路径敏感型 mflac"→**解密前先复制到纯 ASCII 路径**(`pick_safe_tmp_dir`:盘根 `_qqmusic_tmp` → 项目根 → `tempfile.gettempdir()`) | 只实装了这一个变体 |
|
||||
| `qq/internal_direct.py` / `qq/export_fallback.py` | — | **存在但未接入主流程 = 死代码**,不可当作可用的回退能力承诺 |
|
||||
| `platforms/netease/adapter.py` | 输出扩展白名单法 | **它没有自研 ncm 算法**——直接 `from ncmdump import NeteaseCloudMusicFile` 委托 PyPI 的 `ncmdump-py`;且 `predicted_extension()` 会**多解密一遍**(性能坑) |
|
||||
| `Application/decrypt_service.py` | 事件粒度 = **逐文件 `index`/`total`**;`file_finished.result ∈ success/failed/already_decrypted` | 事件种类过多(20+) |
|
||||
| `cover_art_service.py` | "本地同名图 → 缓存 → 联网"的 local-first 顺序 | **给网易云产物做封面兜底时查的是 QQ 音乐 API** |
|
||||
| `THIRD_PARTY_LICENSES.md` | 合规口径与风险表述 | 内置 FFmpeg 为 `--enable-gpl --enable-version3` 构建 → 传染面比"仓库 GPLv3"更大 |
|
||||
|
||||
**对本文档的两处直接修正**:
|
||||
|
||||
1. **"输出扩展名看音频首帧魔数"得到双重印证**——QKKDecrypt 的最终扩展名同样**不取映射表**,而是 `detect_audio_container()` 从实际字节判定(`fLaC`/`OggS`/`RIFF..WAVE`/`ID3`/`0xFF 0xFB|0xF3|0xF2`/偏移 4 处 `ftyp`)。故 §3.2 的输出扩展名表仅作**声明/预期**用,实际以魔数为准。
|
||||
2. **`.mgg` 解出后它强制归一为 `.m4a`**(`normalize_target_format` 把 `ogg→m4a`)。本项目**不跟**这个行为——`Cargo.toml:112` 已确认 symphonia 默认特性含 `ogg/vorbis`,直接落 `.ogg` 即可播,保持"所见即所得"(§3.1 原口径)。
|
||||
3. QKKDecrypt 不支持 `.mflac0/.mgg1/.mflac1/.qmc*`——**我们的扩展面比它宽**(§4.3),但格式知识来源是 qmc-decoder 的**文档**(GPLv3,不抄代码)。
|
||||
|
||||
### A.2 借鉴到 P0 的一条设计(**最终未采用,附理由**)
|
||||
|
||||
QKKDecrypt 的 `file_finished.result` 含 `already_decrypted` 与 `stopped_by_user` 两个态。
|
||||
**`stopped_by_user` 已采纳**(取消后 `finished.cancelled > 0`,任务落为"已取消")。
|
||||
**`already_decrypted` 决定不做**:它要判断"某份已存在的产物是否就是本次输入的产物",
|
||||
在扁平输出目录里只能靠文件名猜,猜错就静默跳过用户的文件——代价大于收益。
|
||||
P0 改为**永不跳过**:目标名被占用就写 `<名>_1.<ext>`,宁可多一份产物也不丢工作。
|
||||
(`ncm::unique_output` 同时处理"磁盘上已存在"与"本批次内已占用"两种情况。)
|
||||
@@ -0,0 +1,303 @@
|
||||
# 音乐模块 · 手机端连接与控制规划(Music Remote Plan)
|
||||
|
||||
> 状态:**规划中**(未开始实施)
|
||||
> 定位:音乐模块的"手机互联"子能力,不是独立模块——挂靠 `music` 模块,Rust 侧新增 `music/remote/` 子系统
|
||||
> 日期:2026-09-25
|
||||
> 关联文档:`AI_DEV_GUIDE.md`(模块注册 / IPC 范式——注意其未涵盖 specta,绑定范例见 `lib.rs` 的 `export_bindings()`)、`TERMINAL_MODULE_PLAN.md`(规划文档范式)
|
||||
> 对端文档:`F:\AtieProject\LFMusic\PLAN.md`(手机端 LFMusic 的功能与实现规划,协议以本文 §4(协议)/ §5(实现)为准)
|
||||
|
||||
---
|
||||
|
||||
## 0. 结论先行
|
||||
|
||||
四个关键判断,先摆在这里,后文展开论证:
|
||||
|
||||
1. **"获取电脑端正在播放的内容(不管是不是 Thing 播的)"必须走 GSMTC**(`GlobalSystemMediaTransportControlsSessionManager`),而不是扩展现有的 `smtc.rs`。`smtc.rs` 以"Thing → 系统"的元数据/进度上报为主(`ISystemMediaTransportControlsInterop::GetForWindow`),并经 `TypedEventHandler` 接收系统按钮回传(双向)——但它只管自己这条会话;要读到**系统里所有应用的媒体会话**(网易云、QQ 音乐、浏览器、Thing 自己……),唯一官方通道是 GSMTC 的全局会话管理器。两者方向相反、互不冲突,`smtc.rs` 原样保留。
|
||||
|
||||
2. **控制链路统一走 GSMTC 的 `Try*Async`,Thing 自己不特殊处理**。手机发的播放/暂停/切歌 → Thing 的 GSMTC 调用 → 系统把按钮事件派发给目标会话。Thing 自己因为已在 `smtc.rs` 注册了 SMTC 会话并有按钮事件回传链路(`music-smtc-button` → 前端执行),这条环路是现成的,**对 Thing 自身会话近乎零新增执行代码**(需补的是 cmd-ack 语义与派发时序定义,见 §4.2 / §5.2)。不要为 Thing 自建"直通 AudioEngine"的旁路——多一条路径就多一类不一致(P1 若延迟体感明显再优化)。
|
||||
|
||||
3. **局域网服务用 axum(已有依赖)新增 HTTP + WebSocket 双通道,发现用"电脑广播 beacon + 手动扫码"双保险**。axum 已在 `download_engine/server.rs` 和 `feiniu/proxy.rs` 两处落地,范式现成。发现协议不选 mDNS 做 P0 主路径:Android/iOS 的 mDNS 栈碎片化、路由器 AP 隔离下失效、iOS 后台受限;而电脑端周期性 UDP 广播 + 手机被动监听实现最简、权限最友好,配合二维码手动配对兜底已覆盖 99% 场景。mDNS 降级为 P1 增强。
|
||||
|
||||
4. **安全按"配对制"设计,不做裸奔**。首次连接用一次性配对码(Thing 弹窗展示,手机扫码/手输),换取长期设备 token;token 两侧持久化(Thing 侧入 keyring,手机侧入系统安全存储),后续连接 WS 握手鉴权,设置页可随时撤销设备。局域网明文 HTTP 在 P0 可接受(风险面:同网段已配对 token 泄露才会被利用),TLS 自签放 P2。
|
||||
|
||||
**工作量估算**:P0(系统会话捕获 + LAN 服务 + 发现配对 + 基础遥控)约 6~9 个工作日;P1(mDNS、多会话切换、系统音量、投播)约 5~8 个工作日;P2(TLS、队列投播完善)按需。
|
||||
|
||||
---
|
||||
|
||||
## 1. 需求解构
|
||||
|
||||
用户需求拆成可执行的规格:
|
||||
|
||||
| 用户原话 | 解构为 | 落点 |
|
||||
|---|---|---|
|
||||
| 「手机端 app 打开后自动连接局域网电脑上的 Thing」 | 电脑端局域网服务(HTTP+WS)+ 自动发现(UDP beacon)+ 配对与鉴权 | §3.2 / §3.3 / §3.4 |
|
||||
| 「可以获取到电脑端正在播放的内容(不管是 Thing 自己播放的,或是其他应用播放的)」 | GSMTC 全局会话监视:当前活跃会话的元数据、进度、播放状态、封面 | §3.1 / §5.2 |
|
||||
| 「显示例如歌曲名,歌手,专辑,封面,进度」 | `NowPlaying` 状态模型 + WS 增量推送 + 封面 HTTP 端点 | §4 / §5.2 |
|
||||
| 「控制等等」 | 播放/暂停/上一首/下一首/seek/停止,走 GSMTC `Try*Async`;音量 P1 | §3.1 / §5.3 |
|
||||
| (自然延伸,非本次明说) | 投播:手机选歌 → 电脑播放(Thing 曲库播放队列控制) | §7 P2 |
|
||||
| 「打开后自动连接」的边界 | 首次需用户在电脑设置页点「连接手机」弹出配对码/二维码,5 分钟内完成一次配对;此后已配对设备才自动重连 | §3.4 / 对端文档 §5.1 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 现状勘察(2026-09-25 从仓库实际读取)
|
||||
|
||||
### 2.1 已具备的基建(直接复用)
|
||||
|
||||
| 能力 | 现有实现 | 本功能可复用的部分 |
|
||||
|---|---|---|
|
||||
| 播放引擎 | `music/audio/engine.rs`:`AudioEngine`(symphonia + cpal/WASAPI 独立线程),`AudioState` 快照 + `music-audio-ended` / `music-audio-error` 事件 | Thing 自身播放状态的事实来源;封面/元数据兜底可直读播放队列 |
|
||||
| SMTC 上报 | `music/smtc.rs`:`SmtcController`(GetForWindow 全字段上报 + 系统按钮事件 `music-smtc-button` 回传前端) | **零改动保留**;它让 Thing 拥有一条标准 SMTC 会话,GSMTC 控制才能作用到 Thing 自己 |
|
||||
| HTTP 服务范式 | `download_engine/server.rs`、`feiniu/proxy.rs` 均为 axum + `tokio::net` | 新 LAN 服务照抄此范式(`axum::serve` + tokio) |
|
||||
| WebSocket | `tokio-tungstenite 0.24` 已在依赖树 | 备选;WS 通道直接用 axum 的 `ws` feature 更统一 |
|
||||
| 凭据存储 | `secrets.rs`(keyring + Windows 凭据管理器)、`music/secrets.rs` | 设备 token / 配对密钥持久化 |
|
||||
| 类型绑定 | tauri-specta 自动生成 `src/lib/bindings.ts` | remote 命令与消息类型走 specta,前端零手写类型 |
|
||||
| 设置持久化 | `MusicManager::load_settings / save_settings`(settings.json + 500ms 缓存) | remote 开关/端口等设置项追加到 `MusicSettings` |
|
||||
| 日志 | `logger.rs` 统一日志 | remote 全链路日志 |
|
||||
|
||||
### 2.2 关键缺口(需新增)
|
||||
|
||||
| 缺口 | 现状 | 方案 |
|
||||
|---|---|---|
|
||||
| 系统媒体会话读取 | 无。`windows` crate 未开 `Media_Control` feature | 开启 feature,新增 `music/remote/glsmtc.rs`(见 §3.1) |
|
||||
| 局域网服务 | axum 仅用于本机/代理场景,无对外 LAN 端点 | 新增 `music/remote/server.rs`,监听 `0.0.0.0` |
|
||||
| 设备发现 | 无 | 新增 `music/remote/discovery.rs`(UDP beacon) |
|
||||
| 配对与设备管理 | 无 | 新增 `music/remote/pairing.rs` |
|
||||
| 二维码渲染 | 无 | 前端引入 `qrcode`/`qr-code-styling`(纯前端生成即可) |
|
||||
|
||||
---
|
||||
|
||||
## 3. 技术选型
|
||||
|
||||
### 3.1 系统媒体捕获:GSMTC
|
||||
|
||||
Windows 10 1809+ 的 `Windows.Media.Control` 命名空间是**唯一**能枚举/监视/控制系统全部 SMTC 会话的公开 API。凡是有标准系统集成(SMTC)的播放器——网易云、QQ 音乐、foobar2000、浏览器、以及 Thing 自己——都会出现在会话列表里。
|
||||
|
||||
Rust 侧路径:`windows` crate(当前 0.52)增加 `"Media_Control"` feature,类型位于 `windows::Media::Control`:
|
||||
|
||||
```rust
|
||||
use windows::Media::Control::{
|
||||
GlobalSystemMediaTransportControlsSessionManager,
|
||||
GlobalSystemMediaTransportControlsSession,
|
||||
};
|
||||
```
|
||||
|
||||
核心 API 清单:
|
||||
|
||||
| API | 用途 |
|
||||
|---|---|
|
||||
| `SessionManager::RequestAsync()` | 取全局管理器单例(惰性初始化,失败则整个能力降级关闭) |
|
||||
| `manager.GetSessions()` | 枚举所有会话——**同步**返回 `IVectorView`(0.52 投影无 Async 版本,计划原文 `GetSessionsAsync` 有误,以实测为准) |
|
||||
| `manager.GetCurrentSession()` | 当前"活跃"会话(系统自动判定:最近操作的会话);**同步**,无会话时 ABI 返回 null → windows-rs 投影为 `Err(E_POINTER)`,按"无会话"分支处理。**实测修正:WinRT 没有 `SetCurrentSessionAsync`**——P1 多会话切换采用 Thing 侧"选中覆盖"(§7),不修改系统判定 |
|
||||
| `session.SourceAppUserModelId` | 来源应用标识(用于显示"正在播放的应用",也作为会话 key) |
|
||||
| `session.TryGetMediaPropertiesAsync()` | 元数据:Title / Artist / AlbumTitle / AlbumArtist / **Thumbnail** |
|
||||
| `session.GetTimelineProperties()` | Position / EndTime / **LastUpdatedTime**(进度推算基准,见 §6.4) |
|
||||
| `session.GetPlaybackInfo()` | PlaybackStatus / Controls(`IsPlayEnabled` 等能力位)/ PlaybackRate |
|
||||
| `TryPlayAsync` / `TryPauseAsync` / `TryStopAsync` / `TrySkipNextAsync` / `TrySkipPreviousAsync` | 控制(即手机端全部按钮的实现) |
|
||||
| `TryChangePlaybackPositionAsync(ticks)` | seek(仅当会话 `IsSeekEnabled`) |
|
||||
| 事件:`CurrentSessionChanged` / `MediaPropertiesChanged` / `TimelinePropertiesChanged` / `PlaybackInfoChanged` / `SessionsChanged` | 状态变更推送源 |
|
||||
|
||||
**线程与套间**(沿用 `smtc.rs` 已验证的范式,但有一处关键差异):
|
||||
|
||||
- 初始化(`RequestAsync`)与事件订阅在**主线程**执行(`run_on_main_thread` 抛过去),与 `smtc.rs` 一致。
|
||||
- **`Try*Async` 的 `.get()` 阻塞等待必须放专用工作线程**,不能在主线程 `.get()`——STA 上阻塞等待 WinRT async 有死锁风险,而 `smtc.rs` 那种"fire-and-forget 更新属性"不涉及等待所以没踩到。设计上:主线程只做"发起",等待统一丢给 `tokio::task::spawn_blocking` 或专用线程。
|
||||
- 所有 GSMTC 对象是 agile 的,跨线程传引用安全(与 smtc.rs 注释同源结论)。
|
||||
|
||||
**失败策略**:与 `smtc.rs` 同哲学——GSMTC 任何一步失败只记日志,不影响播放;GSMTC 初始化失败时整个"远程查看/控制其他应用"能力降级为"仅 Thing 自身"(可从 `AudioEngine.state()` 兜底聚合,见 §5.2)。
|
||||
|
||||
### 3.2 局域网服务:axum HTTP + WebSocket
|
||||
|
||||
单端口(默认候选 **26124**,被占则 +1 重试至 26139,实际端口写进 beacon 与二维码):
|
||||
|
||||
| 端点 | 方法 | 用途 |
|
||||
|---|---|---|
|
||||
| `/ws` | GET(Upgrade) | 主通道:鉴权、状态推送(server→client)、控制指令(client→server) |
|
||||
| `/api/state` | GET | REST 兜底快照(WS 不可用/调试用),Bearer token 鉴权 |
|
||||
| `/cover/:hash` | GET | 封面字节流(内存缓存,`hash` 由状态推送携带,`?v=` 控制刷新),Bearer token(query 参数 `t=`,`<img>` 标签无法带 header);**访问日志不打印 query**,token 不落日志 |
|
||||
| `/pair` | POST | 配对:`{ pairingCode, deviceName }` → `{ token, deviceId }` |
|
||||
|
||||
WS 承载双向消息(协议见 §4.2);HTTP 承载资源(封面)与低频操作。全部监听 `0.0.0.0`。
|
||||
|
||||
**防火墙注意**:首次监听 LAN 端口 Windows 会弹防火墙授权(专用网络勾选即可)。在设置页 remote 开关旁给出说明文案;不做 `netsh` 自动加规则(改系统防火墙属于越权行为,且需要管理员)。
|
||||
|
||||
### 3.3 设备发现:UDP beacon(P0 主)+ 扫码兜底(P0)+ mDNS(P1)
|
||||
|
||||
| 方案 | 机制 | 判断 |
|
||||
|---|---|---|
|
||||
| **UDP beacon(推荐 P0)** | 电脑每 3s 向 `255.255.255.255:26123` 与各网卡定向广播地址发 JSON 包:`{ "service": "thing-music", "deviceId", "name", "port", "protoVer" }`;手机监听 26123 被动收集 | 实现最简(一个 tokio interval + UdpSocket);手机端只需 bind 收包,**Android 免多播权限问题,iOS 不触发 multicast entitlement**(仍会触发本地网络权限弹窗,属正常) |
|
||||
| 扫码/手输(P0 兜底) | Thing 设置页展示二维码:`thingmusic://connect?ip=…&port=…&code=…`;手机扫码或手输 IP+配对码 | AP 隔离下 beacon 不可达时的最后手段;同时它就是配对入口(见 §3.4) |
|
||||
| mDNS(P1 增强) | `mdns-sd` crate 注册 `_thingmusic._tcp.local.`,手机 browse | 生态标准、后台发现友好;但依赖各端 mDNS 栈质量,放 P1 不阻塞 |
|
||||
|
||||
beacon 里**不含**任何敏感信息(无 token、无配对码),只描述"这里有一个 Thing 音乐服务"。手机端根据 deviceId 去重。
|
||||
|
||||
### 3.4 安全与配对
|
||||
|
||||
流程(对齐业界遥控 App 的标准做法):
|
||||
|
||||
1. 手机端发起配对:beacon 得到 ip:port 后 POST `/pair`,携带 6 位一次性配对码 + 设备名。
|
||||
2. 配对码由 Thing 侧生成:用户在设置页点击「连接手机」→ 弹窗展示 6 位码 + 二维码(码内含 ip/port/code,扫码即完成 1、2 两步),有效期 5 分钟,一次性。
|
||||
3. 校验通过 → 生成 32 字节随机 hex 设备 token,返回手机;Thing 侧持久化 `{deviceId, deviceName, token}` 到 keyring(复用 `secrets.rs` 范式),列表落 settings。
|
||||
4. 后续连接:WS 握手首条消息 `hello { token }`(或 HTTP `Authorization: Bearer`),校验失败 3 次即拉黑该 IP 60s;`/pair` 的配对码校验执行同一限速(防 6 位码爆破,配对响应也只在成功时下发 token)。
|
||||
5. 设置页设备列表:展示在线/离线、最后连接时间,可撤销(吊销 token)。
|
||||
|
||||
P2 增强:自签 TLS(`rcgen` 生成 + `rustls`,二维码里带证书指纹)。P0 明文 HTTP 的风险面评估:同局域网内明文嗅探只能看到 token 之后的媒体元数据;token 本身仅在配对响应中明文传输一次,可接受。
|
||||
|
||||
---
|
||||
|
||||
## 4. 状态模型与协议设计
|
||||
|
||||
### 4.1 `NowPlaying`(核心状态, specta 类型双端共享)
|
||||
|
||||
```typescript
|
||||
interface NowPlaying {
|
||||
sessionId: string // 会话 key(SourceAppUserModelId;Thing 自身 = "thing.self")
|
||||
sourceApp: string // 来源应用显示名(AUMID 末段或注册表友好名)
|
||||
isThing: boolean // 是否 Thing 自身播放(决定封面/元数据兜底来源)
|
||||
title: string
|
||||
artist: string
|
||||
album: string
|
||||
coverHash: string | null // 封面缓存键;封面从 /cover/:hash 拉
|
||||
status: 'playing' | 'paused' | 'stopped'
|
||||
durationSec: number
|
||||
positionSec: number // 推送时刻的位置
|
||||
positionUpdatedAtMs: number // 电脑时钟毫秒(源自 TimelineProperties.LastUpdatedTime,见 §6.4);仅供校准,手机端 elapsed 一律以本地收包时刻起算(见 §6.10)
|
||||
playbackRate: number
|
||||
canControl: { play: boolean; pause: boolean; next: boolean; prev: boolean; seek: boolean }
|
||||
deviceId: string // 电脑标识(多电脑预留)
|
||||
}
|
||||
```
|
||||
|
||||
### 4.2 WS 消息(JSON,`type` 字段区分)
|
||||
|
||||
| 方向 | type | 载荷 | 时机 |
|
||||
|---|---|---|---|
|
||||
| c→s | `hello` | `{ token, deviceName, protoVer }` | 连接后首条;失败即断开 |
|
||||
| s→c | `welcome` | `{ deviceId, deviceName, protoVer }` | 鉴权通过 |
|
||||
| s→c | `state` | `NowPlaying`(全量) | 连接后、以及任何变更(见 §6.3 节流;**由 `cmd` 触发的变更立即推一帧,绕过节流**) |
|
||||
| c→s | `cmd` | `{ id, action, args? }`,action ∈ `play / pause / toggle / next / prev / stop / seek(posSec)` | 用户操作 |
|
||||
| s→c | `cmd-ack` | `{ id, ok, error? }` | 回执语义 = **"指令已被接受/派发"**(GSMTC 路径 = Try*Async 完成;前端兜底路径 = 事件已投递),不代表播放状态已切换;UI 轻提示,真实状态以随后的 `state` 为准 |
|
||||
| c→s | `ping` / s→c `pong` | `{ ts }` | 30s 心跳,双向判活 |
|
||||
|
||||
版本策略:`protoVer` 从 1 起,不匹配时 `welcome` 带最新版本号,手机端提示升级。
|
||||
|
||||
---
|
||||
|
||||
## 5. 架构与模块设计
|
||||
|
||||
### 5.1 Rust 侧:`src-tauri/src/music/remote/`
|
||||
|
||||
```
|
||||
src-tauri/src/music/remote/
|
||||
├── mod.rs # RemoteManager:manage() 进 State;启动/停止服务与 beacon;开关状态
|
||||
├── server.rs # axum app:路由 /ws /api/state /cover /pair;WS 会话表(fanout 广播)
|
||||
├── glsmtc.rs # GsmtcMonitor:GSMTC 初始化、事件订阅 → 聚合 NowPlaying → 广播
|
||||
├── discovery.rs # UdpBeacon:3s 周期广播(255.255.255.255 + 各网卡定向广播)
|
||||
├── pairing.rs # 配对码生成/校验、设备 token 签发、设备表(keyring + settings)
|
||||
└── proto.rs # NowPlaying / WS 消息类型(serde + specta,前端 bindings 自动生成)
|
||||
```
|
||||
|
||||
数据流:
|
||||
|
||||
```
|
||||
GSMTC 事件(主线程订阅)──→ GsmtcMonitor 聚合/节流 ──→ Server 广播到全部 WS 客户端
|
||||
AudioEngine.state()(兜底聚合,isThing 时封面/元数据来源之一)┘
|
||||
手机 cmd ──→ server.rs ──→ glsmtc.rs(spawn_blocking 调 Try*Async)──→ 系统派发给目标会话
|
||||
└─ Thing 自身会话:SMTC 按钮 → smtc.rs 既有链路 → 前端 feiniuStore 执行(既有链路,约束见 §5.2)
|
||||
```
|
||||
|
||||
`MusicManager` 增加 `remote: RemoteManager` 字段(或平级 manage,倾向后者,避免 MusicManager 继续膨胀);`lib.rs` 注册 `remote_*` 系列命令:
|
||||
|
||||
| 命令 | 用途 |
|
||||
|---|---|
|
||||
| `remote_get_config` / `remote_set_enabled` | 开关(MusicSettings 追加 `remote_enabled`、`remote_port`) |
|
||||
| `remote_status` | 服务状态、端口、在线设备 |
|
||||
| `remote_start_pairing` | 生成配对码 + 二维码 payload(前端渲染二维码) |
|
||||
| `remote_cancel_pairing` | 取消 |
|
||||
| `remote_list_devices` / `remote_revoke_device` | 设备管理 |
|
||||
|
||||
### 5.2 双来源聚合规则(GSMTC 为主,AudioEngine 兜底)
|
||||
|
||||
- GSMTC 可用:一切以 GSMTC 当前会话为准。Thing 自身播放时它就是一条普通会话(`SourceAppUserModelId` 识别后标 `isThing: true`)。
|
||||
- GSMTC 无会话但 `AudioEngine` 在播放(GSMTC 初始化失败或会话丢失的兜底):从 `AudioEngine.state()` + 播放队列聚合出 `NowPlaying`(`isThing: true`);控制指令由 server 复用 `music-smtc-button` 事件(同名、同 payload)emit 给前端执行。**既有架构约束**:队列控制逻辑(toggle/next/prev/播放模式)在前端 `feiniuStore`,AudioEngine 本身只有 play/set_playing/seek/stop——兜底路径依赖 WebView 存活,WebView 未就绪时直接回 `cmd-ack { ok: false, error: "frontend-unavailable" }`。
|
||||
- 两者都无:`status: 'stopped'`,手机端显示"电脑未在播放"。
|
||||
|
||||
### 5.3 前端侧
|
||||
|
||||
- `src/modules/music/components/settings/RemoteSettings.vue`:总开关、端口、设备列表(在线状态/撤销)、「连接手机」按钮 → 配对码 + 二维码(`qrcode` 库,5s 轮询 status 刷新倒计时/在线态)。
|
||||
- 状态存放:P0 用 RemoteSettings **组件本地状态**(5s 轮询 `remote_status`),不扩 musicStore——当前无其他消费方;遥控 UI 出现共享需求时再入 store。
|
||||
- `constants.rs`:`REMOTE_WS_*` 等消息类型常量(如需要);本功能的"事件"主要是 WS 而非 Tauri event,前端基本只走 invoke + bindings。
|
||||
|
||||
### 5.4 生命周期
|
||||
|
||||
- 随应用启动初始化(不随模块启用——music 默认启用且常驻),`remote_enabled = false` 时仅不启服务/beacon,GSMTC 监视可保持惰性。
|
||||
- 应用退出:axum graceful shutdown、beacon 停发(`cleanup_on_exit` 挂钩,参照 `MusicManager::cleanup_on_exit` 范式)。
|
||||
- 系统休眠/网络切换:WS 断开由心跳判活;beacon 无状态持续广播即可,无需额外处理。
|
||||
|
||||
---
|
||||
|
||||
## 6. 关键实现细节与已知的坑
|
||||
|
||||
1. **GSMTC 在非打包桌面应用可用**(unpackaged desktop app 明确支持,1809+)。不要被"WinRT 需要 package identity"的泛泛说法劝退——GSMTC 不在受限之列,开源社区大量此类工具可佐证。**2026-09-25 已实证**:`examples/gsmtc_probe.rs`(unpackaged 控制台进程)跑通,读到当前会话元数据/状态/时间轴,核心假设成立。
|
||||
2. **封面(Thumbnail)是 `RandomAccessStreamReference`**:`OpenReadAsync()` → 按 `ContentType`(image/png|jpeg)读全量字节 → 以 `hash(sourceApp + title + album + 尺寸)` 为键存内存 LRU(上限 ~20 张)。推送里只带 `coverHash`,封面走 HTTP 拉取,避免 WS 帧被几百 KB 图片打爆。
|
||||
3. **事件风暴节流**:`TimelinePropertiesChanged` 在部分播放器上高频触发(每次内部时钟更新都发)。聚合层统一节流:任何状态变更合并后**最快 1Hz** 推送 `state`;进度靠手机端 `positionSec + elapsed` 本地推算(`status=playing` 时每秒 +1,收到新 `state` 校准),不依赖高频推送。**例外**:由 `cmd` 触发的状态变更立即推一帧(绕过 1Hz 节流),避免按钮"没反应"的体感——节流仅约束进度等自然高频变更。
|
||||
4. **进度推算基准用 `TimelineProperties.LastUpdatedTime`**,不要用"收到事件的本地时刻"——事件分发有延迟,`LastUpdatedTime` 是播放器侧的权威时间戳。(本条约束 **Thing 侧**把 GSMTC 事件组装成 `positionSec/positionUpdatedAtMs` 的动作;**手机侧** elapsed 的起算基准见 §6.10,两层不要混用。)
|
||||
5. **会话 key 的稳定性**:GSMTC 无显式 sessionId,用 `SourceAppUserModelId` 作 key;同一应用双会话(极少见)时后者覆盖前者,P1 的多会话切换再处理。
|
||||
6. **`Try*Async` 的返回值不可全信**:部分播放器对不可用操作静默成功,回执只做 UI 轻提示,真实状态以下一帧 `state` 为准(`canControl` 能力位已尽力过滤)。
|
||||
7. **AUMID → 友好名**:`SourceAppUserModelId` 是 `PackageFamilyName!App` 或注册表 AUMID,显示名需查 `Get-StartApps` 等价逻辑(注册表 `HKCU\Software\Classes\AppUserModelId`);先显示末段兜底,友好名缓存 LRU。
|
||||
8. **防火墙弹窗只出现一次**(每个 exe 路径 × 网络类型),开发期 `tauri dev` 与正式版 exe 路径不同会各弹一次,属预期。
|
||||
9. **Windows 通知区域"媒体"浮层与 GSMTC 互不干扰**:`smtc.rs` 的上报会话照常工作;手机控制 Thing 自身时,系统面板同步可见,是 feature 不是 bug。
|
||||
10. **进度推算的时钟基准分两层,不要混用**:Thing 侧组装 `positionSec/positionUpdatedAtMs` 用 `TimelineProperties.LastUpdatedTime`(§6.4);手机侧 `elapsed` **一律以本地收到该条 `state` 的时刻起算**,禁止拿 `positionUpdatedAtMs` 与手机本机时间直接做差——电脑时钟偏差(手动对时/休眠漂移可差数秒以上)会整体拖偏进度条。手机端检测到两端时钟偏差 >5s 时冻结推算、只显示基准值,等待下一条 `state` 校准。两端时钟正常时(NTP 同步)此方案残差 ≤ 推送延迟(LAN 上 <1s,且播放中 ~1Hz 校准)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 分阶段计划
|
||||
|
||||
### P0:可用版本(目标:手机能看到并控制电脑当前播放)
|
||||
|
||||
- [x] `windows` crate 开 `Media_Control` feature;10 行探测 demo 验证 GSMTC 在本机可用 —— **2026-09-25 实测通过**(`examples/gsmtc_probe.rs`,unpackaged 控制台进程:读到 1 会话 + 元数据/状态/时间轴全通;注意 `GetSessions`/`GetCurrentSession` 是同步 API,见 §3.1)
|
||||
- [x] `remote/proto.rs`:类型定义(serde,未进 specta——WS 对端是手机,Thing 前端不消费)+ 单测(序列化往返/时间换算/会话 key)——**2026-09-26 完成,8 单测全绿**
|
||||
- [x] `remote/glsmtc.rs`:初始化、事件订阅、`NowPlaying` 聚合、封面 LRU、节流(1Hz + cmd Force 例外)——**完成**;订阅 P0 只挂 Manager 级两事件 + 500ms 节拍轮询(会话级事件需随会话订阅/退订,列入 P1)
|
||||
- [x] `remote/server.rs`:axum 路由 + WS 会话表 + 广播 + 心跳判活 + Bearer/hello 鉴权(+ /pair 限速、封面 token 走 query)——**完成**
|
||||
- [x] `remote/discovery.rs`:UDP beacon(GetAdaptersAddresses 各网卡定向广播)——**完成**
|
||||
- [x] `remote/pairing.rs`:配对码 + token 签发 + 设备表(keyring `music-remote-token-*`)——**完成**(单测含限速)
|
||||
- [x] 控制指令:play/pause/toggle/next/prev/stop/seek → `Try*Async`(spawn_blocking);**Thing 自身 seek 直通 AudioEngine**(SMTC 回环无 seek 通道)——**完成**
|
||||
- [x] 命令注册(collect_commands + generate_handler 双处)+ `RemoteSettings.vue`(开关/配对二维码/设备列表;qrcode 库前端生成)——**完成**;改为组件本地状态,不扩 musicStore(当前无其他消费方,需要时再入 store)
|
||||
- [x] `AudioEngine` 兜底聚合(+ `SmtcMetaCache` 回填标题/歌手/专辑)——**完成**
|
||||
- [x] 运行时冒烟(2026-09-26):自启绑定 `0.0.0.0:26124` ✓、beacon 实收(`addrs=["192.168.110.40"]`、deviceId 落盘)✓、`/api/state` 401 ✓、`/pair` 错码 403 ✓、日志「GSMTC 已初始化(专用线程 MTA)」✓、运行时 bindings 导出含 remote 命令 ✓
|
||||
- [x] 联调:**真机 E2E 完成(2026-09-26)**——LFMusic 真机客户端全流程实测:配对码 142919 → `/pair` 成功(192.168.110.27)→ WS hello 鉴权 → state 推送(封面/元数据/thing.self/能力位)→ 播放暂停上下首控制生效 → App 重启后自动重连。过程修复:手机端 deviceId 语义(存电脑 id 而非 Thing 分配的行 id)与对端显示名两处关联 bug
|
||||
- [ ] P0 验收口径(联调时执行):遥控界面显示 GSMTC `GetCurrentSession` 判定的活跃会话("最近操作"语义,多会话切换只留 UI 入口);进度推算按 §6.10 时钟基准联调;`cmd` 后 1s 内看到状态变化
|
||||
|
||||
### P1:体验完善 —— **2026-09-26 除两项暂缓外全部完成**
|
||||
|
||||
- [ ] mDNS 发现(mdns-sd 注册 `_thingmusic._tcp`)——**暂缓**:beacon 在目标网络 100% 可用且扫码兜底已覆盖;双端 mDNS(含 Android MulticastLock/Kotlin 桥)成本高、当前无失效场景驱动,等 beacon 实际失效案例再做
|
||||
- [x] 多会话列表与手动切换——**完成**:`sessions` WS 消息(watch 变化推送 + 连接首帧)+ `select` 动作(**WinRT 无 SetCurrentSession,实测修正**:Thing 侧选中覆盖,空 id = 跟随系统 current;选中会话消失自动回落);手机端 chips UI(高亮 `isCurrent`)+「跟随系统」
|
||||
- [x] **会话级事件精细化订阅**——**完成**:`SessionSubs` 随目标会话换绑 `MediaPropertiesChanged`/`TimelinePropertiesChanged`/`PlaybackInfoChanged`(切换时先退订后订阅,线程退出统一清理);Manager 级两事件 + 500ms 节拍轮询保留为保底
|
||||
- [x] 系统音量控制 + 手机端音量条——**完成**:`volume.rs`(MMDevice → `IAudioEndpointVolume`,每次现取 COM 对象避免 Send/Sync 争议);监视线程 500ms 轮询进 `NowPlaying.volume/muted`(指纹纳入、变化即推);`volume` 动作 0~1、**>0 自动解除静音**;手机端 🔊 音量条(松手发送)
|
||||
- [x] Thing 直通控制路径评估——**评估结论:落地直通**:`isThing` 按钮类指令直接 emit `music-smtc-button`(跳过 GSMTC→系统→SMTC 回环,少一跳系统派发延迟);seek 本就直通 AudioEngine;非 Thing 会话仍走 GSMTC `Try*Async`。系统面板同步不受影响(面板状态由前端持续上报 smtc.rs)。**真机复测**:非 Thing 路径(QQMusic 播放恢复)通过;isThing 直通与 P0 事件链同码,待 Thing 下次自身播放时自然覆盖
|
||||
- [x] AUMID 友好名缓存、封面本地持久化缓存——**完成**:`friendly_name`(`HKCU\Software\Classes\AppUserModelId\<aumid>\DisplayName` 查询 + 128 条缓存,查不到退回 AUMID 简化段;路径形 AUMID 跳过注册表);`CoverStore` 写透 `{app_data}/remote_covers`(内存+磁盘双层 LRU 各 20 张,冷启动可回源)。**真机复测**:友好名生效(QQMusic / Microsoft.ZuneMusic);持久化目录已创建,落盘写入待下次取到封面时自然验证(当前可见会话均无缩略图)
|
||||
- [ ] 手机端通知栏/锁屏媒体控件联动(LFMusic 侧 native-audio / MediaSession,见对端文档)——**暂缓**:被 LFMusic M1(集成 `tauri-plugin-native-audio`)阻塞,M1 完成后按对端文档回填
|
||||
|
||||
### P2:增强(按需)
|
||||
|
||||
- [ ] 自签 TLS(rcgen + rustls,二维码带证书指纹)
|
||||
- [ ] 投播:手机浏览 Thing 曲库 → 远程下发放进 Thing 播放队列(`/queue` 端点 + AudioEngine 队列 API 暴露)
|
||||
- [ ] 歌词推送(Thing 已有 lyric 能力,同步到手机端滚动显示)
|
||||
- [ ] 多电脑:beacon 天然支持,配对表按 deviceId 区分,UI 侧完善
|
||||
|
||||
---
|
||||
|
||||
## 8. 风险与开放问题
|
||||
|
||||
| 风险/问题 | 影响 | 对策 |
|
||||
|---|---|---|
|
||||
| GSMTC 某播放器不上报专辑/封面(上报方行为,非 bug) | 手机端显示缺字段 | UI 兜底占位;Thing 自身播放时从曲库元数据补全(lofty 已有) |
|
||||
| 路由器 AP 隔离导致广播不可达 | 手机发现不了电脑 | 扫码/手输 IP 兜底(P0 已含);mDNS 同样受影响,不是银弹 |
|
||||
| 防火墙/杀软拦截 LAN 监听 | 手机连不上 | 设置页说明 + 连接失败诊断提示(检测本机端口监听、提示放行) |
|
||||
| 手机休眠断 WS | 状态不实时 | 心跳 + 重连退避(手机端职责,见对端文档);恢复前台即拉 `/api/state` 快照 |
|
||||
| `TryChangePlaybackPositionAsync` 部分应用不支持 | seek 无效 | `canControl.seek` 能力位隐藏进度条拖动 |
|
||||
| 多网段/VPN 虚拟网卡产生杂音 beacon | 发现列表脏数据 | beacon 携带本机各网卡地址,手机端按连通性优选;显示名可区分 |
|
||||
|
||||
**开放问题**(实施前确认):
|
||||
1. 是否需要"电脑端显示已连接手机"的托盘/OSD 提示?(倾向 P1,托盘菜单加一行在线设备数即可)
|
||||
2. 投播的队列控制 API 形态(P2 前与 LFMusic 端一起定)。
|
||||
3. 遥控界面是否需要歌词显示?用户需求"显示音乐信息"是否含歌词——Thing 已有 lyric 能力,但"歌词推送"列在 P2,需两端确认是否提前。
|
||||
4. 音量控制是否提前到 P0?用户"控制电脑端"可能隐含音量——当前计划在 P1(`IAudioEndpointVolume`)。
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,797 @@
|
||||
# Thing UI 设计系统与开发约束
|
||||
|
||||
> **适用范围**:`src/` 下全部前端代码(12 个模块、220+ 组件)
|
||||
> **约束力**:第 7 章为硬性约束,Code Review 据此判定;第 3–5 章为实现规范
|
||||
> **配套**:`UI Design System` 画布(色彩 / 排版 / 组件 / 骨架四屏可视化规范)
|
||||
> **唯一事实来源**:token 值以 `src/style.css` 为准,本文档与之同步
|
||||
|
||||
---
|
||||
|
||||
## 1. 设计原则
|
||||
|
||||
以下 8 条为不可协商项,贯穿全部模块。
|
||||
|
||||
**P1 · 单一强调色**
|
||||
全应用只有 `--primary` 一种交互色,用于按钮、链接、选中态、焦点环。不存在"第二个主题色"。状态色(success/warning/danger)仅表达**状态**,不得用于可点击元素。
|
||||
|
||||
**P2 · 颜色只能来自 token**
|
||||
禁止在组件内写 hex、rgb、oklch,禁止引用 Tailwind 原生色阶(`bg-blue-500`、`text-emerald-700`)。组件里出现的每个颜色都必须能追溯到 `style.css` 的一个语义变量。
|
||||
|
||||
**P3 · 状态必须四态齐全**
|
||||
任何数据驱动的界面必须实现 **加载 / 空 / 错误 / 成功** 四态。禁止空白,禁止静默失败。这是最容易漏、也最影响质感的一条。
|
||||
|
||||
**P4 · 一个主区域,一个主操作**
|
||||
每屏有且仅有一个视觉重心、一个主按钮。破坏性操作(停止内核、删除记录)必须视觉降级或二次确认,且不得与主操作同权重。
|
||||
|
||||
**P5 · 骨架统一,内容区自治**
|
||||
所有模块共享同一套外壳(侧边栏 / 标题栏 / Tab 行)。**模块之间允许不同的只有内容区布局**——这是"统一"与"灵活"的分界线。
|
||||
|
||||
**P6 · 密度一致**
|
||||
全应用统一使用**紧凑偏中**密度:13px 正文、34px 控件、16px 卡片内边距。禁止在同一屏内混用疏密两种节奏。
|
||||
|
||||
**P7 · 卡片统一描边 + 轻阴影,浮层用重阴影**
|
||||
层级靠**表面色差 + 1px 描边 + 轻阴影(`shadow-sm` / `--shadow-card`)**表达。浮层(下拉、气泡、对话框)使用更重的 `--shadow-popover` / `--shadow-dialog`。
|
||||
|
||||
**P8 · 中文界面不做负字距**
|
||||
字体模板中的负字距(`-0.28px` 等)是为拉丁字母设计的,会让中文发挤。**拉丁文与数字可保留微调,中文一律 `letter-spacing: 0`。**
|
||||
|
||||
---
|
||||
|
||||
## 2. Design Token
|
||||
|
||||
### 2.1 命名与结构
|
||||
|
||||
Token 分四组,**在现有 shadcn 变量之上扩展,不另起一套**:
|
||||
|
||||
```
|
||||
shadcn 既有(值调整) → --background / --foreground / --primary / --card / --border / ...
|
||||
本项目扩展 → --canvas / --fg-* / --success / --warning / --data-* / --shadow-*
|
||||
```
|
||||
|
||||
**关键调整**:把 shadcn 的 `--primary` 从当前近黑色(`oklch(0.21 0.006 285.885)`)改为强调蓝 `#0066CC`。这样全部 shadcn 组件(Button / Switch / Checkbox / focus ring)自动获得统一的交互色,无需逐组件改样式。
|
||||
|
||||
### 2.2 色彩
|
||||
|
||||
#### 浅色模式(`:root`)
|
||||
|
||||
```css
|
||||
:root {
|
||||
/* ── 表面 ───────────────────────────── */
|
||||
--canvas: #F5F5F7; /* 应用底 / 模块内容区背景 */
|
||||
--background: #FFFFFF; /* shadcn 基准面 */
|
||||
--card: #FFFFFF; /* 卡片 / 面板 */
|
||||
--popover: #FFFFFF; /* 浮层 */
|
||||
--subtle: #F0F0F2; /* 次级填充:搜索框底、分段控件槽、代码块 */
|
||||
--hover: #EBEBED; /* 通用中性 hover:按钮、菜单项、数据表、导航 */
|
||||
--active: #E4E4E7; /* 幽灵控件 active */
|
||||
--row-hover: #EBF3FB; /* 内容行 hover(= primary 8% 混入 card,随主题色变) */
|
||||
--row-selected: #D9E8F7; /* 内容行选中(= primary 15% 混入 card) */
|
||||
--row-hover-veil: color-mix(in srgb, var(--primary) 16%, transparent); /* mica 弹窗行 hover */
|
||||
--row-selected-veil: color-mix(in srgb, var(--primary) 30%, transparent); /* mica 弹窗行选中 */
|
||||
|
||||
/* ── 描边 ───────────────────────────── */
|
||||
--border: #E4E4E7; /* 卡片外框、输入框 */
|
||||
--border-strong: #D1D1D6; /* 需要更强分隔时 */
|
||||
--divider: #F0F0F2; /* 卡片内部分隔线(1px) */
|
||||
--input: #E4E4E7;
|
||||
|
||||
/* ── 文字 ───────────────────────────── */
|
||||
--foreground: #1D1D1F; /* 主文字:标题、正文、数值 */
|
||||
--fg-secondary: #55555C; /* 次文字:键名、标签说明、幽灵控件文字 */
|
||||
--muted-foreground: #8A8A90; /* 辅助:占位符、规格说明、次级 meta */
|
||||
--fg-disabled: #B4B4BA; /* 禁用 */
|
||||
|
||||
/* ── 强调 ───────────────────────────── */
|
||||
--primary: #0066CC;
|
||||
--primary-hover: #0055B3;
|
||||
--primary-active: #004A9E;
|
||||
--primary-foreground: #FFFFFF;
|
||||
--primary-soft: #E8F1FC; /* 选中 Tab 底、选中行底 */
|
||||
--primary-soft-text: #004F9E; /* 上述底上的文字 */
|
||||
--ring: #0071E3;
|
||||
|
||||
/* ── 语义状态 ───────────────────────── */
|
||||
--success: #0F7B4F; --success-soft: #E7F5EE; --success-text: #0B5C3B;
|
||||
--warning: #A96B00; --warning-soft: #FDF4E4; --warning-text: #7D4F00;
|
||||
--danger: #C7362F; --danger-soft: #FDECEA; --danger-text: #9A2620;
|
||||
--info: #0066CC; --info-soft: #E8F1FC; --info-text: #004F9E;
|
||||
--neutral: #8A8A90; --neutral-soft: #F0F0F2; --neutral-text: #55555C;
|
||||
--destructive: #C7362F; /* shadcn 兼容别名,指向 danger */
|
||||
--destructive-foreground: #FFFFFF;
|
||||
|
||||
/* ── 数据方向(与状态语义解耦)───────── */
|
||||
--data-down: #0F7B4F; /* 下载 / 入站 */
|
||||
--data-up: #C7362F; /* 上传 / 出站 */
|
||||
|
||||
/* ── 尺寸 ───────────────────────────── */
|
||||
--radius: 12px;
|
||||
--radius-xs: 4px; --radius-sm: 6px; --radius-md: 8px;
|
||||
--radius-lg: 12px; --radius-xl: 16px;
|
||||
|
||||
/* ── 阴影 ───────────────────────────── */
|
||||
--shadow-card: 0 1px 2px rgba(0,0,0,0.06);
|
||||
--shadow-popover: 0 1px 3px rgba(0,0,0,0.06), 0 4px 16px rgba(0,0,0,0.10);
|
||||
--shadow-dialog: 0 4px 12px rgba(0,0,0,0.08), 0 20px 48px rgba(0,0,0,0.16);
|
||||
}
|
||||
```
|
||||
|
||||
#### 深色模式(`.dark`)
|
||||
|
||||
深色下**必须成对重定义**,且强调色改为亮蓝(`#0066CC` 在深底上对比度不足):
|
||||
|
||||
```css
|
||||
.dark {
|
||||
--canvas: #16161A;
|
||||
--background: #16161A;
|
||||
--card: #1E1E22;
|
||||
--popover: #1E1E22;
|
||||
--subtle: #26262B;
|
||||
--hover: #2C2C32;
|
||||
--active: #33333A;
|
||||
--row-hover: #1F2B3A; /* = primary 11% 混入 card(深色下用更高强度) */
|
||||
--row-selected: #213E5C; /* = primary 26% 混入 card */
|
||||
/* --row-*-veil 刻意不在此重写:半透明叠在壁纸上,深浅由 --primary 自动决定 */
|
||||
|
||||
--border: #2E2E34;
|
||||
--border-strong: #3A3A42;
|
||||
--divider: #26262B;
|
||||
--input: #2E2E34;
|
||||
|
||||
--foreground: #FFFFFF; /* 深色下主文字用纯白 */
|
||||
--fg-secondary: #ECECF2;
|
||||
--muted-foreground: #D2D2DA;
|
||||
--fg-disabled: #9A9AA4;
|
||||
|
||||
--primary: #2997FF;
|
||||
--primary-hover: #4AA8FF;
|
||||
--primary-active: #1A85E8;
|
||||
--primary-foreground: #FFFFFF;
|
||||
--primary-soft: #14304D;
|
||||
--primary-soft-text: #7FC0FF;
|
||||
--ring: #2997FF;
|
||||
|
||||
--success: #3DC77F; --success-soft: #12301F; --success-text: #7FE0AB;
|
||||
--warning: #E0A83C; --warning-soft: #33260E; --warning-text: #F0C976;
|
||||
--danger: #FF6B60; --danger-soft: #3A1A18; --danger-text: #FF9E96;
|
||||
--info: #2997FF; --info-soft: #14304D; --info-text: #7FC0FF;
|
||||
--neutral: #7A7A82; --neutral-soft: #26262B; --neutral-text: #A8A8B0;
|
||||
--destructive: #FF6B60; --destructive-foreground: #FFFFFF;
|
||||
|
||||
--data-down: #3DC77F;
|
||||
--data-up: #FF6B60;
|
||||
}
|
||||
```
|
||||
|
||||
#### 状态色三件套的用法
|
||||
|
||||
每个语义状态有 **3 个** token,用途严格区分:
|
||||
|
||||
| Token | 用途 | 示例 |
|
||||
|---|---|---|
|
||||
| `--success` | 实心:状态点、图标、粗体数值 | ● 运行中 的圆点 |
|
||||
| `--success-soft` | 浅底:徽章背景、行高亮 | `<span class="bg-success-soft">` |
|
||||
| `--success-text` | 浅底上的文字 | 徽章内的"已安装" |
|
||||
|
||||
**禁止**把 `--success` 用作文字色 + `--success-soft` 以外的底色组合,也**禁止**用状态色做可点击元素的颜色(见 P1)。
|
||||
|
||||
#### 强调色的使用边界
|
||||
|
||||
`--primary` 只表达两件事:**这里可以点**、**这里是当前项**。
|
||||
|
||||
| 用 | 不用 |
|
||||
|---|---|
|
||||
| 主按钮底色、开关开启态、焦点环 | 卡片标题前的**装饰性图标** |
|
||||
| 当前 Tab / 选中列表行 / 选中项 | 全部 Tab 的图标 |
|
||||
| 可点击的文字链接 | 状态徽章(那是状态语义色的职责) |
|
||||
| 输入框聚焦态 | 大面积背景、分隔线、装饰元素 |
|
||||
|
||||
**反例(已修正)**:proxy 概览页的 6 个卡片标题图标全部用了 `text-primary`,加上主按钮、开关、选中态,整屏发蓝 —— 结果"蓝色"不再意味着"可点击",层次感也丢了。已统一改为 `--fg-secondary`。
|
||||
|
||||
#### 数据方向色(`--data-*`)
|
||||
|
||||
下载/上传速率沿用现有视觉(绿/红),但独立成 token,**与 `success/danger` 解耦**。
|
||||
|
||||
> **待决策**:当前 `data-up` 与 `danger` 同色,会让人把"上传速率"误读为"异常"。若希望彻底解耦,建议改为
|
||||
> `--data-down: #0066CC`(蓝)/ `--data-up: #A96B00`(琥珀)。这是**唯一改动成本为零**的时机——只需改两个 token。
|
||||
|
||||
### 2.3 排版
|
||||
|
||||
字体族保持不变(现有 `--font-sans` 已正确针对中文优化):
|
||||
|
||||
```css
|
||||
--font-sans: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
|
||||
'Microsoft YaHei', 'PingFang SC', 'Noto Sans SC', sans-serif;
|
||||
--font-mono: 'JetBrains Mono', 'Cascadia Code', Consolas, monospace;
|
||||
```
|
||||
|
||||
生产代码不引用外部字体 CDN(设计稿 / 原型页可保留 Inter);数值对齐通过全局 `font-feature-settings: 'tnum','lnum'` 实现,不依赖具体字体。
|
||||
|
||||
字号标尺(9 级,全部为 `px`):
|
||||
|
||||
| Token | 字号 / 字重 | 行高 | 用途 |
|
||||
|---|---|---|---|
|
||||
| `display` | 28 / 700 | 36 | 页面级大标题(设置页、关于页),**全应用不超过 1 处/屏** |
|
||||
| `metric` | 22 / 600 | 28 | 关键数值(速率、容量)· **必须 `font-variant-numeric: tabular-nums`** |
|
||||
| `h1` | 16 / 600 | 24 | 模块标题、卡片标题 |
|
||||
| `h2` | 14 / 600 | 20 | 区块标题、卡片标题(小卡) |
|
||||
| `h3` | 13 / 600 | 20 | 小节标题、列表分组标题 |
|
||||
| `body` | 13 / 400 | 20 | **界面默认正文** |
|
||||
| `body-strong` | 13 / 600 | 20 | 行内强调、键值行的键 |
|
||||
| `caption` | 12 / 400 | 18 | 辅助说明、参数解释 |
|
||||
| `label` | 11 / 500 | 16 | 徽章、标签、表头、单位 |
|
||||
|
||||
**规则**:
|
||||
|
||||
1. 字号只从以上 9 级中取,**禁止 `text-[13.5px]` 这类任意值**。
|
||||
2. 数值(速率、版本号、计数)统一用 `tabular-nums`,避免刷新时数字跳动。
|
||||
3. 中文 `letter-spacing: 0`;拉丁小标题可 `-0.1px`,正文一律 `0`。
|
||||
4. 行高按表中固定值写,不用 Tailwind 默认相对行高。
|
||||
|
||||
### 2.4 间距
|
||||
|
||||
4px 基数,**8 个值,用尽即止**:
|
||||
|
||||
| Token | 值 | 典型用途 |
|
||||
|---|---|---|
|
||||
| `space-1` | 4 | 图标与文字间隙、徽章内边距(纵向) |
|
||||
| `space-2` | 8 | 控件内元素间隙、徽章内边距(横向) |
|
||||
| `space-3` | 12 | 列表行内间隙、卡片标题与内容间距 |
|
||||
| `space-4` | 16 | **卡片内边距、卡片间距** |
|
||||
| `space-5` | 20 | **模块内容区默认内边距** |
|
||||
| `space-6` | 24 | 区块之间、对话框内边距 |
|
||||
| `space-8` | 32 | 大区块分隔 |
|
||||
| `space-12` | 48 | 页面级分段 |
|
||||
|
||||
**禁止** `p-[18px]`、`gap-[14px]`、`mt-[6px]`。需要更细的调整时,说明是布局问题而非间距问题。
|
||||
|
||||
### 2.5 圆角
|
||||
|
||||
| Token | 值 | 适用 |
|
||||
|---|---|---|
|
||||
| `radius-xs` | 4 | 内联小元素:标签内块、进度条端点 |
|
||||
| `radius-sm` | 6 | 徽章、小按钮、下拉项 |
|
||||
| `radius-md` | 8 | **按钮、输入框、下拉框、分段控件、Tab 项** |
|
||||
| `radius-lg` | 12 | **卡片、面板、样张容器** |
|
||||
| `radius-xl` | 16 | 对话框、大浮层 |
|
||||
| `radius-full` | 9999 | 状态点、开关、头像、搜索框(胶囊) |
|
||||
|
||||
**规则**:同层级控件必须同圆角。按钮 8px 就全应用 8px,不允许某模块用 6px。
|
||||
|
||||
### 2.6 阴影与层级
|
||||
|
||||
**层级主要靠表面色差 + 描边 + 轻阴影**(P7):
|
||||
|
||||
| 层级 | 表现 | 用途 |
|
||||
|---|---|---|
|
||||
| L0 应用底 | `--canvas`,无描边无阴影 | 窗口、模块内容区 |
|
||||
| L1 卡片 | `--card` + 1px `--border` + 轻阴影 `shadow-sm` | 所有卡片、面板 |
|
||||
| L1.5 次级容器 | `--subtle`,无描边 | 搜索框底、分段控件槽、代码块 |
|
||||
| L2 浮层 | `--card` + `--shadow-popover` | 下拉菜单、气泡、tooltip、右键菜单 |
|
||||
| L3 模态 | `--card` + `--shadow-dialog` + 遮罩 | 对话框、AlertDialog |
|
||||
|
||||
卡片默认使用轻阴影 `--shadow-card`(`shadow-sm`);`--shadow-popover` / `--shadow-dialog` 仅用于浮层与模态。
|
||||
|
||||
### 2.7 动效
|
||||
|
||||
```css
|
||||
--ease-standard: cubic-bezier(0.22, 0.61, 0.36, 1); /* 沿用现有 tab-animate 曲线 */
|
||||
--duration-fast: 120ms; /* hover、颜色变化 */
|
||||
--duration-base: 200ms; /* 展开、浮层出现 */
|
||||
--duration-slow: 320ms; /* 页面/Tab 切换 */
|
||||
```
|
||||
|
||||
**规则**:
|
||||
|
||||
1. 只对 `opacity` 和 `transform` 做动画(性能)。
|
||||
2. 按钮按下统一 `transform: scale(0.97)`,不用颜色变化模拟按压。
|
||||
3. 所有动画必须包在 `@media (prefers-reduced-motion: reduce)` 里降级为 `none`(现有 `.music-eq` 已正确实现,作为模板)。
|
||||
4. Tab 切换复用现有全局 `.tab-animate` 类,**不要各模块自建过渡**。
|
||||
|
||||
### 2.8 图标
|
||||
|
||||
- 库:`@lucide/vue`,**禁止混用其他图标库或内联 Unicode 符号**(`↓` `✓` `●` 等)。
|
||||
- 尺寸只有 3 档:`14`(行内 / 徽章内)、`16`(按钮、Tab、默认)、`20`(侧边栏、卡片标题)。
|
||||
- `stroke-width` 统一 `1.75`(lucide 默认 2,偏粗,与 13px 正文不协调)—— 在 `style.css` 里对 `.lucide` 全局设置,不要逐个组件写。
|
||||
- 图标**不单独承载语义**:状态点旁必须有文字,工具栏图标必须有 tooltip 或文字标签(P4 可理解性)。
|
||||
|
||||
### 2.9 主题色自定义(已落地)
|
||||
|
||||
**需求**:设置页提供主题色选择,统一改变全应用的强调色。
|
||||
|
||||
**可行性**:可行且成本低 —— 因为全应用的"可交互色"已经收敛到单一来源 `--primary`。落地后组件层改动为 0。
|
||||
|
||||
**实现**:`src/lib/theme.ts`(派生 + 应用)+ `appStore.setAccent()` + 设置页「主题色」卡片。
|
||||
用户**只选一个基色**,深浅两套由代码派生 —— 不需要为浅色/深色各选一次(同色相两个亮度是既有做法:
|
||||
浅 `#0066cc` / 深 `#2997ff`),也不会出现"浅色选青、深色选紫"的语义割裂。
|
||||
|
||||
#### 需要派生的变量
|
||||
|
||||
只改基色是不够的,必须同时派生 7 个变量,否则 hover / 选中态仍是旧色:
|
||||
|
||||
| 变量 | 派生规则(OKLCH,色相 H 原样保留) | 用途 |
|
||||
|---|---|---|
|
||||
| `--primary` | 基色,L 归一到 `0.42–0.58`(浅)/ `0.68–0.80`(深),C 限制在 `0.06–0.20` | 主按钮、开关、焦点环 |
|
||||
| `--primary-hover` | 浅:L − 0.08;深:L + 0.06 | 主按钮 hover |
|
||||
| `--primary-active` | 浅:L − 0.16;深:L − 0.10 | 主按钮按下 |
|
||||
| `--primary-soft` | 浅:`oklch(0.95, C×0.30, H)`;深:`oklch(0.30, C×0.45, H)` | 选中底、幽灵按钮 hover |
|
||||
| `--primary-soft-text` | 基色加深/提亮起步,再按对比度推进到 ≥4.5:1 | 上述底上的文字 |
|
||||
| `--ring` | 同 `--primary` | 焦点环 |
|
||||
| `--primary-foreground` | 白字低于 2.5:1 时才换 `#1D1D1F` | 填充上的文字 |
|
||||
|
||||
深色模式**单独派生一套**(深底上要提亮),不能复用浅色值。
|
||||
|
||||
行高亮这一族(`--row-hover` / `--row-selected` / `--row-hover-veil` / `--row-selected-veil`)
|
||||
**不在这 7 个之内**:它们在 `style.css` 里写成 `color-mix(..., var(--primary) ...)`,
|
||||
而 `--primary` 的行内覆盖是惰性求值的,所以换主题色时自动跟着变,
|
||||
不需要进 `theme.ts` 的派生组,也不需要新增断言。
|
||||
|
||||
#### 关键技术点
|
||||
|
||||
1. **用 OKLCH 做派生,不要用 HSL。**
|
||||
只换色相 H、锁定 L 与 C,才能保证换任意色相后对比度一致。HSL 的"明度"感知不均匀,换色相会时亮时暗。
|
||||
|
||||
2. **对比度靠"推进亮度"而不是固定阈值判定。**
|
||||
同一 OKLCH L 下不同色相的 WCAG 亮度差很多(L=0.58 的青柠对白底只有 ~2.8:1,蓝色却有 ~5:1),
|
||||
所以归一到区间后还要继续推进 L 直到达标:
|
||||
- 浅色:`--primary` 对 `#FFFFFF` ≥ 4.5:1(它会被当文字用在白卡上)→ 选亮色自动压暗
|
||||
- 深色:`--primary` 对 `#1E1E22` ≥ 4.5:1 → 自动提亮
|
||||
- `--primary-soft-text` 对 `--primary-soft` ≥ 4.5:1
|
||||
以上断言在 `src/lib/theme.test.ts` 里对 10 个预设 × 2 模式全量校验。
|
||||
|
||||
3. **`--primary-foreground` 的取舍是有意的。**
|
||||
深色模式下强调色必须够亮才能在深底上当文字用(≥4.5:1),同一颜色做填充时白字只能到 2.7–3:1 ——
|
||||
现有主题就是这个取舍(`#2997ff` + 白字 ≈ 2.98:1)。因此门槛按 UI 组件的 2.5:1 兜底,
|
||||
只在自定义极亮色时才改深墨。
|
||||
|
||||
4. **只开放"强调色",不开放状态色。**
|
||||
`success` / `warning` / `danger` 是语义色,改了会破坏"绿色=成功"的心智模型。`--data-*` 同理。
|
||||
`--info` 一族当前取值与强调色相同(蓝),但**不跟随**主题色 —— 它表达"信息"而非"可交互",
|
||||
换紫/绿主色后少数徽标(代理"国外"、HTTP 1xx/3xx、快速面板分类)仍是蓝色,属有意的语义区分。
|
||||
|
||||
5. **预设 + 自定义。**
|
||||
10 个预设(默认蓝 / 靛蓝 / 紫罗兰 / 玫红 / 橙 / 琥珀 / 青柠 / 翠绿 / 青绿 / 石墨)+ 原生取色器。
|
||||
纯自由取色很容易选出对比度不达标的颜色,所以色板优先。
|
||||
色板显示色用**派生后的浅色模式主色**(所见即所得,如青柠显示为压暗后的绿)。
|
||||
|
||||
6. **实时预览 + 可回滚。**
|
||||
点击色块 / 拖动取色器立即生效(写 7 个变量,无防抖);「恢复默认」清除行内变量回到内置蓝。
|
||||
|
||||
7. **持久化**:随其它设置写入 `thing_app_settings`(`accentId` + `accentHex`)。
|
||||
属**纯增量字段**,`SETTINGS_VERSION` 不递增 —— 递增会命中"版本不匹配清空"分支,
|
||||
把用户的模块排序/启停/开机自启一并抹掉,为零收益付真实数据损失。
|
||||
|
||||
8. **行内变量的优先级陷阱。**
|
||||
变量写在 `documentElement` 的行内样式上,优先级高于 `:root` 与 `.dark` 两条规则,因此:
|
||||
切模式必须**整组 7 个重写**(否则浅色的行内值会残留到深色模式);
|
||||
恢复默认必须 `removeProperty`(写空串仍算"已设置")。
|
||||
|
||||
#### 落地范围
|
||||
|
||||
- `src/lib/theme.ts` —— 派生计算 + 应用/清除(新增,含单测)
|
||||
- `src/stores/appStore.ts` —— `accentId`/`accentHex` + `setAccent()`,在 `applyTheme()` 与
|
||||
`handleSystemThemeChange()` 里按当前模式应用
|
||||
- `src/modules/settings/GeneralSettings.vue` —— 「主题色」卡片
|
||||
- 9 个独立窗口(快速面板 / 托盘菜单 / 下载窗 / 剪贴板弹窗与预览 / 翻译弹窗 / 截图覆盖层·编辑器·贴图)
|
||||
各加一行 `applyStoredAccent()`;托盘菜单额外补 `storage` 监听
|
||||
- `src/style.css` —— **无需改动**(7 个变量已是 CSS 变量)
|
||||
- **首屏闪烁(FOUC)不需要额外处理**:主窗口 `visible: false`,`appStore.init()` 在 `show()` 前完成应用;
|
||||
文档原建议的 Rust `initialization_script` 方案与本仓库 localStorage 方案冲突,不实施
|
||||
|
||||
**影响面:0 处组件改动。** 这正是把交互色收敛到 `--primary` 单点带来的收益 —— 现在不做,将来也不用挨个改组件。
|
||||
|
||||
---
|
||||
|
||||
## 3. 页面框架
|
||||
|
||||
框架只定义三件事:**谁多高、谁滚动、padding 加在哪**。这三件事定死之前,任何模块级的美化都会被布局 bug 吃掉。
|
||||
|
||||
### 3.1 分区与高度约束链
|
||||
|
||||
```
|
||||
AppShell h-screen flex-col
|
||||
├ TitleBar h-14 shrink-0 固定 · 侧栏图标 + 模块 Tab + 搜索
|
||||
└ 主体 flex-1 min-h-0 flex-row
|
||||
├ Sidebar w-15 shrink-0 60px 固定
|
||||
└ 内容滚动区 flex-1 min-h-0 overflow-y-auto ← 全应用唯一滚动容器
|
||||
└ 内容 wrapper p-5(占满内容宽,无 max-width)
|
||||
```
|
||||
|
||||
Tab 已并入标题栏(见 3.5),内容区不含独立 Tab 行,纵向空间最大化。
|
||||
|
||||
**三个必须遵守的点**(都是实际踩过的坑,不是理论):
|
||||
|
||||
1. **`min-h-0` 不能漏。**
|
||||
flex 子项默认 `min-height: auto` —— 内容变高时它**不收缩**,直接把父容器顶破,底部 padding 被推出视口。这就是"卡片贴着应用底部"的根因。
|
||||
|
||||
2. **padding 加在滚动容器**内部**的 wrapper 上。**
|
||||
加在滚动容器自身,底部 padding 会被内容高度覆盖,滚动到底依然贴边。
|
||||
|
||||
3. **断点按内容宽度选,不按视口宽度。**
|
||||
侧边栏固定占 60px —— 视口 1000px 时内容只剩 940px。两列网格必须用 `md`(768) 而不是 `lg`(1024),否则窗口一窄就退化成单列全宽、卡片大片留白。
|
||||
|
||||
### 3.2 滚动归属
|
||||
|
||||
**全应用只有一处滚动容器。**
|
||||
|
||||
- 模块内容区随外层滚动,**不是**每个模块各建一个滚动容器
|
||||
- 模块根 / 页面级容器**禁止** `overflow-y-auto` —— 那会绕过外层 `ScrollArea`,出现原生宽滚动条(快速面板踩过);根容器一律 `min-h-full`
|
||||
- 局部列表(剪贴板历史、音乐队列等)**可以用 `ScrollArea` 组件**做独立滚动 —— 这是「局部区域」而非「页面级」
|
||||
- 需要固定表头的长表格:用 `position: sticky` 固定表头,而不是给表格单独开滚动容器
|
||||
- 例外:terminal / translate 的工作台面板内部滚动(workbench 模式特征)
|
||||
- 代价:切换 Tab 时共享同一个滚动位置(可以接受,反而更符合"翻页"直觉)
|
||||
|
||||
**统一组件使用规则**(违规即 UI 不一致,等同违反第 5 章 D 系):
|
||||
|
||||
| 需求 | 用 | 禁止 |
|
||||
|---|---|---|
|
||||
| 页面滚动 | 外层 `ScrollArea`(自动,模块无需处理) | 模块根 `overflow-y-auto` |
|
||||
| 局部列表滚动 | `ScrollArea` 组件 | 原生 `overflow` |
|
||||
| 键值行 / 状态点 / 徽章 / 大数值 | `@/components/common` 对应组件 | 手写 flex 结构 |
|
||||
| 卡片 | `Card` / `InfoGroup(card)` / `StatCard`(统一 `shadow-sm`) | 手写描边块 |
|
||||
| 多分组设置表单 | `SettingGroup` + `SettingRow` | 手写行 |
|
||||
|
||||
### 3.3 内容区宽度
|
||||
|
||||
内容区**不限宽,占满窗口宽度**(已移除 `max-w-6xl` 限制)。窗口拉宽时卡片随内容区延展,不再居中约束。
|
||||
|
||||
### 3.4 内容区布局模式
|
||||
|
||||
内容区**只能**从以下五种里选,不得自创:
|
||||
|
||||
| 模式 | 适用 | 规格 |
|
||||
|---|---|---|
|
||||
| `grid` | 概览 / 状态总览 | `grid-cols-1 md:grid-cols-2`·gap 16·`items-start` 让卡片各自高度 |
|
||||
| `split` | 列表类(clipboard / music / terminal) | 左栏 280–320px·右栏 fill·中间 1px `--border`·无 padding |
|
||||
| `workbench` | 输入-输出类(devtools / translate) | 纵向堆叠·gap 12 |
|
||||
| `settings` | 设置页 | 纵向堆叠·gap 24·复用 `SettingGroup` |
|
||||
| `plain` | 其他 | 纵向堆叠·gap 12 |
|
||||
|
||||
**`grid` 的用法边界**:只适合「各块内容量接近」的概览页。若各块信息量差异大,两列会让矮的那列留空。
|
||||
|
||||
**概览页标准结构 · 「状态横幅 + 卡片网格」**(适用于 proxy / 下载 / 硬件监控,四处横幅已统一,见下方「落地状态」):
|
||||
|
||||
```
|
||||
第一行:状态横幅(全宽,独立于网格,高约 76px)
|
||||
├ 容器 `Card`(`!py-0 !gap-0`)+ `CardContent`(`flex flex-wrap items-center gap-x-6 gap-y-3 px-4 py-4`)
|
||||
│ 圆角/描边/阴影一律由 Card 提供(`rounded-xl + border + shadow-sm`),禁止手写 `rounded-lg border bg-card`
|
||||
├ 左组成组(状态 → 核心属性 → 实时指标,依次靠左,不把指标悬在中间)
|
||||
│ 状态区 状态点 8px + 状态文字 13px/500 + 进程名 13px 次要色(状态点/文字用语义色;运行态加 status-dot-pulse)
|
||||
│ 指标区 label 11px 灰 + 数值 18px/600 tabular-nums;核心属性(如内核版本、PID)也占一个指标位
|
||||
└ 操作区 运行中 = 重启(outline)+停止(destructive);停止 = 启动(primary);sm = 32px;`ml-auto` 推到行尾
|
||||
下方:**两列瀑布流** `columns-1 md:columns-2`(卡片 `break-inside-avoid`,列间距/卡间距 16px),`InfoGroup variant="card"`
|
||||
├ 卡内键值**一律单列**(`InfoGroup columns=1`,一行一条)—— 双列键值会挤压值区,路径类长值被截断
|
||||
├ 瀑布流各卡自然高度、列内堆叠,**没有「同行等高」的配对压力** —— 双列网格的配对调整是反复返工的根源,已废弃
|
||||
├ 表单类内容(下拉/输入)用「label 在上 + 控件全宽」纵排,不塞进键值行的值区
|
||||
└ 阅读顺序为纵向(先左列后右列),分组按重要性排序;列底部不齐是模型特征,不是缺陷
|
||||
```
|
||||
|
||||
**适用判断**:模块概览有「一个核心状态 + 2-4 个实时指标 + 一个主操作」就用横幅;三者不齐的模块直接用卡片网格,不要硬凑横幅。
|
||||
|
||||
**落地状态**(2026-09-21 统一):proxy 概览 / proxy 连接 / 下载任务 / 硬件监控概览四处横幅均按本节实现 ——
|
||||
- 硬件监控:`PID / 传感器 / 重启 / 事件` 从 `text-xs` 内联「标签: 值」提升为指标位,进程名用 `ThingHK`,操作区 `xs` → `sm`,停止按钮改 `destructive`
|
||||
- 下载:`下载中 / 等待 / 已暂停 / 已完成 / 已取消` 从 `Badge` 改为指标位,且恒显(0 比隐藏更真实,也避免位置漂移)
|
||||
- 状态文字一律「状态 + 进程名」顺序(`运行中 mihomo` / `已连接 ThingHK` / `运行中 下载引擎`)
|
||||
|
||||
**已否决的两个方案**(避免回头再试):
|
||||
- **平铺分组**(InfoGroup 无容器版):无容器所以视觉"散";键值两端对齐导致一行一条时"空"。
|
||||
- **等宽两列卡片**:内容量不齐导致列内留白。D2 之所以成立,是横幅吸收了最"高"的内容(状态+指标),剩下的卡片内容量天然接近。
|
||||
|
||||
**设置行**结构(`SettingGroup` + `SettingRow`):
|
||||
```
|
||||
分组标题(h2 14/600)+ 可选说明
|
||||
└ 设置行:左 label · 右控件,行高 44,行间 1px --divider
|
||||
```
|
||||
|
||||
### 3.5 导航与 Tab
|
||||
|
||||
**Tab 只有一处:标题栏。** 模块内容区不再渲染 Tab 行。
|
||||
|
||||
| 层级 | 位置 | 内容 |
|
||||
|---|---|---|
|
||||
| 一级导航 | 侧边栏 60px | 模块图标(代理 / 音乐 / 剪贴板…) |
|
||||
| 二级导航 | **标题栏内** | 当前模块的 Tab(概览 / 连接 / 节点 / 订阅 / 设置) |
|
||||
|
||||
**为什么**:Tab 行独占 48px 纵向空间,却只承载一个切换器。并入标题栏后,内容区最大化。
|
||||
|
||||
**实现**:
|
||||
```ts
|
||||
useModuleTabs('proxy', activeTab, tabs, { alwaysVisible: true })
|
||||
```
|
||||
- 模块**不渲染** `TabsList`,标题栏切换器常驻
|
||||
- 传 `alwaysVisible` 后不再注册 `IntersectionObserver`
|
||||
- 未传该选项的模块保持原行为(Tab 行滚出视口时才在标题栏补一个)—— 属过渡状态,应逐步迁移
|
||||
|
||||
**选中态**:`--primary` 实心胶囊 + 白字。标题栏空间小、Tab 数量少,实心比下划线更易扫读。
|
||||
|
||||
> 过渡期存在两套 Tab 外观:模块内的 `TabsList`(下划线)与标题栏切换器(实心胶囊)。**全部模块迁移完成后,只保留标题栏这一套**,那时 `TabsTrigger` 的下划线样式可以简化掉。
|
||||
|
||||
### 3.6 状态覆盖(P3 落地)
|
||||
|
||||
每种模式都必须实现四态,**抽成通用组件,不在模块内手写**:
|
||||
|
||||
| 状态 | 组件 | 表现 |
|
||||
|---|---|---|
|
||||
| 加载 | `<StateBlock variant="loading">` | Spinner 16px + "加载中…",高度撑满容器最小 120px |
|
||||
| 空 | `<StateBlock variant="empty">` | 图标 32px(`--muted-foreground`) + 说明 caption + 可选主按钮 |
|
||||
| 错误 | `<StateBlock variant="error">` | 图标 32px(`--danger`) + 错误信息 + "重试"次按钮 |
|
||||
| 无权限 | `<StateBlock variant="denied">` | 图标 + 说明 + 引导操作 |
|
||||
|
||||
**验收**:随机打开任一模块的任一 Tab,断网/清空数据/制造错误,都必须看到对应的块,而不是空白。
|
||||
|
||||
### 3.7 页面构造示例 · proxy(样板,含其余四页规划)
|
||||
|
||||
概览页已定稿(横幅 + 瀑布流)。其余四页用**同一套模式**组装,空态一律按 M8(结构恒定 + `—` 占位):
|
||||
|
||||
**统一原则(四页共用)**
|
||||
1. 每页从 3.4 的模式里选一种承载,不自创
|
||||
2. 统计类信息统一用「指标行」形态(与横幅指标区同构:label 11 + 数值 18/600),容器口径同横幅 —— 用 `Card` 承载,不做裸指标行(M8)
|
||||
3. 表格/列表统一用卡片承载,长表头 `sticky`
|
||||
4. 行内操作集中在行尾,用 `icon-sm`(28px),禁微缩按钮
|
||||
|
||||
**连接** —— 指标行 + 表格卡(workbench 变体)
|
||||
```
|
||||
指标行:活跃连接 + 规则命中 chips(与概览横幅同容器 Card + `px-4 py-4`;chips 紧挨活跃连接,随命中项变化向右延伸)
|
||||
下载/上传速率已删(与概览横幅重复);命中规则计数已删(恒等于活跃连接数)
|
||||
表格卡(全宽):进程/域名 + 国内国外徽章 + 规则 + 上下行流量 + 断开
|
||||
表头 sticky · 行 hover(bg-hover) · 空态「暂无活跃连接」
|
||||
```
|
||||
|
||||
**节点** —— 组导航 + 节点网格
|
||||
```
|
||||
顶部:代理组切换(SegmentedNav,组多时降级为 Select)+ 测速按钮(行右)
|
||||
节点网格:节点小卡(名称 + 延迟徽章 + 选中态 primary-soft),grid-cols-2 lg:grid-cols-3
|
||||
未运行时网格空态「暂无节点」,结构不变
|
||||
```
|
||||
|
||||
**订阅** —— 列表卡 + 导入区(plain 模式)
|
||||
```
|
||||
列表卡:行式(名称 / 更新时间 / 节点数 + 更新、删除),行高 52,行间 1px divider
|
||||
导入区:URL 输入 + 导入按钮,置于列表卡上方
|
||||
空态「暂无订阅」+ 主按钮引导导入
|
||||
```
|
||||
|
||||
**设置** —— 单卡 + 卡内标题(峰定稿偏好:设置页标题留在卡片内)
|
||||
```
|
||||
单张设置卡承载全部设置项,卡片占满内容宽(放大居中与概览/连接一致)
|
||||
输入类双列(md:grid-cols-2)、开关行「左说明右开关」、提示条 primary-soft 底;保存按钮在标题栏
|
||||
(SettingGroup / SettingRow 保留,用于全局设置页等多分组场景)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 组件规范
|
||||
|
||||
### 4.1 业务组件清单(统一从 `@/components/common` 导入)
|
||||
|
||||
以下 14 个组件已建立完成。**模块内不得再手写同类结构**——这是"UI 不统一"反复复发的根本原因:只要没有现成的替代品,开发者就只能手写。
|
||||
|
||||
| # | 组件 | 解决的问题 | 关键 props |
|
||||
|---|---|---|---|
|
||||
| 1 | `ModuleShell` | **页面框架落地件**:高度约束链 + 滚动归属 + 内容区 padding/限宽 | `layout`, `padded`, `maxWidth`, `tabs` |
|
||||
| 2 | `ModuleToolbar` | 模块内容区顶部操作条 | `slot: left/right` |
|
||||
| 3 | `SectionHeader` | 区块标题 + 说明 + 右侧操作 | `title`, `description`, `slot: action` |
|
||||
| 4 | `StatCard` | 键值卡片(需要视觉分组的独立块) | `title`, `description`, `slot: action` |
|
||||
| 4a | `InfoGroup` | **平铺分组**(概览页键值快照,密度优先) | `title`, `columns`, `slot: action` / `slot: footer` |
|
||||
| 5 | `MetricValue` | 大数值 + 标签 + 单位 + 方向色 | `value`, `unit`, `label`, `trend` |
|
||||
| 6 | `KeyValueRow` | 键值行(状态/版本/路径) | `label`, `value`, `slot: value` |
|
||||
| 7 | `StatusDot` | 状态点 + 文字 | `state: success/warning/danger/neutral`, `label` |
|
||||
| 8 | `StatusBadge` | 徽章 | `variant`, `size: sm/md` |
|
||||
| 9 | `SettingRow` | 设置行 | `label`, `description`, `slot: control` |
|
||||
| 10 | `SettingGroup` | 设置分组 | `title`, `description` |
|
||||
| 11 | `DataListRow` | 列表行(主从分栏左栏) | `title`, `subtitle`, `active`, `slot: trailing` |
|
||||
| 12 | `StateBlock` | 加载/空/错误/无权限 | `variant`, `title`, `description`, `slot: action` |
|
||||
| 13 | `CopyField` | 可复制文本(路径、版本号) | `value`, `mono` |
|
||||
| 14 | `ConfirmDialog` | 破坏性操作确认 | `title`, `description`, `variant: danger` |
|
||||
|
||||
### 4.2 关键组件规格
|
||||
|
||||
**按钮**(基于 shadcn `Button`,只调 token 与尺寸)
|
||||
|
||||
| 变体 | 底色 | 文字 | 描边 | 用途 |
|
||||
|---|---|---|---|---|
|
||||
| `default`(主) | `--primary` | `--primary-foreground` | 无 | 每屏仅 1 个 |
|
||||
| `outline`(次) | `--card` | `--foreground` | `--border-strong` | 常规操作 |
|
||||
| `ghost`(幽灵) | 无底 / hover `--primary-soft` | `--fg-secondary` / hover `--primary-soft-text` | 无 | 工具栏、行内 |
|
||||
| `destructive`(危险) | `--danger` | 白 | 无 | 停止/删除,需确认 |
|
||||
|
||||
尺寸:`sm` 高 28 / `default` 高 34 / `lg` 高 40。内边距 `px-3.5`(default),圆角 `radius-md`。按下统一 `scale(0.97)`。
|
||||
**禁止** `h-4 px-1.5 text-[10px]` 这类微缩按钮(`ProxyModule.vue:1768` 有此写法)——需要更小的按钮时用 `StatusBadge`。
|
||||
|
||||
**交互反馈(hover / active / focus)**
|
||||
|
||||
| 场景 | hover | active |
|
||||
|---|---|---|
|
||||
| 主按钮 | `--primary-hover`(变深) | `--primary-active` |
|
||||
| 次按钮 / 卡片 | `--hover`(中性加深) | `--active` |
|
||||
| 幽灵按钮 / 图标按钮 | `--primary-soft` + `--primary-soft-text` | `--primary-soft` |
|
||||
| 内容列表行 / 选项卡片 | `--row-hover`(主题色弱底) | — |
|
||||
| mica / acrylic 弹窗内的行(快速面板、托盘菜单) | `--row-hover-veil`(半透明蒙层) | `--row-selected-veil`(按下/光标) |
|
||||
| 菜单项 / 数据表行 / 导航 / 分段 / 折叠头 | `--hover` | — |
|
||||
| 选中行 | — | `--row-selected` |
|
||||
| 选中 Tab | — | `--primary-soft` |
|
||||
|
||||
**焦点环**全应用统一:`ring-2 ring-ring/40`。hover ≠ selected:hover 表达"可以点",selected 表达"已经选中",后者才用强调色。
|
||||
|
||||
**内容行 vs 通用中性(2026-09 修订)**
|
||||
|
||||
`--hover` 与行高亮的分工,不是"哪个好看",而是语义:
|
||||
|
||||
| | 用 `--hover`(中性) | 用行高亮(主题色) |
|
||||
|---|---|---|
|
||||
| 判断依据 | 控件本身可点,不承载数据对象 | 一行/一卡承载一个**对象**(歌曲、任务、主机、密钥、设备、剪贴项) |
|
||||
| 典型 | 按钮、菜单项、代理连接表、侧栏、Tab、设置行 | 音乐列表/队列/歌单/搜索结果、任务列表、主机/密钥/shell 卡片、监控设备项、历史命令、剪贴板条目、快速面板与托盘菜单条目 |
|
||||
|
||||
**四种值的选择(2×2)**
|
||||
|
||||
先问两件事:**是不是"一行一个对象"** → 否则用 `--hover`;**这一行坐在什么底上** → 决定用哪一对:
|
||||
|
||||
| 行所在的面 | hover | 选中 |
|
||||
|---|---|---|
|
||||
| 不透明(卡片、面板、弹窗自带底色) | `--row-hover` 8% / 11% | `--row-selected` 15% / 26% |
|
||||
| mica / acrylic 糊化层(行直接画在壁纸上,窗口无自身底色) | `--row-hover-veil` 16% | `--row-selected-veil` 30% |
|
||||
|
||||
五条硬约束:
|
||||
|
||||
1. **不能全局把 `--hover` 改成主题色**。次按钮 hover 会与幽灵按钮(`--primary-soft`)撞色,菜单项与数据表整片变蓝,按钮层级和"hover 中性"的既有观感一起塌。必须是新增 token 分开用。
|
||||
2. **行选中不能用 `--primary-soft`**。`--primary-soft` ≈ primary 10% 混白,和 8% 的 `--row-hover` 只差 2 个色阶,悬停已选中项时看不出区别 —— 这就是 `--row-selected`(15%)存在的原因。`--primary-soft` 留给"选中 Tab / 幽灵按钮 hover"。
|
||||
3. **透明面上的行必须用 veil 而不是不透明色**。不透明浅底在糊化层上会变成一块"贴上去的白块",并盖掉 mica 质感;半透明会与壁纸自然叠合(浅壁纸偏浅、深壁纸偏深),因此 veil 只在 `:root` 定义一次,不在 `.dark` 重写。veil 也明显更重(16% vs 8%)—— 不透明的 8% 放到壁纸上基本看不见;但也不能一路加重,20% 起就偏"罩住"了,16% / 30% 是实测的手感点。
|
||||
4. **禁止在内容行上继续用 `--accent/40 ~ /60`**。半透明中性灰在白卡上只有 3% 明度差,等于 hover 无效——这是本次修订要清掉的存量问题。
|
||||
5. **选中态必须显式盖过 hover**。二者的 CSS 特异性经常是平的或反过来:纯 CSS 里 `:hover`((0,2,0))高于单类((0,1,0)),要写 `.sel:hover` 同规则;Vue 里静态的 `hover:bg-row-hover` 不能和条件类的 `bg-row-selected` 并存,必须写成三元互斥(见 `SftpPanel.vue` 文件表格与 `TrackItem.vue`)。
|
||||
|
||||
**状态点**
|
||||
|
||||
```
|
||||
8px 圆 · border-radius: full · 底色 = 对应 --<state>
|
||||
与文字间距 6px · 文字用 body 或 label
|
||||
```
|
||||
可选呼吸动效(运行中):`opacity` 1↔0.55,1.8s 循环,`prefers-reduced-motion` 下禁用。
|
||||
|
||||
**徽章**
|
||||
|
||||
```
|
||||
高 20 · 内边距 3px 8px · 圆角 radius-sm
|
||||
底 --<state>-soft · 文字 --<state>-text · 字号 label(11/500)
|
||||
```
|
||||
|
||||
**卡片**
|
||||
|
||||
```
|
||||
底 --card · 1px --border · 圆角 radius-lg(12) · 内边距 space-4(16)
|
||||
标题 h2(14/600) · 标题与内容间距 space-3(12)
|
||||
统一轻阴影 shadow-sm(--shadow-card)—— shadcn Card / InfoGroup card / StatCard 一致
|
||||
```
|
||||
|
||||
**输入 / 下拉 / 分段控件**
|
||||
|
||||
```
|
||||
高度 34 · 圆角 radius-md(8) · 1px --border
|
||||
输入与下拉态:底 --card
|
||||
分段控件:外槽底 --subtle,内边距 3,选中项底 --card + 文字 --foreground,未选中项文字 --fg-secondary
|
||||
聚焦:border 不变,box-shadow: 0 0 0 2px --ring(40% alpha)
|
||||
```
|
||||
|
||||
### 4.3 组件用法要点
|
||||
|
||||
- 业务组件统一从 `@/components/common` 导入(见 4.1 清单),模块内禁止手写同类结构。
|
||||
- 页面用 `ModuleShell` 包裹,通过 `layout`(grid / split / workbench / settings / plain)选内容区模式。
|
||||
- 内容区先按四态组织:先 `loading`,再 `empty`/`error`,最后才是数据内容(见 3.6 / M8)。
|
||||
- 颜色只用 token 类名(`bg-card border border-border`),禁止 hex 与原生色阶(见第 5 章 D1–D2)。
|
||||
- 数值统一 `tabular-nums`;状态点 / 徽章用 `StatusDot` / `StatusBadge`,键值用 `KeyValueRow` / `InfoGroup`。
|
||||
|
||||
---
|
||||
|
||||
## 5. 开发约束(硬性)
|
||||
|
||||
### 5.1 禁止清单
|
||||
|
||||
| # | 禁止 | 替代方案 |
|
||||
|---|---|---|
|
||||
| D1 | 组件内出现 hex / rgb / oklch 字面量 | 用语义 token 类名 |
|
||||
| D2 | Tailwind 原生色阶 `bg-blue-500` `text-emerald-700` `border-slate-200` | 用 `bg-primary` `text-success-text` `border-border` |
|
||||
| D3 | 间距/圆角/尺寸的任意值 `p-[18px]` `rounded-[10px]` | 归位 4px 栅格:`p-4` `rounded-md`(非 4 倍数就近归档)。**字号例外**:正文标准档 `text-[11px]`~`text-[14px]` 是项目字号体系(Tailwind 无 13px 预设),允许保留;非标准档(15/13.5/16px 等)归位最近标准档 |
|
||||
| D4 | 用状态色表达可点击性(绿色按钮 = 主操作) | 主操作一律 `--primary` |
|
||||
| D5 | 卡片使用重阴影(shadow-popover / shadow-dialog 或 hover 抬起阴影) | 卡片统一轻阴影 `shadow-sm` |
|
||||
| D6 | 模块内手写状态点 / 徽章 / 卡片标题 / 键值行 | 用第 4.1 节组件 |
|
||||
| D7 | 混用图标库,或用 Unicode 符号(`↓ ✓ ● ▸`)当图标 | lucide,尺寸 14/16/20 |
|
||||
| D8 | 中文加负字距 | `letter-spacing: 0` |
|
||||
| D9 | 生产代码 `@import` 外部字体 CDN | 系统字体栈 |
|
||||
| D10 | 数据驱动界面缺四态之一 | `StateBlock` |
|
||||
| D11 | 一屏多个主按钮 / 破坏性操作与主操作同权重 | 视觉降级 + `ConfirmDialog` |
|
||||
| D12 | 在 `.dark` 下靠改组件类名做适配 | 只改 token,组件代码不感知主题 |
|
||||
|
||||
### 5.2 必须清单
|
||||
|
||||
- **M1** 新增模块必须使用 `ModuleShell`,内容区三选一(第 3.2 节)
|
||||
- **M2** 所有颜色/间距/圆角/字号可追溯到 `style.css` 的 token
|
||||
- **M3** 深色模式与浅色模式同时验证,不得只测一套
|
||||
- **M4** 数值使用 `tabular-nums`
|
||||
- **M5** 动效尊重 `prefers-reduced-motion`
|
||||
- **M6** 控件最小点击区 28×28(桌面标准,非触摸的 44)
|
||||
- **M7** 文字与背景对比度 ≥ 4.5:1;`--muted-foreground` 不得用于正文,只用于 ≥12px 的辅助信息
|
||||
- **M8** 数据驱动的界面**结构恒定**:无数据时保持完整结构、值用 `—` 占位(横幅、键值行、表格单元同规则);**不得**用「xx 未运行」之类文案整块替换结构。运行状态由横幅状态区或状态点表达,不在卡片内复述。控件在不可用时禁用,而不是隐藏整块。
|
||||
`—` 与 `0` 的区分:`—` = 数据缺失/不适用(如未运行时的 PID);`0` = 语义上就是零(如未运行时的连接数、速率)—— 可计数指标显示 0 比 `—` 更真实。指标行/横幅必须有容器(卡片),裸指标行浮在画布上与页面不协调。
|
||||
- **M9** 动态数值的指标位**按数据类型固定最小宽度**:速率/流量/计数高频刷新,宽度变化会左右推移兄弟元素。做法同 OSD(`tabular-nums` + `min-width`)。**宽度按内容定,不要一刀切**——速率 `min-w-24`(容纳 `999 KB/s`)、版本/累计 `min-w-20`、纯计数 `min-w-12`;统一给大值会留白并把同卡操作按钮挤换行
|
||||
- **M8** 键盘可聚焦元素必须有可见焦点环(`ring-2 ring-ring/40`)
|
||||
|
||||
### 5.3 Code Review 检查点
|
||||
|
||||
提交前自查(建议做成 MR 模板 checklist):
|
||||
|
||||
1. `grep -rE "(#[0-9a-fA-F]{3,8}|(bg|text|border)-(slate|gray|zinc|blue|emerald|amber|red|rose|orange|sky|purple|violet)-[0-9]{2,3})" src/` **无新增命中**
|
||||
2. `grep -rE "\w-\[[^\]]+\]" src/` 新增行数可控且能说明理由
|
||||
3. 深浅两套主题截图留存
|
||||
4. 加载/空/错误三态至少手动触发过一次
|
||||
5. 破坏性操作有确认
|
||||
|
||||
**建议自动化**:加入 ESLint 规则,直接拦截 D1–D3。
|
||||
|
||||
```js
|
||||
// eslint 思路示例:禁止特定 class 模式
|
||||
{
|
||||
files: ['**/*.vue'],
|
||||
rules: {
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
{
|
||||
selector: 'Literal[value=/(bg|text|border)-(slate|gray|zinc|blue|emerald|amber|red|rose|orange|sky|purple|violet)-\\d{3}/]',
|
||||
message: '禁止使用 Tailwind 原生色阶,请使用语义 token(见 UI_DESIGN_SYSTEM.md 第 5.1 节 D2)'
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 工具与状态
|
||||
|
||||
### 6.1 组件预览页(改 token 后的回归工具)
|
||||
|
||||
路径:`preview/` —— **不在生产构建入口内**,只在 `bun dev` 时可访问。
|
||||
|
||||
```bash
|
||||
bun dev
|
||||
# 浏览器打开 http://localhost:14210/preview/index.html
|
||||
```
|
||||
|
||||
用途:改完 `src/style.css` 的 token 后,把全部基础组件与业务组件过一遍,确认浅色 / 深色两套都正确 —— 替代"改完 token 靠记忆推断影响面"。本页不依赖任何 Tauri API,纯浏览器即可运行。
|
||||
|
||||
查询参数:
|
||||
|
||||
| 参数 | 作用 | 示例 |
|
||||
|---|---|---|
|
||||
| `theme=dark` | 以深色模式启动 | `?theme=dark` |
|
||||
| `only=<id>` | 只渲染指定分区,便于放大核对 | `?only=data` |
|
||||
|
||||
已内置 `id` 的分区:`forms`、`data`、`shell`。需要放大看其他分区时,按同样方式给 `<section>` 加 `id` 即可。
|
||||
|
||||
> **实现注意**:`only` 的隔离 CSS 只能用**显式标记**(`[data-block]` / `[data-page-header]`),**不能用 `section` / `header` 这类标签选择器**——`StatCard` 内部也用 `<section>` 和 `<header>`,会被一起隐藏,产生"组件没渲染"的假象。
|
||||
|
||||
### 6.2 当前状态
|
||||
|
||||
- 业务组件层(第 4.1 节 14 个组件)与 Token 层已落地,`preview/` 预览页已完成浅色/深色视觉回归。
|
||||
- 色阶治理:Tailwind 原生色阶从约 155 处降至 3 处(proxy / terminal / monitor / translate / music 的色阶与 Tabs 已完成)。
|
||||
- proxy 概览页定稿为「状态横幅 + 两列瀑布流」,InfoGroup 新增 `variant="card"`。
|
||||
- 状态横幅统一(2026-09-21):proxy 概览 / proxy 连接 / 下载任务 / 硬件监控概览四处横幅统一为 §3.4 的三段式(状态区 → 指标区 → 操作区)+ `Card` 容器;监控与下载的旧样式(`text-xs` 内联键值、Badge 计数、`xs` 按钮)已废弃。
|
||||
- 主题色自定义落地(2026-09-21,见 §2.9):`src/lib/theme.ts` + `appStore.setAccent()` + 设置页「主题色」卡片(10 预设 + 自定义),深浅两套自动派生、对比度自动兜底;组件层 0 改动。
|
||||
- 终端模块非终端页对齐(2026-09-21,见 TERMINAL_MODULE_PLAN.md §5):根 padding 归类、列表 Card 化、表单走 `@/components/ui` 原语、四态/徽章走 `@/components/common`、设置页用 `SettingGroup`/`SettingRow`(此后二者与 `StateBlock`/`StatusBadge` 有真实消费者);终端画布、状态栏、`h-11` 契约、xterm 链保持不动。
|
||||
- 剩余项:
|
||||
- `OsdWindow` 免改(功能性配置,非 UI token 问题)
|
||||
- `DownloadWindow` / `ClipboardPopup` 仍有少量 hex,待统一
|
||||
- ESLint 约束规则(第 5.3 节)尚未搭建
|
||||
|
||||
### 6.3 待决策
|
||||
|
||||
| # | 问题 | 状态 | 结论 / 影响 |
|
||||
|---|---|---|---|
|
||||
| 1 | 数据方向色是否与状态色解耦 | 已定(暂保留现有取值) | 保留"下载=绿、上传=红",已独立成 `--data-*` token,要换色只改这 2 个值 |
|
||||
| 2 | 强调色用 `#0066CC` | ✅ 已采用 | 落地;同时解决 shadcn primary 近黑导致按钮发灰 |
|
||||
| 3 | 浮窗(OSD/截图/下载)是否纳入统一体系 | 部分已定 | `OsdWindow` 免改(功能性配置);`DownloadWindow`/`ClipboardPopup` 少量 hex 待统一;不强行并入主界面 token |
|
||||
| 4 | `--font-mono` 是否用网络字体 | ✅ 已定 | 系统 `Cascadia Code` / `Consolas`,不引外部字体 |
|
||||
| 5 | 侧边栏宽度 60px | ✅ 已定 | 沿用现有实现 |
|
||||
| 6 | 内容区限宽 | ✅ 已定 | 改为**不限宽占满**窗口宽度(原 `max-w-6xl` 限制已移除) |
|
||||
| 7 | 卡片阴影 | ✅ 已定 | 卡片统一轻阴影 `shadow-sm`(shadcn Card / InfoGroup card / StatCard 一致),浮层仍用 `shadow-popover`/`shadow-dialog` |
|
||||
|
||||
---
|
||||
|
||||
**维护约定**:Token 值以 `src/style.css` 为唯一事实来源,本文档与之同步;两者冲突时以本文档为准并修正代码。新增 token 或组件须同步更新第 2、4 章。
|
||||
@@ -0,0 +1,80 @@
|
||||
// ESLint 平坦配置 —— 落地 UI_DESIGN_SYSTEM.md 第 5 章的 D 系约束。
|
||||
// 依赖:eslint / eslint-plugin-vue / @vue/eslint-config-typescript(见 package.json devDependencies)
|
||||
// 运行:bun run lint
|
||||
import pluginVue from 'eslint-plugin-vue'
|
||||
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript'
|
||||
|
||||
export default defineConfigWithVueTs(
|
||||
{
|
||||
ignores: [
|
||||
'dist/**',
|
||||
'node_modules/**',
|
||||
'src-tauri/**',
|
||||
'release_stage/**',
|
||||
'ThingHK/**',
|
||||
],
|
||||
},
|
||||
|
||||
// flat/essential:只保留「防错」规则(v-for key、重复 attr 等),
|
||||
// 不含缩进/引号等格式规则 —— 3183 条里 3038 条是格式噪音,与既有代码风格无关
|
||||
pluginVue.configs['flat/essential'],
|
||||
vueTsConfigs.recommended,
|
||||
|
||||
{
|
||||
rules: {
|
||||
// ---- D2:禁止 Tailwind 原生色阶,必须使用语义 token ----
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
{
|
||||
selector:
|
||||
"Literal[value=/(bg|text|border|ring|fill|stroke)-(slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-[0-9]{2,3}(\\/[0-9]{1,3})?/]",
|
||||
message:
|
||||
'D2 禁止 Tailwind 原生色阶:请使用语义 token(bg-card / text-success-text / border-border 等),见 UI_DESIGN_SYSTEM.md',
|
||||
},
|
||||
{
|
||||
// D9:生产代码禁止外部字体 CDN
|
||||
selector:
|
||||
"Literal[value=/@import\\s+url\\(['\\\"]?https:\\/\\/(fonts\\.googleapis|fonts\\.gstatic)\\./]",
|
||||
message: 'D9 禁止外部字体 CDN:使用系统字体栈',
|
||||
},
|
||||
],
|
||||
|
||||
// ---- 未使用变量:_ 前缀豁免(Pinia action 占位、解构占位等惯例)----
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'error',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_',
|
||||
caughtErrors: 'none',
|
||||
},
|
||||
],
|
||||
|
||||
// ---- Vue 风格:与既有代码一致 ----
|
||||
'vue/multi-word-component-names': 'off',
|
||||
'vue/max-attributes-per-line': 'off',
|
||||
'vue/singleline-html-element-content-newline': 'off',
|
||||
'vue/html-self-closing': 'off',
|
||||
'vue/attributes-order': 'off',
|
||||
},
|
||||
},
|
||||
|
||||
// .d.ts 声明文件:Vue 官方模板的 ImportMetaEnv 写法使用 {} 与 any,豁免
|
||||
{
|
||||
files: ['**/*.d.ts'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-empty-object-type': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
|
||||
// feiniuStore 是飞牛 NAS 的 API 适配层:后端原始结构未在前端定型(字段类型化需对接 Rust 端),
|
||||
// 边界层暂豁免 no-explicit-any;定型后应移除此豁免
|
||||
{
|
||||
files: ['src/stores/feiniuStore.ts'],
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
},
|
||||
},
|
||||
|
||||
// xterm 等第三方深色区域如需豁免,在下方追加 overrides
|
||||
)
|
||||
Generated
+3073
-74
File diff suppressed because it is too large.
Load diff
+62
-11
@@ -1,29 +1,75 @@
|
||||
{
|
||||
"name": "thing",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "26.10.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"build": "vue-tsc --noEmit && node --max-old-space-size=8192 node_modules/vite/bin/vite.js build",
|
||||
"build:vite": "node --max-old-space-size=8192 node_modules/vite/bin/vite.js build",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"lint": "eslint src",
|
||||
"preview": "vite preview",
|
||||
"test": "node --test src/modules/quickpanel/engine.test.ts src/lib/calc.test.ts",
|
||||
"test": "node --test src/modules/quickpanel/engine.test.ts src/lib/calc.test.ts src/lib/theme.test.ts src/modules/notes/editor/outline.test.ts src/modules/notes/editor/markdownExport.test.ts",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@lucide/vue": "^1.28.0",
|
||||
"@codemirror/autocomplete": "^6.20.3",
|
||||
"@codemirror/commands": "^6.11.1",
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
"@codemirror/lang-go": "^6.0.1",
|
||||
"@codemirror/lang-html": "^6.4.12",
|
||||
"@codemirror/lang-java": "^6.0.2",
|
||||
"@codemirror/lang-javascript": "^6.2.5",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/lang-less": "^6.0.2",
|
||||
"@codemirror/lang-markdown": "^6.5.2",
|
||||
"@codemirror/lang-php": "^6.0.2",
|
||||
"@codemirror/lang-python": "^6.2.1",
|
||||
"@codemirror/lang-rust": "^6.0.2",
|
||||
"@codemirror/lang-sass": "^6.0.2",
|
||||
"@codemirror/lang-sql": "^6.10.0",
|
||||
"@codemirror/lang-vue": "^0.1.3",
|
||||
"@codemirror/lang-xml": "^6.1.0",
|
||||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/language": "^6.12.4",
|
||||
"@codemirror/language-data": "^6.5.2",
|
||||
"@codemirror/legacy-modes": "^6.5.4",
|
||||
"@codemirror/merge": "^6.12.2",
|
||||
"@codemirror/search": "^6.7.2",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@codemirror/view": "^6.43.13",
|
||||
"@lucide/vue": "^1.48.0",
|
||||
"@replit/codemirror-lang-csharp": "^6.2.0",
|
||||
"@replit/codemirror-lang-svelte": "^6.0.0",
|
||||
"@tailwindcss/vite": "^4.3.2",
|
||||
"@tauri-apps/api": "^2",
|
||||
"@tauri-apps/plugin-autostart": "~2",
|
||||
"@tauri-apps/plugin-dialog": "^2",
|
||||
"@tauri-apps/plugin-global-shortcut": "^2",
|
||||
"@tauri-apps/plugin-opener": "^2",
|
||||
"@tauri-apps/api": "^2.12.0",
|
||||
"@tauri-apps/plugin-autostart": "~2.6.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.0",
|
||||
"@tauri-apps/plugin-global-shortcut": "^2.4.0",
|
||||
"@tauri-apps/plugin-opener": "^2.7.0",
|
||||
"@uiw/codemirror-themes": "^4.25.12",
|
||||
"@vueuse/core": "^14.4.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-search": "^0.16.0",
|
||||
"@xterm/addon-serialize": "^0.14.0",
|
||||
"@xterm/addon-unicode11": "^0.9.0",
|
||||
"@xterm/addon-web-links": "^0.12.0",
|
||||
"@xterm/addon-webgl": "^0.19.0",
|
||||
"@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",
|
||||
"reka-ui": "^2.10.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"reka-ui": "^2.10.5",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tailwindcss": "^4.3.2",
|
||||
"vue": "^3.5.13",
|
||||
@@ -31,9 +77,14 @@
|
||||
"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",
|
||||
"@vue/eslint-config-typescript": "^14.9.0",
|
||||
"eslint": "^10.11.0",
|
||||
"eslint-plugin-vue": "^10.11.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "~5.6.2",
|
||||
"vite": "^6.0.3",
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# SMTC full info query script (must run in Windows PowerShell 5.1)
|
||||
# Output: EVERY session (not only GetCurrentSession), full media properties
|
||||
|
||||
Add-Type -AssemblyName System.Runtime.WindowsRuntime -ErrorAction SilentlyContinue
|
||||
|
||||
$null = [Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager, Windows.Media.Control, ContentType=WindowsRuntime]
|
||||
$null = [Windows.Media.Control.GlobalSystemMediaTransportControlsSessionMediaProperties, Windows.Media.Control, ContentType=WindowsRuntime]
|
||||
$null = [Windows.Storage.Streams.IInputStream, Windows.Storage.Streams, ContentType=WindowsRuntime]
|
||||
|
||||
function Await($WinRtTask, $ResultType) {
|
||||
$asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() |
|
||||
Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
|
||||
$asTaskGeneric = $asTask.MakeGenericMethod($ResultType)
|
||||
$netTask = $asTaskGeneric.Invoke($null, @($WinRtTask))
|
||||
$netTask.Wait(-1) | Out-Null
|
||||
$netTask.Result
|
||||
}
|
||||
|
||||
$mgr = Await ([Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager]::RequestAsync()) ([Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager])
|
||||
$current = $mgr.GetCurrentSession()
|
||||
|
||||
# IVectorView 用 Size/GetAt 枚举:foreach 在 PS 5.1 上经常拿不到元素
|
||||
$sessions = New-Object System.Collections.ArrayList
|
||||
try {
|
||||
$raw = $mgr.GetSessions()
|
||||
if ($null -ne $raw) {
|
||||
$n = $raw.Size
|
||||
for ($i = 0; $i -lt $n; $i++) {
|
||||
[void]$sessions.Add($raw.GetAt($i))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
Write-Host "GetSessions failed: $_" -ForegroundColor Red
|
||||
}
|
||||
|
||||
Write-Host "===== SMTC Sessions ($($sessions.Count)) =====" -ForegroundColor Cyan
|
||||
$currentId = if ($current) { $current.SourceAppUserModelId } else { '' }
|
||||
Write-Host "CurrentSession : $(if ($currentId) { $currentId } else { '(none)' })" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
|
||||
if ($sessions.Count -eq 0) {
|
||||
if ($current) { [void]$sessions.Add($current) }
|
||||
else {
|
||||
Write-Host "No SMTC media sessions found." -ForegroundColor Yellow
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
$index = 0
|
||||
foreach ($session in $sessions) {
|
||||
$index++
|
||||
$appId = $session.SourceAppUserModelId
|
||||
$isCurrent = $currentId -and ($appId -eq $currentId)
|
||||
$mark = if ($isCurrent) { " [CURRENT]" } else { "" }
|
||||
|
||||
$props = $null
|
||||
try {
|
||||
$props = Await ($session.TryGetMediaPropertiesAsync()) ([Windows.Media.Control.GlobalSystemMediaTransportControlsSessionMediaProperties])
|
||||
} catch {
|
||||
$props = $null
|
||||
}
|
||||
$playback = $session.GetPlaybackInfo()
|
||||
$timeline = $session.GetTimelineProperties()
|
||||
|
||||
$position = $timeline.Position
|
||||
$duration = $timeline.EndTime - $timeline.StartTime
|
||||
$progress = if ($duration.TotalSeconds -gt 0) { [math]::Round(($position.TotalSeconds / $duration.TotalSeconds) * 100, 1) } else { 0 }
|
||||
|
||||
Write-Host ("----- Session #{0}{1} -----" -f $index, $mark) -ForegroundColor Cyan
|
||||
Write-Host "App ID : $appId"
|
||||
if ($props) {
|
||||
Write-Host "Playback Type : $($props.PlaybackType)"
|
||||
Write-Host "Title : $($props.Title)"
|
||||
Write-Host "Subtitle : $($props.Subtitle)"
|
||||
Write-Host "Artist : $($props.Artist)"
|
||||
Write-Host "AlbumArtist : $($props.AlbumArtist)"
|
||||
Write-Host "AlbumTitle : $($props.AlbumTitle)"
|
||||
Write-Host "TrackNumber : $($props.TrackNumber)"
|
||||
Write-Host "Genres : $($props.Genres -join ', ')"
|
||||
$thumbnail = $props.Thumbnail
|
||||
if ($thumbnail) { Write-Host "Thumbnail : (present)" }
|
||||
else { Write-Host "Thumbnail : No thumbnail" }
|
||||
} else {
|
||||
Write-Host "MediaProperties: (failed to read)"
|
||||
}
|
||||
Write-Host "Playback Status: $($playback.PlaybackStatus)"
|
||||
Write-Host "Progress : $position / $duration ($progress%)"
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
Write-Host "===================================" -ForegroundColor Cyan
|
||||
@@ -0,0 +1,61 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
set "SCRIPT=%~dp0release.ps1"
|
||||
|
||||
echo ================================================
|
||||
echo Thing Build Pubilsh
|
||||
echo 发布目标:https://gitea.atie.fun/LFeng/Thing
|
||||
echo ================================================
|
||||
echo.
|
||||
|
||||
:: ---------- 版本号 ----------
|
||||
set "VERSION="
|
||||
set /p "VERSION=请输入版本号(如 26.8.1,直接回车沿用当前版本): "
|
||||
set "VER_ARG="
|
||||
if not "%VERSION%"=="" set "VER_ARG=-Version %VERSION%"
|
||||
|
||||
:: ---------- 发布模式 ----------
|
||||
echo.
|
||||
echo [1] Build + Pubilsh Gitea
|
||||
echo [2] Build Only
|
||||
echo [3] Pubilsh Gitea
|
||||
set "MODE="
|
||||
set /p "MODE=请输入数字选择(回车默认 1): "
|
||||
if "%MODE%"=="" set "MODE=1"
|
||||
|
||||
set "EXTRA="
|
||||
if "%MODE%"=="2" (
|
||||
set "EXTRA=-SkipPush"
|
||||
) else if "%MODE%"=="3" (
|
||||
set "EXTRA=-SkipBuild"
|
||||
)
|
||||
|
||||
:: ---------- Gitea Token(仅完整发布模式需要) ----------
|
||||
if "%MODE%"=="1" if not defined GITEA_TOKEN (
|
||||
echo.
|
||||
echo 未检测到环境变量 GITEA_TOKEN,上传到 Gitea 需要它。
|
||||
echo 可在此临时输入(仅本次会话生效),留空则自动改为"只构建不上传"。
|
||||
set /p "GITEA_TOKEN=请输入 Gitea Token: "
|
||||
if "!GITEA_TOKEN!"=="" (
|
||||
set "EXTRA=-SkipPush"
|
||||
set "MODE=2"
|
||||
echo [提示] 已切换为"只构建并整理产物,不上传"。
|
||||
)
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Start:release.ps1 %VER_ARG% %EXTRA%
|
||||
echo ------------------------------------------------
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%SCRIPT%" %VER_ARG% %EXTRA%
|
||||
set "RESULT=%ERRORLEVEL%"
|
||||
|
||||
echo.
|
||||
if "%RESULT%"=="0" (
|
||||
echo 执行完成。
|
||||
) else (
|
||||
echo 执行出错,请查看上方日志。
|
||||
)
|
||||
echo.
|
||||
pause
|
||||
@@ -0,0 +1,167 @@
|
||||
# ============================================================
|
||||
# Thing 构建发布脚本(目标:自建 Gitea release)
|
||||
#
|
||||
# 用法:
|
||||
# .\scripts\release.ps1 -Version 0.2.0 # 同步版本号 + 构建 + 发布
|
||||
# .\scripts\release.ps1 -Version 0.2.0 -SkipBuild # 复用现有构建产物,直接发布
|
||||
# .\scripts\release.ps1 -Version 0.2.0 -SkipPush # 只构建+整理产物,不上传
|
||||
#
|
||||
# 发布产物(上传到 https://gitea.atie.fun/LFeng/Thing 的 v{Version} release):
|
||||
# thing_{v}_x64.exe 便携免安装版(无内核)
|
||||
# thing_{v}_x64.msi 安装版 MSI(去掉 tauri 默认的 _zh-CN 后缀)
|
||||
# thing_{v}_x64-setup.exe 安装版 NSIS
|
||||
# thing-hk_{v}.zip ThingHK 硬件监控内核(mihomo 继续走代理模块内置的 GitHub 下载)
|
||||
#
|
||||
# 前提:
|
||||
# - Gitea token 已配置为环境变量 GITEA_TOKEN(-SkipPush 时不需要)
|
||||
# - 可选 -NotesPath 指定 release notes 文件(Markdown 文本),
|
||||
# 缺省时使用 scripts/release-notes.md(若存在),否则用简单占位文本
|
||||
# ============================================================
|
||||
|
||||
param(
|
||||
[string]$Version = '',
|
||||
[switch]$SkipBuild,
|
||||
[switch]$SkipPush,
|
||||
[string]$NotesPath = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$Root = Split-Path -Parent $PSScriptRoot
|
||||
$TargetDir = Join-Path $Root 'src-tauri\target\release'
|
||||
$BundleDir = Join-Path $TargetDir 'bundle'
|
||||
$RepoOwner = 'LFeng'
|
||||
$RepoName = 'Thing'
|
||||
$ApiBase = 'https://gitea.atie.fun/api/v1'
|
||||
$Product = 'thing'
|
||||
|
||||
function Write-Step([string]$msg) { Write-Host "`n==> $msg" -ForegroundColor Cyan }
|
||||
|
||||
# ---------- 0. 版本号 ----------
|
||||
if ([string]::IsNullOrWhiteSpace($Version)) {
|
||||
$conf = Get-Content (Join-Path $Root 'src-tauri\tauri.conf.json') -Raw | ConvertFrom-Json
|
||||
$Version = $conf.version
|
||||
Write-Step "未指定 -Version,沿用现有版本 $Version"
|
||||
}
|
||||
# 校验 X.Y.Z 格式
|
||||
if ($Version -notmatch '^\d+\.\d+\.\d+$') {
|
||||
throw "版本号格式错误(应为 X.Y.Z):$Version"
|
||||
}
|
||||
Write-Step "发布版本:v$Version"
|
||||
|
||||
# ---------- 1. 同步版本号到三处 ----------
|
||||
$tauriConf = Join-Path $Root 'src-tauri\tauri.conf.json'
|
||||
$cargoToml = Join-Path $Root 'src-tauri\Cargo.toml'
|
||||
$pkgJson = Join-Path $Root 'package.json'
|
||||
|
||||
# UTF-8 安全读写:`Get-Content` 默认按系统 ANSI(如 GBK) 解码,会把本就含中文/乱码的文件二次编码损坏(曾导致
|
||||
# Cargo.toml 的 keyring 依赖行被弄丢)。这里统一用显式 UTF-8 无 BOM 读写,保证逐字节稳定往返。
|
||||
function Set-Utf8Version([string]$Path, [string]$Pattern, [string]$NewVersion) {
|
||||
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
|
||||
$content = [System.IO.File]::ReadAllText($Path, $utf8NoBom)
|
||||
$content = $content -replace $Pattern, "`${1}$NewVersion`${2}"
|
||||
[System.IO.File]::WriteAllText($Path, $content, $utf8NoBom)
|
||||
}
|
||||
|
||||
Set-Utf8Version -Path $tauriConf -Pattern '("version"\s*:\s*")[^"]*(")' -NewVersion $Version
|
||||
Set-Utf8Version -Path $cargoToml -Pattern '(?m)^(version\s*=\s*")[^"]*(")' -NewVersion $Version
|
||||
Set-Utf8Version -Path $pkgJson -Pattern '("version"\s*:\s*")[^"]*(")' -NewVersion $Version
|
||||
Write-Step "版本号已同步:tauri.conf.json / Cargo.toml / package.json"
|
||||
|
||||
# ---------- 2. 构建 ----------
|
||||
if (-not $SkipBuild) {
|
||||
Write-Step '开始构建(bun run tauri build)...'
|
||||
Push-Location $Root
|
||||
try { bun run tauri build }
|
||||
finally { Pop-Location }
|
||||
if ($LASTEXITCODE -ne 0) { throw 'tauri build 失败' }
|
||||
} else {
|
||||
Write-Step '跳过构建,复用现有产物'
|
||||
}
|
||||
|
||||
# ---------- 3. 整理产物 ----------
|
||||
# 版本号此时已解析,再确定暂存目录
|
||||
$StageDir = Join-Path $Root "release_stage\$Version"
|
||||
New-Item -ItemType Directory -Force -Path $StageDir | Out-Null
|
||||
|
||||
$exeSrc = Join-Path $TargetDir "$Product.exe"
|
||||
$msiSrc = Join-Path $BundleDir "msi\${Product}_${Version}_x64_zh-CN.msi"
|
||||
$nsisSrc = Join-Path $BundleDir "nsis\${Product}_${Version}_x64-setup.exe"
|
||||
$hkSrc = Join-Path $Root 'src-tauri\binaries\ThingHK.exe'
|
||||
|
||||
$exeOut = Join-Path $StageDir "${Product}_${Version}_x64.exe"
|
||||
$msiOut = Join-Path $StageDir "${Product}_${Version}_x64.msi"
|
||||
$nsisOut = Join-Path $StageDir "${Product}_${Version}_x64-setup.exe"
|
||||
$hkZip = Join-Path $StageDir "thing-hk_${Version}.zip"
|
||||
|
||||
if (Test-Path $exeSrc) { Copy-Item $exeSrc $exeOut } else { Write-Warning "缺少便携版:$exeSrc" }
|
||||
if (Test-Path $msiSrc) { Copy-Item $msiSrc $msiOut } else { Write-Warning "缺少 MSI(已跳过重命名):$msiSrc" }
|
||||
if (Test-Path $nsisSrc) { Copy-Item $nsisSrc $nsisOut } else { Write-Warning "缺少 NSIS:$nsisSrc" }
|
||||
|
||||
if (Test-Path $hkSrc) {
|
||||
$tmp = Join-Path $env:TEMP "thinghk_$([guid]::NewGuid().ToString('N'))"
|
||||
New-Item -ItemType Directory -Force -Path $tmp | Out-Null
|
||||
Copy-Item $hkSrc (Join-Path $tmp 'ThingHK.exe')
|
||||
Compress-Archive -Path (Join-Path $tmp 'ThingHK.exe') -DestinationPath $hkZip -Force
|
||||
Remove-Item -Recurse -Force $tmp
|
||||
Write-Step "ThingHK 内核包:$hkZip"
|
||||
} else {
|
||||
Write-Warning "缺少 ThingHK.exe:$hkSrc"
|
||||
}
|
||||
|
||||
Write-Step "产物已整理到:$StageDir"
|
||||
Get-ChildItem $StageDir | Select-Object Name, @{n='Size(MB)';e={[math]::Round($_.Length/1MB,1)}} | Format-Table -AutoSize
|
||||
|
||||
# ---------- 4. 上传到 Gitea ----------
|
||||
if ($SkipPush) {
|
||||
Write-Step '已跳过上传(-SkipPush)'
|
||||
exit 0
|
||||
}
|
||||
|
||||
$token = $env:GITEA_TOKEN
|
||||
if ([string]::IsNullOrWhiteSpace($token)) {
|
||||
throw '未设置环境变量 GITEA_TOKEN,无法发布到 Gitea(或使用 -SkipPush 跳过上传)'
|
||||
}
|
||||
$auth = @{ Authorization = "token $token" }
|
||||
|
||||
# 4.1 release notes
|
||||
if (-not [string]::IsNullOrWhiteSpace($NotesPath)) {
|
||||
$body = Get-Content $NotesPath -Raw
|
||||
} elseif (Test-Path (Join-Path $PSScriptRoot 'release-notes.md')) {
|
||||
$body = Get-Content (Join-Path $PSScriptRoot 'release-notes.md') -Raw
|
||||
} else {
|
||||
$body = "Thing v$Version"
|
||||
}
|
||||
|
||||
# 4.2 创建 release(已存在同名 tag 则复用)
|
||||
Write-Step "创建 release v$Version ..."
|
||||
$releaseUrl = "$ApiBase/repos/$RepoOwner/$RepoName/releases"
|
||||
$releasePayload = @{
|
||||
tag_name = "v$Version"
|
||||
name = "Thing v$Version"
|
||||
body = $body
|
||||
draft = $false
|
||||
prerelease = $false
|
||||
} | ConvertTo-Json
|
||||
|
||||
try {
|
||||
$release = Invoke-RestMethod -Method Post -Uri $releaseUrl -Headers $auth -ContentType 'application/json' -Body $releasePayload
|
||||
} catch {
|
||||
# tag 已存在:尝试用该 tag 查找现有 release,后续资产上传会追加
|
||||
Write-Warning "创建 release 失败,尝试复用已有 release:$_"
|
||||
$release = Invoke-RestMethod -Method Get -Uri "$releaseUrl/tags/v$Version" -Headers $auth
|
||||
}
|
||||
$releaseId = $release.id
|
||||
Write-Step "release id=$releaseId"
|
||||
|
||||
# 4.3 逐个上传资产
|
||||
$assets = @($exeOut, $msiOut, $nsisOut, $hkZip) | Where-Object { Test-Path $_ }
|
||||
foreach ($file in $assets) {
|
||||
$name = Split-Path $file -Leaf
|
||||
Write-Step "上传 $name ..."
|
||||
$assetUrl = "$releaseUrl/$releaseId/assets?name=$([uri]::EscapeDataString($name))"
|
||||
$resp = Invoke-RestMethod -Method Post -Uri $assetUrl -Headers $auth -ContentType 'application/octet-stream' -InFile $file
|
||||
Write-Host " -> $($resp.browser_download_url)" -ForegroundColor Green
|
||||
}
|
||||
|
||||
Write-Step "发布完成:https://gitea.atie.fun/$RepoOwner/$RepoName/releases/tag/v$Version"
|
||||
Generated
+3490
-345
File diff suppressed because it is too large.
Load diff
+218
-5
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "thing"
|
||||
version = "0.1.0"
|
||||
version = "26.10.1"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
edition = "2021"
|
||||
@@ -24,38 +24,141 @@ tauri-plugin-dialog = "2"
|
||||
tauri-plugin-snap-layout = "1"
|
||||
tauri-plugin-global-shortcut = "2"
|
||||
tauri-plugin-notification = "2"
|
||||
# 翻译引擎抽象:TranslateEngine 需要 Box<dyn> 动态分派(多源在运行期决定),
|
||||
# 原生 async fn in trait 在 dyn 场景下不可用
|
||||
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"
|
||||
tauri-specta = { version = "=2.0.0-rc.25", features = ["typescript"] }
|
||||
chrono = "0.4"
|
||||
reqwest = { version = "0.12", features = ["json", "stream"] }
|
||||
futures-util = "0.3"
|
||||
# blocking:音乐播放引擎在**独立 std 线程**上解码(symphonia 的 MediaSource 是同步
|
||||
# Read+Seek),需要同步 HTTP 客户端去按 Range 拉 NAS 音频流。放在 std 线程上用
|
||||
# blocking 是安全的(在 tokio 运行时线程里用才会 panic)。
|
||||
# gzip:智能家居模块走反代(Cloudflare Tunnel)链路时,`/api/states` 是几百 KB JSON。
|
||||
# **默认不开压缩就不会发 Accept-Encoding**,CF 会回未压缩响应,远端首屏流量翻 5–10 倍
|
||||
# (见 doc/SMART_HOME_MODULE_PLAN.md §3.7-b)。
|
||||
reqwest = { version = "0.12", features = ["json", "stream", "multipart", "blocking", "gzip"] }
|
||||
# `sink`:WebSocket 客户端要把流拆成读/写两半(`SinkExt` / `StreamExt`)。
|
||||
# default 特性里**不含** `sink`(已核对 0.3.32 的 Cargo.toml),目前只是因为
|
||||
# tokio-tungstenite 自己开了它才传递可用 —— 依赖传递特性不该被当成前提,故显式打开。
|
||||
futures-util = { version = "0.3", features = ["sink"] }
|
||||
tokio = { version = "1", features = ["io-util", "time", "rt-multi-thread", "macros", "sync", "fs", "net"] }
|
||||
axum = "0.7"
|
||||
axum = { version = "0.7", features = ["ws"] }
|
||||
url = "2"
|
||||
zip = "2"
|
||||
dirs = "5"
|
||||
# ===== 终端模块 =====
|
||||
# 字符编码转换:老服务器(CentOS 6/7 默认 LANG=zh_CN.GBK)输出 GBK 字节,
|
||||
# 直接按 UTF-8 解码会得到乱码。encoding_rs 是 Firefox 的实现抽出,比 iconv 绑定
|
||||
# 干净(纯 Rust、无 C 依赖),且本项目依赖树里已存在(reqwest → encoding_rs 0.8.35),
|
||||
# 提升为直接依赖不会新增编译单元。
|
||||
encoding_rs = "0.8"
|
||||
# SSH 客户端:纯 Rust + 原生 async,与项目 tokio 运行时契合。
|
||||
# 选 russh 而非 ssh2(libssh2 绑定)的理由见 terminal/ssh/mod.rs 模块注释。
|
||||
# 注意:实施时核实该 crate 已到 0.63.x(规划文档中的 0.5 已过时)。
|
||||
russh = "0.63"
|
||||
# SSH 密钥的生成/解析/加密统一走 `russh::keys::ssh_key` re-export。
|
||||
#
|
||||
# **不要**声明与 russh 钉住版本不同的 `ssh-key`——若声明 0.6 会引入第二个不兼容
|
||||
# 版本,两边的 PrivateKey/PublicKey 无法互转(这是 P0 踩过的坑)。
|
||||
#
|
||||
# 唯一的例外是下面这一行:必须声明**完全相同**的版本号 `=0.7.0-rc.11`。
|
||||
# 原因是 russh 的 `[features]` **没有向 ssh-key 转发 `ppk`**
|
||||
# (只有 dsa / rsa / serde 三个转发项),而 P2 要支持 PuTTY `.ppk` 导入,
|
||||
# 只能由我们自己打开 `ssh-key/ppk`。
|
||||
#
|
||||
# Cargo 会把「russh 的 `=0.7.0-rc.11`」与「这里的 `=0.7.0-rc.11`」**合并为同一个
|
||||
# 依赖节点**(版本要求完全相同,不存在二选一),因此不会产生分叉。
|
||||
# 已用 `cargo tree -i ssh-key` 复核:图中只有 `ssh-key v0.7.0-rc.11` 一个节点。
|
||||
#
|
||||
# 注意:改这里之后必须重跑 `cargo tree -i ssh-key` 确认仍只有一个节点。
|
||||
ssh-key = { version = "=0.7.0-rc.11", default-features = false, features = ["ppk", "encryption", "alloc"] }
|
||||
|
||||
# 系统随机源:ssh-key 0.7 的 `getrandom` feature 默认**未启用**(russh 没开,
|
||||
# 我们上面的 ssh-key 声明也没开),故 `ssh_key::getrandom::SysRng` 不可见。
|
||||
# 这里直接依赖 getrandom 0.4 ——它与 ssh-key 共用同一份 `rand_core 0.10`,
|
||||
# `UnwrapErr(SysRng)` 能直接满足 ssh-key 的 `CryptoRng`/`TryCryptoRng` 约束
|
||||
# (见 terminal/keys.rs 的 sys_rng)。
|
||||
getrandom = "0.4"
|
||||
# SFTP 客户端。**russh 本身不含 SFTP**——只是一个 SSH 传输层,SFTP 协议
|
||||
# (OPEN/READ/WRITE/READDIR 等报文)由独立的 russh-sftp 实现。
|
||||
# 版本配套:russh-sftp 3.0.0 的依赖是 `russh ^0.63.2`,与上面的 0.63 同源,
|
||||
# 共用同一份 russh 实例类型 —— 这一点关键:SFTP 通道必须从**已认证的同一个
|
||||
# Session** 上开(`request_subsystem(true, "sftp")`),跨版本是做不到的。
|
||||
# 另注:3.0.0 把 `russh` 列为 dev-dependency,故不会重复引入第二个 russh。
|
||||
russh-sftp = "3.0"
|
||||
# ConPTY 之外还需要窗口/进程相关 API;Win32_System_Console 为 CreatePseudoConsole 所在 feature
|
||||
# 终端会话并发注册表:读多写少(每次输出批次都查表),分片锁避免各会话 I/O 互相等待
|
||||
dashmap = "6"
|
||||
# 音频标签解析(本地曲库元数据:标题/歌手/专辑/时长/内嵌封面)
|
||||
lofty = "0.22"
|
||||
sysinfo = "0.32"
|
||||
rusqlite = { version = "0.32", features = ["bundled"] }
|
||||
base64 = "0.22"
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
sha2 = "0.10"
|
||||
md-5 = "0.10"
|
||||
hmac = "0.12"
|
||||
aes = "0.8"
|
||||
cbc = "0.1"
|
||||
rsa = { version = "0.9", features = ["pem"] }
|
||||
rand = "0.8"
|
||||
# WebSocket 客户端(智能家居模块 P4 的实时推送 / 规则引擎)。
|
||||
# `connect` 已随 default 启用(`cargo tree -e features -i tokio-tungstenite` 复核过:
|
||||
# 它由本项 + axum 的 `ws` 共同引入),这里显式写出来是为了让"要连"这件事在清单里可见。
|
||||
# **TLS 默认未启用** —— 反代是 HTTPS(`wss://`,D5 已定必须支持),故补
|
||||
# `rustls-tls-webpki-roots`:纯 Rust、无 C 依赖,与项目姿态一致(`native-tls` 会引入系统依赖),
|
||||
# 且复用依赖树里已存在的 rustls 0.23(经 russh),不新增编译单元。
|
||||
# 注意:自签证书的 `wss://` 仍是缺口 —— `insecure`(危险开关)目前只覆盖 REST。
|
||||
tokio-tungstenite = { version = "0.24", features = ["connect", "rustls-tls-webpki-roots"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
|
||||
walkdir = "2"
|
||||
notify = { version = "6", features = [] }
|
||||
librqbit = "9"
|
||||
bytes = "1"
|
||||
windows-capture = "2.0.1"
|
||||
# 音频解码(纯 Rust)。**默认特性不含 mp3/aac/alac/isomp4**——0.6 起这几项被移出
|
||||
# default,必须显式打开,否则 mp3 与 m4a 直接报「不支持的格式」。
|
||||
# default 已含:flac / wav / ogg / vorbis / pcm / adpcm / mkv + 全部元数据。
|
||||
# 注意:`ape` 只是**元数据**特性(symphonia-metadata/ape),没有 APE 解码器;
|
||||
# 也没有 opus 特性(ogg 里若是 Opus 轨道无法解码)。这两点已与用户确认接受。
|
||||
symphonia = { version = "0.6", features = ["mp3", "aac", "alac", "isomp4"] }
|
||||
# 音频输出。Windows 走 WASAPI:cpal 的共享模式输出带
|
||||
# AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | SRC_DEFAULT_QUALITY,因此**可以用源采样率
|
||||
# 直接建流**,由 Windows 自己转换到设备混音格式 —— 不需要额外引入重采样库。
|
||||
cpal = "0.18"
|
||||
# WebDAV 的 PROPFIND 响应是 XML,且命名空间前缀由服务端随意指定(D: / d: / lp1: /
|
||||
# 无前缀),因此只能按 local name 做宽容的事件流解析。quick-xml 是纯 Rust、无 C 依赖,
|
||||
# 且比 serde 反序列化更能吃下各家 NAS 不一致的字段集合(见 notes/webdav/client.rs)。
|
||||
quick-xml = "0.42.0"
|
||||
tauri-plugin-single-instance = "2.5.1"
|
||||
# HDR 截图说明:windows-capture 的 Windows Graphics Capture 后端在 HDR 显示器上
|
||||
# 可能输出 scRGB / rgba16F 或 HDR10(PQ) 格式的帧,与项目其余截图路径
|
||||
# (GDI BitBlt,sRGB 8bit)色彩空间不一致。capture 层统一转成 sRGB 8bit
|
||||
# 后再交给编码器,否则 HDR 屏上截出的图会整体偏灰 / 过曝。
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = "0.52"
|
||||
# WebDAV 凭据加密存储(Windows 凭据管理器,DPAPI 保护)
|
||||
keyring = { version = "3", features = ["windows-native"] }
|
||||
raw-window-handle = "0.6"
|
||||
windows-sys = { version = "0.52", features = [
|
||||
"Win32_Networking_WinInet",
|
||||
"Win32_Foundation",
|
||||
"Win32_Globalization",
|
||||
"Win32_Security",
|
||||
"Win32_System_Threading",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_Memory",
|
||||
"Win32_System_DataExchange",
|
||||
"Win32_System_SystemInformation",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_HiDpi",
|
||||
@@ -64,8 +167,118 @@ windows-sys = { version = "0.52", features = [
|
||||
"Win32_Graphics_Dwm",
|
||||
"Win32_Storage_Xps",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_Devices_Display",
|
||||
# 终端模块:ConPTY(CreatePseudoConsole / ResizePseudoConsole / ClosePseudoConsole)
|
||||
"Win32_System_Console",
|
||||
# 终端模块:CreatePipe(ConPTY 的输入/输出管道)
|
||||
"Win32_System_Pipes",
|
||||
# 终端模块:ReadFile / CancelIoEx / GetOverlappedResult(ConPTY 输出读取)
|
||||
# 注意:0.52 起 ReadFile 定义在 Storage_FileSystem 但被 Win32_System_IO 特性门控,
|
||||
# 两个特性必须同时开启,否则导入会解析失败。
|
||||
"Win32_System_IO",
|
||||
# 音乐模块「解密」:QQ音乐新版 musicex 的 ekey 不落盘,只能联网取;而
|
||||
# authst 仅存在于 QQMusic.exe 运行期内存里 —— 需要进程枚举(ToolHelp:
|
||||
# CreateToolhelp32Snapshot / Process32FirstW)与跨进程读内存
|
||||
# (Diagnostics::Debug::ReadProcessMemory + System::Memory::VirtualQueryEx)。
|
||||
"Win32_System_Diagnostics_ToolHelp",
|
||||
"Win32_System_Diagnostics_Debug",
|
||||
] }
|
||||
# Explorer ShellWindows COM:用于枚举已打开的资源管理器窗口并取当前路径
|
||||
# (快速面板「用资源管理器打开」联动)。依赖 Win32_System_Com 特性。
|
||||
windows = { version = "0.52", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_Variant",
|
||||
"Win32_UI_Shell",
|
||||
# 快速面板「保存截图后定位并进入重命名」:SHParseDisplayName / SHOpenFolderAndSelectItems
|
||||
# 与 ITEMIDLIST 都被 Win32_UI_Shell_Common 门控(windows 0.52 源码 cfg)
|
||||
"Win32_UI_Shell_Common",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
# 翻译模块:Windows.Media.Ocr 本地识别(WinRT)
|
||||
# Foundation_Collections:OcrResult.Lines / OcrEngine.AvailableRecognizerLanguages 返回 IVectorView
|
||||
# Security_Cryptography:用 CryptographicBuffer 从内存字节构造 IBuffer(不落盘)
|
||||
"Foundation",
|
||||
"Foundation_Collections",
|
||||
"Globalization",
|
||||
"Graphics_Imaging",
|
||||
"Media_Ocr",
|
||||
# 音乐模块:系统媒体传输控件(SMTC)。Windows.Media 提供
|
||||
# SystemMediaTransportControls / DisplayUpdater / MusicDisplayProperties /
|
||||
# TimelineProperties;Win32_System_WinRT 提供桌面应用唯一的取用入口
|
||||
# ISystemMediaTransportControlsInterop::GetForWindow。
|
||||
# 之所以不用前端 navigator.mediaSession 当唯一通道:WebView2 只转发标题/歌手/进度,
|
||||
# 专辑与封面不送达,且会话挂在浏览器进程 AUMID 上只显示「未知应用」。
|
||||
"Media",
|
||||
"Win32_System_WinRT",
|
||||
# 音乐模块·手机遥控:GSMTC 全局会话管理器(Windows.Media.Control),
|
||||
# 枚举/监视/控制系统全部 SMTC 会话(MUSIC_REMOTE_PLAN §3.1)
|
||||
"Media_Control",
|
||||
# 手机遥控·UDP beacon:GetAdaptersAddresses 枚举各网卡 IPv4/广播地址
|
||||
# (多网卡/VPN 场景下定向广播,MUSIC_REMOTE_PLAN §3.3)。
|
||||
# GetAdaptersAddresses 另受 Ndis + WinSock 两个 feature 门控(windows 0.52 源码 cfg)
|
||||
"Win32_NetworkManagement_IpHelper",
|
||||
"Win32_NetworkManagement_Ndis",
|
||||
"Win32_Networking_WinSock",
|
||||
# 手机遥控·P1 系统音量:MMDevice + IAudioEndpointVolume(Endpoints 有独立 feature 门控;
|
||||
# IMMDevice::Activate 另需 Com_StructuredStorage)
|
||||
"Win32_Media_Audio",
|
||||
"Win32_Media_Audio_Endpoints",
|
||||
"Win32_System_Com_StructuredStorage",
|
||||
"Security_Cryptography",
|
||||
# 划词取词的智能路径:UIA 直读焦点元素选区(IUIAutomation / ITextProvider)
|
||||
"Win32_UI_Accessibility",
|
||||
# OCR:CryptographicBuffer / SoftwareBitmap::CreateCopyFromBuffer 的 IBuffer 属于
|
||||
# Windows.Storage.Streams,缺这个 feature 会 E0599 找不到 CreateFromByteArray
|
||||
"Storage_Streams",
|
||||
# HDR 探测:DXGI 的 advanced color 查询用于判断显示器是否处于 HDR / WCG 状态,
|
||||
# 并读取其色域与传递函数(G2084/PQ 表示 HDR10)。截图前据此决定是否做色调映射。
|
||||
# 对应 feature:Win32_Graphics_Dxgi / Win32_Graphics_Dxgi_Common。
|
||||
"Win32_Graphics_Dxgi_Common",
|
||||
"Win32_Graphics_Gdi",
|
||||
] }
|
||||
# 与 tauri / wry 同版本的 windows crate(**重命名**以便与上面项目自用的 0.52 并存;
|
||||
# 同名不同版本不能写在同一个表里)。仅用于 editor/drag_drop.rs 实现 IDropTarget:
|
||||
# 需要与 `WebviewWindow::hwnd()` 返回的 HWND 是同一个类型,才能直接对接。
|
||||
windows62 = { package = "windows", version = "0.62", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_System_Com",
|
||||
# 窗口级 AppUserModelID:PROPVARIANT 在 Com\StructuredStorage 下
|
||||
"Win32_System_Com_StructuredStorage",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_SystemServices",
|
||||
"Win32_UI_Shell",
|
||||
# 窗口级 AUMID:SHGetPropertyStoreForWindow / IPropertyStore(Shell\PropertiesSystem)
|
||||
"Win32_UI_Shell_PropertiesSystem",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
# PKEY_AppUserModel_ID 常量声明在 Storage\EnhancedStorage 下
|
||||
"Win32_Storage_EnhancedStorage",
|
||||
] }
|
||||
# `#[implement]` 宏展开出的代码按裸名引用 `windows_core`,因此必须直接依赖同名 crate。
|
||||
windows-core = "0.62"
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
tauri-plugin-autostart = "2"
|
||||
|
||||
# ===== 编译配置 =====
|
||||
# dev profile:日常 `tauri dev` 的取舍。
|
||||
# - incremental = true:增量编译,改一行代码只需重编受影响的 crate
|
||||
# - debug = "line-tables-only":只保留行号表,去掉完整 DWARF,交付期
|
||||
# target/ 目录因此从数 GB 降到数百 MB,而 panic 回溯仍能定位到源码行。
|
||||
# 注意:这里没开 opt-level。依赖 crate(尤其 tauri/wry/windows-sys)
|
||||
# 在 opt-level=0 下开销明显;若 dev 下界面卡顿,可只给依赖提优化。
|
||||
|
||||
[profile.dev]
|
||||
incremental = true
|
||||
debug = "line-tables-only"
|
||||
|
||||
# release profile:交付构建。
|
||||
# - strip = true:剥离符号信息,显著缩小产物体积
|
||||
# - lto = true:全程序链接时优化,跨 crate 内联,通常带来 10~20% 性能提升,
|
||||
# 代价是链接时间从秒级升到分钟级。只在 release 构建付出这个代价。
|
||||
# 未开 codegen-units=1:会再压榨约 5% 性能,但编译时间翻倍,不值得。
|
||||
[profile.release]
|
||||
strip = true
|
||||
lto = true
|
||||
|
||||
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "clipboard-preview",
|
||||
"description": "Capability for clipboard independent preview window",
|
||||
"windows": ["clipboard-preview"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-effects",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
"dialog:default",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-unminimize",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-hide",
|
||||
@@ -26,6 +27,9 @@
|
||||
"core:window:allow-set-always-on-top",
|
||||
"core:window:allow-set-skip-taskbar",
|
||||
"core:window:allow-set-decorations",
|
||||
"global-shortcut:allow-register",
|
||||
"global-shortcut:allow-unregister",
|
||||
"global-shortcut:allow-is-registered",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "diff-window",
|
||||
"description": "Capability for the compare window (singleton, label = diff-window). Dual-pane merge view + folder tree — needs the editor window's control set (self-drawn title bar, mica/acrylic effects) plus drag & drop for setting either side from Explorer.",
|
||||
"windows": ["diff-window"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-effects",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit",
|
||||
"dialog:default",
|
||||
"opener:default",
|
||||
"opener:allow-open-path",
|
||||
"opener:allow-reveal-item-in-dir",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "download-window",
|
||||
"description": "Capability for the per-download one-time window",
|
||||
"windows": ["download-window-*"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-unminimize",
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-set-size",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-always-on-top",
|
||||
"core:window:allow-set-skip-taskbar",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-effects",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:window:allow-close",
|
||||
"core:event:allow-emit",
|
||||
"core:event:allow-listen",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "dsh-window",
|
||||
"description": "Capability for the dsh startup progress window (#dsh-window). Self-drawn title bar + theme; only local app commands are invoked.",
|
||||
"windows": ["dsh-window"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "editor-window",
|
||||
"description": "Capability for the editor windows (multi-open, label = editor-window-<n>). Needs the CM6 editor's window controls, events (settings/library sync) and opener.",
|
||||
"windows": ["editor-window-*"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-effects",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit",
|
||||
"dialog:default",
|
||||
"opener:default",
|
||||
"opener:allow-open-path",
|
||||
"opener:allow-reveal-item-in-dir",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "file-window",
|
||||
"description": "Capability for the file manager window (singleton, label = file-window). Dual-pane local/SSH browser — needs the same window/event/dialog/opener set as the main window's file page, plus window controls for its self-drawn title bar.",
|
||||
"windows": ["file-window"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit",
|
||||
"dialog:default",
|
||||
"opener:default",
|
||||
"opener:allow-open-path",
|
||||
"opener:allow-reveal-item-in-dir",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "screenshot",
|
||||
"description": "Capability for screenshot overlay and editor windows",
|
||||
"windows": ["screenshot-overlay*", "screenshot-editor-*"],
|
||||
"description": "Capability for screenshot overlay, editor, pin and scroll-control windows",
|
||||
"windows": ["screenshot-overlay*", "screenshot-editor*", "screenshot-pin", "screenshot-scroll-*"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-hide",
|
||||
@@ -11,12 +11,14 @@
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-position",
|
||||
"core:window:allow-set-size",
|
||||
"core:window:allow-set-resizable",
|
||||
"core:window:allow-set-always-on-top",
|
||||
"core:window:allow-set-skip-taskbar",
|
||||
"core:window:allow-set-decorations",
|
||||
"core:window:allow-close",
|
||||
"core:event:allow-emit",
|
||||
"core:event:allow-listen",
|
||||
"core:webview:allow-create-webview-window",
|
||||
"dialog:default",
|
||||
"snap-layout:default"
|
||||
]
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "terminal-window",
|
||||
"description": "Capability for detached terminal windows (one session per window, label = terminal-window-<sessionId>)",
|
||||
"windows": ["terminal-window-*"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit",
|
||||
"opener:default",
|
||||
"opener:allow-open-path",
|
||||
"opener:allow-reveal-item-in-dir",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "translate-popup",
|
||||
"description": "Capability for the non-activating translate popup window",
|
||||
"windows": ["translate-popup"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-effects",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! **临时**端到端验证:对真实 musicex 样本走完整「取密钥 → 解密 → 校验」流程。
|
||||
//!
|
||||
//! 用法(需要 QQ 音乐在运行且已登录):
|
||||
//! ```text
|
||||
//! cargo run --example decrypt_musicex_probe -- "C:\path\to\file.mflac"
|
||||
//! ```
|
||||
//! 验证完即可删除本文件。
|
||||
|
||||
use thing_lib::music::decrypt::probe::{probe_musicex, ProbeOutcome};
|
||||
|
||||
fn main() {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let path = args.next().expect(
|
||||
"用法:decrypt_musicex_probe <文件路径> [输出目录]\n\
|
||||
给了输出目录则会用**生产路径**真正写盘(生成可播放文件)",
|
||||
);
|
||||
let out_dir = args.next();
|
||||
|
||||
match probe_musicex(std::path::Path::new(&path)) {
|
||||
Ok(ProbeOutcome {
|
||||
ekey_len,
|
||||
key_len,
|
||||
raw_key_bytes,
|
||||
cipher_magic,
|
||||
plain_magic,
|
||||
decrypted_bytes,
|
||||
guessed_format,
|
||||
expiration_secs,
|
||||
}) => {
|
||||
println!("=== 成功 ===");
|
||||
println!("ekey 长度 : {ekey_len}");
|
||||
println!("派生密钥长度 : {key_len}");
|
||||
println!(
|
||||
"密钥前 8 字节 : {:02x?}",
|
||||
&raw_key_bytes[..raw_key_bytes.len().min(8)]
|
||||
);
|
||||
println!("密文头 : {:02x?}", cipher_magic);
|
||||
println!("解密后字节数 : {decrypted_bytes}");
|
||||
println!("明文首帧魔数 : {:02x?}", plain_magic);
|
||||
println!("判定格式 : {guessed_format}");
|
||||
println!("ekey 有效期(秒) : {expiration_secs}");
|
||||
if guessed_format == "flac" && plain_magic.starts_with(b"fLaC") {
|
||||
println!("=> 合法 FLAC 头,产物可播");
|
||||
} else {
|
||||
println!("=> 头不合法,需要排查");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("=== 失败 ===");
|
||||
println!("{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 可选:调用**生产路径**真正落盘(验证 decrypt_musicex 本身,而不只是核心算法)
|
||||
if let Some(dir) = out_dir {
|
||||
println!("\n=== 生产路径落盘 ===");
|
||||
match thing_lib::music::decrypt::qq_online::decrypt_musicex(
|
||||
std::path::Path::new(&path),
|
||||
std::path::Path::new(&dir),
|
||||
"QQ音乐",
|
||||
|done, total| {
|
||||
if done == total {
|
||||
println!("进度:{done} 字节(完成)");
|
||||
}
|
||||
},
|
||||
) {
|
||||
Ok(outcome) => {
|
||||
let size = std::fs::metadata(&outcome.output)
|
||||
.map(|m| m.len())
|
||||
.unwrap_or(0);
|
||||
println!("产物 : {}", outcome.output.display());
|
||||
println!("大小 : {size} 字节");
|
||||
println!("格式 : {}", outcome.format);
|
||||
println!("备注 : {}", outcome.note);
|
||||
}
|
||||
Err(e) => {
|
||||
println!("落盘失败:{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! 诊断:枚举全部 GSMTC 会话的时间轴原始值(判断"来源不提供进度"的形态)。
|
||||
//!
|
||||
//! 运行:`cargo run --example gsmtc_dump`
|
||||
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use windows::Media::Control::GlobalSystemMediaTransportControlsSessionManager;
|
||||
|
||||
fn ticks_to_unix_ms(ticks: i64) -> i64 {
|
||||
ticks / 10_000 - 62_135_596_800_000
|
||||
}
|
||||
|
||||
fn main() -> windows::core::Result<()> {
|
||||
let mgr = GlobalSystemMediaTransportControlsSessionManager::RequestAsync()?.get()?;
|
||||
let sessions = mgr.GetSessions()?;
|
||||
let now_ms = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as i64)
|
||||
.unwrap_or(0);
|
||||
println!("now(unix ms) = {now_ms}");
|
||||
println!("sessions = {}", sessions.Size()?);
|
||||
|
||||
for i in 0..sessions.Size()? {
|
||||
let s = sessions.GetAt(i)?;
|
||||
println!("--- [{}] {}", i, s.SourceAppUserModelId()?);
|
||||
if let Ok(p) = s.TryGetMediaPropertiesAsync()?.get() {
|
||||
println!(
|
||||
" title={:?} artist={:?} album={:?}",
|
||||
p.Title()?,
|
||||
p.Artist()?,
|
||||
p.AlbumTitle()?
|
||||
);
|
||||
}
|
||||
let info = s.GetPlaybackInfo()?;
|
||||
println!(" status={:?}", info.PlaybackStatus()?);
|
||||
if let Ok(c) = info.Controls() {
|
||||
println!(
|
||||
" controls play={} pause={} next={} prev={} seek={}",
|
||||
c.IsPlayEnabled().unwrap_or(false),
|
||||
c.IsPauseEnabled().unwrap_or(false),
|
||||
c.IsNextEnabled().unwrap_or(false),
|
||||
c.IsPreviousEnabled().unwrap_or(false),
|
||||
c.IsPlaybackPositionEnabled().unwrap_or(false)
|
||||
);
|
||||
}
|
||||
let tl = s.GetTimelineProperties()?;
|
||||
let pos = tl.Position()?.Duration;
|
||||
let end = tl.EndTime().map(|t| t.Duration).unwrap_or(-1);
|
||||
let upd = tl.LastUpdatedTime()?.UniversalTime;
|
||||
let upd_ms = ticks_to_unix_ms(upd);
|
||||
println!(
|
||||
" position={}s end={}s lastUpdatedTicks={upd} -> unixMs={upd_ms} (deltaMs={})",
|
||||
pos as f64 / 1e7,
|
||||
end as f64 / 1e7,
|
||||
upd_ms - now_ms
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! GSMTC 可用性探测(MUSIC_REMOTE_PLAN §7 P0 第 1 项 / §6 第 1 条)
|
||||
//!
|
||||
//! 关键假设:GSMTC(Windows.Media.Control)在**非打包**桌面应用可用(Windows 10 1809+)。
|
||||
//! 本 example 以普通控制台进程运行(无 package identity),跑通即证明假设成立。
|
||||
//!
|
||||
//! 运行:`cargo run --example gsmtc_probe`
|
||||
//! 建议先在任意播放器(网易云/浏览器/Thing)放一首歌,可看到当前会话的元数据与时间轴。
|
||||
|
||||
use windows::Media::Control::GlobalSystemMediaTransportControlsSessionManager;
|
||||
use windows::core::Result;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
// 1. 取全局会话管理器(失败 = 整个能力需降级,见计划 §3.1 失败策略)
|
||||
let mgr = GlobalSystemMediaTransportControlsSessionManager::RequestAsync()?.get()?;
|
||||
|
||||
// 2. 枚举系统全部 SMTC 会话(注意:0.52 投影里 GetSessions/GetCurrentSession 是同步的)
|
||||
let sessions = mgr.GetSessions()?;
|
||||
println!("[ok] GSMTC 可用(unpackaged),当前会话数: {}", sessions.Size()?);
|
||||
|
||||
// 3. 当前活跃会话的元数据 / 播放状态 / 时间轴
|
||||
// 无会话时 ABI 返回 null → windows-rs 投影为 Err(E_POINTER),按"无会话"处理
|
||||
match mgr.GetCurrentSession() {
|
||||
Ok(cur) => {
|
||||
println!("current: {}", cur.SourceAppUserModelId()?);
|
||||
let p = cur.TryGetMediaPropertiesAsync()?.get()?;
|
||||
println!(" {} - {} | album: {}", p.Artist()?, p.Title()?, p.AlbumTitle()?);
|
||||
println!(" status: {:?}", cur.GetPlaybackInfo()?.PlaybackStatus()?);
|
||||
let tl = cur.GetTimelineProperties()?;
|
||||
println!(
|
||||
" position(ticks): {} | lastUpdated(ticks): {}",
|
||||
tl.Position()?.Duration,
|
||||
tl.LastUpdatedTime()?.UniversalTime
|
||||
);
|
||||
}
|
||||
Err(e) => println!("current session: <none> ({e})(先放一首歌再跑,可看完整元数据)"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//! **临时**校验:用产物解析器确认解密出来的文件是合法音频。
|
||||
//!
|
||||
//! 用法:`cargo run --example verify_audio -- <文件路径>`
|
||||
|
||||
fn main() {
|
||||
let path = std::env::args()
|
||||
.nth(1)
|
||||
.expect("用法:verify_audio <文件路径>");
|
||||
let p = std::path::Path::new(&path);
|
||||
|
||||
let size = std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);
|
||||
println!("文件 : {}", p.display());
|
||||
println!("大小 : {size} 字节");
|
||||
|
||||
// 1) 头部魔数
|
||||
let head = std::fs::read(p).map(|b| b[..16.min(b.len())].to_vec());
|
||||
match head {
|
||||
Ok(h) => println!("首帧 : {:02x?}", h),
|
||||
Err(e) => {
|
||||
println!("读取失败:{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 交给项目同款的解析器(lofty):能读出时长与格式才算真合法
|
||||
match lofty::probe::Probe::open(p).and_then(|probe| probe.read()) {
|
||||
Ok(tagged) => {
|
||||
use lofty::file::AudioFile;
|
||||
let props = tagged.properties();
|
||||
println!("时长 : {:?}", props.duration());
|
||||
println!("码率 : {:?}", props.audio_bitrate());
|
||||
println!("采样率 : {:?}", props.sample_rate());
|
||||
println!("声道 : {:?}", props.channels());
|
||||
println!("=> lofty 成功解析,文件合法可播");
|
||||
}
|
||||
Err(e) => {
|
||||
println!("lofty 解析失败:{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,6 @@ const DEFAULT_CONFIG = {
|
||||
interceptDownload: true,
|
||||
minSize: 0,
|
||||
excludeDomains: [],
|
||||
showNotifications: true,
|
||||
// 嗅探开关
|
||||
sniffEnabled: true,
|
||||
// 嗅探的资源类型:只保留视频/音频/图片/压缩包/种子/安装包
|
||||
@@ -359,6 +358,11 @@ async function addDownload(url, filename, referer, cookies, headers) {
|
||||
}
|
||||
|
||||
// ===== 下载拦截 =====
|
||||
// 处理中的 URL(防止同一 URL 并发/重入,也避免与引擎去重检查竞态)
|
||||
const processingUrls = new Set()
|
||||
// 我们自己用 chrome.downloads.download 回退创建的下载 URL(短时间内跳过,防止再次被拦截形成死循环)
|
||||
const fallbackUrls = new Map() // url -> 过期时间戳
|
||||
|
||||
async function shouldIntercept(downloadItem) {
|
||||
const config = await getConfig()
|
||||
if (!config.interceptDownload) return false
|
||||
@@ -374,42 +378,172 @@ async function shouldIntercept(downloadItem) {
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为"历史下载"(本次浏览器会话开始之前就存在、浏览器重启/恢复后才重新触发的下载)
|
||||
* 这类下载一律不接管,交给浏览器原生处理,实现"只接管以后的下载,历史都不管"
|
||||
*
|
||||
* 三重判据(任一命中即视为历史下载):
|
||||
* 1. canResume=true:已存在有效的部分文件,说明浏览器在恢复旧下载
|
||||
* 2. 开始时间早于插件首次安装时间
|
||||
* 3. 开始时间早于**本次浏览器会话**起点:浏览器重启时会恢复上次未完成的下载,
|
||||
* 这些下载的 startTime 仍是上次会话的时间,因此一定会落在会话起点之前。
|
||||
* (只靠 1/2 不够:上次会话启动的下载若被浏览器重新排队,canResume 可能为 false,
|
||||
* 而 startTime 又晚于安装时间 —— 这正是"关掉浏览器后莫名多出历史下载"的成因)
|
||||
*/
|
||||
async function isHistoricalDownload(item) {
|
||||
// 1) canResume=true 表示已存在有效的部分文件,说明浏览器在恢复旧下载
|
||||
if (item.canResume) return true
|
||||
|
||||
const start = item.startTime ? new Date(item.startTime).getTime() : 0
|
||||
|
||||
// 2) 开始时间早于插件首次安装时间(浏览器重启后恢复的旧下载会保留原来的开始时间)
|
||||
try {
|
||||
const stored = await chrome.storage.local.get('installTime')
|
||||
const installTime = stored.installTime || 0
|
||||
if (installTime > 0 && start > 0 && start < installTime) return true
|
||||
} catch { /* ignore */ }
|
||||
|
||||
// 3) 开始时间早于本次浏览器会话起点(含 5s 宽限,避免刚启动时误判新下载)
|
||||
const sessionStart = await ensureSessionStart()
|
||||
if (start > 0 && start < sessionStart - RESTORE_GRACE_MS) return true
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/** 浏览器会话起点(chrome.storage.session 在浏览器关闭后自动清空) */
|
||||
const SESSION_START_KEY = 'sessionStart'
|
||||
/** 会话起点宽限:会话刚建立时新下载的 startTime 可能略早于起点记录时刻 */
|
||||
const RESTORE_GRACE_MS = 5000
|
||||
let sessionStartCache = 0
|
||||
|
||||
/**
|
||||
* 取本次浏览器会话的起点时间戳(首次调用时写入 storage.session)。
|
||||
* 用 storage.session 而非 storage.local 的原因:它随浏览器关闭而清空,
|
||||
* "存在"本身就等价于"本次会话已开始",无需自己判断重启。
|
||||
*/
|
||||
async function ensureSessionStart() {
|
||||
if (sessionStartCache) return sessionStartCache
|
||||
try {
|
||||
const s = await chrome.storage.session.get(SESSION_START_KEY)
|
||||
if (s[SESSION_START_KEY]) {
|
||||
sessionStartCache = s[SESSION_START_KEY]
|
||||
return sessionStartCache
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
sessionStartCache = Date.now()
|
||||
try {
|
||||
await chrome.storage.session.set({ [SESSION_START_KEY]: sessionStartCache })
|
||||
} catch { /* ignore */ }
|
||||
return sessionStartCache
|
||||
}
|
||||
|
||||
/** 已处理过的下载 guid(持久化,浏览器重启后仍能认出同一条下载) */
|
||||
const SEEN_GUIDS_KEY = 'seenDownloadGuids'
|
||||
/** 记录上限:只用于识别"同一条下载被重复通知",不需要长期留存 */
|
||||
const SEEN_GUIDS_MAX = 300
|
||||
let seenGuidsCache = null
|
||||
|
||||
async function loadSeenGuids() {
|
||||
if (seenGuidsCache) return seenGuidsCache
|
||||
try {
|
||||
const s = await chrome.storage.local.get(SEEN_GUIDS_KEY)
|
||||
seenGuidsCache = Array.isArray(s[SEEN_GUIDS_KEY]) ? s[SEEN_GUIDS_KEY] : []
|
||||
} catch {
|
||||
seenGuidsCache = []
|
||||
}
|
||||
return seenGuidsCache
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录 guid 并返回它此前是否已见过。
|
||||
* `true` 表示这条下载我们处理过/见过,本次是重复通知(浏览器恢复旧下载时会复用原 guid),
|
||||
* 必须跳过,否则会把历史下载重新丢进 Thing。
|
||||
*/
|
||||
async function markGuidSeen(guid) {
|
||||
const seen = await loadSeenGuids()
|
||||
if (seen.includes(guid)) return true
|
||||
seen.push(guid)
|
||||
if (seen.length > SEEN_GUIDS_MAX) seen.splice(0, seen.length - SEEN_GUIDS_MAX)
|
||||
seenGuidsCache = seen
|
||||
try {
|
||||
await chrome.storage.local.set({ [SEEN_GUIDS_KEY]: seen })
|
||||
} catch { /* ignore */ }
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询引擎是否已有同 URL 的非终态任务(活跃/排队/暂停)
|
||||
* 用于防止同一下载被重复转发、重复下载
|
||||
*/
|
||||
async function hasExistingTask(url) {
|
||||
try {
|
||||
const tasks = await apiRequest('/api/downloads')
|
||||
return tasks.some(t => {
|
||||
const s = t.status
|
||||
if (s === 'complete' || s === 'error') return false
|
||||
return t.url === url
|
||||
})
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDownloadCreated(downloadItem) {
|
||||
const url = downloadItem.finalUrl || downloadItem.url
|
||||
|
||||
// 同一条下载只处理一次:浏览器重启后恢复的旧下载会带着原 guid 再次触发 onCreated,
|
||||
// 不拦下来就会把「早已看过/已完成」的下载重新丢进 Thing(表现为莫名弹出历史下载)
|
||||
if (downloadItem.guid && await markGuidSeen(downloadItem.guid)) return
|
||||
|
||||
// 回退下载:我们自己用 chrome.downloads.download 创建的,直接跳过,避免无限循环
|
||||
const fbExp = fallbackUrls.get(url)
|
||||
if (fbExp && Date.now() < fbExp) {
|
||||
fallbackUrls.delete(url)
|
||||
return
|
||||
}
|
||||
|
||||
// 历史下载(安装前的旧下载被浏览器恢复)一律不接管
|
||||
if (await isHistoricalDownload(downloadItem)) return
|
||||
|
||||
if (!await shouldIntercept(downloadItem)) return
|
||||
|
||||
// 同一 URL 已在处理中,跳过(防并发/防重复转发)
|
||||
if (processingUrls.has(url)) return
|
||||
|
||||
// 引擎不可达时不接管(保留浏览器原生下载),避免取消后下载无处可去
|
||||
let connected = false
|
||||
try { connected = await testConnection() } catch { connected = false }
|
||||
if (!connected) return
|
||||
|
||||
// 引擎已有同 URL 的非终态任务,不重复转发
|
||||
if (await hasExistingTask(url)) return
|
||||
|
||||
processingUrls.add(url)
|
||||
try {
|
||||
try {
|
||||
await chrome.downloads.cancel(downloadItem.id)
|
||||
await chrome.downloads.erase({ id: downloadItem.id })
|
||||
} catch { /* ignore */ }
|
||||
|
||||
const url = downloadItem.finalUrl || downloadItem.url
|
||||
const filename = downloadItem.filename || ''
|
||||
|
||||
try {
|
||||
const id = await addDownload(url, filename, downloadItem.referrer, '')
|
||||
await notify('已添加到 Thing', `${filename || url}`)
|
||||
await addDownload(url, filename, downloadItem.referrer, '')
|
||||
} catch (e) {
|
||||
await notify('Thing 添加失败', `${filename || url}\n${e.message}`)
|
||||
// 添加失败:回退为浏览器自带下载,并标记该 URL 短时间内跳过,防止再次被拦截形成死循环
|
||||
fallbackUrls.set(url, Date.now() + 3000)
|
||||
try { await chrome.downloads.download({ url }) } catch { /* ignore */ }
|
||||
}
|
||||
} finally {
|
||||
processingUrls.delete(url)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 通知 =====
|
||||
async function notify(title, message) {
|
||||
const config = await getConfig()
|
||||
if (!config.showNotifications) return
|
||||
try {
|
||||
await chrome.notifications.create({
|
||||
type: 'basic',
|
||||
iconUrl: 'icons/icon-128.png',
|
||||
title,
|
||||
message
|
||||
})
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// ===== 右键菜单 =====
|
||||
chrome.runtime.onInstalled.addListener(() => {
|
||||
// ===== 右键菜单 & 安装标记 =====
|
||||
chrome.runtime.onInstalled.addListener(async (details) => {
|
||||
// 记录首次安装时间:用于区分"安装前的历史下载"(被浏览器恢复的旧下载)与"安装后的新下载"
|
||||
if (details.reason === 'install') {
|
||||
await chrome.storage.local.set({ installTime: Date.now() })
|
||||
}
|
||||
chrome.contextMenus.create({
|
||||
id: 'thing-download-link',
|
||||
title: '使用 Thing 下载此链接',
|
||||
@@ -428,10 +562,7 @@ chrome.contextMenus.onClicked.addListener(async (info, tab) => {
|
||||
const filename = url.split('/').pop()?.split('?')[0] || ''
|
||||
try {
|
||||
await addDownload(url, filename, info.pageUrl, '')
|
||||
await notify('已添加到 Thing', `${filename || url}`)
|
||||
} catch (e) {
|
||||
await notify('Thing 添加失败', `${e.message}`)
|
||||
}
|
||||
} catch (e) { /* 忽略:添加失败时不打扰用户 */ }
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Thing Extension",
|
||||
"version": "0.2.0",
|
||||
"version": "0.31",
|
||||
"description": "发送浏览器下载到 Thing 下载引擎,嗅探网页资源。",
|
||||
"icons": {
|
||||
"16": "icons/icon-16.png",
|
||||
@@ -11,9 +11,7 @@
|
||||
"permissions": [
|
||||
"downloads",
|
||||
"storage",
|
||||
"notifications",
|
||||
"webRequest",
|
||||
"webNavigation",
|
||||
"contextMenus",
|
||||
"tabs",
|
||||
"scripting"
|
||||
|
||||
@@ -87,11 +87,6 @@
|
||||
<span>启用资源嗅探</span>
|
||||
</label>
|
||||
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="showNotifications" />
|
||||
<span>显示桌面通知</span>
|
||||
</label>
|
||||
|
||||
<label class="field">
|
||||
<span>下载最小文件大小(字节,0=全部)</span>
|
||||
<input type="number" id="minSize" min="0" placeholder="0" />
|
||||
|
||||
@@ -12,7 +12,6 @@ const DEFAULT_CONFIG = {
|
||||
interceptDownload: true,
|
||||
minSize: 0,
|
||||
excludeDomains: [],
|
||||
showNotifications: true,
|
||||
sniffEnabled: true,
|
||||
sniffTypes: ['video', 'audio', 'image', 'archive', 'torrent', 'installer'],
|
||||
sniffMaxItems: 200,
|
||||
@@ -57,7 +56,6 @@ function fillForm(config) {
|
||||
$('secret').value = config.secret || ''
|
||||
$('interceptDownload').checked = config.interceptDownload !== false
|
||||
$('sniffEnabled').checked = config.sniffEnabled !== false
|
||||
$('showNotifications').checked = config.showNotifications !== false
|
||||
$('minSize').value = config.minSize || 0
|
||||
$('sniffMinSize').value = config.sniffMinSize ?? DEFAULT_CONFIG.sniffMinSize
|
||||
$('excludeDomains').value = (config.excludeDomains || []).join(',')
|
||||
@@ -69,7 +67,6 @@ function readForm() {
|
||||
secret: $('secret').value.trim(),
|
||||
interceptDownload: $('interceptDownload').checked,
|
||||
sniffEnabled: $('sniffEnabled').checked,
|
||||
showNotifications: $('showNotifications').checked,
|
||||
minSize: parseInt($('minSize').value, 10) || 0,
|
||||
sniffMinSize: parseInt($('sniffMinSize').value, 10) || 0,
|
||||
excludeDomains: $('excludeDomains').value
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,447 @@
|
||||
//! OpenAI 兼容的通用对话客户端(非翻译语义)。
|
||||
//!
|
||||
//! 一套代码覆盖 DeepSeek / OpenAI / Gemini(OpenAI 兼容端点)/ 通义 DashScope /
|
||||
//! Kimi / 智谱 / 豆包 / Mistral / Groq / OpenRouter / 本地 Ollama / LM Studio /
|
||||
//! one-api 等中转——它们都提供 `POST {baseUrl}/chat/completions` 且结构一致。
|
||||
//!
|
||||
//! 与 `translate::engines::ai` 的分工:
|
||||
//! - 本模块:调用方**全量给定 messages**(终端助手等),不含翻译提示词语义;
|
||||
//! - translate 的 AiEngine:流式、视觉、翻译模板、空流自愈等翻译专属逻辑。
|
||||
//!
|
||||
//! 两者共享端点归一、密钥读取(凭据管理器)与 HTTP 错误分类的约定。
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
|
||||
use super::{
|
||||
provider_api_key, AiErrorKind, AiProviderConfig, AiSettings, DEFAULT_CHAT_TIMEOUT_MS,
|
||||
};
|
||||
|
||||
/// 自检与连通性测试使用的探测文本
|
||||
const PROBE_TEXT: &str = "Hello, world.";
|
||||
|
||||
/// 通用对话请求的结构化错误:**分类 + 可直接展示的中文文案**。
|
||||
///
|
||||
/// 调用方各自取所需:终端助手只要文案([`chat_once`] 直接给 String),
|
||||
/// 设置页的连通性测试还需要分类,用来给「改 Key」「查网络」这类不同的下一步提示。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChatError {
|
||||
pub kind: AiErrorKind,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl ChatError {
|
||||
fn new(kind: AiErrorKind, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ChatError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
/// API 根地址。容错:用户常把完整端点(`.../chat/completions`)粘进来,
|
||||
/// 不剥掉会拼出双重后缀,上游表现为 404。
|
||||
pub fn api_root(cfg: &AiProviderConfig) -> Result<String, ChatError> {
|
||||
let raw = cfg.base_url.trim();
|
||||
if raw.is_empty() {
|
||||
return Err(ChatError::new(
|
||||
AiErrorKind::Config,
|
||||
format!("供应商「{}」尚未配置 Base URL", cfg.name),
|
||||
));
|
||||
}
|
||||
if !(raw.starts_with("http://") || raw.starts_with("https://")) {
|
||||
return Err(ChatError::new(
|
||||
AiErrorKind::Config,
|
||||
format!("Base URL 需以 http:// 或 https:// 开头,当前为「{raw}」"),
|
||||
));
|
||||
}
|
||||
let mut root = raw.trim_end_matches('/').to_string();
|
||||
for suffix in ["/chat/completions", "/completions", "/models"] {
|
||||
if let Some(stripped) = root.strip_suffix(suffix) {
|
||||
root = stripped.trim_end_matches('/').to_string();
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(root)
|
||||
}
|
||||
|
||||
pub fn chat_endpoint(cfg: &AiProviderConfig) -> Result<String, ChatError> {
|
||||
Ok(format!("{}/chat/completions", api_root(cfg)?))
|
||||
}
|
||||
|
||||
pub fn models_endpoint(cfg: &AiProviderConfig) -> Result<String, ChatError> {
|
||||
Ok(format!("{}/models", api_root(cfg)?))
|
||||
}
|
||||
|
||||
/// 取本次请求使用的密钥。
|
||||
///
|
||||
/// `override_key` 非空时优先——设置页「检查」允许用**刚填好、还没保存**的 Key 直接验证,
|
||||
/// 省掉「先保存密钥再测试」的来回。它只活在这一次请求里,不入凭据库、不落盘。
|
||||
fn require_key(cfg: &AiProviderConfig, override_key: Option<&str>) -> Result<String, ChatError> {
|
||||
let key = match override_key.map(str::trim).filter(|k| !k.is_empty()) {
|
||||
Some(k) => k.to_string(),
|
||||
None => provider_api_key(&cfg.id),
|
||||
};
|
||||
if key.trim().is_empty() {
|
||||
return Err(ChatError::new(
|
||||
AiErrorKind::Auth,
|
||||
format!(
|
||||
"供应商「{}」尚未配置 API Key,请在主设置 → AI 服务中填写",
|
||||
cfg.name
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
fn require_model(cfg: &AiProviderConfig) -> Result<String, ChatError> {
|
||||
let model = cfg.model.trim();
|
||||
if model.is_empty() {
|
||||
return Err(ChatError::new(
|
||||
AiErrorKind::Config,
|
||||
format!(
|
||||
"供应商「{}」尚未选择模型,可在设置中拉取模型列表后选择",
|
||||
cfg.name
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(model.to_string())
|
||||
}
|
||||
|
||||
/// 解析请求体公共字段(temperature / max_tokens / extra_body)。
|
||||
fn apply_common_params(body: &mut serde_json::Map<String, serde_json::Value>, cfg: &AiProviderConfig) {
|
||||
body.insert("temperature".into(), json!(cfg.temperature));
|
||||
body.insert("max_tokens".into(), json!(cfg.max_tokens));
|
||||
if let Some(extra) = cfg.extra_body.as_deref().map(str::trim) {
|
||||
if !extra.is_empty() {
|
||||
if let Ok(serde_json::Value::Object(map)) = serde_json::from_str::<serde_json::Value>(extra)
|
||||
{
|
||||
for (k, v) in map {
|
||||
body.insert(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 按设置选择 HTTP 客户端:开了代理且能解析到 mixed 端口 → 走代理,否则直连。
|
||||
///
|
||||
/// 与翻译模块同一姿态:代理不可用时**静默回退直连**,让请求自己去失败。
|
||||
async fn select_client(settings: &AiSettings, data_dir: &std::path::Path) -> reqwest::Client {
|
||||
let direct = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(120))
|
||||
.build()
|
||||
.unwrap_or_else(|_| reqwest::Client::new());
|
||||
if !settings.use_proxy {
|
||||
return direct;
|
||||
}
|
||||
let Ok(raw) = std::fs::read_to_string(data_dir.join("proxy").join("settings.json")) else {
|
||||
return direct;
|
||||
};
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&raw) else {
|
||||
return direct;
|
||||
};
|
||||
let Some(port) = value.get("mixedPort").and_then(|v| v.as_u64()) else {
|
||||
return direct;
|
||||
};
|
||||
if port == 0 || port > 65535 {
|
||||
return direct;
|
||||
}
|
||||
let proxy_url = format!("http://127.0.0.1:{port}");
|
||||
match reqwest::Proxy::all(&proxy_url).ok().and_then(|p| {
|
||||
reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(120))
|
||||
.proxy(p)
|
||||
.build()
|
||||
.ok()
|
||||
}) {
|
||||
Some(client) => client,
|
||||
None => direct,
|
||||
}
|
||||
}
|
||||
|
||||
/// 通用对话补全(结构化错误版):消息由调用方全量给定。
|
||||
async fn post_chat(
|
||||
cfg: &AiProviderConfig,
|
||||
messages: Vec<(&str, String)>,
|
||||
api_key_override: Option<&str>,
|
||||
settings: &AiSettings,
|
||||
data_dir: &std::path::Path,
|
||||
) -> Result<String, ChatError> {
|
||||
let key = require_key(cfg, api_key_override)?;
|
||||
let model = require_model(cfg)?;
|
||||
let endpoint = chat_endpoint(cfg)?;
|
||||
|
||||
let mut body = serde_json::Map::new();
|
||||
body.insert("model".into(), json!(model));
|
||||
body.insert("stream".into(), json!(false));
|
||||
body.insert(
|
||||
"messages".into(),
|
||||
json!(messages
|
||||
.into_iter()
|
||||
.map(|(role, content)| json!({ "role": role, "content": content }))
|
||||
.collect::<Vec<_>>()),
|
||||
);
|
||||
apply_common_params(&mut body, cfg);
|
||||
|
||||
let client = select_client(settings, data_dir).await;
|
||||
let resp = client
|
||||
.post(&endpoint)
|
||||
.bearer_auth(&key)
|
||||
.timeout(Duration::from_millis(DEFAULT_CHAT_TIMEOUT_MS))
|
||||
.json(&serde_json::Value::Object(body))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| classify_reqwest(e, &cfg.name))?;
|
||||
|
||||
let status = resp.status();
|
||||
let raw = resp
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
ChatError::new(
|
||||
AiErrorKind::Network,
|
||||
format!("读取「{}」响应失败: {e}", cfg.name),
|
||||
)
|
||||
})?;
|
||||
if !status.is_success() {
|
||||
return Err(classify_http(status.as_u16(), &raw, &cfg.name, &model));
|
||||
}
|
||||
|
||||
let parsed: ChatResponse = serde_json::from_str(&raw).map_err(|e| {
|
||||
ChatError::new(
|
||||
AiErrorKind::Parse,
|
||||
format!("「{}」响应不是预期的 JSON: {e}", cfg.name),
|
||||
)
|
||||
})?;
|
||||
if let Some(err) = parsed.error {
|
||||
let msg = err
|
||||
.message
|
||||
.filter(|m| !m.trim().is_empty())
|
||||
.unwrap_or_else(|| "上游返回了错误对象".to_string());
|
||||
return Err(ChatError::new(
|
||||
AiErrorKind::Unknown,
|
||||
format!("「{}」返回错误:{msg}", cfg.name),
|
||||
));
|
||||
}
|
||||
|
||||
parsed
|
||||
.choices
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|c| c.message.content)
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.ok_or_else(|| {
|
||||
ChatError::new(AiErrorKind::Empty, format!("「{}」返回了空内容", cfg.name))
|
||||
})
|
||||
}
|
||||
|
||||
/// 通用对话补全:消息由调用方全量给定。
|
||||
///
|
||||
/// 只要文案的调用方(终端 AI 助手)走这里;需要错误分类的用 [`test_provider`]。
|
||||
pub async fn chat_once(
|
||||
cfg: &AiProviderConfig,
|
||||
messages: Vec<(&str, String)>,
|
||||
settings: &AiSettings,
|
||||
data_dir: &std::path::Path,
|
||||
) -> Result<String, String> {
|
||||
post_chat(cfg, messages, None, settings, data_dir)
|
||||
.await
|
||||
.map_err(|e| e.message)
|
||||
}
|
||||
|
||||
/// 连通性自检:发一条极短同步请求。
|
||||
///
|
||||
/// `api_key_override` 见 [`require_key`]:设置页「检查」可以带上用户刚填、还没保存的 Key。
|
||||
pub async fn test_provider(
|
||||
cfg: &AiProviderConfig,
|
||||
api_key_override: Option<&str>,
|
||||
settings: &AiSettings,
|
||||
data_dir: &std::path::Path,
|
||||
) -> Result<String, ChatError> {
|
||||
let started = std::time::Instant::now();
|
||||
let text = post_chat(
|
||||
cfg,
|
||||
vec![
|
||||
("system", "You are a connectivity probe. Reply with OK only.".to_string()),
|
||||
("user", PROBE_TEXT.to_string()),
|
||||
],
|
||||
api_key_override,
|
||||
settings,
|
||||
data_dir,
|
||||
)
|
||||
.await?;
|
||||
Ok(format!(
|
||||
"连通正常 · 模型 {} · {}ms · 回显「{}」",
|
||||
cfg.model,
|
||||
started.elapsed().as_millis() as u64,
|
||||
text.chars().take(40).collect::<String>()
|
||||
))
|
||||
}
|
||||
|
||||
/// 拉取上游模型列表(`GET {baseUrl}/models`)。
|
||||
pub async fn list_models(
|
||||
cfg: &AiProviderConfig,
|
||||
settings: &AiSettings,
|
||||
data_dir: &std::path::Path,
|
||||
) -> Result<Vec<String>, String> {
|
||||
list_models_typed(cfg, settings, data_dir)
|
||||
.await
|
||||
.map_err(|e| e.message)
|
||||
}
|
||||
|
||||
async fn list_models_typed(
|
||||
cfg: &AiProviderConfig,
|
||||
settings: &AiSettings,
|
||||
data_dir: &std::path::Path,
|
||||
) -> Result<Vec<String>, ChatError> {
|
||||
let key = require_key(cfg, None)?;
|
||||
let endpoint = models_endpoint(cfg)?;
|
||||
let client = select_client(settings, data_dir).await;
|
||||
let resp = client
|
||||
.get(&endpoint)
|
||||
.bearer_auth(&key)
|
||||
.timeout(Duration::from_millis(15_000))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| classify_reqwest(e, &cfg.name))?;
|
||||
|
||||
let status = resp.status();
|
||||
let raw = resp.text().await.map_err(|e| {
|
||||
ChatError::new(
|
||||
AiErrorKind::Network,
|
||||
format!("读取「{}」模型列表失败: {e}", cfg.name),
|
||||
)
|
||||
})?;
|
||||
if !status.is_success() {
|
||||
return Err(classify_http(
|
||||
status.as_u16(),
|
||||
&raw,
|
||||
&cfg.name,
|
||||
cfg.model.as_str(),
|
||||
));
|
||||
}
|
||||
|
||||
let parsed: ModelsResponse = serde_json::from_str(&raw).map_err(|e| {
|
||||
ChatError::new(
|
||||
AiErrorKind::Parse,
|
||||
format!("「{}」的模型列表无法解析: {e}", cfg.name),
|
||||
)
|
||||
})?;
|
||||
let mut ids: Vec<String> = parsed
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|m| m.id)
|
||||
.filter(|id| !id.trim().is_empty())
|
||||
.collect();
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn classify_reqwest(e: reqwest::Error, provider: &str) -> ChatError {
|
||||
if e.is_timeout() {
|
||||
return ChatError::new(
|
||||
AiErrorKind::Timeout,
|
||||
format!("请求「{provider}」超时,可在设置中调大超时时间,或检查网络"),
|
||||
);
|
||||
}
|
||||
if e.is_connect() {
|
||||
return ChatError::new(
|
||||
AiErrorKind::Network,
|
||||
format!("无法连接「{provider}」:{e}(若该服务在境外,请检查网络或在 AI 设置中开启代理)"),
|
||||
);
|
||||
}
|
||||
ChatError::new(
|
||||
AiErrorKind::Network,
|
||||
format!("请求「{provider}」失败:{e}"),
|
||||
)
|
||||
}
|
||||
|
||||
fn classify_http(status: u16, body: &str, provider: &str, model: &str) -> ChatError {
|
||||
let snippet = body.trim();
|
||||
let lower = snippet.to_lowercase();
|
||||
match status {
|
||||
401 | 403 => ChatError::new(
|
||||
AiErrorKind::Auth,
|
||||
format!("「{provider}」认证失败(HTTP {status}),请检查 API Key 是否正确、是否有该模型的权限"),
|
||||
),
|
||||
402 => ChatError::new(
|
||||
AiErrorKind::Auth,
|
||||
format!("「{provider}」余额不足或未开通计费(HTTP 402)"),
|
||||
),
|
||||
429 => ChatError::new(
|
||||
AiErrorKind::RateLimit,
|
||||
format!("「{provider}」请求过于频繁(HTTP 429),请稍后重试或降低频率"),
|
||||
),
|
||||
400 | 404 | 422 if lower.contains("model") => ChatError::new(
|
||||
AiErrorKind::Config,
|
||||
format!(
|
||||
"「{provider}」不识别模型「{model}」(HTTP {status}):上游模型名可能已变更,\
|
||||
请在设置中拉取模型列表后重新选择"
|
||||
),
|
||||
),
|
||||
400 | 404 | 422 => ChatError::new(
|
||||
AiErrorKind::Config,
|
||||
format!("「{provider}」拒绝了该请求(HTTP {status})"),
|
||||
),
|
||||
408 | 504 => ChatError::new(
|
||||
AiErrorKind::Timeout,
|
||||
format!("「{provider}」上游超时(HTTP {status})"),
|
||||
),
|
||||
s if (500..600).contains(&s) => ChatError::new(
|
||||
AiErrorKind::Network,
|
||||
format!("「{provider}」服务端错误(HTTP {status}),可稍后重试"),
|
||||
),
|
||||
s => ChatError::new(AiErrorKind::Unknown, format!("「{provider}」返回 HTTP {s}")),
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 响应结构(宽松解析) =====
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ChatResponse {
|
||||
#[serde(default)]
|
||||
choices: Vec<ChatChoice>,
|
||||
#[serde(default)]
|
||||
error: Option<ApiErrorBody>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ChatChoice {
|
||||
#[serde(default)]
|
||||
message: ChatMessage,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
struct ChatMessage {
|
||||
#[serde(default)]
|
||||
content: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ApiErrorBody {
|
||||
#[serde(default)]
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ModelsResponse {
|
||||
#[serde(default)]
|
||||
data: Vec<ModelEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ModelEntry {
|
||||
#[serde(default)]
|
||||
id: String,
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! 全局 AI 模块 Tauri 命令层。
|
||||
//!
|
||||
//! 与 translate 命令层同一安全约定:
|
||||
//! - **不存在读取 API Key 明文的命令**。列表只回传「是否已配置」与掩码;
|
||||
//! - 写入走 `ai_secret_set`,删除走 `ai_secret_clear`。
|
||||
|
||||
use serde::{Serialize};
|
||||
use specta::Type;
|
||||
use tauri::State;
|
||||
|
||||
use super::{AiErrorKind, AiManager, AiProviderConfig, AiSettings, AiTestResult};
|
||||
|
||||
/// 供应商前端视图:配置 + 派生状态(密钥是否已配、是否可用)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiProviderView {
|
||||
pub config: AiProviderConfig,
|
||||
pub has_api_key: bool,
|
||||
pub api_key_masked: String,
|
||||
pub ready: bool,
|
||||
pub issue: Option<String>,
|
||||
}
|
||||
|
||||
/// 读取全局 AI 设置。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn ai_get_settings(state: State<'_, AiManager>) -> Result<AiSettings, String> {
|
||||
Ok(state.load_settings())
|
||||
}
|
||||
|
||||
/// 保存全局 AI 设置(整体覆盖;供应商列表以传入为准)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn ai_save_settings(
|
||||
state: State<'_, AiManager>,
|
||||
settings: AiSettings,
|
||||
) -> Result<(), String> {
|
||||
let mut next = settings;
|
||||
for p in &mut next.providers {
|
||||
p.id = p.id.trim().to_string();
|
||||
p.name = p.name.trim().to_string();
|
||||
}
|
||||
next.providers.retain(|p| !p.id.is_empty());
|
||||
next.heal();
|
||||
state.save_settings(&next)
|
||||
}
|
||||
|
||||
/// 列出供应商视图(含密钥状态与可用性),保持配置中的顺序。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn ai_list_providers(state: State<'_, AiManager>) -> Result<Vec<AiProviderView>, String> {
|
||||
let settings = state.load_settings();
|
||||
Ok(settings.providers.iter().map(to_view).collect())
|
||||
}
|
||||
|
||||
/// 新增或更新一个供应商(按 id upsert)。
|
||||
///
|
||||
/// 校验 id:它会进入凭据键(`ai-provider-<id>`),限定为字母/数字/下划线/短横线。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn ai_provider_save(
|
||||
state: State<'_, AiManager>,
|
||||
config: AiProviderConfig,
|
||||
) -> Result<(), String> {
|
||||
let id = config.id.trim().to_string();
|
||||
if id.is_empty() {
|
||||
return Err("供应商标识不能为空".to_string());
|
||||
}
|
||||
if !id
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
|
||||
{
|
||||
return Err("供应商标识只能包含字母、数字、下划线和短横线".to_string());
|
||||
}
|
||||
if config.name.trim().is_empty() {
|
||||
return Err("供应商名称不能为空".to_string());
|
||||
}
|
||||
|
||||
let mut settings = state.load_settings();
|
||||
let mut next = config;
|
||||
next.id = id;
|
||||
// 输出/上下文夹到合法档位上限(UI 提供档位,后端再兜一道)
|
||||
next.max_tokens = next.max_tokens.clamp(1, 131_072);
|
||||
next.max_context = next.max_context.clamp(1_024, 1_048_576);
|
||||
if next.max_tokens == 0 {
|
||||
next.max_tokens = super::settings::DEFAULT_MAX_OUTPUT;
|
||||
}
|
||||
if next.max_context < 1_024 {
|
||||
next.max_context = super::settings::DEFAULT_MAX_CONTEXT;
|
||||
}
|
||||
match settings.providers.iter_mut().find(|p| p.id == next.id) {
|
||||
Some(slot) => *slot = next,
|
||||
None => settings.providers.push(next),
|
||||
}
|
||||
// 不按优先级排序:优先级是翻译等模块的场景参数,AI 列表保持添加顺序
|
||||
state.save_settings(&settings)
|
||||
}
|
||||
|
||||
/// 删除供应商(连同它在系统凭据管理器中的密钥)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn ai_provider_delete(state: State<'_, AiManager>, id: String) -> Result<(), String> {
|
||||
let mut settings = state.load_settings();
|
||||
let before = settings.providers.len();
|
||||
settings.providers.retain(|p| p.id != id);
|
||||
if settings.providers.len() == before {
|
||||
return Err(format!("找不到供应商「{id}」"));
|
||||
}
|
||||
if settings.default_provider_id == id {
|
||||
settings.default_provider_id = "auto".to_string();
|
||||
}
|
||||
state.save_settings(&settings)?;
|
||||
if let Err(e) = crate::secrets::secret_delete(&super::provider_secret_key(&id)) {
|
||||
crate::logger::log_error("ai", &format!("删除供应商「{id}」的密钥失败: {e}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 写入供应商的 API Key(明文只在此处进入系统凭据管理器,永不回写配置文件)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn ai_secret_set(state: State<'_, AiManager>, id: String, api_key: String) -> Result<(), String> {
|
||||
if state.load_settings().provider(&id).is_none() {
|
||||
return Err(format!("找不到供应商「{id}」"));
|
||||
}
|
||||
let key = super::provider_secret_key(&id);
|
||||
let value = api_key.trim();
|
||||
if value.is_empty() {
|
||||
return crate::secrets::secret_delete(&key);
|
||||
}
|
||||
crate::secrets::secret_write(&key, value)
|
||||
}
|
||||
|
||||
/// 清除供应商的 API Key。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn ai_secret_clear(id: String) -> Result<(), String> {
|
||||
crate::secrets::secret_delete(&super::provider_secret_key(&id))
|
||||
}
|
||||
|
||||
/// 连通性自检:用前端传入的草稿配置测试(**不落盘**)。
|
||||
///
|
||||
/// `api_key` 是可选的「临时密钥」覆盖:设置页允许用户**填好 Key、还没保存**就先检查一次,
|
||||
/// 省掉「先保存再测试」的来回。它只用于这一次请求——不写凭据管理器、不落配置文件,
|
||||
/// 也不会被回传到前端;为空时退回凭据管理器里已保存的密钥。
|
||||
///
|
||||
/// 之所以仍按 `config.id` 取已保存的密钥作为默认值:多数场景(改 Base URL / 换模型后复测)
|
||||
/// 用户并不想重新输入 Key。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn ai_provider_test(
|
||||
state: State<'_, AiManager>,
|
||||
config: AiProviderConfig,
|
||||
api_key: Option<String>,
|
||||
) -> Result<AiTestResult, String> {
|
||||
if config.id.trim().is_empty() || config.name.trim().is_empty() {
|
||||
return Ok(AiTestResult::failure(
|
||||
AiErrorKind::Config,
|
||||
"供应商标识或名称不能为空,请先保存一次".to_string(),
|
||||
0,
|
||||
));
|
||||
}
|
||||
let settings = state.load_settings();
|
||||
let data_dir = state.data_dir().to_path_buf();
|
||||
let started = std::time::Instant::now();
|
||||
let override_key = api_key.as_deref();
|
||||
match super::test_provider(&config, override_key, &settings, &data_dir).await {
|
||||
Ok(message) => Ok(AiTestResult::success(
|
||||
message,
|
||||
started.elapsed().as_millis() as u64,
|
||||
)),
|
||||
Err(e) => Ok(AiTestResult::failure(
|
||||
e.kind,
|
||||
e.message,
|
||||
started.elapsed().as_millis() as u64,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 拉取上游模型列表(按已保存的 id;密钥/地址取自磁盘上的配置与凭据库)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn ai_provider_models(
|
||||
state: State<'_, AiManager>,
|
||||
id: String,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let settings = state.load_settings();
|
||||
let cfg = settings
|
||||
.provider(&id)
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("找不到供应商「{id}」"))?;
|
||||
let data_dir = state.data_dir().to_path_buf();
|
||||
super::list_models(&cfg, &settings, &data_dir).await
|
||||
}
|
||||
|
||||
/// 构造供应商视图并给出「是否可用」的判断。
|
||||
fn to_view(cfg: &AiProviderConfig) -> AiProviderView {
|
||||
let raw_key = super::provider_api_key(&cfg.id);
|
||||
let has_api_key = !raw_key.trim().is_empty();
|
||||
|
||||
let issue = if cfg.base_url.trim().is_empty() {
|
||||
Some("未配置 Base URL".to_string())
|
||||
} else if cfg.model.trim().is_empty() {
|
||||
Some("未选择模型".to_string())
|
||||
} else if !has_api_key {
|
||||
Some("未配置 API Key".to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
AiProviderView {
|
||||
config: cfg.clone(),
|
||||
has_api_key,
|
||||
api_key_masked: crate::secrets::mask(&raw_key),
|
||||
ready: issue.is_none() && cfg.enabled,
|
||||
issue,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! 全局 AI 模块:供应商配置 + OpenAI 兼容客户端。
|
||||
//!
|
||||
//! 架构位置(主应用层,不属于任何业务模块):
|
||||
//!
|
||||
//! ```text
|
||||
//! 主设置 → AI 服务卡片
|
||||
//! ↓ Tauri IPC
|
||||
//! commands.rs 命令层(列表 / CRUD / 密钥 / 测连通 / 拉模型)
|
||||
//! ↓
|
||||
//! AiManager(本文件):设置读写 / 凭据键 / 自愈
|
||||
//! ↓
|
||||
//! chat.rs chat_once / test / list_models(OpenAI 兼容)
|
||||
//! ↓ reqwest
|
||||
//! DeepSeek / OpenAI / Gemini / 通义 / Kimi / 智谱 / Ollama …
|
||||
//! ```
|
||||
//!
|
||||
//! 消费方:
|
||||
//! - **翻译模块**:把已加入翻译候选的供应商转换为 TranslateEngineConfig(kind = "ai"),
|
||||
//! 密钥经 [`provider_api_key`] 读取;翻译专属的提示词模板与优先级仍在 translate 设置。
|
||||
//! - **终端 AI 助手**:直接列本模块的供应商并调用 [`chat::chat_once`]。
|
||||
//!
|
||||
//! **依赖方向:只出不进。** 本模块不引用任何业务模块(translate / terminal …)——
|
||||
//! 它们是消费者,我们是被消费者。连「把历史翻译设置里的 AI 引擎搬过来」这类一次性
|
||||
//! 迁移也不在这里:那段代码必然要同时读懂两边,因此归 translate 侧
|
||||
//! (`translate::migrate_legacy_ai_engines`),由 `setup.rs` 在启动时调用一次。
|
||||
//!
|
||||
//! 安全姿态与 translate 一致:**网络只在 Rust 侧发生**;API Key 只进系统凭据管理器
|
||||
//! (键名 `ai-provider-<id>`),不落 `settings.json`、不经前端明文回传。
|
||||
|
||||
mod chat;
|
||||
mod commands;
|
||||
mod settings;
|
||||
mod test_result;
|
||||
|
||||
pub use chat::{chat_once, list_models, test_provider};
|
||||
pub use commands::{
|
||||
ai_get_settings, ai_list_providers, ai_provider_delete, ai_provider_models,
|
||||
ai_provider_save, ai_provider_test, ai_save_settings, ai_secret_clear, ai_secret_set,
|
||||
};
|
||||
pub use settings::{AiProviderConfig, AiSettings, DEFAULT_CHAT_TIMEOUT_MS, DEFAULT_MAX_CONTEXT};
|
||||
pub use test_result::{AiErrorKind, AiTestResult};
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// 设置内存缓存有效期(与 translate / music 的 500ms 一致)。
|
||||
const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500);
|
||||
|
||||
/// 供应商 API Key 的凭据键前缀。
|
||||
const PROVIDER_KEY_PREFIX: &str = "ai-provider-";
|
||||
|
||||
/// 某供应商实例的凭据键。
|
||||
pub fn provider_secret_key(provider_id: &str) -> String {
|
||||
format!("{PROVIDER_KEY_PREFIX}{provider_id}")
|
||||
}
|
||||
|
||||
/// 读取某供应商的 API Key(未配置或读取失败 → 空串)。
|
||||
///
|
||||
/// 只认 `ai-provider-*`。历史上 AI 引擎曾把密钥存在 translate 的 `translate-engine-*`
|
||||
/// 下,那份由一次性迁移复制过来;这里不做回退读取——回退等于让本模块永久依赖
|
||||
/// translate 的键名约定。迁移复制失败时会记日志,用户在设置页重填即可(界面会显示
|
||||
/// 「未配置 API Key」,不会静默走错端点)。
|
||||
pub fn provider_api_key(provider_id: &str) -> String {
|
||||
if provider_id.trim().is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
crate::secrets::read_or_empty(&provider_secret_key(provider_id))
|
||||
}
|
||||
|
||||
/// 写入 AI 设置文件(`{data_dir}/ai/settings.json`,目录不存在时创建)。
|
||||
///
|
||||
/// 除 `AiManager` 外还单独暴露成自由函数:启动阶段的一次性迁移(由 translate 侧发起)
|
||||
/// 需要在 `AiManager` 尚未注册为 State 时写这份文件。
|
||||
pub fn write_settings(data_dir: &Path, settings: &AiSettings) -> Result<(), String> {
|
||||
let root = data_dir.join("ai");
|
||||
std::fs::create_dir_all(&root).map_err(|e| format!("创建 AI 目录失败: {e}"))?;
|
||||
let json =
|
||||
serde_json::to_string_pretty(settings).map_err(|e| format!("序列化 AI 设置失败: {e}"))?;
|
||||
std::fs::write(root.join("settings.json"), json).map_err(|e| format!("写入 AI 设置失败: {e}"))
|
||||
}
|
||||
|
||||
struct SettingsCache {
|
||||
read_at: Instant,
|
||||
settings: AiSettings,
|
||||
}
|
||||
|
||||
/// 全局 AI 管理器(Tauri State)。
|
||||
pub struct AiManager {
|
||||
/// 应用数据目录(与 translate 同级,代理配置也在这一层)
|
||||
data_dir: PathBuf,
|
||||
/// 模块自身目录:{app_data_dir}/ai
|
||||
root: PathBuf,
|
||||
cache: Mutex<Option<SettingsCache>>,
|
||||
}
|
||||
|
||||
impl AiManager {
|
||||
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||
let root = app_data_dir.join("ai");
|
||||
std::fs::create_dir_all(&root).ok();
|
||||
Self {
|
||||
data_dir: app_data_dir,
|
||||
root,
|
||||
cache: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_path(&self) -> PathBuf {
|
||||
self.root.join("settings.json")
|
||||
}
|
||||
|
||||
/// 应用数据目录(chat 模块解析代理配置用)。
|
||||
pub fn data_dir(&self) -> &Path {
|
||||
&self.data_dir
|
||||
}
|
||||
|
||||
/// 读取设置(带短时缓存;文件缺失时回退默认值;自愈结果落盘)。
|
||||
pub fn load_settings(&self) -> AiSettings {
|
||||
if let Ok(cache) = self.cache.lock() {
|
||||
if let Some(entry) = cache.as_ref() {
|
||||
if entry.read_at.elapsed() < SETTINGS_CACHE_TTL {
|
||||
return entry.settings.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = std::fs::read_to_string(self.settings_path())
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<AiSettings>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
let healed = settings.heal();
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
if healed {
|
||||
if let Err(e) = self.save_settings(&settings) {
|
||||
crate::logger::log_error("ai", &format!("设置自愈落盘失败: {e}"));
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// 保存设置并刷新缓存。
|
||||
pub fn save_settings(&self, settings: &AiSettings) -> Result<(), String> {
|
||||
write_settings(&self.data_dir, settings)?;
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 同步读取 AI 设置(**不经 AiManager 缓存**,供 translate 等在无 State 时使用)。
|
||||
///
|
||||
/// 调用前应保证一次性迁移已跑过(`setup::init` 里在建 State 之前调用
|
||||
/// `translate::migrate_legacy_ai_engines`);文件缺失时回退默认值并自愈,
|
||||
/// 但不写盘——落盘权在 [`write_settings`] 的调用方。
|
||||
pub fn load_settings_sync(data_dir: &Path) -> AiSettings {
|
||||
let path = data_dir.join("ai").join("settings.json");
|
||||
let mut settings = std::fs::read_to_string(path)
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<AiSettings>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
settings.heal();
|
||||
settings
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//! 全局 AI 供应商配置(主应用设置)。
|
||||
//!
|
||||
//! 持久化位置:`{app_data_dir}/ai/settings.json`。
|
||||
//! 容器级 `#[serde(default)]`:新增字段对旧配置文件向后兼容。
|
||||
//!
|
||||
//! 设计边界(对齐主流桌面 Agent 的「模型/连接」设置):
|
||||
//! - **本模块只管引擎本身**:Base URL、模型、密钥、最大输出、最大上下文等
|
||||
//! 与具体调用场景无关的连接与生成参数。
|
||||
//! - **模块自己的参数留在各模块**:翻译的优先级 / 超时 / 提示词覆盖在
|
||||
//! translate 设置里(`TranslateAiParams`),终端等调用方自带超时与 system prompt。
|
||||
//!
|
||||
//! 安全姿态:**API Key 不在这里**。明文一律进系统凭据管理器,
|
||||
//! 键名约定 `ai-provider-<id>`(见 [`super::provider_secret_key`])。
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// 通用对话默认超时(毫秒)。供应商级超时已下沉到翻译等模块。
|
||||
pub const DEFAULT_CHAT_TIMEOUT_MS: u64 = 60_000;
|
||||
|
||||
/// 最大输出(completion tokens)默认值与可选档位(上限 128K)。
|
||||
pub const DEFAULT_MAX_OUTPUT: u32 = 8_192;
|
||||
#[allow(dead_code)] // 档位表与前端 AI_PRESETS / Select 选项保持一致,供后续命令校验复用
|
||||
pub const MAX_OUTPUT_OPTIONS: [u32; 6] = [4_096, 8_192, 16_384, 32_768, 65_536, 131_072];
|
||||
|
||||
/// 最大上下文(context window tokens)默认值与可选档位(上限 1M)。
|
||||
pub const DEFAULT_MAX_CONTEXT: u32 = 131_072;
|
||||
#[allow(dead_code)]
|
||||
pub const MAX_CONTEXT_OPTIONS: [u32; 6] =
|
||||
[32_768, 65_536, 131_072, 262_144, 524_288, 1_048_576];
|
||||
|
||||
/// 单个 AI 供应商实例(OpenAI 兼容端点)。
|
||||
///
|
||||
/// 「实例」而非「类型」:同一厂商可配置多份(官方 API 与本地 Ollama 并存)。
|
||||
/// 翻译、终端助手等模块共用连接与生成参数;场景参数(优先级、超时、提示词)
|
||||
/// 由各模块自行维护。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct AiProviderConfig {
|
||||
/// 实例唯一标识(同时是凭据键的一部分,创建后不建议修改)
|
||||
pub id: String,
|
||||
/// 展示名称
|
||||
pub name: String,
|
||||
/// 预设标识:"deepseek" | "openai" | "gemini" | "qwen" | "kimi" | "zhipu"
|
||||
/// | "doubao" | "mimo" | "mistral" | "groq" | "openrouter" | "siliconflow"
|
||||
/// | "ollama" | "lmstudio" | "custom" …
|
||||
pub preset: String,
|
||||
/// 是否启用(关闭后各模块不再把此供应商当候选)
|
||||
pub enabled: bool,
|
||||
/// API 根地址(末尾可有可无 /,不可含 /chat/completions)
|
||||
pub base_url: String,
|
||||
/// 模型标识
|
||||
pub model: String,
|
||||
/// 采样温度
|
||||
pub temperature: f64,
|
||||
/// 最大输出 tokens(completion 上限,对齐 Agent 常见的「回答长度」)
|
||||
pub max_tokens: u32,
|
||||
/// 最大上下文窗口 tokens(模型可接受的输入+输出规模,供调用方截断与展示)
|
||||
pub max_context: u32,
|
||||
/// 额外请求体字段的 JSON 文本(thinking / enable_thinking 等非标准参数)
|
||||
pub extra_body: Option<String>,
|
||||
/// 是否支持图像输入(多模态能力声明;截图翻译「视觉直传」只发给勾选了此项的供应商)
|
||||
#[serde(default)]
|
||||
pub supports_vision: bool,
|
||||
|
||||
// ===== 旧字段:只读入历史 JSON,迁移后写到 translate.aiParams,不再序列化 =====
|
||||
/// 旧:供应商级优先级(历史键 `priority`)
|
||||
#[serde(default, alias = "priority", skip_serializing)]
|
||||
pub legacy_priority: Option<i32>,
|
||||
/// 旧:供应商级超时(历史键 `timeoutMs`)
|
||||
#[serde(default, alias = "timeoutMs", skip_serializing)]
|
||||
pub legacy_timeout_ms: Option<u64>,
|
||||
/// 旧:翻译 system prompt 覆盖(历史键 `systemPrompt`)
|
||||
#[serde(default, alias = "systemPrompt", skip_serializing)]
|
||||
pub legacy_system_prompt: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for AiProviderConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: String::new(),
|
||||
name: String::new(),
|
||||
preset: "custom".to_string(),
|
||||
enabled: true,
|
||||
base_url: String::new(),
|
||||
model: String::new(),
|
||||
temperature: 0.3,
|
||||
max_tokens: DEFAULT_MAX_OUTPUT,
|
||||
max_context: DEFAULT_MAX_CONTEXT,
|
||||
extra_body: None,
|
||||
supports_vision: false,
|
||||
legacy_priority: None,
|
||||
legacy_timeout_ms: None,
|
||||
legacy_system_prompt: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AiProviderConfig {
|
||||
/// 内置 DeepSeek 预设:默认供应商。模型标识取现行名 `deepseek-flash`
|
||||
/// (`deepseek-chat` / `deepseek-reasoner` 已于 2026-07-24 停用)。
|
||||
///
|
||||
/// 其余预设只在前端 `AI_PRESETS`(`src/types/ai.ts`)维护模板;
|
||||
/// 后端不硬编码供应商清单——预设标识只是个字符串,谁来加都行。
|
||||
pub fn deepseek_default() -> Self {
|
||||
Self {
|
||||
id: "deepseek".to_string(),
|
||||
name: "DeepSeek Flash".to_string(),
|
||||
preset: "deepseek".to_string(),
|
||||
enabled: true,
|
||||
base_url: "https://api.deepseek.com".to_string(),
|
||||
model: "deepseek-flash".to_string(),
|
||||
temperature: 0.3,
|
||||
max_tokens: DEFAULT_MAX_OUTPUT,
|
||||
max_context: DEFAULT_MAX_CONTEXT,
|
||||
extra_body: None,
|
||||
supports_vision: false,
|
||||
legacy_priority: None,
|
||||
legacy_timeout_ms: None,
|
||||
legacy_system_prompt: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 取出旧场景参数(若历史 JSON 带有 priority/timeoutMs/systemPrompt)。
|
||||
pub fn take_legacy(&mut self) -> Option<(i32, u64, String)> {
|
||||
let p = self.legacy_priority.take();
|
||||
let t = self.legacy_timeout_ms.take();
|
||||
let s = self.legacy_system_prompt.take();
|
||||
match (p, t, s) {
|
||||
(None, None, None) => None,
|
||||
(p, t, s) => Some((
|
||||
p.unwrap_or(100),
|
||||
t.unwrap_or(30_000),
|
||||
s.unwrap_or_default(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 全局 AI 设置根结构。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct AiSettings {
|
||||
/// 结构版本号:1 = 含供应商级场景参数;2 = 场景参数下沉到各模块
|
||||
pub version: u32,
|
||||
/// 供应商实例列表
|
||||
pub providers: Vec<AiProviderConfig>,
|
||||
/// 默认供应商 id("auto" 表示不指定;主要给终端等简单消费方)
|
||||
pub default_provider_id: String,
|
||||
/// AI 请求是否走代理模块(mihomo mixed 端口)。
|
||||
/// 默认关闭:DeepSeek 等境内可直连;境外服务由用户显式打开。
|
||||
pub use_proxy: bool,
|
||||
}
|
||||
|
||||
impl Default for AiSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: 2,
|
||||
providers: vec![AiProviderConfig::deepseek_default()],
|
||||
default_provider_id: "deepseek".to_string(),
|
||||
use_proxy: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AiSettings {
|
||||
/// 按 id 找供应商实例。
|
||||
pub fn provider(&self, id: &str) -> Option<&AiProviderConfig> {
|
||||
self.providers.iter().find(|p| p.id == id)
|
||||
}
|
||||
|
||||
/// 自愈:列表为空时补回 DeepSeek;默认 id 失效时回落到「自动」;
|
||||
/// 输出/上下文越界时夹回档位上限;版本推进到 2。
|
||||
/// 返回是否发生了变更(由调用方决定落盘)。
|
||||
pub fn heal(&mut self) -> bool {
|
||||
let mut changed = false;
|
||||
if self.providers.is_empty() {
|
||||
self.providers.push(AiProviderConfig::deepseek_default());
|
||||
changed = true;
|
||||
}
|
||||
for p in &mut self.providers {
|
||||
if p.max_tokens == 0 {
|
||||
p.max_tokens = DEFAULT_MAX_OUTPUT;
|
||||
changed = true;
|
||||
}
|
||||
if p.max_context == 0 {
|
||||
p.max_context = DEFAULT_MAX_CONTEXT;
|
||||
changed = true;
|
||||
}
|
||||
if p.max_tokens > 131_072 {
|
||||
p.max_tokens = 131_072;
|
||||
changed = true;
|
||||
}
|
||||
if p.max_context > 1_048_576 {
|
||||
p.max_context = 1_048_576;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if self.default_provider_id.trim().is_empty() {
|
||||
self.default_provider_id = "auto".to_string();
|
||||
changed = true;
|
||||
}
|
||||
if self.default_provider_id != "auto" && self.provider(&self.default_provider_id).is_none() {
|
||||
self.default_provider_id = "auto".to_string();
|
||||
changed = true;
|
||||
}
|
||||
if self.version < 2 {
|
||||
self.version = 2;
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! 连通性自检结果与错误分类(与翻译模块 EngineTestResult 同形,失败也返回 Ok)。
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
/// AI 请求的错误分类。
|
||||
///
|
||||
/// **本模块自带一份,不复用 `translate::ErrorKind`**:AI 服务是独立的底座,
|
||||
/// 不反向依赖任何业务模块(否则「谁依赖谁」会随功能增长变得无法收敛)。
|
||||
/// 变体名与 translate 的同名枚举刻意保持一致,前端可以共用一套提示文案;
|
||||
/// 只保留 AI 侧**真会产生的**分类(translate 的 unsupported / captcha 是翻译专属语义)。
|
||||
/// 将来若两者要做共享层,再把这个枚举上提合并。
|
||||
#[derive(Debug, Clone, Copy, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AiErrorKind {
|
||||
/// 配置问题:Base URL / 模型名不对
|
||||
Config,
|
||||
/// 认证问题:API Key 无效、无该模型权限、余额不足
|
||||
Auth,
|
||||
/// 上游限流
|
||||
RateLimit,
|
||||
/// 网络不可达 / 上游服务端错误
|
||||
Network,
|
||||
/// 超时
|
||||
Timeout,
|
||||
/// 响应格式异常
|
||||
Parse,
|
||||
/// 上游返回空内容
|
||||
Empty,
|
||||
/// 其它未分类错误
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AiTestResult {
|
||||
pub ok: bool,
|
||||
pub latency_ms: u64,
|
||||
pub message: String,
|
||||
pub error_kind: Option<AiErrorKind>,
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
|
||||
impl AiTestResult {
|
||||
/// 失败结果。`kind` 来自 [`crate::ai::chat::ChatError`]——前端据此给出
|
||||
/// 「改 Key」「查网络」这类不同的下一步提示。
|
||||
pub fn failure(kind: AiErrorKind, message: String, latency_ms: u64) -> Self {
|
||||
Self {
|
||||
ok: false,
|
||||
latency_ms,
|
||||
message,
|
||||
error_kind: Some(kind),
|
||||
detail: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn success(message: String, latency_ms: u64) -> Self {
|
||||
Self {
|
||||
ok: true,
|
||||
latency_ms,
|
||||
message,
|
||||
error_kind: None,
|
||||
detail: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use specta::Type;
|
||||
use tauri::{AppHandle, State};
|
||||
|
||||
use super::manager::{ClipboardManager, ClipboardSettings};
|
||||
use super::reader::dib_to_png;
|
||||
use super::reader::{dib_to_png, dib_to_thumbnail};
|
||||
use super::storage::{ClipboardItem, ClipboardItemDetail};
|
||||
|
||||
#[derive(Serialize, Type)]
|
||||
@@ -95,6 +95,21 @@ pub async fn clipboard_get_item(
|
||||
.map_err(|e| format!("查询任务失败: {}", e))
|
||||
}
|
||||
|
||||
/// 获取图片缩略图 PNG base64(弹窗悬停预览用,避免加载全尺寸图片)
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_get_thumb(
|
||||
id: i64,
|
||||
manager: State<'_, ClipboardManager>,
|
||||
) -> Result<Option<String>, String> {
|
||||
let storage = manager.storage().clone();
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
storage.get_thumb(id, |dib| dib_to_thumbnail(dib, 256))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("查询任务失败: {}", e))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_set_pinned(
|
||||
@@ -162,25 +177,44 @@ pub async fn clipboard_save_settings(
|
||||
app: AppHandle,
|
||||
manager: State<'_, ClipboardManager>,
|
||||
) -> Result<(), String> {
|
||||
let prev_enabled = manager.get_settings().enabled;
|
||||
let prev_shortcut = manager.get_settings().shortcut.clone();
|
||||
let prev = manager.get_settings();
|
||||
let prev_enabled = prev.enabled;
|
||||
let prev_shortcut = prev.shortcut.clone();
|
||||
|
||||
// 快捷键变化且新值非空:先注册(原子化 + 冲突检测),成功后才保存设置。
|
||||
// 注册失败时恢复旧快捷键并中止保存,避免设置被写入无法生效的组合键、旧键丢失。
|
||||
if settings.shortcut != prev_shortcut && !settings.shortcut.trim().is_empty() {
|
||||
if let Err(e) = crate::shortcut::register_shortcut(&app, "剪贴板", &settings.shortcut, |a| {
|
||||
super::popup::show_popup(a)
|
||||
}) {
|
||||
// register_shortcut 内部已注销旧快捷键,失败时需重新注册旧键以恢复
|
||||
if !prev_shortcut.trim().is_empty() {
|
||||
let _ = crate::shortcut::register_shortcut(&app, "剪贴板", &prev_shortcut, |a| {
|
||||
super::popup::show_popup(a)
|
||||
});
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
// 新快捷键非空时确保弹窗/预览窗口已预创建
|
||||
super::popup::ensure_popup_window(&app);
|
||||
super::popup::ensure_preview_window(&app);
|
||||
}
|
||||
|
||||
// 保存设置
|
||||
manager.save_settings(settings.clone());
|
||||
|
||||
// 监听开关变化时联动启停
|
||||
if settings.enabled && !prev_enabled {
|
||||
manager.start(&app);
|
||||
} else if !settings.enabled && prev_enabled {
|
||||
manager.stop();
|
||||
}
|
||||
// 快捷键变化时重新注册(共享工具模块,原子化 + 冲突检测)
|
||||
if settings.shortcut != prev_shortcut {
|
||||
crate::shortcut::register_shortcut(&app, "剪贴板", &settings.shortcut, |a| {
|
||||
super::popup::show_popup(a)
|
||||
})?;
|
||||
// 新快捷键非空时确保弹窗窗口已预创建
|
||||
if !settings.shortcut.trim().is_empty() {
|
||||
super::popup::ensure_popup_window(&app);
|
||||
}
|
||||
|
||||
// 快捷键改为空字符串(禁用):注销旧快捷键
|
||||
if settings.shortcut.trim().is_empty() && settings.shortcut != prev_shortcut {
|
||||
crate::shortcut::unregister_shortcut(&app, "剪贴板");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -262,3 +296,52 @@ pub async fn clipboard_paste_to_target(app: AppHandle) -> Result<(), String> {
|
||||
super::popup::paste_to_target(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 在弹窗旁显示独立预览窗口(悬停/键盘选中时调用)
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_show_preview(app: AppHandle, id: i64) -> Result<(), String> {
|
||||
super::popup::show_preview(&app, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 隐藏独立预览窗口
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_hide_preview(app: AppHandle) -> Result<(), String> {
|
||||
super::popup::hide_preview(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 按内容自适应调整预览窗大小(逻辑像素)。前端加载内容(文本测高、图片按宽高比)后调用,
|
||||
/// 窗口贴合内容消除留白;后端按弹窗所在屏工作区钳制并重新对齐弹窗。
|
||||
/// allow_flip:初始落位为 true(优先侧放不下可换侧);放大/还原为 false(保持原侧)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_resize_preview(
|
||||
app: AppHandle,
|
||||
width: f64,
|
||||
height: f64,
|
||||
allow_flip: bool,
|
||||
) -> Result<(), String> {
|
||||
super::popup::resize_preview(&app, width, height, allow_flip);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 显示已就绪的预览窗口。前端完成内容加载与 resize 后调用,窗口以最终尺寸出现,
|
||||
/// 消除"先以上次尺寸(可能是放大态大窗)显示再缩回"的闪烁。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_reveal_preview(app: AppHandle) -> Result<(), String> {
|
||||
super::popup::reveal_preview(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 预览窗交互锁定:前端预览窗收到 mousedown(放大/缩小、复制、选择文本)时调用。
|
||||
/// 此后弹窗+预览不因失焦/鼠标离开而关闭,仅当点击外部或弹窗重新聚焦时退出锁定。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_preview_interacted(app: AppHandle) -> Result<(), String> {
|
||||
super::popup::preview_interacted(&app);
|
||||
Ok(())
|
||||
}
|
||||
@@ -12,6 +12,8 @@ use specta::Type;
|
||||
use super::monitor::start_monitor;
|
||||
use super::reader::{write_dib, write_files, write_text};
|
||||
use super::storage::Storage;
|
||||
use super::suppress::SuppressState;
|
||||
use windows_sys::Win32::System::DataExchange::GetClipboardSequenceNumber;
|
||||
|
||||
/// 剪贴板设置(持久化到 clipboard/settings.json)
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
@@ -55,7 +57,9 @@ impl Default for ClipboardSettings {
|
||||
pub struct ClipboardManager {
|
||||
storage: Arc<Storage>,
|
||||
settings: Arc<Mutex<ClipboardSettings>>,
|
||||
suppress: Arc<AtomicBool>,
|
||||
/// 写入抑制状态。由本模块持有(谁启动监听谁负责),但**对其他模块开放**:
|
||||
/// 划词取词会连续改三次剪贴板,同样需要屏蔽,见 `super::suppress`。
|
||||
suppress: Arc<SuppressState>,
|
||||
monitor_stop: Arc<AtomicBool>,
|
||||
monitor_handle: Mutex<Option<JoinHandle<()>>>,
|
||||
settings_path: PathBuf,
|
||||
@@ -73,7 +77,7 @@ impl ClipboardManager {
|
||||
};
|
||||
let settings_path = clip_dir.join("settings.json");
|
||||
let settings = Arc::new(Mutex::new(load_settings(&settings_path)));
|
||||
let suppress = Arc::new(AtomicBool::new(false));
|
||||
let suppress = Arc::new(SuppressState::new());
|
||||
let monitor_stop = Arc::new(AtomicBool::new(true));
|
||||
Self {
|
||||
storage,
|
||||
@@ -139,13 +143,12 @@ impl ClipboardManager {
|
||||
save_settings(&self.settings_path, &s);
|
||||
}
|
||||
|
||||
/// 将某条历史写回剪贴板。写回前置 suppress 标志以避免再次记录。
|
||||
/// 将某条历史写回剪贴板。写回成功后记录剪贴板序列号,供监听跳过自身写入。
|
||||
pub fn copy_back(&self, id: i64) -> Result<(), String> {
|
||||
let (kind, content, blob) = self
|
||||
.storage
|
||||
.get_raw_for_copy(id)
|
||||
.ok_or_else(|| "条目不存在".to_string())?;
|
||||
self.suppress.store(true, Ordering::SeqCst);
|
||||
let ok = match kind.as_str() {
|
||||
"text" => content.as_deref().map(write_text).unwrap_or(false),
|
||||
"image" => blob.as_deref().map(write_dib).unwrap_or(false),
|
||||
@@ -163,10 +166,12 @@ impl ClipboardManager {
|
||||
_ => false,
|
||||
};
|
||||
if ok {
|
||||
// 绑定到写入完成后的剪贴板序列号:仅跳过本次写入产生的记录,
|
||||
// 用户后续复制(序列号不同)不会被误吞。
|
||||
let seq = unsafe { GetClipboardSequenceNumber() };
|
||||
self.suppress.mark_seq(seq);
|
||||
Ok(())
|
||||
} else {
|
||||
// 写入失败也清除 suppress,避免误吞下次复制
|
||||
self.suppress.store(false, Ordering::SeqCst);
|
||||
Err("写回剪贴板失败".into())
|
||||
}
|
||||
}
|
||||
@@ -174,6 +179,20 @@ impl ClipboardManager {
|
||||
pub fn storage(&self) -> &Arc<Storage> {
|
||||
&self.storage
|
||||
}
|
||||
|
||||
/// 写入抑制状态(供划词取词等会改剪贴板的其他模块共享)
|
||||
pub fn suppress(&self) -> Arc<SuppressState> {
|
||||
self.suppress.clone()
|
||||
}
|
||||
|
||||
/// 把**当前**剪贴板序列号登记为「应跳过」。
|
||||
///
|
||||
/// 给其他模块写完剪贴板后调用:它们自己拿不到「写入后」的序列号,
|
||||
/// 但知道「刚刚写完」这件事。把 win32 调用留在这个模块里,
|
||||
/// 别处就不必重复引入 DataExchange。
|
||||
pub fn suppress_current_sequence(&self) {
|
||||
self.suppress.mark_seq(unsafe { GetClipboardSequenceNumber() });
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ClipboardManager {
|
||||
|
||||
@@ -6,12 +6,16 @@ pub mod monitor;
|
||||
pub mod popup;
|
||||
pub mod reader;
|
||||
pub mod storage;
|
||||
pub mod suppress;
|
||||
|
||||
pub use commands::{
|
||||
clipboard_clear, clipboard_copy_back, clipboard_count, clipboard_delete, clipboard_get_history,
|
||||
clipboard_get_item, clipboard_get_pinned, clipboard_get_settings, clipboard_hide_popup,
|
||||
clipboard_paste_to_target, clipboard_register_shortcut, clipboard_save_settings, clipboard_search,
|
||||
clipboard_set_pinned, clipboard_show_popup, clipboard_show_window, clipboard_start,
|
||||
clipboard_get_item, clipboard_get_pinned, clipboard_get_settings, clipboard_get_thumb,
|
||||
clipboard_hide_popup, clipboard_hide_preview, clipboard_paste_to_target,
|
||||
clipboard_preview_interacted, clipboard_register_shortcut,
|
||||
clipboard_reveal_preview,
|
||||
clipboard_save_settings, clipboard_search, clipboard_set_pinned, clipboard_resize_preview,
|
||||
clipboard_show_popup, clipboard_show_preview, clipboard_show_window, clipboard_start,
|
||||
clipboard_status, clipboard_stop, clipboard_unregister_shortcut,
|
||||
};
|
||||
pub use manager::ClipboardManager;
|
||||
@@ -1,7 +1,7 @@
|
||||
//! 剪贴板监听线程:基于 GetClipboardSequenceNumber 轮询
|
||||
//!
|
||||
//! 选用轮询而非 AddClipboardFormatListener 消息窗口:实现更简单、无需消息循环,
|
||||
//! 800ms 间隔对剪贴板场景延迟可接受,且 GetClipboardSequenceNumber 不需要 OpenClipboard,开销极小。
|
||||
//! 250ms 间隔兼顾响应速度与开销,且 GetClipboardSequenceNumber 不需要 OpenClipboard,开销极小。
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -12,21 +12,24 @@ use tauri::{AppHandle, Emitter};
|
||||
|
||||
use super::reader::{read_clipboard, ClipData};
|
||||
use super::storage::{NewItem, Storage};
|
||||
use super::suppress::SuppressState;
|
||||
use windows_sys::Win32::System::DataExchange::GetClipboardSequenceNumber;
|
||||
|
||||
/// 启动监听线程,返回 JoinHandle。
|
||||
/// `suppress` 记录本应用写入剪贴板产生的序列号、以及取词等流程的屏蔽窗口,
|
||||
/// 用于跳过自身写入产生的记录。
|
||||
pub fn start_monitor(
|
||||
storage: Arc<Storage>,
|
||||
app: AppHandle,
|
||||
settings: Arc<Mutex<super::manager::ClipboardSettings>>,
|
||||
suppress: Arc<AtomicBool>,
|
||||
suppress: Arc<SuppressState>,
|
||||
stop: Arc<AtomicBool>,
|
||||
) -> thread::JoinHandle<()> {
|
||||
thread::spawn(move || loop {
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(800));
|
||||
thread::sleep(Duration::from_millis(250));
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
@@ -40,9 +43,9 @@ pub fn start_monitor(
|
||||
if seq == last {
|
||||
continue;
|
||||
}
|
||||
// 序列号变化,处理一次
|
||||
if suppress.swap(false, Ordering::SeqCst) {
|
||||
// 由本应用 copy_back 触发,跳过记录
|
||||
// 序列号变化,但可能来自本应用:精确记账(copy_back)或屏蔽窗口内(取词流程)。
|
||||
// 判定放在读剪贴板之前,避免为一次注定要丢弃的变化做无谓的读取与解码。
|
||||
if suppress.should_skip(seq) {
|
||||
continue;
|
||||
}
|
||||
let (rec_text, rec_image, rec_files, max_items, max_image_kb, dedup) = {
|
||||
@@ -99,6 +102,7 @@ fn build_text_item(t: &str) -> NewItem {
|
||||
kind: "text".into(),
|
||||
content: Some(t.to_string()),
|
||||
blob: None,
|
||||
thumb: None,
|
||||
preview: make_preview(t, 200),
|
||||
size: t.len() as i64,
|
||||
hash: hash_str(t),
|
||||
@@ -110,6 +114,7 @@ fn build_image_item(dib: &[u8], w: u32, h: u32) -> NewItem {
|
||||
kind: "image".into(),
|
||||
content: None,
|
||||
blob: Some(dib.to_vec()),
|
||||
thumb: super::reader::dib_to_thumbnail(dib, 256),
|
||||
preview: format!("图片 {}×{}", w, h),
|
||||
size: dib.len() as i64,
|
||||
hash: hash_bytes(dib),
|
||||
@@ -132,6 +137,7 @@ fn build_files_item(files: &[String]) -> NewItem {
|
||||
kind: "files".into(),
|
||||
content: Some(content),
|
||||
blob: None,
|
||||
thumb: None,
|
||||
preview,
|
||||
size: files.iter().map(|f| f.len()).sum::<usize>() as i64,
|
||||
hash,
|
||||
|
||||
@@ -10,12 +10,27 @@
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder, Emitter};
|
||||
use tauri::window::{Effect, EffectsBuilder};
|
||||
|
||||
/// 弹窗窗口标签
|
||||
pub const POPUP_LABEL: &str = "clipboard-popup";
|
||||
|
||||
/// 预览窗口标签(悬停/键盘选中条目时在弹窗旁显示内容)
|
||||
pub const PREVIEW_LABEL: &str = "clipboard-preview";
|
||||
|
||||
/// 预览窗口初始逻辑尺寸(后续由前端按内容自适应调整,见 resize_preview)
|
||||
const PREVIEW_W: f64 = 340.0;
|
||||
const PREVIEW_H: f64 = 300.0;
|
||||
|
||||
/// 预览窗口最小逻辑尺寸(防止内容过小时窗口退化)
|
||||
const PREVIEW_MIN_W: f64 = 240.0;
|
||||
const PREVIEW_MIN_H: f64 = 160.0;
|
||||
|
||||
/// 弹窗与预览窗之间的可视间距(逻辑像素,左右对称)
|
||||
const PREVIEW_GAP: f64 = 12.0;
|
||||
|
||||
/// 标志:show_popup 兜底创建路径设为 true,前端 onMounted 回调 show_window 时据此判断是否显示。
|
||||
/// 预创建路径不设置,避免应用启动时弹窗自动弹出。
|
||||
static POPUP_PENDING_SHOW: AtomicBool = AtomicBool::new(false);
|
||||
@@ -24,6 +39,50 @@ static POPUP_PENDING_SHOW: AtomicBool = AtomicBool::new(false);
|
||||
/// 避免窗口重建后仍停留在屏幕外 (-10000, -10000)。
|
||||
static PENDING_POS: Mutex<Option<(f64, f64)>> = Mutex::new(None);
|
||||
|
||||
/// 弹窗当前是否可见(同步单一事实来源)。
|
||||
/// show_preview 用它代替 popup.is_visible():后者在 hide 异步在途时可能返回过期 true,
|
||||
/// 导致"弹窗已隐藏但残留的悬停/键盘请求重新弹出孤立预览窗"。该标志在隐藏路径
|
||||
/// 同步置 false,任何在途请求都会直接拒绝。
|
||||
static POPUP_VISIBLE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// 预览窗当前是否可见(同步标志,与 POPUP_VISIBLE 同理:预览窗以原生
|
||||
/// SW_SHOWNOACTIVATE 显示,Tauri 的 is_visible() 可能与其真实状态不同步,
|
||||
/// 故用该标志代替 is_visible 判断预览交互状态)。
|
||||
static PREVIEW_VISIBLE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// 弹窗因预览交互(光标位于预览窗内)而推迟隐藏的标记:
|
||||
/// 点击预览窗(选择/复制文本、放大图片)时,弹窗会收到 Focused(false),但用户正在
|
||||
/// 预览窗内交互,此时不应隐藏弹窗。置该标记后保持弹窗显示,待用户离开预览窗
|
||||
/// (hide_preview)时再连同弹窗一起隐藏,避免"点击预览即关闭弹窗"导致无法交互。
|
||||
static POPUP_DEFER_HIDE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// 失焦隐藏的宽限期:WebView2 透明窗口在 show 后激活期间焦点可能短暂弹跳
|
||||
/// (与快速面板同因),导致 Focused(false) 紧跟在 show 之后触发并立即隐藏刚显示的弹窗。
|
||||
const SHOW_GRACE: Duration = Duration::from_millis(500);
|
||||
|
||||
/// 最近一次 show 的时间,用于失焦宽限期判断。
|
||||
static LAST_SHOWN: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
|
||||
/// 标记"已发起显示",并记录时间供失焦宽限期使用。
|
||||
fn mark_shown() {
|
||||
if let Ok(mut t) = LAST_SHOWN.lock() {
|
||||
*t = Some(Instant::now());
|
||||
}
|
||||
POPUP_VISIBLE.store(true, Ordering::SeqCst);
|
||||
// 重新显示弹窗时复位推迟隐藏标记(上一轮预览交互的遗留状态不应影响本轮)
|
||||
POPUP_DEFER_HIDE.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// 判断距上次 show 是否仍在宽限期内(是则忽略失焦自动隐藏)。
|
||||
fn within_show_grace() -> bool {
|
||||
LAST_SHOWN
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|t| *t)
|
||||
.map(|t| t.elapsed() < SHOW_GRACE)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 创建弹窗窗口(隐藏状态)并注册失焦监听。
|
||||
/// 位置默认在屏幕外,show_popup 时会重新定位。
|
||||
/// 预创建后首次按快捷键走"窗口已存在"分支直接 show,避免首次创建的时序问题。
|
||||
@@ -54,14 +113,42 @@ fn create_popup_window(app: &AppHandle) {
|
||||
}
|
||||
};
|
||||
|
||||
// 监听窗口失焦:自动隐藏
|
||||
// 监听窗口失焦:自动隐藏(同时隐藏预览窗)
|
||||
let app_handle = app.clone();
|
||||
let win_handle = win.clone();
|
||||
win.on_window_event(move |event| {
|
||||
if let tauri::WindowEvent::Focused(false) = event {
|
||||
match event {
|
||||
tauri::WindowEvent::Focused(false) => {
|
||||
// 失焦宽限期:show 后激活期间的焦点弹跳不隐藏弹窗,避免弹窗刚显示就被隐藏
|
||||
if within_show_grace() {
|
||||
return;
|
||||
}
|
||||
// 交互锁定模式(点击过预览窗):弹窗与预览保持显示,仅由看护线程在
|
||||
// "点击外部"时关闭;此处的失焦是点击预览窗(NoActivate)所致,不隐藏。
|
||||
if POPUP_INTERACTED.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
// 鼠标当前位于预览窗或弹窗内(用户正在交互:选择/复制文本、放大图片、或
|
||||
// 已移回弹窗准备继续浏览):弹窗失焦是点击预览窗或焦点反弹所致,不应隐藏弹窗。
|
||||
// 置推迟标记保持弹窗显示,待用户离开整个区域(hide_preview / 再次失焦)再隐藏。
|
||||
if is_cursor_in_preview(&app_handle) || is_cursor_in_popup(&app_handle) {
|
||||
POPUP_DEFER_HIDE.store(true, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
// 先同步标记弹窗不可见,再隐藏窗口/预览:异步 hide 在途时,残留的
|
||||
// show_preview 请求会因该标志为 false 而拒绝,预览窗不会孤立残留。
|
||||
POPUP_VISIBLE.store(false, Ordering::SeqCst);
|
||||
POPUP_DEFER_HIDE.store(false, Ordering::SeqCst);
|
||||
let _ = win_handle.hide();
|
||||
hide_preview(&app_handle);
|
||||
let _ = app_handle.emit(crate::constants::events::CLIPBOARD_POPUP_HIDE, ());
|
||||
}
|
||||
tauri::WindowEvent::Focused(true) => {
|
||||
// 弹窗重新获得焦点(用户点击/移回弹窗):取消推迟隐藏状态
|
||||
POPUP_DEFER_HIDE.store(false, Ordering::SeqCst);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
|
||||
crate::logger::log_info("clipboard", "弹窗窗口已预创建(隐藏状态)");
|
||||
@@ -76,6 +163,30 @@ pub fn ensure_popup_window(app: &AppHandle) {
|
||||
create_popup_window(app);
|
||||
}
|
||||
|
||||
/// 把已显示的弹窗强制置前。
|
||||
///
|
||||
/// 只调 `set_focus` 不够:它内部是 `SetForegroundWindow`,受 Windows **前台锁定**限制 ——
|
||||
/// 从别的应用按 Alt+V(本进程不拥有前台)时会被静默忽略,弹窗「出来了但拿不到焦点」,
|
||||
/// 键盘导航 / 搜索都用不了。这里改用原生强制置前(模拟 Alt 释放重置前台锁定 +
|
||||
/// SetForegroundWindow + BringWindowToTop),与快速面板 / 托盘 / 下载窗口同一套做法。
|
||||
///
|
||||
/// 调用前窗口应已 `show()`。置前失败(拿不到 hwnd)时退回普通 `set_focus`。
|
||||
fn focus_force(win: &tauri::WebviewWindow) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
match win.hwnd() {
|
||||
Ok(hwnd) => crate::win32_util::force_foreground(hwnd.0 as isize),
|
||||
Err(_) => {
|
||||
let _ = win.set_focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = win.set_focus();
|
||||
}
|
||||
}
|
||||
|
||||
/// 在鼠标当前位置显示弹窗。
|
||||
/// 窗口不存在则创建(隐藏状态,等前端挂载后调用 show_window 显示)。
|
||||
/// 窗口已存在则移动到鼠标位置并显示。
|
||||
@@ -112,7 +223,8 @@ pub fn show_popup(app: &AppHandle) {
|
||||
y: y as i32,
|
||||
}));
|
||||
let _ = win.show();
|
||||
let _ = win.set_focus();
|
||||
mark_shown();
|
||||
focus_force(&win);
|
||||
// 通知前端刷新数据
|
||||
let _ = app.emit(crate::constants::events::CLIPBOARD_POPUP_SHOW, ());
|
||||
return;
|
||||
@@ -143,17 +255,27 @@ pub fn show_window(app: &AppHandle) {
|
||||
}));
|
||||
}
|
||||
let _ = win.show();
|
||||
let _ = win.set_focus();
|
||||
mark_shown();
|
||||
focus_force(&win);
|
||||
// 通知前端刷新数据
|
||||
let _ = app.emit(crate::constants::events::CLIPBOARD_POPUP_SHOW, ());
|
||||
}
|
||||
}
|
||||
|
||||
/// 隐藏弹窗(不销毁,保留复用)
|
||||
/// 隐藏弹窗(不销毁,保留复用),并通知前端清理悬停定时器/预览。
|
||||
pub fn hide_popup(app: &AppHandle) {
|
||||
// 复位推迟隐藏标记(先于 hide_preview,避免 hide_preview 重入 hide_popup 形成递归)
|
||||
POPUP_DEFER_HIDE.store(false, Ordering::SeqCst);
|
||||
// 复位交互锁定:弹窗关闭后下次呼出恢复"失焦即隐藏"的常规模式
|
||||
POPUP_INTERACTED.store(false, Ordering::SeqCst);
|
||||
// 同步标记弹窗不可见,拒绝此后在途的 show_preview 请求
|
||||
POPUP_VISIBLE.store(false, Ordering::SeqCst);
|
||||
hide_preview(app);
|
||||
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
||||
let _ = win.hide();
|
||||
}
|
||||
// 通知前端:取消悬停定时器并隐藏预览,避免弹窗隐藏后残留定时器重新弹出预览窗
|
||||
let _ = app.emit(crate::constants::events::CLIPBOARD_POPUP_HIDE, ());
|
||||
}
|
||||
|
||||
/// 隐藏弹窗后延迟模拟 Ctrl+V 粘贴到之前聚焦的窗口。
|
||||
@@ -207,6 +329,465 @@ fn simulate_paste() {
|
||||
// 非 Windows 平台暂不支持自动粘贴
|
||||
}
|
||||
|
||||
// ===== 独立预览窗口 =====
|
||||
|
||||
/// 创建预览窗口(隐藏状态),应用 NoActivate 样式避免抢焦点。
|
||||
fn create_preview_window(app: &AppHandle) {
|
||||
let win = match WebviewWindowBuilder::new(
|
||||
app,
|
||||
PREVIEW_LABEL,
|
||||
WebviewUrl::App("index.html#clipboard-preview".into()),
|
||||
)
|
||||
.title("预览")
|
||||
.inner_size(PREVIEW_W, PREVIEW_H)
|
||||
.position(-10000.0, -10000.0) // 屏幕外,避免隐藏时一闪
|
||||
.decorations(false)
|
||||
.transparent(true)
|
||||
.shadow(true)
|
||||
.always_on_top(true)
|
||||
.skip_taskbar(true)
|
||||
.resizable(false)
|
||||
.visible(false)
|
||||
.focused(false) // 不抢占焦点
|
||||
.effects(EffectsBuilder::new().effects(vec![Effect::Mica]).build())
|
||||
.build()
|
||||
{
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
crate::logger::log_error("clipboard", &format!("创建预览窗失败: {}", e));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// NoActivate:预览窗可交互但不激活,弹窗保持前台(键盘导航/粘贴不受影响)
|
||||
// 圆角:NoActivate 悬浮窗系统不自动圆角,显式指定 DWMWCP_ROUND 与弹窗外观统一
|
||||
#[cfg(windows)]
|
||||
if let Ok(hwnd) = win.hwnd() {
|
||||
crate::win32_util::apply_no_activate(hwnd.0 as isize);
|
||||
crate::win32_util::apply_rounded_corners(hwnd.0 as isize);
|
||||
}
|
||||
|
||||
crate::logger::log_info("clipboard", "预览窗口已预创建(隐藏状态)");
|
||||
}
|
||||
|
||||
/// 应用启动时预创建预览窗口(隐藏),随弹窗一起就绪。
|
||||
pub fn ensure_preview_window(app: &AppHandle) {
|
||||
if app.get_webview_window(PREVIEW_LABEL).is_some() {
|
||||
return;
|
||||
}
|
||||
create_preview_window(app);
|
||||
}
|
||||
|
||||
/// 预览当前所在侧(default=右,left=左),供放大/还原重定位沿用同侧。
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum PreviewSide {
|
||||
Right,
|
||||
Left,
|
||||
}
|
||||
|
||||
static PREVIEW_SIDE: Mutex<Option<PreviewSide>> = Mutex::new(None);
|
||||
|
||||
/// 最近一次显示预览时的鼠标 Y 锚点(物理像素)。预览窗垂直中线对齐该位置
|
||||
/// (贴近鼠标所悬停的条目),resize(切换条目/放大还原)时沿用,保持中线稳定不跳变。
|
||||
static PREVIEW_ANCHOR_Y: Mutex<Option<i32>> = Mutex::new(None);
|
||||
|
||||
/// 弹窗离开看护线程是否已在运行(防重入,见 spawn_popup_leave_watch)。
|
||||
static POPUP_LEAVE_WATCH: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// 交互锁定模式:用户点击过预览窗(放大/缩小、复制文本等)后置位。
|
||||
/// 该模式下弹窗与预览不因失焦/鼠标离开而关闭,仅当点击弹窗+预览之外的
|
||||
/// 区域(看护线程检测鼠标按下沿)或弹窗重新聚焦(恢复正常模式)时才复位。
|
||||
static POPUP_INTERACTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// 重新定位预览窗口(物理像素)。preferred 指定优先放置侧,返回实际落位侧。
|
||||
/// anchor_y 为鼠标 Y 锚点:预览窗垂直中线对齐该位置(贴近悬停条目),
|
||||
/// 上下 clamp 到工作区;None 时退回弹窗顶部对齐。
|
||||
///
|
||||
/// 无边框+阴影窗口(tao 实现)的外框矩形在客户区四周各留一条不可见边框
|
||||
/// (SM_CXSIZEFRAME+SM_CXPADDEDBORDER,典型 8px):outer_position/outer_size 均含该边框,
|
||||
/// 而可视内容仅占客户区。若直接用外框尺寸计算右侧落位,右侧可视间距会比左侧多出
|
||||
/// 两侧边框之和(约 16px)。这里以"可视边缘"对齐:frame = (外框宽 - 客户区宽) / 2,
|
||||
/// 左右两侧使用同一 GAP,保证两侧可视间距一致。
|
||||
fn reposition_preview(
|
||||
popup: &tauri::WebviewWindow,
|
||||
win: &tauri::WebviewWindow,
|
||||
vw: i32,
|
||||
vh: i32,
|
||||
preferred: PreviewSide,
|
||||
anchor_y: Option<i32>,
|
||||
allow_flip: bool,
|
||||
) -> PreviewSide {
|
||||
// 弹窗当前物理位置与尺寸(外框,含不可见边框)
|
||||
let Ok(pos) = popup.outer_position() else { return preferred };
|
||||
let Ok(osz) = popup.outer_size() else { return preferred };
|
||||
let Ok(isz) = popup.inner_size() else { return preferred };
|
||||
let (px, py) = (pos.x, pos.y);
|
||||
let pw = osz.width as i32;
|
||||
// 不可见边框宽度(外框与客户区之差的一半;无阴影窗口为 0)
|
||||
let frame = ((osz.width.saturating_sub(isz.width)) / 2) as i32;
|
||||
|
||||
// 弹窗所在显示器工作区
|
||||
let (wa_left, wa_top, wa_right, wa_bottom) = get_work_area_at_point(px, py)
|
||||
.unwrap_or((0, 0, 1920, 1040));
|
||||
|
||||
let gap = (PREVIEW_GAP * popup.scale_factor().unwrap_or(1.0)).round() as i32;
|
||||
|
||||
// 可视边缘对齐:
|
||||
// 右侧落位 = 弹窗可视右缘(px+pw-frame) + GAP - 预览窗自身左边框(frame)
|
||||
// 左侧落位 = 弹窗可视左缘(px+frame) - GAP - 预览可视宽(vw) - 预览窗左边框(frame)
|
||||
// (frame 两两抵消,与旧公式一致)
|
||||
let right_x = px + pw - 2 * frame + gap;
|
||||
let left_x = px - gap - vw;
|
||||
// 可视区域(含预览窗自身边框偏移)不越工作区
|
||||
let fits_right = right_x + frame + vw <= wa_right;
|
||||
let fits_left = left_x + frame >= wa_left;
|
||||
let mut x = match preferred {
|
||||
PreviewSide::Right => right_x,
|
||||
PreviewSide::Left => left_x,
|
||||
};
|
||||
// 仅初始落位(allow_flip=true)允许换侧:优先侧放不下时切到另一侧。
|
||||
// 内容尺寸变化(放大/还原,allow_flip=false)不允许换侧:窗口跳到另一侧会使
|
||||
// 鼠标瞬间落在窗外,误触发 mouseleave 而关闭预览/弹窗;此时保持原侧并靠
|
||||
// 工作区 clamp(大图可能覆盖弹窗边缘,属合理取舍,鼠标仍在预览窗内可交互)。
|
||||
if allow_flip {
|
||||
match preferred {
|
||||
PreviewSide::Right => {
|
||||
if !fits_right {
|
||||
x = left_x;
|
||||
}
|
||||
}
|
||||
PreviewSide::Left => {
|
||||
if !fits_left {
|
||||
x = right_x;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
x = (x + frame).max(wa_left).min(wa_right - vw) - frame;
|
||||
// 仅初始落位(allow_flip)按最终位置更新所在侧(换侧时位置在弹窗另一侧,判定正确);
|
||||
// 放大/还原(不允许换侧)时即使被工作区 clamp 覆盖到弹窗上方,语义上仍属原侧,
|
||||
// 必须沿用 preferred——否则 clamp 后按位置误判为另一侧并存档,缩小后会跳侧。
|
||||
let side = if allow_flip {
|
||||
if x + vw <= px { PreviewSide::Left } else { PreviewSide::Right }
|
||||
} else {
|
||||
preferred
|
||||
};
|
||||
// 垂直定位:预览窗中线对齐鼠标 Y 锚点(贴近悬停条目),上下 clamp 到工作区;
|
||||
// 无锚点时退回弹窗顶部对齐
|
||||
let y = match anchor_y {
|
||||
Some(ay) => (ay - vh / 2).max(wa_top).min(wa_bottom - vh),
|
||||
None => py.max(wa_top).min(wa_bottom - vh),
|
||||
};
|
||||
|
||||
let _ = win.set_position(tauri::Position::Physical(tauri::PhysicalPosition { x, y }));
|
||||
if let Ok(mut s) = PREVIEW_SIDE.lock() {
|
||||
*s = Some(side);
|
||||
}
|
||||
side
|
||||
}
|
||||
|
||||
/// 通知预览前端加载指定条目。窗口此时保持隐藏:前端测得内容尺寸后先调用
|
||||
/// resize_preview(隐藏状态下完成尺寸/位置调整)再 reveal_preview 显示,
|
||||
/// 避免"先以上次尺寸(可能是放大态大窗)显示再缩回"的闪烁。
|
||||
pub fn show_preview(app: &AppHandle, id: i64) {
|
||||
// 弹窗已隐藏(或隐藏中)时拒绝显示预览:同步标志消除 is_visible() 的异步时序竞态,
|
||||
// 保证"弹窗失焦消失后预览窗不会孤立残留"。
|
||||
if !POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
if app.get_webview_window(PREVIEW_LABEL).is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(popup) = app.get_webview_window(POPUP_LABEL) else {
|
||||
return;
|
||||
};
|
||||
// 弹窗不可见时不显示预览:避免弹窗隐藏后仍在途的悬停请求重新弹出孤立的预览窗
|
||||
if !popup.is_visible().unwrap_or(false) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 记录鼠标 Y 锚点:预览窗中线对齐鼠标所悬停的条目位置;resize 时沿用
|
||||
if let Some((_, y)) = get_cursor_pos() {
|
||||
if let Ok(mut a) = PREVIEW_ANCHOR_Y.lock() {
|
||||
*a = Some(y);
|
||||
}
|
||||
}
|
||||
|
||||
// 通知前端加载条目内容(前端完成后自行 resize + reveal)
|
||||
let _ = app.emit(crate::constants::events::CLIPBOARD_PREVIEW_SHOW, id);
|
||||
}
|
||||
|
||||
/// 显示已就绪的预览窗口(前端完成内容加载与 resize 后调用)。
|
||||
/// 显示前重查弹窗可见性,消除内容加载期间弹窗已隐藏的竞态。
|
||||
pub fn reveal_preview(app: &AppHandle) {
|
||||
// 弹窗已隐藏:在途请求作废
|
||||
if !POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
// 已可见则跳过(放大/还原触发的重复 reveal)
|
||||
if PREVIEW_VISIBLE.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let Some(win) = app.get_webview_window(PREVIEW_LABEL) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// 同步标记预览窗可见(以原生方式显示,Tauri 的 is_visible 可能不同步)
|
||||
PREVIEW_VISIBLE.store(true, Ordering::SeqCst);
|
||||
// 不激活显示(SW_SHOWNOACTIVATE),弹窗保持前台
|
||||
#[cfg(windows)]
|
||||
if let Ok(hwnd) = win.hwnd() {
|
||||
crate::win32_util::show_no_activate(hwnd.0 as isize);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = win.show();
|
||||
|
||||
// 显示期间弹窗可能已被隐藏(失焦/关闭):立即收回预览。
|
||||
// 关闭初次检查与真正 show 之间的竞态——失焦处理器先置 POPUP_VISIBLE=false
|
||||
// 再隐藏,这里 show 之后重查一次,若已被隐藏则收回预览,避免孤立残留。
|
||||
if !POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||
PREVIEW_VISIBLE.store(false, Ordering::SeqCst);
|
||||
let _ = win.hide();
|
||||
}
|
||||
}
|
||||
|
||||
/// 按内容自适应调整预览窗大小(逻辑像素),位置沿用当前所在侧并重新对齐弹窗。
|
||||
/// 前端加载/切换内容(文本测高、图片按宽高比)后调用,窗口贴合内容消除留白。
|
||||
/// allow_flip:初始落位为 true(优先侧放不下可换侧);放大/还原为 false
|
||||
/// (保持原侧靠工作区 clamp,避免窗口跳侧使鼠标落在窗外误触发隐藏)。
|
||||
pub fn resize_preview(app: &AppHandle, width: f64, height: f64, allow_flip: bool) {
|
||||
// 弹窗不可见时忽略(无对齐基准)
|
||||
if !POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let Some(win) = app.get_webview_window(PREVIEW_LABEL) else {
|
||||
return;
|
||||
};
|
||||
let Some(popup) = app.get_webview_window(POPUP_LABEL) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let scale = popup.scale_factor().unwrap_or(1.0);
|
||||
// 以弹窗所在屏工作区为上限钳制(逻辑像素),并保证不小于最小可视尺寸
|
||||
let (wa_left, wa_top, wa_right, wa_bottom) = popup
|
||||
.outer_position()
|
||||
.ok()
|
||||
.and_then(|p| get_work_area_at_point(p.x, p.y))
|
||||
.unwrap_or((0, 0, 1920, 1040));
|
||||
let max_w = ((wa_right - wa_left).max(0) as f64 / scale).floor().max(PREVIEW_MIN_W);
|
||||
let max_h = ((wa_bottom - wa_top).max(0) as f64 / scale).floor().max(PREVIEW_MIN_H);
|
||||
let w = width.clamp(PREVIEW_MIN_W, max_w);
|
||||
let h = height.clamp(PREVIEW_MIN_H, max_h);
|
||||
let vw = (w * scale).round() as i32;
|
||||
let vh = (h * scale).round() as i32;
|
||||
|
||||
let side = PREVIEW_SIDE.lock().ok().and_then(|s| *s).unwrap_or(PreviewSide::Right);
|
||||
// 沿用最近一次的鼠标 Y 锚点:高度变化时中线保持对齐悬停条目,不产生跳变
|
||||
let anchor_y = PREVIEW_ANCHOR_Y.lock().ok().and_then(|a| *a);
|
||||
reposition_preview(&popup, &win, vw, vh, side, anchor_y, allow_flip);
|
||||
let _ = win.set_size(tauri::Size::Physical(tauri::PhysicalSize { width: vw as u32, height: vh as u32 }));
|
||||
}
|
||||
|
||||
/// 交互锁定模式入口:前端预览窗收到 mousedown(放大/缩小、复制、选择文本)时调用。
|
||||
/// 置位锁定标志并启动看护线程:此后弹窗+预览不因失焦/鼠标离开而关闭,
|
||||
/// 仅当点击弹窗+预览之外的区域或弹窗重新聚焦时退出锁定。
|
||||
pub fn preview_interacted(app: &AppHandle) {
|
||||
POPUP_INTERACTED.store(true, Ordering::SeqCst);
|
||||
// 交互锁定取代推迟隐藏模式:清除可能残留的 DEFER 标记,
|
||||
// 避免后续取消钉住时 hide_preview 走 DEFER 分支误关弹窗
|
||||
POPUP_DEFER_HIDE.store(false, Ordering::SeqCst);
|
||||
spawn_popup_leave_watch(app.clone());
|
||||
}
|
||||
|
||||
/// 隐藏预览窗口(保留复用),并通知前端清空内容。
|
||||
pub fn hide_preview(app: &AppHandle) {
|
||||
// 交互锁定模式:弹窗仍显示时预览保持(生命周期由看护线程管理,点击外部才
|
||||
// 随弹窗一起关闭),忽略常规隐藏请求(条目离开、键盘切换等)。
|
||||
if POPUP_INTERACTED.load(Ordering::SeqCst) && POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
POPUP_INTERACTED.store(false, Ordering::SeqCst);
|
||||
// 若此前因预览交互推迟了弹窗隐藏(弹窗已失焦但保持显示),现在用户离开预览窗,
|
||||
// 需判断去向:光标已回到弹窗内(继续浏览弹窗)→ 仅隐藏预览、保持弹窗显示;
|
||||
// 光标在弹窗之外(离开整个区域)→ 连同弹窗一起隐藏。
|
||||
// (hide_popup 会先复位该标记,故此处 swap(false) 后调用不会递归重入)
|
||||
if POPUP_DEFER_HIDE.swap(false, Ordering::SeqCst) {
|
||||
if !is_cursor_in_popup(app) {
|
||||
hide_popup(app);
|
||||
return;
|
||||
}
|
||||
// 光标已回到弹窗内。若弹窗仍持有焦点(曾点击弹窗重新激活),仅隐藏预览即可,
|
||||
// 后续失焦仍走 Focused(false) 正常关闭;若弹窗已失焦(点击预览窗所致),
|
||||
// 它不会再收到 Focused(false) 事件——光标一旦离开弹窗区域,弹窗将永远
|
||||
// 无法关闭(无焦点残留窗口)。启动看护线程兜底关闭。
|
||||
let focused = app
|
||||
.get_webview_window(POPUP_LABEL)
|
||||
.map(|w| w.is_focused().unwrap_or(false))
|
||||
.unwrap_or(false);
|
||||
if !focused {
|
||||
spawn_popup_leave_watch(app.clone());
|
||||
}
|
||||
}
|
||||
PREVIEW_VISIBLE.store(false, Ordering::SeqCst);
|
||||
if let Some(win) = app.get_webview_window(PREVIEW_LABEL) {
|
||||
let _ = win.hide();
|
||||
// 预览窗以原生 SW_SHOWNOACTIVATE 方式显示,Tauri 内部可见性状态可能与其
|
||||
// 不同步;补一次原生 SW_HIDE,确保任何路径下都被可靠隐藏。
|
||||
#[cfg(windows)]
|
||||
if let Ok(hwnd) = win.hwnd() {
|
||||
crate::win32_util::hide_window(hwnd.0 as isize);
|
||||
}
|
||||
}
|
||||
let _ = app.emit(crate::constants::events::CLIPBOARD_PREVIEW_HIDE, ());
|
||||
}
|
||||
|
||||
/// 弹窗失焦但保持显示时的看护线程(防重入单例)。
|
||||
///
|
||||
/// 两种工作模式(每轮动态读取 POPUP_INTERACTED,可中途切换):
|
||||
/// - 常规模式(未点击过预览窗):光标连续 ~300ms 既不在弹窗也不在预览窗内
|
||||
/// (连续计数防"穿越弹窗-预览间隙"时的瞬时离开误判)→ 关闭弹窗;
|
||||
/// - 交互锁定模式(点击过预览窗的放大/缩小/复制等):弹窗已失焦不会再收到
|
||||
/// Focused(false),检测"鼠标按下沿且按下位置在弹窗+预览之外"→ 点击外部,关闭弹窗。
|
||||
///
|
||||
/// 退出条件:弹窗已隐藏/销毁(其他路径关闭);弹窗重新获得焦点(用户点击
|
||||
/// 弹窗,恢复正常失焦关闭路径,并复位交互锁定);**光标回到弹窗内并停留片刻
|
||||
/// (交互锁定解除,但看护继续以常规模式运行)**;超时兜底防线程泄漏
|
||||
/// (常规 30s;交互锁定为事件驱动,放宽至 10min)。
|
||||
fn spawn_popup_leave_watch(app: AppHandle) {
|
||||
// 防重入:已有看护在运行则跳过
|
||||
if POPUP_LEAVE_WATCH.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
std::thread::spawn(move || {
|
||||
// 超时兜底的起点:交互锁定解除时重置(那之后按常规模式的 30s 计)
|
||||
let mut start = Instant::now();
|
||||
let mut outside = 0u32;
|
||||
let mut was_down = false;
|
||||
// 交互锁定期间光标停在弹窗内的连续轮数(30ms/轮)
|
||||
let mut back_in_popup = 0u32;
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
// 弹窗已隐藏或被销毁:看护结束
|
||||
if !POPUP_VISIBLE.load(Ordering::SeqCst)
|
||||
|| app.get_webview_window(POPUP_LABEL).is_none()
|
||||
{
|
||||
break;
|
||||
}
|
||||
// 弹窗重新获得焦点(用户点击弹窗):恢复正常失焦关闭路径,复位交互锁定
|
||||
if app
|
||||
.get_webview_window(POPUP_LABEL)
|
||||
.map(|w| w.is_focused().unwrap_or(false))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
POPUP_INTERACTED.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
// 交互锁定期间光标已回到弹窗内:用户离开预览窗、回到列表继续浏览 ——
|
||||
// 解除锁定,让前端的悬停逻辑重新生效(否则 hide_preview 在锁定期间一律
|
||||
// 被忽略,表现为「鼠标回到弹窗、悬停在不需要预览的条目上,预览窗不关」)。
|
||||
//
|
||||
// 这里**只解除锁定、不 break**:弹窗此刻没有焦点,不会再收到 Focused(false),
|
||||
// 若连看护也退出,它就成了无人负责关闭的残留窗口。继续跑常规模式,
|
||||
// 光标离开弹窗+预览区域约 300ms 后照常关闭。
|
||||
// 连续计数(~210ms)用来排除「弹窗-预览之间的间隙」造成的瞬时误判。
|
||||
if POPUP_INTERACTED.load(Ordering::SeqCst) {
|
||||
if is_cursor_in_popup(&app) {
|
||||
back_in_popup += 1;
|
||||
if back_in_popup >= 7 {
|
||||
POPUP_INTERACTED.store(false, Ordering::SeqCst);
|
||||
back_in_popup = 0;
|
||||
// 兜底超时从「解除锁定」这一刻重新计时
|
||||
start = Instant::now();
|
||||
// 顺势收起预览:用户回到弹窗意味着意图已从「看预览」变回
|
||||
// 「浏览列表」。前端在悬停时发出的那次 hide_preview 落在锁定
|
||||
// 期间、已被忽略,这里补上(否则预览会一直挂到下次悬停)。
|
||||
hide_preview(&app);
|
||||
}
|
||||
} else {
|
||||
back_in_popup = 0;
|
||||
}
|
||||
} else {
|
||||
back_in_popup = 0;
|
||||
}
|
||||
let interacted = POPUP_INTERACTED.load(Ordering::SeqCst);
|
||||
// 超长兜底:避免异常路径下看护线程无限轮询
|
||||
let timeout = if interacted {
|
||||
Duration::from_secs(600)
|
||||
} else {
|
||||
Duration::from_secs(30)
|
||||
};
|
||||
if start.elapsed() > timeout {
|
||||
hide_popup(&app);
|
||||
break;
|
||||
}
|
||||
let cursor_in = is_cursor_in_popup(&app) || is_cursor_in_preview(&app);
|
||||
if interacted {
|
||||
// 交互锁定:左键按下沿发生在弹窗+预览之外 → 点击外部,关闭弹窗+预览。
|
||||
// 按下沿判定(上一轮未按下、本轮按下)配合 30ms 轮询,可捕获常规点击;
|
||||
// 在弹窗/预览内按下后拖出再松开不算外部点击(以按下位置为准)。
|
||||
let down = crate::win32_util::is_left_button_down();
|
||||
if down && !was_down && !cursor_in {
|
||||
hide_popup(&app);
|
||||
break;
|
||||
}
|
||||
was_down = down;
|
||||
} else if cursor_in {
|
||||
outside = 0;
|
||||
} else {
|
||||
outside += 1;
|
||||
// 连续 ~300ms 不在弹窗/预览区域(排除穿越间隙的瞬时状态)才关闭
|
||||
if outside >= 10 {
|
||||
hide_popup(&app);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
POPUP_LEAVE_WATCH.store(false, Ordering::SeqCst);
|
||||
});
|
||||
}
|
||||
|
||||
/// 鼠标当前是否位于弹窗矩形内(弹窗可见且光标在其窗口范围内)。
|
||||
/// 用于 hide_preview 判断"用户是回到弹窗继续浏览,还是离开整个区域"。
|
||||
fn is_cursor_in_popup(app: &AppHandle) -> bool {
|
||||
if !POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||
return false;
|
||||
}
|
||||
let Some(win) = app.get_webview_window(POPUP_LABEL) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(pos) = win.outer_position() else { return false };
|
||||
let Ok(size) = win.outer_size() else { return false };
|
||||
let Some((cx, cy)) = crate::win32_util::get_cursor_pos() else {
|
||||
return false;
|
||||
};
|
||||
let x = pos.x;
|
||||
let y = pos.y;
|
||||
let w = size.width as i32;
|
||||
let h = size.height as i32;
|
||||
cx >= x && cx <= x + w && cy >= y && cy <= y + h
|
||||
}
|
||||
|
||||
/// 鼠标当前是否位于预览窗矩形内(预览窗可见且光标在其窗口范围内)。
|
||||
/// 用于弹窗失焦时判断是否因预览交互所致,决定是否推迟隐藏弹窗。
|
||||
fn is_cursor_in_preview(app: &AppHandle) -> bool {
|
||||
if !PREVIEW_VISIBLE.load(Ordering::SeqCst) {
|
||||
return false;
|
||||
}
|
||||
let Some(win) = app.get_webview_window(PREVIEW_LABEL) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(pos) = win.outer_position() else { return false };
|
||||
let Ok(size) = win.outer_size() else { return false };
|
||||
let Some((cx, cy)) = crate::win32_util::get_cursor_pos() else {
|
||||
return false;
|
||||
};
|
||||
let x = pos.x;
|
||||
let y = pos.y;
|
||||
let w = size.width as i32;
|
||||
let h = size.height as i32;
|
||||
cx >= x && cx <= x + w && cy >= y && cy <= y + h
|
||||
}
|
||||
|
||||
// ===== 屏幕/光标/DPI 工具已迁移至 crate::win32_util(跨模块共享) =====
|
||||
|
||||
use crate::win32_util::{get_cursor_pos, get_work_area_at_point, get_dpi_for_point};
|
||||
@@ -295,3 +295,29 @@ pub fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
|
||||
.ok()?;
|
||||
Some(buf)
|
||||
}
|
||||
|
||||
/// 生成缩略图 PNG(最长边不超过 max_dim 像素)。
|
||||
/// 小图直接复用 `dib_to_png` 结果;大图降采样后重新编码,供弹窗悬停预览使用。
|
||||
pub fn dib_to_thumbnail(dib: &[u8], max_dim: u32) -> Option<Vec<u8>> {
|
||||
use image::codecs::png::PngEncoder;
|
||||
use image::GenericImageView;
|
||||
use image::ImageEncoder;
|
||||
|
||||
let png = dib_to_png(dib)?;
|
||||
let img = image::load_from_memory(&png).ok()?;
|
||||
let (w, h) = img.dimensions();
|
||||
if w.max(h) <= max_dim {
|
||||
return Some(png); // 小图直接使用,避免重复编码
|
||||
}
|
||||
// 让 image 库在 max_dim×max_dim 边界内自动等比缩放,避免手算 nw/nh 与库内部
|
||||
// resize_dimensions 的取整不一致(如手算 256x10 而库实际输出 250x10),
|
||||
// 否则 write_image 的缓冲区长度断言会失败。
|
||||
let resized = img.resize(max_dim, max_dim, image::imageops::FilterType::Triangle);
|
||||
let (rw, rh) = resized.dimensions();
|
||||
let rgba = resized.to_rgba8();
|
||||
let mut buf = Vec::new();
|
||||
let enc = PngEncoder::new(&mut buf);
|
||||
enc.write_image(rgba.as_raw(), rw, rh, image::ExtendedColorType::Rgba8)
|
||||
.ok()?;
|
||||
Some(buf)
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//!
|
||||
//! 表结构见 `init_db`。所有方法线程安全(内部 Mutex 包裹 Connection)。
|
||||
|
||||
use base64::Engine as _;
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use specta::Type;
|
||||
use std::fs;
|
||||
@@ -38,6 +39,8 @@ pub struct NewItem {
|
||||
pub kind: String,
|
||||
pub content: Option<String>,
|
||||
pub blob: Option<Vec<u8>>,
|
||||
/// 图片缩略图 PNG(仅 image 类型,供弹窗悬停预览)
|
||||
pub thumb: Option<Vec<u8>>,
|
||||
pub preview: String,
|
||||
pub size: i64,
|
||||
pub hash: String,
|
||||
@@ -88,6 +91,19 @@ impl Storage {
|
||||
CREATE INDEX IF NOT EXISTS idx_hash ON clipboard_history(hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_kind ON clipboard_history(kind);",
|
||||
);
|
||||
// 迁移:老库无 thumb 列(图片缩略图,供弹窗悬停预览),补列
|
||||
let has_thumb = conn
|
||||
.prepare("PRAGMA table_info(clipboard_history)")
|
||||
.ok()
|
||||
.map(|mut stmt| {
|
||||
stmt.query_map([], |r| r.get::<_, String>(1))
|
||||
.map(|rows| rows.filter_map(|c| c.ok()).any(|c| c == "thumb"))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if !has_thumb {
|
||||
let _ = conn.execute("ALTER TABLE clipboard_history ADD COLUMN thumb BLOB", []);
|
||||
}
|
||||
}
|
||||
|
||||
/// 插入新条目;若 dedup 为 true 且 hash 已存在则仅更新 created_at,返回条目 id。
|
||||
@@ -120,12 +136,13 @@ impl Storage {
|
||||
let now = now_ms();
|
||||
let res = conn.execute(
|
||||
"INSERT INTO clipboard_history
|
||||
(kind, content, blob, preview, size, hash, pinned, pinned_order, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, NULL, ?7)",
|
||||
(kind, content, blob, thumb, preview, size, hash, pinned, pinned_order, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 0, NULL, ?8)",
|
||||
params![
|
||||
item.kind,
|
||||
item.content,
|
||||
item.blob.as_deref(),
|
||||
item.thumb.as_deref(),
|
||||
item.preview,
|
||||
item.size,
|
||||
item.hash,
|
||||
@@ -249,6 +266,26 @@ impl Storage {
|
||||
})
|
||||
}
|
||||
|
||||
/// 获取图片缩略图 PNG base64(弹窗悬停预览用)。
|
||||
/// 老数据无缩略图时回退为 `thumb_from_dib` 现场生成。
|
||||
pub fn get_thumb(&self, id: i64, thumb_from_dib: impl Fn(&[u8]) -> Option<Vec<u8>>) -> Option<String> {
|
||||
let (thumb, blob) = {
|
||||
let conn = self.conn.lock().ok()?;
|
||||
conn.query_row(
|
||||
"SELECT thumb, blob FROM clipboard_history WHERE id = ?1 AND kind = 'image'",
|
||||
params![id],
|
||||
|r| Ok((r.get::<_, Option<Vec<u8>>>(0)?, r.get::<_, Option<Vec<u8>>>(1)?)),
|
||||
)
|
||||
.ok()?
|
||||
};
|
||||
// conn 已在此处释放
|
||||
let png = match thumb {
|
||||
Some(t) if !t.is_empty() => Some(t),
|
||||
_ => blob.as_deref().and_then(|b| thumb_from_dib(b)),
|
||||
};
|
||||
png.map(|p| base64::engine::general_purpose::STANDARD.encode(&p))
|
||||
}
|
||||
|
||||
/// 获取原始字段供 copy_back 写回(避免 base64 转换开销)
|
||||
pub fn get_raw_for_copy(&self, id: i64) -> Option<(String, Option<String>, Option<Vec<u8>>)> {
|
||||
let conn = self.conn.lock().ok()?;
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
//! 剪贴板写入抑制。
|
||||
//!
|
||||
//! 存在的理由:剪贴板监听线程会把**任何**序列号变化录进历史。而应用自身也会写剪贴板
|
||||
//! (copy_back 写回、划词取词时模拟 Ctrl+C 与随后的还原),这些都不该出现在用户的
|
||||
//! 历史里。抑制状态因此必须能被**多个模块**访问,而不是某个模块的私有字段。
|
||||
//!
|
||||
//! 两种机制并存,因为要解决的问题不同:
|
||||
//!
|
||||
//! - **精确抑制(seq)**:只跳过「本应用刚写入的那一次变化」。写入者是我们自己时,
|
||||
//! 写入后的序列号可以立刻读到,于是能精确记账一次;用户随后的复制是另一个序列号,
|
||||
//! 不会被误吞。`copy_back` 用这条。
|
||||
//!
|
||||
//! - **时间窗抑制(burst)**:屏蔽一个区间内的**所有**变化。划词取词要连续动三次剪贴板
|
||||
//! (Ctrl+C 覆盖 → 我们读走 → 还原原文),而监听线程是 250ms 轮询:按序列号逐个记账
|
||||
//! 存在竞态——监听恰好落在我们两次操作之间时,选区文本就被录进历史了。
|
||||
//! 因此取词期间必须整体屏蔽,读完并还原之后再解除。
|
||||
//!
|
||||
//! burst 用**计数**而非布尔:取词流程内部可能再触发一次写入,用布尔会在内层先结束时
|
||||
//! 提前解除屏蔽。配对由 [`SuppressState::burst`] 返回的 RAII 守卫保证,提前 return 也安全。
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct SuppressState {
|
||||
/// 待跳过的序列号(消费一次即清空)
|
||||
seq: Mutex<Option<u32>>,
|
||||
/// 屏蔽窗口嵌套计数
|
||||
burst: AtomicUsize,
|
||||
}
|
||||
|
||||
/// 屏蔽窗口守卫:析构时自动解除,保证与 `begin` 严格配对。
|
||||
pub struct BurstGuard<'a>(&'a SuppressState);
|
||||
|
||||
impl Drop for BurstGuard<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.end_burst();
|
||||
}
|
||||
}
|
||||
|
||||
impl SuppressState {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// 记账:跳过 `seq` 这一次变化(消费一次)。
|
||||
/// 只记一个序列号即可——本应用的写入是串行的,不会同时积压多次。
|
||||
pub fn mark_seq(&self, seq: u32) {
|
||||
if let Ok(mut guard) = self.seq.lock() {
|
||||
*guard = Some(seq);
|
||||
}
|
||||
}
|
||||
|
||||
/// 开始屏蔽窗口。返回的守卫析构时自动结束,**不要**手动配对 end。
|
||||
pub fn burst(&self) -> BurstGuard<'_> {
|
||||
self.burst.fetch_add(1, Ordering::SeqCst);
|
||||
BurstGuard(self)
|
||||
}
|
||||
|
||||
fn end_burst(&self) {
|
||||
// saturating:异常路径下的多余 end 不应让计数下溢,否则会永久屏蔽
|
||||
let _ = self
|
||||
.burst
|
||||
.try_update(Ordering::SeqCst, Ordering::SeqCst, |v| {
|
||||
Some(v.saturating_sub(1))
|
||||
});
|
||||
}
|
||||
|
||||
/// 当前是否处于屏蔽窗口内(供调用方在取词前做提示,不参与判定)
|
||||
pub fn in_burst(&self) -> bool {
|
||||
self.burst.load(Ordering::SeqCst) > 0
|
||||
}
|
||||
|
||||
/// 监听线程询问:这次变化是否应当跳过。
|
||||
/// 命中序列号时**消费**该记账(下次同序列号不再跳过),避免误吞用户后续的复制。
|
||||
pub fn should_skip(&self, seq: u32) -> bool {
|
||||
if self.in_burst() {
|
||||
return true;
|
||||
}
|
||||
let mut guard = match self.seq.lock() {
|
||||
Ok(g) => g,
|
||||
Err(e) => e.into_inner(),
|
||||
};
|
||||
if *guard == Some(seq) {
|
||||
*guard = None;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn seq_suppression_is_consumed_once() {
|
||||
let s = SuppressState::new();
|
||||
s.mark_seq(7);
|
||||
assert!(s.should_skip(7), "记账的那次应被跳过");
|
||||
assert!(!s.should_skip(7), "同序列号不应被反复跳过");
|
||||
assert!(!s.should_skip(8), "其他序列号不受影响");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn burst_suppresses_everything_until_dropped() {
|
||||
let s = SuppressState::new();
|
||||
{
|
||||
let _guard = s.burst();
|
||||
assert!(s.should_skip(1));
|
||||
assert!(s.should_skip(2));
|
||||
assert!(s.in_burst());
|
||||
}
|
||||
assert!(!s.in_burst());
|
||||
assert!(!s.should_skip(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn burst_is_reentrant() {
|
||||
let s = SuppressState::new();
|
||||
let outer = s.burst();
|
||||
{
|
||||
let _inner = s.burst();
|
||||
}
|
||||
// 内层结束不应提前解除外层
|
||||
assert!(s.in_burst());
|
||||
assert!(s.should_skip(9));
|
||||
drop(outer);
|
||||
assert!(!s.in_burst());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_end_does_not_underflow() {
|
||||
let s = SuppressState::new();
|
||||
s.end_burst();
|
||||
s.end_burst();
|
||||
// 下溢会让计数变成极大值从而永久屏蔽,这里确保不会
|
||||
assert!(!s.in_burst());
|
||||
assert!(!s.should_skip(4));
|
||||
}
|
||||
}
|
||||
+142
-2
@@ -10,6 +10,32 @@ pub mod windows {
|
||||
pub const OSD_OVERLAY: &str = "osd-overlay";
|
||||
#[allow(dead_code)]
|
||||
pub const SCREENSHOT_OVERLAY: &str = "screenshot-overlay";
|
||||
#[allow(dead_code)]
|
||||
pub const SCREENSHOT_PIN: &str = "screenshot-pin";
|
||||
#[allow(dead_code)]
|
||||
pub const SCREENSHOT_SCROLL: &str = "screenshot-scroll";
|
||||
/// 取词翻译悬浮窗(由 translate 模块预创建,非激活显示)
|
||||
pub const TRANSLATE_POPUP: &str = "translate-popup";
|
||||
/// 终端独立窗口前缀,实际 label = `${TERMINAL_WINDOW}-<sessionId>`
|
||||
/// 每个终端窗口承载一个会话,脱离主窗口独立存在。
|
||||
pub const TERMINAL_WINDOW: &str = "terminal-window";
|
||||
/// 文件管理器独立窗口。**单例**(label 固定,不含会话 id):
|
||||
/// 它不绑定会话,左右两栏各自选择连接,因此没有「每会话一个窗口」的语义。
|
||||
pub const FILE_WINDOW: &str = "file-window";
|
||||
/// dsh 模块的 Web UI 独立窗口(内容是远端 `http://127.0.0.1:<port>`,
|
||||
/// 因此**不登记 capability**:远端页面不应获得任何 Tauri 权限)。
|
||||
#[allow(dead_code)]
|
||||
pub const DSH_WEB: &str = "dsh-web";
|
||||
/// 笔记 / 编辑器独立窗口前缀,实际 label = `${EDITOR_WINDOW}-<n>`(可多开)
|
||||
#[allow(dead_code)]
|
||||
pub const EDITOR_WINDOW: &str = "editor-window";
|
||||
/// dsh「启动进度」独立窗口(单例,由前端创建)。
|
||||
/// 服务就绪后由前端打开真正的 [`DSH_WEB`] 窗口并关闭它。
|
||||
#[allow(dead_code)]
|
||||
pub const DSH_WINDOW: &str = "dsh-window";
|
||||
/// 对比工具独立窗口(单例,由前端创建)。
|
||||
#[allow(dead_code)]
|
||||
pub const DIFF_WINDOW: &str = "diff-window";
|
||||
}
|
||||
|
||||
/// Tauri 事件名(与前端 constants::EVENTS 对应)
|
||||
@@ -18,15 +44,24 @@ 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";
|
||||
pub const CLIPBOARD_POPUP_HIDE: &str = "clipboard-popup-hide";
|
||||
pub const CLIPBOARD_PREVIEW_SHOW: &str = "clipboard-preview-show";
|
||||
pub const CLIPBOARD_PREVIEW_HIDE: &str = "clipboard-preview-hide";
|
||||
// 快速面板
|
||||
pub const QUICKPANEL_SHOW: &str = "quickpanel-show";
|
||||
pub const QUICKPANEL_HIDE: &str = "quickpanel-hide";
|
||||
pub const QUICKPANEL_EXTRACT_PROGRESS: &str = "quickpanel-extract-progress";
|
||||
/// 文件索引构建完成(闲时自动建立/重建、手动构建),负载为条目数
|
||||
pub const QUICKPANEL_INDEX_UPDATED: &str = "quickpanel-index-updated";
|
||||
// 监控
|
||||
pub const MONITOR_DATA: &str = "monitor-data";
|
||||
pub const MONITOR_NETWORK: &str = "monitor-network";
|
||||
@@ -37,13 +72,118 @@ pub mod events {
|
||||
// OSD 窗口
|
||||
pub const OSD_SYSTEM_UI_ACTIVE: &str = "osd-system-ui-active";
|
||||
pub const OSD_SYSTEM_UI_INACTIVE: &str = "osd-system-ui-inactive";
|
||||
pub const OSD_GAME_ACTIVE: &str = "osd-game-active";
|
||||
pub const OSD_GAME_INACTIVE: &str = "osd-game-inactive";
|
||||
pub const OSD_START_DRAG: &str = "osd-start-drag";
|
||||
pub const OSD_END_DRAG: &str = "osd-end-drag";
|
||||
// 截图
|
||||
pub const SCREENSHOT_SHORTCUT: &str = "screenshot-shortcut";
|
||||
pub const SCREENSHOT_PIN_SHORTCUT: &str = "screenshot-pin-shortcut";
|
||||
/// 滚动截图会话:实时进度 { width, height, auto }
|
||||
pub const SCROLL_PROGRESS: &str = "screenshot-scroll-progress";
|
||||
/// 滚动截图会话:完成并导出
|
||||
pub const SCROLL_COMPLETE: &str = "screenshot-scroll-complete";
|
||||
/// 滚动截图会话:已取消(无负载)
|
||||
pub const SCROLL_CANCELLED: &str = "screenshot-scroll-cancelled";
|
||||
// 内核安装进度
|
||||
pub const KERNEL_INSTALL_PROGRESS: &str = "kernel-install-progress";
|
||||
// 翻译:取词悬浮窗显示(负载见 translate::popup::PopupPayload)/ 隐藏(无负载)
|
||||
pub const TRANSLATE_POPUP_SHOW: &str = "translate-popup-show";
|
||||
pub const TRANSLATE_POPUP_HIDE: &str = "translate-popup-hide";
|
||||
// 翻译:流式输出(负载见 translate::engines::StreamEvent;失败经 start 的 Promise reject,
|
||||
// 已发出 requestId 之后的失败额外走 error 事件兜底)
|
||||
pub const TRANSLATE_STREAM_CHUNK: &str = "translate-stream-chunk";
|
||||
pub const TRANSLATE_STREAM_DONE: &str = "translate-stream-done";
|
||||
pub const TRANSLATE_STREAM_ERROR: &str = "translate-stream-error";
|
||||
// 音乐模块:Python 便携运行时安装进度
|
||||
pub const MUSIC_RUNTIME_INSTALL_PROGRESS: &str = "music-runtime-install-progress";
|
||||
// 终端模块:会话输出批次(负载见 terminal::events::OutputPayload)
|
||||
// 按 8~16ms 窗口聚合,前端用 seq 校验连续性
|
||||
pub const TERMINAL_OUTPUT: &str = "terminal-output";
|
||||
// 终端模块:会话结束(负载见 terminal::events::ExitPayload)
|
||||
pub const TERMINAL_EXIT: &str = "terminal-exit";
|
||||
// 终端模块:会话状态变更(负载为 SessionInfo,前端据此刷新侧栏与标签)
|
||||
pub const TERMINAL_STATE: &str = "terminal-state";
|
||||
// 终端模块:工作目录变化(OSC 7 hook 上报;SFTP 跟随目录依赖此事件)
|
||||
pub const TERMINAL_CWD: &str = "terminal-cwd";
|
||||
// 终端模块:SSH 主机密钥需用户确认(阻塞式交互,握手暂停等待回传)
|
||||
pub const TERMINAL_HOST_KEY_PROMPT: &str = "terminal-host-key-prompt";
|
||||
// 终端模块:请求前端对「关闭仍在运行的会话」二次确认
|
||||
// (P2 起用:P0 的关闭确认在前端 store 内完成,事件通道先占位)
|
||||
#[allow(dead_code)]
|
||||
pub const TERMINAL_CONFIRM_CLOSE: &str = "terminal-confirm-close";
|
||||
// 终端模块:SFTP 传输进度(负载见 terminal::ssh::sftp::TransferProgress)
|
||||
// 节流后发送(约 200ms 一次),前端据此画进度条
|
||||
pub const TERMINAL_TRANSFER_PROGRESS: &str = "terminal-transfer-progress";
|
||||
// 终端模块:设置已保存(无负载)。
|
||||
//
|
||||
// 终端设置存在 Rust 侧,而每个窗口(主窗口 / 终端独立窗口 / 选择窗口)各有
|
||||
// 一份前端副本 —— 没有这个事件,在主窗口改完外观后,已打开的独立窗口会一直
|
||||
// 用旧配色,直到重开窗口。
|
||||
pub const TERMINAL_SETTINGS: &str = "terminal-settings";
|
||||
// 音乐模块:下载任务事件(桥接事件行 → 前端,负载见 bridge.py _emit_event)
|
||||
pub const MUSIC_DOWNLOAD_EVENT: &str = "music-download-event";
|
||||
// 音乐模块:本地解密任务事件(负载见 music::decrypt::DecryptEvent)
|
||||
// 与下载链路同构:命令先回 taskId,进度与逐文件结果都走这个事件。
|
||||
pub const MUSIC_DECRYPT_EVENT: &str = "music-decrypt-event";
|
||||
// 音乐模块:Rust 侧播放引擎(music/audio)。曲目自然播完(缓冲也放完)后发出,无负载
|
||||
pub const MUSIC_AUDIO_ENDED: &str = "music-audio-ended";
|
||||
/// 音乐模块:Rust 侧播放失败(音源打不开 / 解码失败 / 输出设备异常),负载为错误文本
|
||||
pub const MUSIC_AUDIO_ERROR: &str = "music-audio-error";
|
||||
// 后端自动切换节点完成(前端据以刷新节点列表并提示)
|
||||
pub const PROXY_AUTO_SWITCH: &str = "proxy-auto-switch";
|
||||
// 应用更新进度
|
||||
pub const UPDATE_PROGRESS: &str = "update-progress";
|
||||
// 进程与下载
|
||||
pub const PROCESS_STATUS_CHANGED: &str = "process-status-changed";
|
||||
pub const DOWNLOAD_ADDED: &str = "download-added";
|
||||
/// 任务被删除(浏览器扩展通过 HTTP API 删除任务时发出,前端据此刷新任务列表)
|
||||
pub const DOWNLOAD_REMOVED: &str = "download-removed";
|
||||
/// 浏览器扩展通过 HTTP API 新增下载(负载 { id },前端据以为该任务创建专属下载窗口)
|
||||
pub const DOWNLOAD_EXTENSION_ADDED: &str = "download-extension-added";
|
||||
// dsh 模块:安装/下载进度(负载见 dsh::types::DshInstallProgress)
|
||||
pub const DSH_INSTALL_PROGRESS: &str = "dsh-install-progress";
|
||||
// dsh 模块:服务进程状态(负载见 dsh::types::DshServerStatus)
|
||||
pub const DSH_SERVER_STATE: &str = "dsh-server-state";
|
||||
/// dsh 模块:全局快捷键触发「打开独立窗口」(无负载)。
|
||||
/// 窗口由前端创建(它持有带令牌的地址与 label 判重),Rust 侧只负责注册快捷键。
|
||||
pub const DSH_OPEN_WINDOW: &str = "dsh-open-window";
|
||||
// 笔记模块:设置已保存(无负载)。各窗口据以重读设置,实现跨窗口同步(同 terminal-settings)
|
||||
pub const EDITOR_SETTINGS: &str = "editor-settings";
|
||||
// 笔记模块:库内容已变更(新建/保存/重命名/删除/切换库根,无负载)
|
||||
pub const EDITOR_LIBRARY_CHANGED: &str = "editor-library-changed";
|
||||
// 笔记模块:库内某个文件在**应用外**被改动了(负载见 editor::index_service::NoteFileEvent)。
|
||||
// 与 EDITOR_LIBRARY_CHANGED 的区别:那个是「本应用改了,重读即可」,这个是
|
||||
// 「别人改了,当前打开的文档可能已经过时」——前端据此提示而不是静默覆盖。
|
||||
pub const EDITOR_FILE_CHANGED: &str = "editor-file-changed";
|
||||
// 笔记模块:WebDAV 同步进度(负载见 editor::types::SyncProgress)。
|
||||
// 进度事件是高频的,前端按「每 X% 或每 N 条」节流显示即可;Rust 侧逐条发,
|
||||
// 因为节流放在发送端会让「最后一条」容易被丢掉(进度条停在 98%)。
|
||||
pub const EDITOR_SYNC_PROGRESS: &str = "editor-sync-progress";
|
||||
// 笔记模块:全局快捷键按下「新建笔记」(无负载,窗口由前端创建)
|
||||
pub const EDITOR_NEW_NOTE: &str = "editor-new-note";
|
||||
// 笔记模块:全局快捷键按下「打开编辑器窗口」(无负载)
|
||||
pub const EDITOR_OPEN_EDITOR: &str = "editor-open-editor";
|
||||
// 笔记模块:需要打开一个磁盘文件(负载 `{ path }`)。
|
||||
// 来源有三:① 双击关联的 .md(单实例回调把参数转交过来);② 启动命令行参数;
|
||||
// ③ 系统「打开方式」。三种都只发事件,窗口由前端创建。
|
||||
pub const EDITOR_OPEN_FILE: &str = "editor-open-file";
|
||||
// 笔记模块:需要打开一个**文件夹**(负载 `{ path }`)。
|
||||
// 来源:资源管理器右键「用 Thing 编辑器打开」(目录 / 目录背景)。
|
||||
pub const EDITOR_OPEN_FOLDER: &str = "editor-open-folder";
|
||||
// 对比模块:全局快捷键按下「打开对比窗口」(无负载)。
|
||||
// 窗口 label 策略与判重都在前端(它持有窗口),Rust 侧只负责注册快捷键。
|
||||
pub const DIFF_OPEN_WINDOW: &str = "diff-open-window";
|
||||
// 对比模块:目录扫描进度(负载见 diff::types::DiffScanProgress)。
|
||||
// 进度在**发送端**按时间节流(见 diff::commands::diff_compare_dirs):整棵树可能有
|
||||
// 上万个条目、上千次读盘,逐条 emit 会把 IPC 打满;前端只负责显示。
|
||||
pub const DIFF_SCAN_PROGRESS: &str = "diff-scan-progress";
|
||||
// ===== 智能家居(Home Assistant)实时推送与本地规则(P4)=====
|
||||
// 连接状态变化(含 WS):负载 `WsStatus`。前端据此显示顶部横幅与设置页诊断。
|
||||
pub const SMARTHOME_CONNECTION_STATUS: &str = "smarthome-connection-status";
|
||||
// 状态增量批次(**200ms 聚合后**):负载 `StateBatch`。
|
||||
// 逐条 emit 会把 WebView 打爆(一次全屋变化可能几十条),聚合是硬要求。
|
||||
pub const SMARTHOME_STATE_BATCH: &str = "smarthome-state-batch";
|
||||
// 本地规则触发:负载 `RuleFiredEvent`。
|
||||
pub const SMARTHOME_RULE_FIRED: &str = "smarthome-rule-fired";
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! 对比模块的命令层。
|
||||
//!
|
||||
//! 三件事:读取一侧的文件、把一侧的内容写回、对比两棵目录树。文本级差异计算全在前端
|
||||
//! (`@codemirror/merge`);目录级扫描在 [`super::scan`]。
|
||||
//!
|
||||
//! # 尺寸上限为什么要有两个
|
||||
//!
|
||||
//! - [`DIFF_LARGE_MB`]:**软**阈值。超过就置 `large`,前端据此关掉未变化段折叠等
|
||||
//! 高开销特性 —— 文件照样完整读出来,只是更省。
|
||||
//! - [`DIFF_HARD_LIMIT`]:**硬**上限。超过直接拒绝。对比窗口天生同时持有两侧内容
|
||||
//! (不像编辑器只有一篇),单侧 16MB 已经是「两份都塞进 WebView + CM6 状态」的
|
||||
//! 上限量级;再大不是「慢」而是「卡死」,早拒绝比让用户等一分钟再失败好。
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
|
||||
use crate::editor::files;
|
||||
|
||||
use super::scan;
|
||||
use super::types::{DiffFileDoc, DiffScanProgress, DiffSettings, DirDiffReport};
|
||||
use super::DiffManager;
|
||||
|
||||
/// 「大文件」软阈值(MB)。与编辑器设置的默认值一致。
|
||||
const DIFF_LARGE_MB: u32 = 5;
|
||||
/// 硬上限(字节):单侧超过则拒绝读取。
|
||||
const DIFF_HARD_LIMIT: u64 = 16 * 1024 * 1024;
|
||||
/// 二进制探测的头部字节数。**与 `editor::grep` 的判据一致**(头部含 NUL 即二进制),
|
||||
/// 否则会出现「搜索跳过了但对比工具显示了乱码」这种自相矛盾的行为。
|
||||
const BINARY_SNIFF_BYTES: usize = 8 * 1024;
|
||||
|
||||
/// 打开文件并读出头部,同时判断是否二进制(头部含 NUL 字节)。
|
||||
///
|
||||
/// 返回**同一个已打开的句柄**(读位置停在头部之后)与那段头部:文本文件随后要靠这个
|
||||
/// 句柄继续整读(见 `files::read_file_after_head`)—— 于是文件只被打开一次,也不会
|
||||
/// 出现「嗅探时与整读时文件已被换掉」的窗口。二进制则到此为止,绝不整读。
|
||||
fn open_with_head(path: &Path) -> Result<(std::fs::File, Vec<u8>, bool), String> {
|
||||
use std::io::Read;
|
||||
let mut file = std::fs::File::open(path).map_err(|e| format!("读取文件失败: {e}"))?;
|
||||
let mut head = vec![0u8; BINARY_SNIFF_BYTES];
|
||||
let read = file
|
||||
.read(&mut head)
|
||||
.map_err(|e| format!("读取文件失败: {e}"))?;
|
||||
head.truncate(read);
|
||||
let binary = head.contains(&0u8);
|
||||
Ok((file, head, binary))
|
||||
}
|
||||
|
||||
/// 写权限探测:以写模式打开但**不写入**(失败 → 只读)。
|
||||
///
|
||||
/// `editor::files` 里同名的函数是私有的(只服务编辑器自己的打开流程),这里重写一遍
|
||||
/// 三行而不是把它提升为 `pub(crate)`:那个是模块内部细节,把它开放出去会让「谁在读
|
||||
/// 权限探测」变得不清晰。
|
||||
fn is_writable(path: &Path) -> bool {
|
||||
std::fs::OpenOptions::new().write(true).open(path).is_ok()
|
||||
}
|
||||
|
||||
/// 读取对比窗口某一侧的文件。
|
||||
///
|
||||
/// 复用 `editor::files::read_file`(编码探测 / 换行归一 / 只读探测),并顺带登记
|
||||
/// 授权 —— 于是该文件随后可以被 [`diff_write_file`] 写回。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn diff_read_file(path: String) -> Result<DiffFileDoc, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
let meta = std::fs::metadata(p).map_err(|e| format!("读取文件信息失败: {e}"))?;
|
||||
if meta.is_dir() {
|
||||
return Err("这是一个目录 —— 请切到「文件夹」模式并把它设为某一侧".to_string());
|
||||
}
|
||||
if !meta.is_file() {
|
||||
return Err("目标不是普通文件".to_string());
|
||||
}
|
||||
if meta.len() > DIFF_HARD_LIMIT {
|
||||
return Err(format!(
|
||||
"文件过大({} MB),超出对比窗口的 {} MB 上限",
|
||||
meta.len() / (1024 * 1024),
|
||||
DIFF_HARD_LIMIT / (1024 * 1024)
|
||||
));
|
||||
}
|
||||
|
||||
// 先读头部判断二进制(二进制到此为止、不整读),并把这段头部与**同一个句柄**
|
||||
// 交给文本读取路径复用 —— 同一个文件全程只打开一次
|
||||
let (file, head, binary) = open_with_head(p)?;
|
||||
if binary {
|
||||
return Ok(DiffFileDoc::binary_of(p, &meta, is_writable(p)));
|
||||
}
|
||||
|
||||
let doc = files::read_file_after_head(file, p, &meta, &head, DIFF_LARGE_MB)?;
|
||||
// 「打开过就能保存」:读取即登记授权(写回仍会再校验一次授权与写权限)
|
||||
files::authorize(Path::new(&doc.path));
|
||||
Ok(DiffFileDoc::from_file_doc(doc))
|
||||
}
|
||||
|
||||
/// 把某一侧的内容写回磁盘。
|
||||
///
|
||||
/// `encoding` / `eol` 由前端回传**读取时探测到的值**,写回时原样还原 —— 一次「随手
|
||||
/// 保存」不该把 GBK 文件变成 UTF-8、把 CRLF 变成 LF(那会在整个 diff 里掀起风暴)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn diff_write_file(
|
||||
path: String,
|
||||
content: String,
|
||||
encoding: String,
|
||||
eol: String,
|
||||
) -> Result<DiffFileDoc, String> {
|
||||
let doc = files::write_file(&path, &content, &encoding, &eol, DIFF_LARGE_MB)?;
|
||||
Ok(DiffFileDoc::from_file_doc(doc))
|
||||
}
|
||||
|
||||
/// 探测一个路径是文件还是目录(`"dir"` / `"file"` / `"missing"`)。
|
||||
///
|
||||
/// 用途:拖入或 `?path=` 传进来的路径前端拿不到文件系统元信息,而对比窗口需要据此
|
||||
/// 决定「进文件模式还是目录模式」。**刻意不新增 Rust 侧的状态**:只读一次 `metadata`,
|
||||
/// 不写盘、不需授权。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn diff_path_kind(path: String) -> Result<String, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
match std::fs::metadata(trimmed) {
|
||||
Ok(meta) if meta.is_dir() => Ok("dir".to_string()),
|
||||
Ok(meta) if meta.is_file() => Ok("file".to_string()),
|
||||
Ok(_) => Ok("missing".to_string()),
|
||||
Err(_) => Ok("missing".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 对比两棵目录树(只读)。
|
||||
///
|
||||
/// `skip_dirs` 是**目录名**清单(大小写不敏感):默认清单由前端给出(它是界面约定,
|
||||
/// 用户能否修改是 UI 的事),后端只负责按它执行 —— 同 `editor::grep` 把默认跳过清单
|
||||
/// 留在前端的取舍。
|
||||
///
|
||||
/// 走 `spawn_blocking`:两遍目录遍历 + 最多 2000 次读盘都是同步阻塞 IO,放在 Tauri
|
||||
/// 命令线程上会占住它(范式同 `editor_search_in_path`)。
|
||||
///
|
||||
/// `scan_id` 由前端生成并随进度事件原样回传:进度事件是全局的,多选项卡并发扫描时
|
||||
/// 前端据此只认自己那一轮(见 `constants::events::DIFF_SCAN_PROGRESS`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn diff_compare_dirs(
|
||||
app: AppHandle,
|
||||
scan_id: u64,
|
||||
left: String,
|
||||
right: String,
|
||||
skip_dirs: Vec<String>,
|
||||
compare_content: bool,
|
||||
) -> Result<DirDiffReport, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
// 进度按**时间**节流(≥120ms 才发一条):整棵树可能有上万个条目、上千次读盘,
|
||||
// 逐条 emit 会把 IPC 打满;而按条目数节流在「条目少但每个都很大」时又会太稀。
|
||||
// 最后一条进度由前端在命令返回时清掉,不依赖这里补齐。
|
||||
let mut last_emit = Instant::now();
|
||||
let mut progress = |phase: scan::ScanPhase, done: u64, total: u64| {
|
||||
if last_emit.elapsed() < Duration::from_millis(120) {
|
||||
return;
|
||||
}
|
||||
last_emit = Instant::now();
|
||||
let phase = match phase {
|
||||
scan::ScanPhase::Walk => "scan",
|
||||
scan::ScanPhase::Compare => "compare",
|
||||
};
|
||||
let payload = DiffScanProgress {
|
||||
scan_id,
|
||||
phase: phase.to_string(),
|
||||
done,
|
||||
total,
|
||||
};
|
||||
let _ = app.emit(crate::constants::events::DIFF_SCAN_PROGRESS, payload);
|
||||
};
|
||||
scan::compare_dirs(&left, &right, &skip_dirs, compare_content, &mut progress)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("目录对比任务失败: {e}"))?
|
||||
}
|
||||
|
||||
/// 读取对比模块设置。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn diff_get_settings(state: State<'_, DiffManager>) -> DiffSettings {
|
||||
state.load_settings()
|
||||
}
|
||||
|
||||
/// 保存对比模块设置。
|
||||
///
|
||||
/// 保存后**就地重注册**全局快捷键(`register_shortcut` 会先注销本模块的旧键,因此
|
||||
/// 「清空快捷键」也能通过传空串生效)—— 同 `editor_save_settings`。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn diff_save_settings(
|
||||
app: AppHandle,
|
||||
state: State<'_, DiffManager>,
|
||||
settings: DiffSettings,
|
||||
) -> Result<DiffSettings, String> {
|
||||
let mut next = settings;
|
||||
next.heal();
|
||||
state.save_settings(&next)?;
|
||||
state.init_on_launch(&app);
|
||||
Ok(next)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! 对比模块(文本 / 文件 / 目录)。
|
||||
//!
|
||||
//! 架构位置:
|
||||
//!
|
||||
//! ```text
|
||||
//! 主模块页(入口 / 进度) 独立窗口(双栏差异视图)
|
||||
//! ↓ Tauri IPC ↓
|
||||
//! commands.rs 命令层
|
||||
//! ↓
|
||||
//! types.rs(回传前端的 DTO,与前端 src/modules/diff/types.ts 对齐)
|
||||
//! ↓
|
||||
//! editor::files 文件读取与编码探测(**复用**,不重复实现)
|
||||
//! ```
|
||||
//!
|
||||
//! # 为什么复用 `editor::files` 而不自己读文件
|
||||
//!
|
||||
//! 「读一个文本文件」在这里不是 `fs::read_to_string`:要探测 BOM / 严格 UTF-8 /
|
||||
//! GB18030 / Shift_JIS,要让「读到的编码」与「写回的编码」成对(GBK 文件按 UTF-8
|
||||
//! 存回去就是永久损坏),要统一换行风格并原样还原,还要探测只读。这些编辑器模块
|
||||
//! 都已经做完并踩过坑(见 `editor/files.rs` 的模块注释),对比工具没有任何理由
|
||||
//! 再实现一遍 —— 因此 `editor::files` 提升为 `pub(crate)`,本模块直接调用。
|
||||
//!
|
||||
//! # 授权模型沿用编辑器
|
||||
//!
|
||||
//! `editor::files` 的写操作要求路径在会话内被「用户显式选择过」(对话框 / 拖入 /
|
||||
//! 命令行)。本模块在**读取时顺带登记授权**,于是「在对比窗口打开过就能保存」这条
|
||||
//! 最符合直觉的规则自动成立,不需要前端再单独调用一次授权命令。
|
||||
//!
|
||||
//! # 当前进度
|
||||
//!
|
||||
//! P2 落地:单文件读取(`diff_read_file`)与写回(`diff_write_file`)。
|
||||
//! P3 落地:目录对比(`diff_compare_dirs` / `diff_path_kind`,只读)。
|
||||
//! 规划见 `doc/DIFF_MODULE_PLAN.md`。
|
||||
|
||||
mod commands;
|
||||
mod scan;
|
||||
mod types;
|
||||
|
||||
pub use commands::{
|
||||
diff_compare_dirs, diff_get_settings, diff_path_kind, diff_read_file, diff_save_settings,
|
||||
diff_write_file,
|
||||
};
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use types::DiffSettings;
|
||||
|
||||
/// 设置内存缓存有效期(与 ai / translate / terminal / editor 的 500ms 一致)。
|
||||
const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500);
|
||||
|
||||
struct SettingsCache {
|
||||
read_at: Instant,
|
||||
settings: DiffSettings,
|
||||
}
|
||||
|
||||
/// 对比模块管理器(Tauri State)。
|
||||
///
|
||||
/// 目前只承担一件事:设置的读写与全局快捷键注册。目标(左右文件 / 左右目录)**不在这里**
|
||||
/// —— 它们是前端会话状态,Rust 侧不需要知道用户在比哪两个东西。
|
||||
pub struct DiffManager {
|
||||
/// 模块自身目录:`{app_data_dir}/diff`
|
||||
module_dir: PathBuf,
|
||||
cache: Mutex<Option<SettingsCache>>,
|
||||
}
|
||||
|
||||
impl DiffManager {
|
||||
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||
let module_dir = app_data_dir.join("diff");
|
||||
let _ = std::fs::create_dir_all(&module_dir);
|
||||
Self {
|
||||
module_dir,
|
||||
cache: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_path(&self) -> PathBuf {
|
||||
self.module_dir.join("settings.json")
|
||||
}
|
||||
|
||||
/// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。
|
||||
pub fn load_settings(&self) -> DiffSettings {
|
||||
if let Ok(cache) = self.cache.lock() {
|
||||
if let Some(entry) = cache.as_ref() {
|
||||
if entry.read_at.elapsed() < SETTINGS_CACHE_TTL {
|
||||
return entry.settings.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = std::fs::read_to_string(self.settings_path())
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<DiffSettings>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
let healed = settings.heal();
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
if healed {
|
||||
if let Err(e) = self.save_settings(&settings) {
|
||||
crate::logger::log_error("diff", &format!("设置自愈落盘失败: {e}"));
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// 保存设置并刷新缓存。
|
||||
pub fn save_settings(&self, settings: &DiffSettings) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(settings)
|
||||
.map_err(|e| format!("序列化对比设置失败: {e}"))?;
|
||||
std::fs::write(self.settings_path(), json).map_err(|e| format!("写入对比设置失败: {e}"))?;
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 启动时按设置注册「打开对比窗口」全局快捷键(默认 Alt+C)。
|
||||
///
|
||||
/// 失败只记日志:快捷键被别的应用占了不该阻断启动(同 editor / translate / terminal)。
|
||||
/// 触发时**只发事件**:窗口 label 策略与判重都在前端(它持有窗口),Rust 侧不该操心。
|
||||
pub fn init_on_launch(&self, app: &tauri::AppHandle) {
|
||||
use tauri::Emitter;
|
||||
let settings = self.load_settings();
|
||||
let shortcut = settings.open_diff_shortcut.clone();
|
||||
if let Err(e) =
|
||||
crate::shortcut::register_shortcut(app, "diff-open-window", &shortcut, |app| {
|
||||
if let Err(e) = app.emit(crate::constants::events::DIFF_OPEN_WINDOW, ()) {
|
||||
crate::logger::log_warn("diff", &format!("发出打开对比窗口事件失败: {e}"));
|
||||
}
|
||||
})
|
||||
{
|
||||
crate::logger::log_warn("diff", &format!("注册「打开对比窗口」快捷键失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 模块目录(保留给将来的诊断 / 导出用)。
|
||||
#[allow(dead_code)]
|
||||
pub fn module_dir(&self) -> &Path {
|
||||
&self.module_dir
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
//! 目录对比:递归遍历两侧 + 三态分类(**只读**,本期不做写回)。
|
||||
//!
|
||||
//! # 为什么是三层判据,而不是逐字节比对
|
||||
//!
|
||||
//! 一个几万文件的目录树逐字节比对,等于把两边全读一遍 —— 慢且没必要。判据按代价递增:
|
||||
//!
|
||||
//! 1. **size 不同** → 直接判「不同」(两文件大小都不同,内容不可能相同,不必读盘);
|
||||
//! 2. **两侧都是空文件** → 直接判「相同」(长度都是 0,内容必然相同;这一条必须显式判,
|
||||
//! 否则「空文件 + 时间戳不同」会掉进下面「按时间戳判不同」的兜底,把两个空文件报成差异);
|
||||
//! 3. **size 相同且 mtime 相同** → 判「相同」(各对比工具的通行快速路径);
|
||||
//! 4. **size 相同但 mtime 不同** → 才读内容逐字节比对。
|
||||
//!
|
||||
//! 第 4 步有预算([`MAX_CONTENT_COMPARES`] 条数与 [`MAX_CONTENT_BYTES`] 单文件体积):
|
||||
//! 超出后不再读盘,按时间戳归入「不同」并把 `content_compared` 置 false ——
|
||||
//! 结论仍然是「不同」,但**明确标记它未经内容比对**,而不是给出一个看起来同样确定的答案。
|
||||
//!
|
||||
//! # 为什么返回扁平列表而不是树
|
||||
//!
|
||||
//! 递归类型在 specta 的 `Type` 派生下容易生成无穷展开的 TS 类型(`editor::types::LibraryEntry`
|
||||
//! 的注释里踩过同一个坑)。这里同样返回扁平列表(`rel_path` 用 `/` 分隔),由前端组装成树。
|
||||
//!
|
||||
//! # 只读
|
||||
//!
|
||||
//! 本模块**不写任何文件**。目录写回(复制 / 镜像 / 双向同步)是另一个量级的工程
|
||||
//! (冲突策略、部分失败回滚、覆盖确认),已与用户确认不在本期。
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::time::{Instant, UNIX_EPOCH};
|
||||
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use crate::editor::files::display_path;
|
||||
|
||||
use super::types::{DirDiffEntry, DirDiffReport, NodeInfo};
|
||||
|
||||
/// 单次对比最多回传的条目数(超出即截断并置 `truncated`)。
|
||||
///
|
||||
/// 取值权衡:条目是扁平 JSON,每条含两侧绝对路径,约 200 字节 —— 8000 条约 1.6MB 一次性
|
||||
/// 走 IPC,是「还能接受」与「再大就该让用户缩小范围」的分界。
|
||||
const MAX_ENTRIES: usize = 8000;
|
||||
/// 最多读多少个文件的内容做逐字节比对(防止「上万文件大小相同、时间戳不同」时把盘读穿)。
|
||||
const MAX_CONTENT_COMPARES: usize = 2000;
|
||||
/// 单个文件超过这个体积就不读内容比对(按时间戳判定)。
|
||||
const MAX_CONTENT_BYTES: u64 = 4 * 1024 * 1024;
|
||||
|
||||
/// 扫描阶段(进度事件用;事件名与负载见 [`super::types::DiffScanProgress`])。
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ScanPhase {
|
||||
/// 遍历目录树(此时总数无从预知)
|
||||
Walk,
|
||||
/// 读内容逐字节核对(总数 = 预算上限)
|
||||
Compare,
|
||||
}
|
||||
|
||||
/// 一次遍历的产出。
|
||||
struct Collected {
|
||||
files: HashMap<String, NodeInfo>,
|
||||
skipped_dirs: u32,
|
||||
truncated: bool,
|
||||
}
|
||||
|
||||
/// 把根路径解析成「存在的目录」的绝对路径。
|
||||
fn resolve_root(raw: &str, label: &str) -> Result<std::path::PathBuf, String> {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err(format!("{label}目录为空"));
|
||||
}
|
||||
let path = Path::new(trimmed);
|
||||
let meta = std::fs::metadata(path).map_err(|e| format!("读取{label}目录失败: {e}"))?;
|
||||
if !meta.is_dir() {
|
||||
return Err(format!("{label}不是目录(文件对比请用「文件 / 文本」模式)"));
|
||||
}
|
||||
// 规范化:统一成真实位置,避免两侧用不同写法指向同一目录(`C:\a\..\b` / 尾部斜杠)
|
||||
std::fs::canonicalize(path).map_err(|e| format!("解析{label}目录失败: {e}"))
|
||||
}
|
||||
|
||||
/// 递归收集一侧的全部条目。
|
||||
///
|
||||
/// **不跟随符号链接**(walkdir 默认):跟随会让「链接成的环」把遍历变成死循环。
|
||||
///
|
||||
/// 跳过清单用 `filter_entry` **真正剪枝**:walkdir 在返回一个目录条目的**同一次**
|
||||
/// `next()` 里就已把该目录压进遍历栈(见 walkdir 的 `handle_entry`),因此仅对命中的
|
||||
/// 目录条目 `continue` 并不会阻止继续下钻 —— 那会「跳过」得名不副实(构建目录的子项
|
||||
/// 照样进结果),还把整棵构建目录白扫一遍。
|
||||
fn collect(
|
||||
root: &Path,
|
||||
skip: &HashSet<String>,
|
||||
progress: &mut dyn FnMut(ScanPhase, u64, u64),
|
||||
) -> Collected {
|
||||
let mut files: HashMap<String, NodeInfo> = HashMap::new();
|
||||
let skipped = Cell::new(0u32);
|
||||
let truncated = Cell::new(false);
|
||||
let mut encountered: u64 = 0;
|
||||
|
||||
let walker = WalkDir::new(root)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_entry(|entry| {
|
||||
// 根自身永远放行:否则根的名字恰好命中清单时整棵树都没了
|
||||
if entry.depth() == 0 {
|
||||
return true;
|
||||
}
|
||||
if entry.file_type().is_dir() {
|
||||
let name = entry.file_name().to_string_lossy().to_lowercase();
|
||||
if skip.contains(&name) {
|
||||
skipped.set(skipped.get() + 1);
|
||||
return false; // 既不产出该目录,也不再下钻
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
|
||||
for entry in walker {
|
||||
if truncated.get() {
|
||||
break;
|
||||
}
|
||||
let Ok(entry) = entry else { continue };
|
||||
// 根自身不作为条目
|
||||
if entry.depth() == 0 {
|
||||
continue;
|
||||
}
|
||||
encountered += 1;
|
||||
// 每 512 个条目报一次(真正的节流由命令层按时间做,见 `diff_compare_dirs`)
|
||||
if encountered % 512 == 0 {
|
||||
progress(ScanPhase::Walk, encountered, 0);
|
||||
}
|
||||
if files.len() >= MAX_ENTRIES {
|
||||
truncated.set(true);
|
||||
break;
|
||||
}
|
||||
|
||||
let is_dir = entry.file_type().is_dir();
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
let Ok(meta) = entry.metadata() else { continue };
|
||||
let rel = entry
|
||||
.path()
|
||||
.strip_prefix(root)
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_else(|_| name.clone());
|
||||
|
||||
files.insert(
|
||||
rel,
|
||||
NodeInfo {
|
||||
is_dir,
|
||||
size: if is_dir { 0 } else { meta.len() },
|
||||
modified: meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0),
|
||||
path: display_path(entry.path()),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// 收尾再报一次:让「最后一截」不被 512 的步长吞掉
|
||||
progress(ScanPhase::Walk, encountered, 0);
|
||||
|
||||
Collected {
|
||||
files,
|
||||
skipped_dirs: skipped.get(),
|
||||
truncated: truncated.get(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 两个文件的内容是否逐字节相同(只在「大小相同、时间戳不同」时才调用)。
|
||||
///
|
||||
/// 分块比较而不是把两个文件整体读进内存:单文件上限 [`MAX_CONTENT_BYTES`](4MB),
|
||||
/// 整体读要一次性占两块 4MB;分块读的峰值只有缓冲区大小,遇到首个差异就能立刻返回。
|
||||
fn same_content(left: &Path, right: &Path) -> Result<bool, std::io::Error> {
|
||||
let mut a = std::io::BufReader::new(std::fs::File::open(left)?);
|
||||
let mut b = std::io::BufReader::new(std::fs::File::open(right)?);
|
||||
let mut buf_a = [0u8; 64 * 1024];
|
||||
let mut buf_b = [0u8; 64 * 1024];
|
||||
loop {
|
||||
let n = read_full(&mut a, &mut buf_a)?;
|
||||
let m = read_full(&mut b, &mut buf_b)?;
|
||||
// 长度不同(含「一个先到 EOF」)即判不同
|
||||
if n != m || buf_a[..n] != buf_b[..m] {
|
||||
return Ok(false);
|
||||
}
|
||||
if n == 0 {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 把缓冲区读到满(除非到达 EOF)。
|
||||
///
|
||||
/// `Read::read` 允许短读,直接拿短读的字节数比较会误判「不同」,因此这里循环到读满。
|
||||
fn read_full(reader: &mut impl std::io::Read, buf: &mut [u8]) -> Result<usize, std::io::Error> {
|
||||
let mut filled = 0;
|
||||
while filled < buf.len() {
|
||||
let n = reader.read(&mut buf[filled..])?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
filled += n;
|
||||
}
|
||||
Ok(filled)
|
||||
}
|
||||
|
||||
/// 对比两棵目录树。
|
||||
///
|
||||
/// `skip_dirs` 由前端给出(大小写不敏感、按目录名匹配):默认清单是**界面约定**而不是
|
||||
/// 后端常量 —— 用户能不能改这份清单是 UI 的事,后端只负责按它执行(同 `editor::grep`
|
||||
/// 把默认清单留在前端的取舍)。
|
||||
///
|
||||
/// `progress` 是进度回调(阶段, 已完成, 总数):本函数只负责在关键节点调用它,
|
||||
/// 事件名 / 节流 / 发给谁都在命令层决定(见 `super::commands`)。
|
||||
pub fn compare_dirs(
|
||||
left: &str,
|
||||
right: &str,
|
||||
skip_dirs: &[String],
|
||||
compare_content: bool,
|
||||
progress: &mut dyn FnMut(ScanPhase, u64, u64),
|
||||
) -> Result<DirDiffReport, String> {
|
||||
let started = Instant::now();
|
||||
let left_root = resolve_root(left, "左侧")?;
|
||||
let right_root = resolve_root(right, "右侧")?;
|
||||
|
||||
// 跳过清单归一成集合:命中的目录要在剪枝判定里按名做 O(1) 查表(清单有十几项、
|
||||
// 目录数可达上万,逐个线性比对不值得)
|
||||
let skip: HashSet<String> = skip_dirs
|
||||
.iter()
|
||||
.map(|s| s.trim().to_lowercase())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
|
||||
let l = collect(&left_root, &skip, &mut *progress);
|
||||
let r = collect(&right_root, &skip, &mut *progress);
|
||||
|
||||
// 两侧相对路径的并集,排序后输出(顺序稳定,前端组装树的观感才稳定)
|
||||
let mut keys: Vec<&String> = l.files.keys().chain(r.files.keys()).collect();
|
||||
keys.sort();
|
||||
keys.dedup();
|
||||
|
||||
let mut entries: Vec<DirDiffEntry> = Vec::with_capacity(keys.len());
|
||||
let mut content_budget = MAX_CONTENT_COMPARES;
|
||||
let mut compared: u64 = 0;
|
||||
|
||||
for key in keys {
|
||||
let left_node = l.files.get(key);
|
||||
let right_node = r.files.get(key);
|
||||
|
||||
let is_dir = left_node.map(|n| n.is_dir).unwrap_or(false)
|
||||
|| right_node.map(|n| n.is_dir).unwrap_or(false);
|
||||
|
||||
let mut content_compared = false;
|
||||
let status: &str = match (left_node, right_node) {
|
||||
(Some(_), None) => "left-only",
|
||||
(None, Some(_)) => "right-only",
|
||||
(Some(a), Some(b)) => {
|
||||
if a.is_dir != b.is_dir {
|
||||
// 同名但一侧是文件、另一侧是目录:无法比较内容,单独归类
|
||||
"type-mismatch"
|
||||
} else if a.is_dir {
|
||||
// 目录本身没有内容,是否「相同」由它的子条目决定;前端按子树判断
|
||||
"identical"
|
||||
} else if a.size != b.size {
|
||||
"different"
|
||||
} else if a.size == 0 {
|
||||
// 两侧都是空文件(上面的 size 不等已排除「单侧为空」):内容必然相同。
|
||||
// 不单独判的话会掉进最后的兜底,按时间戳把两个空文件报成「不同」
|
||||
"identical"
|
||||
} else if a.modified == b.modified {
|
||||
"identical"
|
||||
} else if compare_content && content_budget > 0 && a.size <= MAX_CONTENT_BYTES {
|
||||
content_budget -= 1;
|
||||
content_compared = true;
|
||||
compared += 1;
|
||||
// 核对阶段是最慢的一段(每处都要读两个文件),进度最有价值
|
||||
progress(ScanPhase::Compare, compared, MAX_CONTENT_COMPARES as u64);
|
||||
match same_content(Path::new(&a.path), Path::new(&b.path)) {
|
||||
Ok(true) => "identical",
|
||||
Ok(false) => "different",
|
||||
// 读失败(权限 / 竞态删除):按时间戳判定,不把错误伪装成结论
|
||||
Err(_) => "different",
|
||||
}
|
||||
} else {
|
||||
// 体积超限 / 预算用尽:按时间戳判定,标记未比对内容
|
||||
"different"
|
||||
}
|
||||
}
|
||||
(None, None) => unreachable!("key 来自两侧键的并集"),
|
||||
};
|
||||
|
||||
entries.push(DirDiffEntry {
|
||||
rel_path: key.clone(),
|
||||
is_dir,
|
||||
status: status.to_string(),
|
||||
left_path: left_node.map(|n| n.path.clone()).unwrap_or_default(),
|
||||
right_path: right_node.map(|n| n.path.clone()).unwrap_or_default(),
|
||||
left_size: left_node.map(|n| n.size).unwrap_or(0),
|
||||
right_size: right_node.map(|n| n.size).unwrap_or(0),
|
||||
left_modified: left_node.map(|n| n.modified).unwrap_or(0),
|
||||
right_modified: right_node.map(|n| n.modified).unwrap_or(0),
|
||||
content_compared,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(DirDiffReport {
|
||||
left_root: display_path(&left_root),
|
||||
right_root: display_path(&right_root),
|
||||
entries,
|
||||
truncated: l.truncated || r.truncated,
|
||||
skipped_dirs: l.skipped_dirs + r.skipped_dirs,
|
||||
elapsed_ms: started.elapsed().as_millis() as u64,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! 对比模块的数据模型(回传前端的 DTO)。
|
||||
//!
|
||||
//! 与前端 `src/modules/diff/types.ts` 一一对应;新增字段两侧都要改。
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::fs::Metadata;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::editor::files::{display_path, FileDoc};
|
||||
|
||||
/// 设置结构版本号。字段增减时递增,由 [`DiffSettings::heal`] 推进。
|
||||
pub const DIFF_SETTINGS_VERSION: u32 = 1;
|
||||
|
||||
/// 对比模块设置(持久化到 `{app_data_dir}/diff/settings.json`,范式同 editor / translate)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct DiffSettings {
|
||||
pub version: u32,
|
||||
/// 全局快捷键:打开 / 唤出对比窗口(空串 = 不注册)。
|
||||
///
|
||||
/// 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译 / 编辑器同一套);触发时只发
|
||||
/// `diff-open-window` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
|
||||
pub open_diff_shortcut: String,
|
||||
/// 目录对比:默认是否比对内容(大小相同、时间戳不同时读文件逐字节比对)
|
||||
pub compare_content: bool,
|
||||
/// 目录对比:默认是否跳过常见构建目录
|
||||
pub skip_build_dirs: bool,
|
||||
}
|
||||
|
||||
impl Default for DiffSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: DIFF_SETTINGS_VERSION,
|
||||
open_diff_shortcut: "Alt+C".to_string(),
|
||||
compare_content: true,
|
||||
skip_build_dirs: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DiffSettings {
|
||||
/// 自愈:推进版本号(并在首次遇到旧配置时补上默认快捷键)。返回是否发生了变化。
|
||||
///
|
||||
/// 刻意**不**把空的 `open_diff_shortcut` 补回默认:空串是「用户主动清空快捷键」的
|
||||
/// 合法表达,快捷键被静默改回来比不生效更让人困惑。只有版本号为 0(从未写过这份
|
||||
/// 配置)时才补一次 Alt+C。
|
||||
pub fn heal(&mut self) -> bool {
|
||||
if self.version >= DIFF_SETTINGS_VERSION {
|
||||
return false;
|
||||
}
|
||||
if self.version == 0 && self.open_diff_shortcut.is_empty() {
|
||||
self.open_diff_shortcut = "Alt+C".to_string();
|
||||
}
|
||||
self.version = DIFF_SETTINGS_VERSION;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// 对比窗口里**一侧**文件的状态。
|
||||
///
|
||||
/// 刻意不复用 `FileDoc`:对比窗口需要额外的 `binary` 标记(二进制文件不进入文本
|
||||
/// diff,只报「不同」),而 `FileDoc` 是编辑器模块的对外契约,为对比工具加字段会
|
||||
/// 把「谁需要什么」搅在一起。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiffFileDoc {
|
||||
/// 绝对路径(Windows 下已剥掉 `\\?\` 前缀)
|
||||
pub path: String,
|
||||
/// 显示名(文件名)
|
||||
pub name: String,
|
||||
/// 文本内容(换行已统一为 `\n`,写回时按 `eol` 还原)。二进制文件为空串
|
||||
pub content: String,
|
||||
/// 探测到的编码(`utf-8` / `utf-8-bom` / `gbk` / …)。二进制文件为空串
|
||||
pub encoding: String,
|
||||
/// 换行风格:"lf" | "crlf"。二进制文件为空串
|
||||
pub eol: String,
|
||||
/// 文件字节数
|
||||
pub size: u64,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 行数(二进制文件为 0)
|
||||
pub lines: u64,
|
||||
/// 是否超过「大文件」阈值(前端据此关掉折叠等高开销特性)
|
||||
pub large: bool,
|
||||
/// 是否只读(写权限探测失败)
|
||||
pub readonly: bool,
|
||||
/// 是否为二进制(头部含 NUL 字节):此类文件不渲染 diff
|
||||
pub binary: bool,
|
||||
}
|
||||
|
||||
impl DiffFileDoc {
|
||||
/// 由编辑器的读取结果构造(文本文件路径)。
|
||||
pub fn from_file_doc(doc: FileDoc) -> Self {
|
||||
Self {
|
||||
path: doc.path,
|
||||
name: doc.name,
|
||||
content: doc.content,
|
||||
encoding: doc.encoding,
|
||||
eol: doc.eol,
|
||||
size: doc.size,
|
||||
modified: doc.modified,
|
||||
lines: doc.lines,
|
||||
large: doc.large,
|
||||
readonly: doc.readonly,
|
||||
binary: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 二进制文件:**不读内容**(避免把无意义的字节解码成一大段乱码再走 IPC)。
|
||||
pub fn binary_of(path: &Path, meta: &Metadata, readonly: bool) -> Self {
|
||||
Self {
|
||||
path: display_path(path),
|
||||
name: path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
content: String::new(),
|
||||
encoding: String::new(),
|
||||
eol: String::new(),
|
||||
size: meta.len(),
|
||||
modified: meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0),
|
||||
lines: 0,
|
||||
large: false,
|
||||
readonly,
|
||||
binary: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 遍历时一侧的一个条目(**内部结构**,不回传前端)。
|
||||
pub struct NodeInfo {
|
||||
pub is_dir: bool,
|
||||
/// 目录为 0
|
||||
pub size: u64,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 绝对路径(回传前端用于「下钻到文件对比」)
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// 目录对比中的一个条目(扁平列表,由前端组装成树)。
|
||||
///
|
||||
/// `status` 取值:`left-only` / `right-only` / `different` / `identical` / `type-mismatch`
|
||||
/// (同名但一侧是文件、另一侧是目录)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DirDiffEntry {
|
||||
/// 相对根的路径,`/` 分隔(前端据此组装树,显示名自己从最后一段取)
|
||||
pub rel_path: String,
|
||||
/// 是否目录(type-mismatch 时为 true)
|
||||
pub is_dir: bool,
|
||||
pub status: String,
|
||||
/// 该侧的绝对路径;该侧不存在时为空串
|
||||
pub left_path: String,
|
||||
pub right_path: String,
|
||||
/// 该侧字节数;不存在为 0
|
||||
pub left_size: u64,
|
||||
pub right_size: u64,
|
||||
/// 该侧最后修改时间(Unix 毫秒);不存在为 0
|
||||
pub left_modified: u64,
|
||||
pub right_modified: u64,
|
||||
/// 结论是否**由内容逐字节比对**得出。
|
||||
///
|
||||
/// false 表示「大小相同、时间戳不同」且未读内容(体积超限 / 预算用尽),
|
||||
/// 此时 `different` 是**按时间戳**判定的 —— 界面要据此提示,不能与已确认的差异
|
||||
/// 用同一种语气呈现。
|
||||
pub content_compared: bool,
|
||||
}
|
||||
|
||||
/// 目录对比的扫描进度(**事件负载**,不是命令返回值)。
|
||||
///
|
||||
/// 前端按 `scan_id` 过滤:进度事件是全局的(Rust 不区分选项卡),多选项卡并发扫描时
|
||||
/// 只有属于本轮的那一份进度才该被采用。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiffScanProgress {
|
||||
/// 本轮扫描的标识(前端生成,随命令传入并原样回传)
|
||||
pub scan_id: u64,
|
||||
/// `scan` = 正在遍历目录;`compare` = 正在读内容逐字节核对
|
||||
pub phase: String,
|
||||
/// 已完成数(遍历 = 已过的条目数;核对 = 已比对的文件数)
|
||||
pub done: u64,
|
||||
/// 总数(遍历阶段无从预知,为 0;核对阶段为预算上限)
|
||||
pub total: u64,
|
||||
}
|
||||
|
||||
/// 一次目录对比的结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DirDiffReport {
|
||||
pub left_root: String,
|
||||
pub right_root: String,
|
||||
pub entries: Vec<DirDiffEntry>,
|
||||
/// 条目数达到上限、遍历被截断(界面提示用户缩小范围)
|
||||
pub truncated: bool,
|
||||
/// 按跳过清单略过的目录数
|
||||
pub skipped_dirs: u32,
|
||||
/// 扫描耗时(毫秒;状态栏显示)
|
||||
pub elapsed_ms: u64,
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use tauri::{AppHandle, State};
|
||||
use tauri::{AppHandle, Manager, State};
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
|
||||
use super::engine::{CheckUrlResult, DownloadEngine};
|
||||
use super::task::{DownloadTask, DownloaderSettings};
|
||||
use super::torrent::TorrentInfo;
|
||||
|
||||
/// 获取所有任务
|
||||
#[tauri::command]
|
||||
@@ -13,6 +14,20 @@ pub fn downloader_get_tasks(engine: State<'_, DownloadEngine>) -> Vec<DownloadTa
|
||||
engine.get_tasks()
|
||||
}
|
||||
|
||||
/// 解析磁力链 / .torrent 文件,返回种子信息(名称 / infohash / 文件列表),供前端做文件勾选
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn downloader_inspect(engine: State<'_, DownloadEngine>, input: String) -> Result<TorrentInfo, String> {
|
||||
engine.inspect(&input).await
|
||||
}
|
||||
|
||||
/// 磁力任务:元数据解析成功后,用户勾选文件并确认开始下载
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn downloader_select_bt_files(engine: State<'_, DownloadEngine>, id: String, only_files: Vec<u32>) -> Result<(), String> {
|
||||
engine.select_bt_files(&id, only_files).await
|
||||
}
|
||||
|
||||
/// 检查 URL 重复性并探测文件信息(添加下载前调用)
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -57,8 +72,9 @@ pub async fn downloader_add_task(
|
||||
dir: Option<String>,
|
||||
headers: Option<HashMap<String, String>>,
|
||||
auto_rename: Option<bool>,
|
||||
only_files: Option<Vec<u32>>,
|
||||
) -> Result<String, String> {
|
||||
engine.add_task(url, filename, dir, headers.unwrap_or_default(), auto_rename.unwrap_or(false)).await
|
||||
engine.add_task(url, filename, dir, headers.unwrap_or_default(), auto_rename.unwrap_or(false), only_files).await
|
||||
}
|
||||
|
||||
/// 暂停任务
|
||||
@@ -75,6 +91,20 @@ pub fn downloader_resume_task(engine: State<'_, DownloadEngine>, id: String) ->
|
||||
engine.resume_task(&id)
|
||||
}
|
||||
|
||||
/// 取消任务(置为已取消,清空进度并删除下载文件,但保留记录)
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn downloader_cancel_task(engine: State<'_, DownloadEngine>, id: String) -> Result<(), String> {
|
||||
engine.cancel_task(&id)
|
||||
}
|
||||
|
||||
/// 重新下载已取消/出错的任务
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn downloader_redownload(engine: State<'_, DownloadEngine>, id: String) -> Result<(), String> {
|
||||
engine.redownload(&id).await
|
||||
}
|
||||
|
||||
/// 移除任务
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -141,3 +171,24 @@ pub fn downloader_open_url(app: AppHandle, url: String) -> Result<(), String> {
|
||||
.open_url(url, None::<&str>)
|
||||
.map_err(|e| format!("打开链接失败: {}", e))
|
||||
}
|
||||
|
||||
/// 将指定 label 的下载窗口显示并强制置为前台。
|
||||
/// Tauri 的 set_focus 在 Windows 上受前台锁定限制(尤其下载窗口由后台进程创建、
|
||||
/// 或创建到非主显示器时更明显),改用原生 SetForegroundWindow + BringWindowToTop
|
||||
/// (模拟 Alt 键重置前台锁定),保证开始/完成下载时窗口能正确定位到前台。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn downloader_focus_window(app: AppHandle, label: String) -> Result<(), String> {
|
||||
let Some(window) = app.get_webview_window(&label) else {
|
||||
return Ok(()); // 窗口已关闭则忽略
|
||||
};
|
||||
window.show().map_err(|e| e.to_string())?;
|
||||
window.unminimize().map_err(|e| e.to_string())?;
|
||||
match window.hwnd() {
|
||||
Ok(hwnd) => crate::win32_util::force_foreground(hwnd.0 as isize),
|
||||
Err(_) => {
|
||||
window.set_focus().ok();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,47 +1,174 @@
|
||||
use futures_util::StreamExt;
|
||||
use reqwest::Proxy;
|
||||
use reqwest::Client;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::SeekFrom;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::io::{AsyncSeekExt, AsyncWriteExt};
|
||||
use tokio::task::JoinSet;
|
||||
|
||||
use super::rate_limit::RateLimiter;
|
||||
use super::task::{ProbeResult, Segment};
|
||||
|
||||
/// 请求超时:连接 + 响应头必须在 30s 内就绪(分段请求若无超时,
|
||||
/// 服务器挂死时任务将永久卡在 Active,pause→resume 会出现新旧任务并发写同一临时文件)
|
||||
const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
/// 分块读取停滞超时:30s 内无任何数据视为连接挂死,主动中断(配合取消标志及时退出)
|
||||
const READ_STALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
/// 取消轮询间隔。
|
||||
///
|
||||
/// **这不是下载超时**:下载路径不再因「长时间无数据/无响应头」中断,服务器慢就继续等,
|
||||
/// 只有用户暂停/取消或真正报错才结束。这个 200ms 轮询的唯一作用是让暂停/取消在
|
||||
/// 「连接挂死、`stream.next()` 一直 pending」时也能及时被感知——
|
||||
/// 否则等待 future 永不返回,取消标志就永远读不到。
|
||||
const CANCEL_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(200);
|
||||
|
||||
/// 交互式探测超时(仅用于「添加下载」校验等用户正盯着界面等结果的场景:
|
||||
/// 无限等待等于界面卡死)。真正的下载/后台探测路径不设超时。
|
||||
pub const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
|
||||
/// 等待一个 future 完成,期间每 200ms 检查一次取消标志;**不设超时**。
|
||||
///
|
||||
/// 返回 `Err("已取消")` 表示用户暂停/取消(调用方据此把任务置为 Paused 而非 Error)。
|
||||
async fn wait_cancellable<F>(fut: F, cancel: &AtomicBool) -> Result<F::Output, String>
|
||||
where
|
||||
F: std::future::Future,
|
||||
{
|
||||
tokio::pin!(fut);
|
||||
loop {
|
||||
if cancel.load(Ordering::SeqCst) {
|
||||
return Err("已取消".to_string());
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = tokio::time::sleep(CANCEL_POLL_INTERVAL) => continue,
|
||||
out = &mut fut => return Ok(out),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 按需给「发送请求」加超时:`None` 表示不设超时(服务器慢就继续等)。
|
||||
/// `Err(())` 只表示超时,这样调用方能把它与「请求失败」区分开(后者要回退 HEAD)。
|
||||
async fn send_with_optional_timeout(
|
||||
req: reqwest::RequestBuilder,
|
||||
timeout: Option<std::time::Duration>,
|
||||
) -> Result<reqwest::Result<reqwest::Response>, ()> {
|
||||
match timeout {
|
||||
Some(d) => tokio::time::timeout(d, req.send()).await.map_err(|_| ()),
|
||||
None => Ok(req.send().await),
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP/HTTPS 下载器
|
||||
#[derive(Clone)]
|
||||
pub struct HttpDownloader {
|
||||
client: Client,
|
||||
/// 直连客户端:强制禁用代理(no_proxy),用于降级重试与控制端探测
|
||||
direct_client: Client,
|
||||
/// mihomo 显式代理客户端缓存(与代理地址一一对应):走 http://127.0.0.1:{mixed_port}。
|
||||
/// 地址未配置(mihomo 未运行)时为 no_proxy 直连。Arc 共享同一状态,任意 clone 统一生效。
|
||||
mihomo: Arc<Mutex<(Option<String>, Client)>>,
|
||||
}
|
||||
|
||||
impl HttpDownloader {
|
||||
pub fn new() -> Self {
|
||||
let client = Client::builder()
|
||||
let direct_client = Client::builder()
|
||||
// 强制直连:即使系统代理已开启,下载也不经过系统代理
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap_or_else(|_| Client::new());
|
||||
Self { client }
|
||||
Self {
|
||||
direct_client: direct_client.clone(),
|
||||
mihomo: Arc::new(Mutex::new((None, direct_client))),
|
||||
}
|
||||
}
|
||||
|
||||
/// 配置 mihomo 显式代理客户端。
|
||||
/// - `Some("http://127.0.0.1:{port}")`:走本地 mihomo 的 mixed 端口;
|
||||
/// - `None`:回退直连(不走系统代理)。
|
||||
/// 地址未变化时复用缓存,不重复重建,避免丢失连接复用。
|
||||
pub fn configure_mihomo_proxy(&self, proxy_url: Option<String>) {
|
||||
let mut guard = self.mihomo.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if guard.0 == proxy_url {
|
||||
return;
|
||||
}
|
||||
let client = match &proxy_url {
|
||||
Some(url) => {
|
||||
let mut cb = Client::builder();
|
||||
if let Ok(p) = Proxy::all(url.clone()) {
|
||||
cb = cb.proxy(p);
|
||||
}
|
||||
cb.build().unwrap_or_else(|_| Client::new())
|
||||
}
|
||||
None => Client::builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.unwrap_or_else(|_| Client::new()),
|
||||
};
|
||||
*guard = (proxy_url, client);
|
||||
}
|
||||
|
||||
/// 探测 mihomo 外部控制端是否在线(用于判断代理模块是否真正运行)。
|
||||
/// 走直连客户端,避免探测本身依赖代理。
|
||||
pub async fn probe_controller(&self, controller: &str) -> bool {
|
||||
let url = format!("http://{}/version", controller);
|
||||
match tokio::time::timeout(
|
||||
std::time::Duration::from_secs(3),
|
||||
self.direct_client.get(&url).send(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(r)) => r.status().is_success(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 根据 use_proxy 选择客户端(克隆句柄,Client 内部共享连接池)
|
||||
fn client(&self, use_proxy: bool) -> Client {
|
||||
if use_proxy {
|
||||
self.mihomo
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.1
|
||||
.clone()
|
||||
} else {
|
||||
self.direct_client.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// 探测下载资源信息(大小、是否支持 Range、文件名)
|
||||
/// 优先用 GET + Range: bytes=0-0(返回 206 + Content-Range),回退到 HEAD
|
||||
/// 优先用 GET + Range: bytes=0-0(返回 206 + Content-Range),回退到 HEAD。
|
||||
/// 代理降级:use_proxy=true 时先走系统代理,失败则回退 no_proxy 直连重试一次。
|
||||
///
|
||||
/// `timeout`:`Some` 用于交互式探测(用户正等界面结果);`None` 表示不设超时
|
||||
/// (后台探测,如更新包下载,服务器慢就继续等)。
|
||||
pub async fn probe(
|
||||
&self,
|
||||
url: &str,
|
||||
headers: &HashMap<String, String>,
|
||||
use_proxy: bool,
|
||||
timeout: Option<std::time::Duration>,
|
||||
) -> Result<ProbeResult, String> {
|
||||
let first = self.client(use_proxy);
|
||||
match self.probe_with_client(&first, url, headers, timeout).await {
|
||||
Ok(r) => return Ok(r),
|
||||
Err(e) if use_proxy => {
|
||||
let direct = self.client(false);
|
||||
self.probe_with_client(&direct, url, headers, timeout)
|
||||
.await
|
||||
.map_err(|e2| format!("代理探测失败({}),直连重试也失败({})", e, e2))
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// 用指定 client 执行探测(GET Range → 回退 HEAD),供代理降级复用
|
||||
async fn probe_with_client(
|
||||
&self,
|
||||
client: &Client,
|
||||
url: &str,
|
||||
headers: &HashMap<String, String>,
|
||||
timeout: Option<std::time::Duration>,
|
||||
) -> Result<ProbeResult, String> {
|
||||
// 先尝试 Range 请求(能同时判断 Accept-Ranges 和获取大小)
|
||||
let mut req = self
|
||||
.client
|
||||
let mut req = client
|
||||
.get(url)
|
||||
.header("Range", "bytes=0-0")
|
||||
.header("User-Agent", "Thing-Download-Engine/1.0");
|
||||
@@ -49,10 +176,14 @@ impl HttpDownloader {
|
||||
req = req.header(k, v);
|
||||
}
|
||||
|
||||
match tokio::time::timeout(REQUEST_TIMEOUT, req.send())
|
||||
.await
|
||||
.map_err(|_| "探测超时(30s 内未收到响应头)".to_string())?
|
||||
{
|
||||
// 先拿到「发送结果」:超时(仅交互式探测会有)直接上抛,
|
||||
// 发送失败则回退 HEAD。注意不能把发送失败也上抛——那会让 HEAD 回退失效。
|
||||
let first = match send_with_optional_timeout(req, timeout).await {
|
||||
Err(()) => return Err("探测超时(未收到响应头)".to_string()),
|
||||
Ok(r) => r,
|
||||
};
|
||||
|
||||
match first {
|
||||
Ok(resp) => {
|
||||
let status = resp.status();
|
||||
let headers_map = resp.headers().clone();
|
||||
@@ -97,13 +228,13 @@ impl HttpDownloader {
|
||||
}
|
||||
Err(_) => {
|
||||
// GET 失败,尝试 HEAD 作为回退
|
||||
let mut head_req = self.client.head(url);
|
||||
let mut head_req = client.head(url);
|
||||
for (k, v) in headers {
|
||||
head_req = head_req.header(k, v);
|
||||
}
|
||||
let resp = tokio::time::timeout(REQUEST_TIMEOUT, head_req.send())
|
||||
let resp = send_with_optional_timeout(head_req, timeout)
|
||||
.await
|
||||
.map_err(|_| "探测超时(HEAD 30s 内未收到响应头)".to_string())?
|
||||
.map_err(|_| "探测超时(HEAD 未收到响应头)".to_string())?
|
||||
.map_err(|e| format!("探测失败(GET 和 HEAD 均失败): {}", e))?;
|
||||
let headers_map = resp.headers().clone();
|
||||
let total_size = headers_map
|
||||
@@ -132,6 +263,7 @@ impl HttpDownloader {
|
||||
/// - `cancel`: 取消标志
|
||||
/// - `progress`: 每个分段的已下载字节(AtomicU64,与 segments 一一对应)
|
||||
/// - `limiter`: 全局限速器
|
||||
/// - `use_proxy`: 是否使用系统代理(false=强制直连)
|
||||
pub async fn download(
|
||||
&self,
|
||||
url: &str,
|
||||
@@ -141,6 +273,37 @@ impl HttpDownloader {
|
||||
cancel: Arc<AtomicBool>,
|
||||
progress: &[Arc<AtomicU64>],
|
||||
limiter: Arc<RateLimiter>,
|
||||
use_proxy: bool,
|
||||
) -> Result<(), String> {
|
||||
// 代理降级:仅当 use_proxy=true 才有"走代理→失败回退直连"的意义。
|
||||
// use_proxy=false 直接用直连客户端,无需回退。
|
||||
// 注意:用户主动暂停/取消(返回"已取消")必须原样透传,不能触发代理回退,
|
||||
// 否则会把"已取消"包装成"代理失败",导致引擎将其误判为错误而非暂停。
|
||||
let first = self.client(use_proxy);
|
||||
match self.download_with_client(&first, url, headers, segments, file_path, cancel.clone(), progress, &limiter).await {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) if use_proxy && e != "已取消" => {
|
||||
// 回退直连重试(不继承 use_proxy,保证用 no_proxy 客户端)
|
||||
let direct = self.client(false);
|
||||
self.download_with_client(&direct, url, headers, segments, file_path, cancel, progress, &limiter)
|
||||
.await
|
||||
.map_err(|e2| format!("代理下载失败({}),直连重试也失败({})", e, e2))
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// 用指定 client 执行下载(支持单线程与多线程分段),供代理降级复用
|
||||
async fn download_with_client(
|
||||
&self,
|
||||
client: &Client,
|
||||
url: &str,
|
||||
headers: &HashMap<String, String>,
|
||||
segments: &[Segment],
|
||||
file_path: &Path,
|
||||
cancel: Arc<AtomicBool>,
|
||||
progress: &[Arc<AtomicU64>],
|
||||
limiter: &Arc<RateLimiter>,
|
||||
) -> Result<(), String> {
|
||||
let total_size = segments.iter().map(|s| s.len()).sum();
|
||||
|
||||
@@ -167,7 +330,7 @@ impl HttpDownloader {
|
||||
// 单线程下载(不支持 Range 或文件太小)
|
||||
let seg = &segments[0];
|
||||
let prog = &progress[0];
|
||||
self.download_segment(url, headers, seg, file_path, cancel.clone(), prog.clone(), limiter)
|
||||
self.download_segment(url, headers, seg, file_path, cancel.clone(), prog.clone(), limiter.clone(), client)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
@@ -187,7 +350,7 @@ impl HttpDownloader {
|
||||
.unwrap_or_default();
|
||||
let limiter = limiter.clone();
|
||||
let file_path = file_path.to_path_buf();
|
||||
let client = self.client.clone();
|
||||
let client = client.clone();
|
||||
|
||||
join_set.spawn(async move {
|
||||
download_segment_with_client(
|
||||
@@ -241,9 +404,10 @@ impl HttpDownloader {
|
||||
cancel: Arc<AtomicBool>,
|
||||
progress: Arc<AtomicU64>,
|
||||
limiter: Arc<RateLimiter>,
|
||||
client: &Client,
|
||||
) -> Result<(), String> {
|
||||
download_segment_with_client(
|
||||
&self.client,
|
||||
client,
|
||||
url,
|
||||
headers,
|
||||
seg,
|
||||
@@ -304,9 +468,10 @@ async fn download_segment_with_client(
|
||||
req = req.header(k, v);
|
||||
}
|
||||
|
||||
let resp = tokio::time::timeout(REQUEST_TIMEOUT, req.send())
|
||||
.await
|
||||
.map_err(|_| "请求超时(30s 内未收到响应头)".to_string())?
|
||||
// 等响应头:不设超时(服务器慢就继续等),但期间轮询取消标志,
|
||||
// 保证用户暂停/取消时能立刻中断这次请求。
|
||||
let resp = wait_cancellable(req.send(), &cancel)
|
||||
.await?
|
||||
.map_err(|e| format!("请求失败: {}", e))?;
|
||||
|
||||
let status = resp.status();
|
||||
@@ -336,9 +501,14 @@ async fn download_segment_with_client(
|
||||
return Err("已取消".to_string());
|
||||
}
|
||||
|
||||
// 停滞超时:30s 无数据即中断,确保 cancel 标志能及时被感知(配合代际句柄防并发写)
|
||||
match tokio::time::timeout(READ_STALL_TIMEOUT, stream.next()).await {
|
||||
Ok(Some(Ok(chunk))) => {
|
||||
// 读数据:**不做停滞超时**——30s 无数据不代表失败(慢速源、网络抖动很常见),
|
||||
// 只要用户没暂停就继续等。select 里那个 200ms 计时器只负责周期性回到循环头
|
||||
// 读一次取消标志:否则 `stream.next()` 一直 pending 时暂停/取消永远感知不到。
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = tokio::time::sleep(CANCEL_POLL_INTERVAL) => continue,
|
||||
next = stream.next() => match next {
|
||||
Some(Ok(chunk)) => {
|
||||
buf.extend_from_slice(&chunk);
|
||||
// 接收到数据立即更新进度(避免监控周期内进度无变化导致速度显示为 0)
|
||||
local_completed += chunk.len() as u64;
|
||||
@@ -353,10 +523,10 @@ async fn download_segment_with_client(
|
||||
buf.clear();
|
||||
}
|
||||
}
|
||||
Ok(Some(Err(e))) => {
|
||||
Some(Err(e)) => {
|
||||
return Err(format!("读取数据失败: {}", e));
|
||||
}
|
||||
Ok(None) => {
|
||||
None => {
|
||||
// 流结束,写入剩余数据
|
||||
if !buf.is_empty() {
|
||||
file.write_all(&buf)
|
||||
@@ -366,11 +536,18 @@ async fn download_segment_with_client(
|
||||
limiter.consume(buf.len() as u64).await;
|
||||
buf.clear();
|
||||
}
|
||||
// 校验:已知大小的分段若流提前结束(收到的字节数不足分段长度),
|
||||
// 说明服务器提前断开或返回不完整内容,不能标记为完成,否则文件会被截断
|
||||
if !unknown_size && local_completed < seg.len() {
|
||||
return Err(format!(
|
||||
"文件不完整:已接收 {} / {} 字节,服务器提前结束连接",
|
||||
local_completed,
|
||||
seg.len()
|
||||
));
|
||||
}
|
||||
break;
|
||||
}
|
||||
Err(_) => {
|
||||
return Err("读取超时(30s 无数据,已中断下载)".to_string());
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,10 +5,11 @@ pub mod rate_limit;
|
||||
pub mod server;
|
||||
pub mod storage;
|
||||
pub mod task;
|
||||
pub mod torrent;
|
||||
|
||||
pub use commands::{
|
||||
downloader_add_task, downloader_check_url, downloader_get_extension_info, downloader_get_settings, downloader_get_tasks,
|
||||
downloader_open_dir, downloader_open_url, downloader_pause_task, downloader_remove_task,
|
||||
downloader_add_task, downloader_cancel_task, downloader_check_url, downloader_focus_window, downloader_get_extension_info, downloader_get_settings, downloader_get_tasks, downloader_inspect, downloader_select_bt_files,
|
||||
downloader_open_dir, downloader_open_url, downloader_pause_task, downloader_redownload, downloader_remove_task,
|
||||
downloader_resume_task, downloader_save_settings, downloader_status,
|
||||
};
|
||||
pub use engine::DownloadEngine;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
@@ -9,13 +11,25 @@ use axum::{
|
||||
Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
|
||||
use super::engine::DownloadEngine;
|
||||
use super::task::DownloadTask;
|
||||
use super::task::{DownloadTask, TaskStatus};
|
||||
|
||||
/// 扩展 HTTP API 服务器
|
||||
pub struct ExtensionServer;
|
||||
|
||||
/// 最近处理过的下载 URL(短窗口去重):记录对应任务 id 与创建时刻,
|
||||
/// 用于拦截"探测期间并发 POST"与"任务已结束但扩展重试"造成的重复创建
|
||||
#[derive(Clone)]
|
||||
struct RecentEntry {
|
||||
id: String,
|
||||
at: Instant,
|
||||
}
|
||||
|
||||
/// 同 URL 去重窗口:窗口内重复 POST 复用既有任务 id
|
||||
const DEDUP_WINDOW: Duration = Duration::from_secs(30);
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct HealthResponse {
|
||||
ok: bool,
|
||||
@@ -45,14 +59,19 @@ struct ErrorResponse {
|
||||
|
||||
impl ExtensionServer {
|
||||
/// 启动 HTTP API 服务器(绑定到 127.0.0.1:port)
|
||||
pub async fn start(engine: DownloadEngine, port: u16, secret: String) {
|
||||
pub async fn start(engine: DownloadEngine, port: u16, secret: String, app_handle: AppHandle) {
|
||||
let addr: SocketAddr = format!("127.0.0.1:{}", port).parse().expect("无效端口");
|
||||
|
||||
let app = Router::new()
|
||||
.route("/health", get(health))
|
||||
.route("/api/downloads", post(create_download).get(list_downloads))
|
||||
.route("/api/downloads/:id", axum::routing::delete(remove_download))
|
||||
.with_state(AppState { engine, secret });
|
||||
.with_state(AppState {
|
||||
engine,
|
||||
secret,
|
||||
app_handle,
|
||||
recent: Arc::new(Mutex::new(HashMap::new())),
|
||||
});
|
||||
|
||||
let listener = match tokio::net::TcpListener::bind(&addr).await {
|
||||
Ok(l) => l,
|
||||
@@ -74,6 +93,9 @@ impl ExtensionServer {
|
||||
struct AppState {
|
||||
engine: DownloadEngine,
|
||||
secret: String,
|
||||
app_handle: AppHandle,
|
||||
/// 最近创建的 URL→任务 id(短窗口去重)
|
||||
recent: Arc<Mutex<HashMap<String, RecentEntry>>>,
|
||||
}
|
||||
|
||||
/// 鉴权检查:如果配置了 secret,校验 Bearer token
|
||||
@@ -108,8 +130,48 @@ async fn create_download(
|
||||
return Err((StatusCode::UNAUTHORIZED, Json(ErrorResponse { error: "未授权".into() })));
|
||||
}
|
||||
|
||||
match state.engine.add_task(req.url, req.filename, req.dir, req.headers, true).await {
|
||||
Ok(id) => Ok(Json(CreateDownloadResponse { id })),
|
||||
// 1. 检查短窗口缓存:同 URL 30s 内已有创建记录,直接返回(拦截浏览器/扩展重试和并发 POST)
|
||||
{
|
||||
let mut recent = state.recent.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(entry) = recent.get(&req.url) {
|
||||
if entry.at.elapsed() < DEDUP_WINDOW {
|
||||
// 30 秒内重复请求 → 返回已创建任务 id,不重复新建
|
||||
return Ok(Json(CreateDownloadResponse { id: entry.id.clone() }));
|
||||
} else {
|
||||
// 窗口过期 → 删除旧记录继续检查引擎层去重
|
||||
recent.remove(&req.url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 引擎层去重:同 URL 已有非终态任务(活跃/排队/暂停)时直接返回既有任务,
|
||||
// 避免浏览器重复转发同一下载造成重复下载
|
||||
if let Some(existing) = state.engine.get_tasks().into_iter().find(|t| {
|
||||
matches!(t.status, TaskStatus::Active | TaskStatus::Queued | TaskStatus::Paused) && t.url == req.url
|
||||
}) {
|
||||
// 添加到短窗口缓存以便拦截重试
|
||||
let mut recent = state.recent.lock().unwrap_or_else(|e| e.into_inner());
|
||||
recent.insert(req.url.clone(), RecentEntry { id: existing.id.clone(), at: Instant::now() });
|
||||
return Ok(Json(CreateDownloadResponse { id: existing.id }));
|
||||
}
|
||||
|
||||
// add_task 会 move 掉 req 的字段,先取出 url 供去重缓存使用
|
||||
let task_url = req.url.clone();
|
||||
match state.engine.add_task(req.url, req.filename, req.dir, req.headers, true, None).await {
|
||||
Ok(id) => {
|
||||
// 记录到短窗口缓存:拦截后续同一 URL 的重复转发/重试
|
||||
let url = task_url.clone();
|
||||
let mut recent = state.recent.lock().unwrap_or_else(|e| e.into_inner());
|
||||
recent.insert(url, RecentEntry { id: id.clone(), at: Instant::now() });
|
||||
drop(recent);
|
||||
// 浏览器扩展发起下载:不再置前主窗口,改为带 task id 通知前端,
|
||||
// 由前端为该任务创建一个专属的一次性下载窗口(不打断主界面)
|
||||
let _ = state.app_handle.emit(
|
||||
crate::constants::events::DOWNLOAD_EXTENSION_ADDED,
|
||||
serde_json::json!({ "id": id }),
|
||||
);
|
||||
Ok(Json(CreateDownloadResponse { id }))
|
||||
}
|
||||
Err(e) => Err((StatusCode::BAD_REQUEST, Json(ErrorResponse { error: e }))),
|
||||
}
|
||||
}
|
||||
@@ -133,7 +195,11 @@ async fn remove_download(
|
||||
return Err((StatusCode::UNAUTHORIZED, Json(ErrorResponse { error: "未授权".into() })));
|
||||
}
|
||||
match state.engine.remove_task(&id, false) {
|
||||
Ok(()) => Ok(StatusCode::NO_CONTENT),
|
||||
Ok(()) => {
|
||||
// 通知前端刷新任务列表(扩展删除时前端无从感知,否则列表残留已删除任务)
|
||||
let _ = state.app_handle.emit(crate::constants::events::DOWNLOAD_REMOVED, serde_json::json!({ "id": id }));
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
Err(e) => Err((StatusCode::NOT_FOUND, Json(ErrorResponse { error: e }))),
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,17 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// 任务下载协议类型
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Type, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum TaskProtocol {
|
||||
/// HTTP/HTTPS 直链
|
||||
#[default]
|
||||
Http,
|
||||
/// BitTorrent(磁力链 / .torrent 文件)
|
||||
BitTorrent,
|
||||
}
|
||||
|
||||
/// 任务状态
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Type)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
@@ -16,6 +27,8 @@ pub enum TaskStatus {
|
||||
Complete,
|
||||
/// 错误
|
||||
Error,
|
||||
/// 已取消(用户取消:进度与文件已清除,仅保留记录,只能再次下载)
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// 下载分段(多线程 Range 下载 / 断点续传用)
|
||||
@@ -37,24 +50,57 @@ impl Segment {
|
||||
pub fn len(&self) -> u64 {
|
||||
self.end.saturating_sub(self.start) + 1
|
||||
}
|
||||
/// 是否为未知大小哨兵段(start=0, end=0,表示不支持 Range 或未探测到大小)
|
||||
pub fn is_unknown_size(&self) -> bool {
|
||||
self.start == 0 && self.end == 0
|
||||
}
|
||||
/// 是否已完成
|
||||
pub fn is_done(&self) -> bool {
|
||||
// 未知大小段无法用长度判断是否完成,由流结束(Ok(None))判定;
|
||||
// 若按 len()=1 判断,暂停/恢复后 completed>=1 会误判为已完成,导致文件被截断
|
||||
if self.is_unknown_size() {
|
||||
return false;
|
||||
}
|
||||
self.completed >= self.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// BT 种子内文件条目(多文件任务用;阶段1下载全部文件,但保留列表供 UI 展示)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BtFileInfo {
|
||||
/// 文件在种子内的索引
|
||||
pub index: u32,
|
||||
/// 相对种子根目录的路径(如 "sub/file.mkv")
|
||||
pub path: String,
|
||||
/// 文件大小(字节)
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
/// 下载任务
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DownloadTask {
|
||||
/// 任务 ID(自增 hex 字符串)
|
||||
pub id: String,
|
||||
/// 下载地址
|
||||
/// 下载地址(HTTP URL 或磁力链接)
|
||||
pub url: String,
|
||||
/// 文件名
|
||||
/// 文件名(HTTP:目标文件名;BT:种子名称)
|
||||
pub filename: String,
|
||||
/// 保存目录(绝对路径)
|
||||
pub dir: String,
|
||||
/// 协议类型
|
||||
#[serde(default)]
|
||||
pub protocol: TaskProtocol,
|
||||
/// BT 种子 infohash(协议=BitTorrent 时存在)
|
||||
#[serde(default)]
|
||||
pub info_hash: Option<String>,
|
||||
/// BT 种子内文件列表(协议=BitTorrent 时存在)
|
||||
#[serde(default)]
|
||||
pub bt_files: Vec<BtFileInfo>,
|
||||
/// BT 元数据是否已解析就绪(异步添加时:后台解析完成前为 false,调度器跳过)
|
||||
#[serde(default)]
|
||||
pub bt_metadata_ready: bool,
|
||||
/// 状态
|
||||
pub status: TaskStatus,
|
||||
/// 文件总大小(字节),0=未知
|
||||
@@ -129,6 +175,21 @@ pub struct DownloaderSettings {
|
||||
/// 添加下载前检查重复(URL 或文件名重复时询问)
|
||||
#[serde(default = "default_true")]
|
||||
pub check_duplicate: bool,
|
||||
/// 下载是否使用代理:true=尊重系统代理(mihomo 开启系统代理时经其转发),false=强制直连
|
||||
#[serde(default = "default_true")]
|
||||
pub use_proxy: bool,
|
||||
/// BitTorrent 上传限速 KB/s(0=不限)
|
||||
#[serde(default)]
|
||||
pub bt_upload_limit_kb: u64,
|
||||
/// BitTorrent 下载完成后是否继续做种上传(false=下载完即停止上传)
|
||||
#[serde(default)]
|
||||
pub bt_seed_after_download: bool,
|
||||
/// BitTorrent 监听端口(0=自动选择)
|
||||
#[serde(default)]
|
||||
pub bt_listen_port: u16,
|
||||
/// BitTorrent 使用代理下载:开启后自动使用代理模块(mihomo)的 SOCKS5 端口;代理不可用时降级直连
|
||||
#[serde(default)]
|
||||
pub bt_use_proxy: bool,
|
||||
}
|
||||
|
||||
fn default_max_concurrent() -> u32 {
|
||||
@@ -167,6 +228,11 @@ impl Default for DownloaderSettings {
|
||||
extension_secret: String::new(),
|
||||
delete_files_on_remove: false,
|
||||
check_duplicate: true,
|
||||
use_proxy: true,
|
||||
bt_upload_limit_kb: 0,
|
||||
bt_seed_after_download: false,
|
||||
bt_listen_port: 0,
|
||||
bt_use_proxy: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
// 会话字段专用 tokio 异步互斥(与 std 互斥区分开):
|
||||
// 创建 Session 是 async 操作,必须持锁跨 await,否则"双重检查"在 await 期间失效,
|
||||
// 并发首次添加 BT 任务可能各建一个全局会话,产生孤儿会话与跨会话无效句柄。
|
||||
use tokio::sync::Mutex as AsyncMutex;
|
||||
|
||||
use librqbit::api::TorrentIdOrHash;
|
||||
use librqbit::{AddTorrent, AddTorrentOptions, AddTorrentResponse, ManagedTorrent, Session};
|
||||
|
||||
use super::task::BtFileInfo;
|
||||
|
||||
/// 磁力元数据解析超时(秒):依赖 DHT/tracker 拉取,过短易误报,过长体验差
|
||||
pub(crate) const INSPECT_TIMEOUT_SECS: u64 = 60;
|
||||
|
||||
/// 每日 tracker 同步源(XIU2/TrackersListCollection,官方新域名 cf.trackerslist.com)。
|
||||
/// 注意:GitHub 仓库 raw 路径(raw.githubusercontent.com/...trackers_best.txt)已随项目
|
||||
/// 迁移失效(404),不要再用 GitHub 代理镜像。以下为官方 Cloudflare 分发地址,
|
||||
/// 国内直连通常可达,按顺序尝试、首个成功即用。
|
||||
const TRACKER_SYNC_SOURCES: &[&str] = &[
|
||||
"https://cf.trackerslist.com/best.txt",
|
||||
"https://trackerslist.com/best.txt",
|
||||
"https://cf.trackerslist.com/all.txt",
|
||||
];
|
||||
/// 动态 tracker 持久化文件与同步元数据
|
||||
const TRACKERS_FILE: &str = "bt_trackers.txt";
|
||||
const TRACKERS_META_FILE: &str = "bt_trackers_meta.json";
|
||||
|
||||
/// 常用公共 tracker:磁力链接本身可能只带很少 tracker,追加这些可提升解析成功率。
|
||||
/// 混合 UDP/HTTP(S)/WebSocket,覆盖 UDP 被屏蔽但 HTTP 可用的网络环境。
|
||||
pub const PUBLIC_TRACKERS: &[&str] = &[
|
||||
// UDP
|
||||
"udp://tracker.opentrackr.org:1337/announce",
|
||||
"udp://open.tracker.cl:1337/announce",
|
||||
"udp://tracker.openbittorrent.com:6969/announce",
|
||||
"udp://tracker.torrent.eu.org:451/announce",
|
||||
"udp://open.stealth.si:80/announce",
|
||||
"udp://exodus.desync.com:6969/announce",
|
||||
"udp://tracker.tiny-vps.com:6969/announce",
|
||||
"udp://open.demonii.com:1337/announce",
|
||||
"udp://tracker.moeking.me:6969/announce",
|
||||
"udp://ipv4.tracker.harry.lu:80/announce",
|
||||
"udp://explodie.org:6969/announce",
|
||||
"udp://tracker.birkenfeld.ru:7496/announce",
|
||||
"udp://tracker.pomf.se:80/announce",
|
||||
"udp://tracker.tamersunion.org:6969/announce",
|
||||
"udp://retracker.lanta-net.ru:2710/announce",
|
||||
// HTTP(S)
|
||||
"http://tracker.opentrackr.org:1337/announce",
|
||||
"http://tracker.openbittorrent.com:80/announce",
|
||||
"http://tracker1.itzmx.com:8080/announce",
|
||||
"http://tracker4.itzmx.com:2710/announce",
|
||||
"https://tracker.gbitt.info:443/announce",
|
||||
"https://tracker.nanoha.org:443/announce",
|
||||
"http://tracker.bt4g.com:2095/announce",
|
||||
"http://tracker.gbitt.info:80/announce",
|
||||
];
|
||||
|
||||
/// 种子信息(inspect 解析结果,供命令返回给前端做文件勾选)
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TorrentInfo {
|
||||
/// 种子名称
|
||||
pub name: String,
|
||||
/// infohash(hex 小写字符串)
|
||||
pub info_hash: String,
|
||||
/// 种子内全部文件总大小(字节)
|
||||
pub total_size: u64,
|
||||
/// 种子内文件列表
|
||||
pub files: Vec<BtFileInfo>,
|
||||
}
|
||||
|
||||
/// BitTorrent 下载器:封装 librqbit 全局会话(多任务共享 DHT / 监听端口 / tracker 缓存)。
|
||||
/// 会话懒创建:只有真正添加 BT 任务时才初始化,避免引擎启动即拉起 BT 内核。
|
||||
#[derive(Clone)]
|
||||
pub struct TorrentDownloader {
|
||||
/// 全局会话(懒创建;tokio 异步互斥保证并发首次添加只创建一个会话)
|
||||
session: Arc<AsyncMutex<Option<Arc<Session>>>>,
|
||||
/// 会话默认输出目录(每个任务用 AddTorrentOptions.output_folder 覆盖)
|
||||
base_dir: PathBuf,
|
||||
/// 上传限速 bytes/s(0=不限),per-torrent 应用
|
||||
upload_limit_bps: Arc<std::sync::atomic::AtomicU64>,
|
||||
/// 监听端口(0=自动)
|
||||
listen_port: Arc<std::sync::atomic::AtomicU16>,
|
||||
/// SOCKS5 代理地址(None=直连;来自代理模块,不可用时降级直连)
|
||||
proxy_addr: Arc<Mutex<Option<String>>>,
|
||||
/// 动态公共 tracker(每日从外部列表同步,叠加到内置列表)
|
||||
dynamic_trackers: Arc<RwLock<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl TorrentDownloader {
|
||||
pub fn new(base_dir: PathBuf) -> Self {
|
||||
Self {
|
||||
session: Arc::new(AsyncMutex::new(None)),
|
||||
base_dir,
|
||||
upload_limit_bps: Arc::new(std::sync::atomic::AtomicU64::new(0)),
|
||||
listen_port: Arc::new(std::sync::atomic::AtomicU16::new(0)),
|
||||
proxy_addr: Arc::new(Mutex::new(None)),
|
||||
dynamic_trackers: Arc::new(RwLock::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 更新 BT 专属设置(上传限速 KB/s、监听端口、SOCKS5 代理地址)— 会话创建时生效
|
||||
pub fn set_settings(&self, upload_limit_kb: u64, listen_port: u16, proxy_addr: Option<String>) {
|
||||
self.upload_limit_bps
|
||||
.store(upload_limit_kb.saturating_mul(1024), std::sync::atomic::Ordering::SeqCst);
|
||||
self.listen_port
|
||||
.store(listen_port, std::sync::atomic::Ordering::SeqCst);
|
||||
*self.proxy_addr.lock().unwrap_or_else(|e| e.into_inner()) = proxy_addr;
|
||||
}
|
||||
|
||||
/// 设置动态 tracker(合并去重)
|
||||
pub fn add_dynamic_trackers(&self, list: Vec<String>) {
|
||||
if list.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut g = self.dynamic_trackers.write().unwrap_or_else(|e| e.into_inner());
|
||||
for t in list {
|
||||
let t = t.trim().to_string();
|
||||
if !t.is_empty() && !g.contains(&t) {
|
||||
g.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前动态 tracker 数量
|
||||
pub fn dynamic_count(&self) -> usize {
|
||||
self.dynamic_trackers.read().unwrap_or_else(|e| e.into_inner()).len()
|
||||
}
|
||||
|
||||
/// 合并内置 + 动态 tracker(去重),供 inspect / add_async 共用
|
||||
fn build_trackers(&self) -> Vec<String> {
|
||||
let dyn_trackers = self.dynamic_trackers.read().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
let mut trackers: Vec<String> = PUBLIC_TRACKERS.iter().map(|s| s.to_string()).collect();
|
||||
for t in dyn_trackers {
|
||||
if !trackers.contains(&t) {
|
||||
trackers.push(t);
|
||||
}
|
||||
}
|
||||
trackers
|
||||
}
|
||||
|
||||
/// 每日同步动态 tracker:读取本地缓存 → 判断今天是否已同步 → 未同步则拉取更新。
|
||||
/// 失败静默降级:保留上次成功的列表。
|
||||
pub async fn sync_dynamic_trackers(&self, data_dir: &Path) {
|
||||
fn parse_list(text: &str) -> Vec<String> {
|
||||
text.lines()
|
||||
.map(|l| l.trim())
|
||||
.filter(|l| l.starts_with("http://") || l.starts_with("https://") || l.starts_with("udp://") || l.starts_with("ws://") || l.starts_with("wss://"))
|
||||
.map(|l| l.to_string())
|
||||
.collect()
|
||||
}
|
||||
let trackers_path = data_dir.join(TRACKERS_FILE);
|
||||
let meta_path = data_dir.join(TRACKERS_META_FILE);
|
||||
let today = chrono::Local::now().format("%Y-%m-%d").to_string();
|
||||
|
||||
// 1. 先加载上次成功保存的列表到内存(覆盖"重启后内存被清空")
|
||||
if let Ok(s) = std::fs::read_to_string(&trackers_path) {
|
||||
self.add_dynamic_trackers(parse_list(&s));
|
||||
}
|
||||
|
||||
// 2. 今天已同步过则不再下载
|
||||
if let Ok(meta) = std::fs::read_to_string(&meta_path) {
|
||||
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&meta) {
|
||||
if v.get("date").and_then(|d| d.as_str()) == Some(&today) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 依次尝试各镜像源(记录每个源的失败原因,便于判断是 DNS 还是连接超时)
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(10))
|
||||
.build()
|
||||
.ok();
|
||||
for url in TRACKER_SYNC_SOURCES {
|
||||
let Some(c) = &client else { break };
|
||||
match c.get(*url).send().await {
|
||||
Err(e) => {
|
||||
crate::logger::log_line("download", crate::logger::LogLevel::Debug, &format!("动态 tracker 源不可达 {}: {}", url, e));
|
||||
continue;
|
||||
}
|
||||
Ok(resp) => {
|
||||
let text = match resp.text().await {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
crate::logger::log_line("download", crate::logger::LogLevel::Debug, &format!("动态 tracker 源读取失败 {}: {}", url, e));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let list = parse_list(&text);
|
||||
if list.is_empty() {
|
||||
crate::logger::log_line("download", crate::logger::LogLevel::Debug, &format!("动态 tracker 源返回空列表 {}", url));
|
||||
continue;
|
||||
}
|
||||
// 保存列表与同步元数据
|
||||
let _ = std::fs::write(&trackers_path, format!("{}\n", list.join("\n")));
|
||||
let _ = std::fs::write(&meta_path, serde_json::json!({ "date": today }).to_string());
|
||||
self.add_dynamic_trackers(list);
|
||||
crate::logger::log_info("download", &format!("已同步动态 tracker(共 {} 条)", self.dynamic_count()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::logger::log_warn("download", "动态 tracker 全部同步源不可达,使用上次成功列表或内置列表(不影响磁力解析,公共 tracker 仍会生效)");
|
||||
}
|
||||
|
||||
/// 会话级公共 tracker(HashSet<Url>,供 SessionOptions.trackers 使用)。
|
||||
/// 注意:librqbit 对磁力链接只采用 magnet URL 自带的 tr= 参数,完全忽略
|
||||
/// AddTorrentOptions.trackers(见 librqbit session.rs 的 magnet 分支),导致
|
||||
/// 纯磁力(无自带 tr)解析元数据时 "trackers list is empty"。而会话级
|
||||
/// SessionOptions.trackers 会在 make_peer_rx 中合并进每个种子(含磁力),
|
||||
/// 因此必须放到这里才能让磁力链接真正带上公共 tracker。
|
||||
fn session_trackers(&self) -> std::collections::HashSet<url::Url> {
|
||||
self.build_trackers()
|
||||
.into_iter()
|
||||
.filter_map(|t| url::Url::parse(&t).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 获取或创建全局会话。
|
||||
/// 持 tokio 互斥锁覆盖整个构造过程:并发调用在此串行化,
|
||||
/// 先进入者创建并写入,后续者锁内二次检查直接复用(避免多会话竞态)。
|
||||
/// 开启代理时先尝试用代理初始化;失败则降级为直连(记录下来供 add 重试判断)。
|
||||
async fn get_session(&self) -> Result<Arc<Session>, String> {
|
||||
let mut guard = self.session.lock().await;
|
||||
if let Some(s) = guard.as_ref() {
|
||||
return Ok(s.clone());
|
||||
}
|
||||
let _ = std::fs::create_dir_all(&self.base_dir);
|
||||
let port = self.listen_port.load(std::sync::atomic::Ordering::SeqCst);
|
||||
let proxy = self.proxy_addr.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
let connect_opt = proxy.as_ref().map(|p| librqbit::ConnectionOptions { proxy_url: Some(p.clone()), ..Default::default() });
|
||||
let had_proxy = connect_opt.is_some();
|
||||
|
||||
// 构造带代理(若启用)+ 监听端口 + 会话级公共 tracker 的会话选项
|
||||
let mut opts = lib_session_options();
|
||||
opts.trackers = self.session_trackers();
|
||||
if connect_opt.is_some() {
|
||||
opts.connect = connect_opt;
|
||||
}
|
||||
if port > 0 {
|
||||
if let Ok(addr) = format!("0.0.0.0:{}", port).parse::<std::net::SocketAddr>() {
|
||||
opts.listen = Some(librqbit::ListenerOptions {
|
||||
listen_addr: addr,
|
||||
..Default::default()
|
||||
});
|
||||
} else {
|
||||
crate::logger::log_error("download", &format!("BT 监听端口 {} 无效,使用自动端口", port));
|
||||
}
|
||||
}
|
||||
// 尝试创建会话:先按配置(可能带代理),失败且有代理则降级直连重试
|
||||
let s = match Session::new_with_opts(self.base_dir.clone(), opts).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
if had_proxy {
|
||||
crate::logger::log_error("download", &format!("BT 代理会话初始化失败({}),降级为直连", e));
|
||||
let mut m = lib_session_options();
|
||||
m.trackers = self.session_trackers();
|
||||
if port > 0 {
|
||||
if let Ok(addr) = format!("0.0.0.0:{}", port).parse::<std::net::SocketAddr>() {
|
||||
m.listen = Some(librqbit::ListenerOptions { listen_addr: addr, ..Default::default() });
|
||||
}
|
||||
}
|
||||
Session::new_with_opts(self.base_dir.clone(), m).await.map_err(|e2| format!("初始化 BitTorrent 会话失败: {}", e2))?
|
||||
} else {
|
||||
return Err(format!("初始化 BitTorrent 会话失败: {}", e));
|
||||
}
|
||||
}
|
||||
};
|
||||
*guard = Some(s.clone());
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// 解析磁力链 / 本地 .torrent 文件,返回种子信息(不开始下载)。
|
||||
/// list_only 模式:仅获取元数据,不加入会话,因此不影响后续真正添加。
|
||||
/// 磁力元数据依赖 DHT/tracker 拉取,无超时会永久等待,故加超时。
|
||||
pub async fn inspect(&self, input: &str) -> Result<TorrentInfo, String> {
|
||||
let session = self.get_session().await?;
|
||||
let trackers = self.build_trackers();
|
||||
// 磁力:需从网络拉取元数据,可能较慢(取决于种子热度与网络连通性);
|
||||
// 本地 .torrent / http(s) .torrent URL:元数据在文件内,from_cli_argument 会读取/下载并解析
|
||||
let add = AddTorrent::from_cli_argument(input).map_err(|e| format!("无效的种子输入: {}", e))?;
|
||||
let add_fut = session.add_torrent(
|
||||
add,
|
||||
Some(AddTorrentOptions {
|
||||
list_only: true,
|
||||
trackers: Some(trackers),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
let resp = tokio::time::timeout(std::time::Duration::from_secs(INSPECT_TIMEOUT_SECS), add_fut)
|
||||
.await
|
||||
.map_err(|_| "解析磁力元数据超时:未能从 DHT/Tracker 获取种子信息,请确认种子有做种源或网络可直连 BT".to_string())?
|
||||
.map_err(|e| format!("解析种子失败: {}", e))?;
|
||||
|
||||
let AddTorrentResponse::ListOnly(lo) = resp else {
|
||||
return Err("该链接未返回有效的种子元数据".to_string());
|
||||
};
|
||||
|
||||
let info = lo.info.info();
|
||||
let name = info
|
||||
.name
|
||||
.as_ref()
|
||||
.map(|b| String::from_utf8_lossy(b.as_ref()).into_owned())
|
||||
.or_else(|| lo.info.name().map(|c| c.to_string()))
|
||||
.unwrap_or_else(|| "未命名种子".to_string());
|
||||
|
||||
let mut files = Vec::new();
|
||||
let mut total_size = 0u64;
|
||||
if let Some(fs) = &info.files {
|
||||
for (i, f) in fs.iter().enumerate() {
|
||||
let path = f
|
||||
.path
|
||||
.iter()
|
||||
.map(|p| String::from_utf8_lossy(p.as_ref()).into_owned())
|
||||
.collect::<Vec<_>>()
|
||||
.join("/");
|
||||
files.push(BtFileInfo {
|
||||
index: i as u32,
|
||||
path,
|
||||
size: f.length,
|
||||
});
|
||||
total_size += f.length;
|
||||
}
|
||||
} else if let Some(len) = info.length {
|
||||
// 单文件种子
|
||||
files.push(BtFileInfo {
|
||||
index: 0,
|
||||
path: name.clone(),
|
||||
size: len,
|
||||
});
|
||||
total_size = len;
|
||||
}
|
||||
|
||||
Ok(TorrentInfo {
|
||||
name,
|
||||
info_hash: hex_encode(&lo.info_hash.0),
|
||||
total_size,
|
||||
files,
|
||||
})
|
||||
}
|
||||
|
||||
/// 异步添加种子:立即返回句柄(不等待元数据),由调用方后台解析。
|
||||
/// 附加公共 tracker 提升磁力元数据解析成功率;上传限速 per-torrent 应用。
|
||||
pub async fn add_async(
|
||||
&self,
|
||||
input: &str,
|
||||
output_dir: &str,
|
||||
) -> Result<(usize, Arc<ManagedTorrent>), String> {
|
||||
let session = self.get_session().await?;
|
||||
std::fs::create_dir_all(output_dir).map_err(|e| format!("创建下载目录失败: {}", e))?;
|
||||
let up = self.upload_limit_bps.load(std::sync::atomic::Ordering::SeqCst);
|
||||
let upload_bps = std::num::NonZeroU32::new(up.min(u32::MAX as u64) as u32);
|
||||
let trackers = self.build_trackers();
|
||||
let opts = AddTorrentOptions {
|
||||
paused: true,
|
||||
output_folder: Some(output_dir.to_string()),
|
||||
overwrite: true,
|
||||
trackers: Some(trackers),
|
||||
ratelimits: librqbit::limits::LimitsConfig {
|
||||
upload_bps,
|
||||
download_bps: None,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let add = AddTorrent::from_cli_argument(input).map_err(|e| format!("无效的种子输入: {}", e))?;
|
||||
let resp = session
|
||||
.add_torrent(add, Some(opts))
|
||||
.await
|
||||
.map_err(|e| format!("添加种子失败: {}", e))?;
|
||||
match resp {
|
||||
AddTorrentResponse::Added(id, handle) => Ok((id, handle)),
|
||||
AddTorrentResponse::AlreadyManaged(id, handle) => Ok((id, handle)),
|
||||
_ => Err("种子已存在或元数据无效".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 等待种子元数据初始化就绪(磁力需要从网络拉取,带超时)
|
||||
pub async fn wait_initialized(&self, handle: &Arc<ManagedTorrent>) -> Result<(), String> {
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(INSPECT_TIMEOUT_SECS),
|
||||
handle.wait_until_initialized(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| "解析磁力元数据超时:未能从 DHT/Tracker 获取种子信息,请确认种子有做种源或网络可直连 BT".to_string())?
|
||||
.map_err(|e| format!("获取种子元数据失败: {}", e))
|
||||
}
|
||||
|
||||
/// 设置要下载的种子文件子集(用户文件勾选;传全部索引则全选)
|
||||
pub async fn set_only_files(&self, handle: &Arc<ManagedTorrent>, files: &[u32]) -> Result<(), String> {
|
||||
let session = self.get_session().await?;
|
||||
let set: std::collections::HashSet<usize> = files.iter().map(|&i| i as usize).collect();
|
||||
session
|
||||
.update_only_files(handle, &set)
|
||||
.await
|
||||
.map_err(|e| format!("设置下载文件失败: {}", e))
|
||||
}
|
||||
|
||||
/// 读取句柄当前进度:返回 (已下载字节, 总字节, 每文件已下载字节)
|
||||
/// `file_progress` 与种子文件一一对应,供前端详情页展示单文件进度。
|
||||
pub fn progress_full(handle: &Arc<ManagedTorrent>) -> (u64, u64, Vec<u64>) {
|
||||
let s = handle.stats();
|
||||
(s.progress_bytes, s.total_bytes, s.file_progress.clone())
|
||||
}
|
||||
|
||||
/// 暂停种子(下载中的连接会停止,已下载片段保留,可继续)
|
||||
pub async fn pause(&self, handle: &Arc<ManagedTorrent>) -> Result<(), String> {
|
||||
let session = self.get_session().await?;
|
||||
session
|
||||
.pause(handle)
|
||||
.await
|
||||
.map_err(|e| format!("暂停种子失败: {}", e))
|
||||
}
|
||||
|
||||
/// 继续种子(幂等):恢复已暂停的种子。
|
||||
/// 若种子本已处于 Live(例如 select_bt_files 的 set_only_files 内部已恢复过、
|
||||
/// 或暂停期间被其他逻辑恢复),直接视为成功,避免 librqbit 报 "torrent is already live"
|
||||
/// 而导致 pause→resume 链路被误判为失败。
|
||||
pub async fn unpause(&self, handle: &Arc<ManagedTorrent>) -> Result<(), String> {
|
||||
let session = self.get_session().await?;
|
||||
match handle.stats().state {
|
||||
librqbit::TorrentStatsState::Live => Ok(()),
|
||||
librqbit::TorrentStatsState::Error => Err("种子处于错误状态,无法继续".to_string()),
|
||||
librqbit::TorrentStatsState::Paused
|
||||
| librqbit::TorrentStatsState::Initializing { .. } => session
|
||||
.unpause(handle)
|
||||
.await
|
||||
.map_err(|e| format!("继续种子失败: {}", e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 删除种子(info_hash 为 hex 字符串;delete_files 是否同时删除已下载文件)
|
||||
pub async fn delete(&self, info_hash: &str, delete_files: bool) -> Result<(), String> {
|
||||
let session = self.get_session().await?;
|
||||
let id = TorrentIdOrHash::parse(info_hash)
|
||||
.map_err(|_| format!("无效的 infohash: {}", info_hash))?;
|
||||
session
|
||||
.delete(id, delete_files)
|
||||
.await
|
||||
.map_err(|e| format!("删除种子失败: {}", e))
|
||||
}
|
||||
|
||||
/// 读取句柄当前下载进度 (已下载字节, 总字节)
|
||||
pub fn progress(handle: &Arc<ManagedTorrent>) -> (u64, u64) {
|
||||
let s = handle.stats();
|
||||
(s.progress_bytes, s.total_bytes)
|
||||
}
|
||||
|
||||
/// 停止全局会话(应用退出时调用)
|
||||
pub async fn stop(&self) {
|
||||
let session = {
|
||||
let mut guard = self.session.lock().await;
|
||||
guard.take()
|
||||
};
|
||||
if let Some(s) = session {
|
||||
let _ = s.stop().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 字节数组转小写十六进制字符串(librqbit 的 Id 未实现 Display)
|
||||
pub(crate) fn hex_encode(bytes: &[u8]) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for &b in bytes {
|
||||
out.push(HEX[(b >> 4) as usize] as char);
|
||||
out.push(HEX[(b & 0x0f) as usize] as char);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 默认会话选项(后续如需新增 DHT/缓存等可在此统一配置)
|
||||
fn lib_session_options() -> librqbit::SessionOptions {
|
||||
librqbit::SessionOptions::default()
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
//! 子窗口拖放「补注入」(仅 Windows 真正生效,其它平台是 no-op)。
|
||||
//!
|
||||
//! # 为什么需要这个模块
|
||||
//!
|
||||
//! wry 只在**创建 webview 的那一刻**枚举一次子窗口、给它们注入 OLE drop target
|
||||
//! (见 wry `webview2/drag_drop.rs` 的 `DragDropController::new` 里那句
|
||||
//! `EnumChildWindows`)。而 WebView2 的 `Chrome_WidgetWin_1` /
|
||||
//! `Chrome_RenderWidgetHostHWND` 是**异步惰性创建**的:
|
||||
//!
|
||||
//! - 由 `tauri.conf.json` 在 setup 阶段创建的主窗口 —— 注入时这些子窗口已存在,正常;
|
||||
//! - 运行时经 IPC 创建的窗口(编辑器 / 对比,`new WebviewWindow`)—— 注入时子窗口
|
||||
//! 还没生出来,于是它们**永远没有 drop target**。表现就是:拖文件进去光标变成禁止
|
||||
//! 符号,Tauri 原生拖放事件与 HTML5 `drop` 都不触发(实测两个窗口的 Win32 样式完全
|
||||
//! 一致,差别只在 `OleDropTargetInterface` 落在哪些子窗口上)。
|
||||
//!
|
||||
//! # 做法
|
||||
//!
|
||||
//! 窗口创建后延迟重试,等 WebView2 子窗口出现,再照 wry 的同一手法
|
||||
//! (`RevokeDragDrop` + `RegisterDragDrop`)给**顶层窗口及其全部后代**补注入自己的
|
||||
//! `IDropTarget`;收到拖放后按 Tauri 原生拖放事件**同样的名字与载荷**发出
|
||||
//! `tauri://drag-enter|over|drop|leave` —— 前端 `onDragDropEvent` 无需任何改动。
|
||||
//!
|
||||
//! **通用**:只对显式传入 label 的窗口生效,调用方传自己的窗口 label(目前是
|
||||
//! 编辑器窗口与对比窗口),不碰主窗口。
|
||||
|
||||
use tauri::AppHandle;
|
||||
|
||||
/// 给指定窗口补注入拖放支持(Windows 专用;其它平台直接返回 `Ok`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn window_attach_drag_drop(app: AppHandle, label: String) -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
imp::spawn_attach(app, label);
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = (app, label);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::sync::{mpsc, Mutex, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use tauri::{AppHandle, Emitter, EventTarget, Manager};
|
||||
use windows62::core::{implement, Ref, BOOL};
|
||||
use windows62::Win32::Foundation::{HWND, LPARAM, POINT, POINTL};
|
||||
use windows62::Win32::Graphics::Gdi::ScreenToClient;
|
||||
use windows62::Win32::System::Com::{IDataObject, DVASPECT_CONTENT, FORMATETC, TYMED_HGLOBAL};
|
||||
use windows62::Win32::System::Ole::{
|
||||
IDropTarget, IDropTarget_Impl, RegisterDragDrop, RevokeDragDrop, CF_HDROP, DROPEFFECT,
|
||||
DROPEFFECT_COPY, DROPEFFECT_NONE,
|
||||
};
|
||||
use windows62::Win32::System::SystemServices::MODIFIERKEYS_FLAGS;
|
||||
use windows62::Win32::UI::Shell::{DragFinish, DragQueryFileW, HDROP};
|
||||
use windows62::Win32::UI::WindowsAndMessaging::{EnumChildWindows, GetClassNameW};
|
||||
|
||||
/// 重试节奏:WebView2 的渲染子窗口在窗口显示后才陆续出现,前几秒足以覆盖。
|
||||
const RETRY_INTERVAL: Duration = Duration::from_millis(400);
|
||||
/// 重试次数上限(400ms × 24 ≈ 10s,与前端窗口冷启动量级一致)。
|
||||
const MAX_RETRY: u32 = 24;
|
||||
|
||||
/// 已注入的 drop target 集合。
|
||||
///
|
||||
/// `RegisterDragDrop` 只保存裸指针,**对象必须由我们保持存活**(同 wry 的
|
||||
/// `DragDropController::drop_targets`)。接口对象是 STA 私有的、实际只在主线程
|
||||
/// 访问,这里标 `Send`/`Sync` 仅为能放进全局表。
|
||||
/// 字段本身从不读取:它的唯一作用是**持有引用**,让 `RegisterDragDrop`
|
||||
/// 存下的裸指针在窗口存活期间始终有效。
|
||||
struct TargetSet(#[allow(dead_code)] Vec<IDropTarget>);
|
||||
unsafe impl Send for TargetSet {}
|
||||
unsafe impl Sync for TargetSet {}
|
||||
|
||||
static INJECTED: OnceLock<Mutex<HashMap<String, TargetSet>>> = OnceLock::new();
|
||||
|
||||
fn injected() -> &'static Mutex<HashMap<String, TargetSet>> {
|
||||
INJECTED.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
// EnumChildWindows 的回调只带 LPARAM,用线程局部变量收集最省事(回调同步执行)。
|
||||
thread_local! {
|
||||
static FOUND: RefCell<Vec<HWND>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
unsafe extern "system" fn collect_child(hwnd: HWND, _lparam: LPARAM) -> BOOL {
|
||||
FOUND.with(|v| v.borrow_mut().push(hwnd));
|
||||
BOOL(1)
|
||||
}
|
||||
|
||||
/// 顶层窗口 + 全部后代(WebView2 的 `Chrome_*`、`WRY_WEBVIEW` 等都在其中)。
|
||||
fn window_and_descendants(hwnd: HWND) -> Vec<HWND> {
|
||||
FOUND.with(|v| v.borrow_mut().clear());
|
||||
let _ = unsafe { EnumChildWindows(Some(hwnd), Some(collect_child), LPARAM(0)) };
|
||||
let descendants: Vec<HWND> = FOUND.with(|v| v.borrow().clone());
|
||||
let mut all = Vec::with_capacity(descendants.len() + 1);
|
||||
all.push(hwnd);
|
||||
all.extend(descendants);
|
||||
all
|
||||
}
|
||||
|
||||
fn class_name(hwnd: HWND) -> String {
|
||||
let mut buf = [0u16; 128];
|
||||
let len = unsafe { GetClassNameW(hwnd, &mut buf) }.max(0) as usize;
|
||||
OsString::from_wide(&buf[..len.min(buf.len())])
|
||||
.to_string_lossy()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// 是否已经出现 WebView2 的**渲染**子窗口。
|
||||
///
|
||||
/// 判据用 `Chrome_RenderWidgetHostHWND`(Chromium 最后创建的那个),而不是
|
||||
/// 「任意 `Chrome_*`」——`Chrome_WidgetWin_0` 出现得更早,用它当"就绪"会过早
|
||||
/// 停止重试,导致真正的落点(RenderWidget)没有 drop target。
|
||||
fn has_render_host(hwnds: &[HWND]) -> bool {
|
||||
hwnds
|
||||
.iter()
|
||||
.any(|h| class_name(*h).contains("RenderWidgetHost"))
|
||||
}
|
||||
|
||||
#[implement(IDropTarget)]
|
||||
struct WindowDropTarget {
|
||||
hwnd: HWND,
|
||||
app: AppHandle,
|
||||
label: String,
|
||||
cursor_effect: Cell<DROPEFFECT>,
|
||||
enter_valid: Cell<bool>,
|
||||
}
|
||||
|
||||
impl WindowDropTarget {
|
||||
fn emit(&self, event: &str, payload: serde_json::Value) {
|
||||
if let Err(e) = self.app.emit_to(
|
||||
EventTarget::AnyLabel {
|
||||
label: self.label.clone(),
|
||||
},
|
||||
event,
|
||||
payload,
|
||||
) {
|
||||
crate::logger::log_warn("drag-drop", &format!("发送拖放事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 从 `IDataObject` 取 CF_HDROP 里的文件路径。
|
||||
///
|
||||
/// 同时把 `HDROP` 交回调用方:**只能在 `Drop` 里 `DragFinish`**,
|
||||
/// `DragEnter`/`DragOver` 阶段释放会让后续拿不到数据。
|
||||
unsafe fn collect_paths(data: Ref<'_, IDataObject>) -> Option<(HDROP, Vec<String>)> {
|
||||
let format = FORMATETC {
|
||||
cfFormat: CF_HDROP.0,
|
||||
ptd: std::ptr::null_mut(),
|
||||
dwAspect: DVASPECT_CONTENT.0,
|
||||
lindex: -1,
|
||||
tymed: TYMED_HGLOBAL.0 as u32,
|
||||
};
|
||||
let medium = data.as_ref()?.GetData(&format).ok()?;
|
||||
let hdrop = HDROP(medium.u.hGlobal.0 as _);
|
||||
let count = DragQueryFileW(hdrop, u32::MAX, None);
|
||||
let mut paths = Vec::with_capacity(count as usize);
|
||||
for index in 0..count {
|
||||
let len = DragQueryFileW(hdrop, index, None) as usize;
|
||||
let mut buf = vec![0u16; len + 1];
|
||||
DragQueryFileW(hdrop, index, Some(&mut buf));
|
||||
paths.push(OsString::from_wide(&buf[..len]).to_string_lossy().to_string());
|
||||
}
|
||||
Some((hdrop, paths))
|
||||
}
|
||||
|
||||
/// 屏幕坐标 → 客户区坐标(与 wry 一致,前端拿到的是相对 webview 的位置)。
|
||||
fn client_pos(&self, point: &POINTL) -> (i32, i32) {
|
||||
let mut pt = POINT {
|
||||
x: point.x,
|
||||
y: point.y,
|
||||
};
|
||||
let _ = unsafe { ScreenToClient(self.hwnd, &mut pt) };
|
||||
(pt.x, pt.y)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
impl IDropTarget_Impl for WindowDropTarget_Impl {
|
||||
fn DragEnter(
|
||||
&self,
|
||||
pDataObj: Ref<'_, IDataObject>,
|
||||
_grfKeyState: MODIFIERKEYS_FLAGS,
|
||||
pt: &POINTL,
|
||||
pdwEffect: *mut DROPEFFECT,
|
||||
) -> windows62::core::Result<()> {
|
||||
let (x, y) = self.client_pos(pt);
|
||||
let found = unsafe { WindowDropTarget::collect_paths(pDataObj) };
|
||||
let valid = found.is_some();
|
||||
self.enter_valid.set(valid);
|
||||
|
||||
if let Some((_hdrop, paths)) = found {
|
||||
self.emit(
|
||||
"tauri://drag-enter",
|
||||
serde_json::json!({ "paths": paths, "position": { "x": x, "y": y } }),
|
||||
);
|
||||
}
|
||||
|
||||
let effect = if valid { DROPEFFECT_COPY } else { DROPEFFECT_NONE };
|
||||
unsafe { *pdwEffect = effect };
|
||||
self.cursor_effect.set(effect);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn DragOver(
|
||||
&self,
|
||||
_grfKeyState: MODIFIERKEYS_FLAGS,
|
||||
pt: &POINTL,
|
||||
pdwEffect: *mut DROPEFFECT,
|
||||
) -> windows62::core::Result<()> {
|
||||
if self.enter_valid.get() {
|
||||
let (x, y) = self.client_pos(pt);
|
||||
self.emit(
|
||||
"tauri://drag-over",
|
||||
serde_json::json!({ "position": { "x": x, "y": y } }),
|
||||
);
|
||||
}
|
||||
unsafe { *pdwEffect = self.cursor_effect.get() };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn DragLeave(&self) -> windows62::core::Result<()> {
|
||||
if self.enter_valid.get() {
|
||||
self.emit("tauri://drag-leave", serde_json::json!(null));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn Drop(
|
||||
&self,
|
||||
pDataObj: Ref<'_, IDataObject>,
|
||||
_grfKeyState: MODIFIERKEYS_FLAGS,
|
||||
pt: &POINTL,
|
||||
pdwEffect: *mut DROPEFFECT,
|
||||
) -> windows62::core::Result<()> {
|
||||
if self.enter_valid.get() {
|
||||
let (x, y) = self.client_pos(pt);
|
||||
if let Some((hdrop, paths)) = unsafe { WindowDropTarget::collect_paths(pDataObj) } {
|
||||
self.emit(
|
||||
"tauri://drag-drop",
|
||||
serde_json::json!({ "paths": paths, "position": { "x": x, "y": y } }),
|
||||
);
|
||||
unsafe { DragFinish(hdrop) };
|
||||
}
|
||||
}
|
||||
unsafe { *pdwEffect = DROPEFFECT_COPY };
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 在**主线程**给该窗口补注入(OLE/COM 必须在初始化过 OLE 的线程上操作)。
|
||||
/// 返回 true 表示 WebView2 子窗口已就位,后续无需再扫。
|
||||
fn inject_now(app: &AppHandle, label: &str) -> bool {
|
||||
let Some(window) = app.get_webview_window(label) else {
|
||||
crate::logger::log_warn("drag-drop", &format!("补注入:找不到窗口 {label}"));
|
||||
return true;
|
||||
};
|
||||
let Ok(hwnd) = window.hwnd() else {
|
||||
crate::logger::log_warn("drag-drop", &format!("补注入:取不到 hwnd({label})"));
|
||||
return false;
|
||||
};
|
||||
|
||||
let all = window_and_descendants(hwnd);
|
||||
let ready = has_render_host(&all);
|
||||
|
||||
let mut targets = Vec::with_capacity(all.len());
|
||||
let mut ok = 0usize;
|
||||
let mut failed = 0usize;
|
||||
for child in all {
|
||||
let target: IDropTarget = WindowDropTarget {
|
||||
hwnd: child,
|
||||
app: app.clone(),
|
||||
label: label.to_string(),
|
||||
cursor_effect: Cell::new(DROPEFFECT_NONE),
|
||||
enter_valid: Cell::new(false),
|
||||
}
|
||||
.into();
|
||||
// 与 wry 同一手法:先撤销(把它早期注入的空壳换掉),再注册自己的
|
||||
let _ = unsafe { RevokeDragDrop(child) };
|
||||
match unsafe { RegisterDragDrop(child, &target) } {
|
||||
Ok(()) => {
|
||||
ok += 1;
|
||||
targets.push(target);
|
||||
}
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!(
|
||||
"补注入:RegisterDragDrop 失败 class={} err={e}",
|
||||
class_name(child)
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("补注入:{label} 后代={} 成功={ok} 失败={failed} ready={ready}", targets.len() + failed),
|
||||
);
|
||||
|
||||
if let Ok(mut map) = injected().lock() {
|
||||
map.insert(label.to_string(), TargetSet(targets));
|
||||
}
|
||||
|
||||
ready
|
||||
}
|
||||
|
||||
/// 后台线程:等到窗口与子窗口都就位后注入;窗口提前关闭则放弃。
|
||||
pub fn spawn_attach(app: AppHandle, label: String) {
|
||||
crate::logger::log_info("drag-drop", &format!("补注入:收到请求 label={label}"));
|
||||
std::thread::spawn(move || {
|
||||
for _ in 0..MAX_RETRY {
|
||||
std::thread::sleep(RETRY_INTERVAL);
|
||||
|
||||
if app.get_webview_window(&label).is_none() {
|
||||
crate::logger::log_info("drag-drop", &format!("补注入:窗口已关闭,放弃 {label}"));
|
||||
if let Ok(mut map) = injected().lock() {
|
||||
map.remove(&label);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let (tx, rx) = mpsc::channel::<bool>();
|
||||
let app_main = app.clone();
|
||||
let label_main = label.clone();
|
||||
if let Err(e) = app.run_on_main_thread(move || {
|
||||
let _ = tx.send(inject_now(&app_main, &label_main));
|
||||
}) {
|
||||
crate::logger::log_warn("drag-drop", &format!("补注入:run_on_main_thread 失败 {e}"));
|
||||
return;
|
||||
}
|
||||
|
||||
// 主线程执行完再决定是否继续(超时按"未就绪"处理)
|
||||
if matches!(rx.recv_timeout(Duration::from_secs(2)), Ok(true)) {
|
||||
crate::logger::log_info("drag-drop", &format!("拖放补注入完成:{label}"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
crate::logger::log_warn("drag-drop", &format!("拖放补注入未完成(子窗口未就位):{label}"));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
//! AI 装载:把主设置(AI 服务)里的供应商映射进 dsh 的 `$DSH_HOME/settings.yaml`,
|
||||
//! 并在启动服务时以环境变量注入 API Key。
|
||||
//!
|
||||
//! 安全姿态(对齐 `crate::ai` 与 `crate::secrets`):**密钥不落盘**。
|
||||
//! settings.yaml 里只写 `apiKeyEnv`(环境变量名),明文由
|
||||
//! [`crate::ai::provider_api_key`] 从系统凭据管理器读出后随子进程环境注入。
|
||||
//!
|
||||
//! 合并规则:只替换 `llm-pi-ai.providers` 下本模块管理的 `thing-*` 键与
|
||||
//! `agent-default-model`,用户自己写的其它段落(profile patch / 第三方插件配置)
|
||||
//! 原样保留;写盘前把旧文件备份为 `settings.yaml.bak`。
|
||||
|
||||
use serde_yaml::{Mapping, Value};
|
||||
use tauri::AppHandle;
|
||||
|
||||
use super::types::{DshAiPreview, DshAiProvider};
|
||||
use super::DshManager;
|
||||
|
||||
/// 本模块写入 settings.yaml 的供应商键前缀。
|
||||
const PROVIDER_PREFIX: &str = "thing-";
|
||||
/// `llm-pi-ai` 段名(dsh 的通用 OpenAI 兼容提供方插件)。
|
||||
const LLM_SECTION: &str = "llm-pi-ai";
|
||||
/// 默认模型段名。
|
||||
const DEFAULT_MODEL_SECTION: &str = "agent-default-model";
|
||||
|
||||
impl DshManager {
|
||||
/// dsh 侧供应商键(`thing-<id>`,只保留小写字母数字与短横线)。
|
||||
fn dsh_provider_id(id: &str) -> String {
|
||||
let sanitized: String = id
|
||||
.trim()
|
||||
.to_lowercase()
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
|
||||
.collect();
|
||||
format!("{PROVIDER_PREFIX}{sanitized}")
|
||||
}
|
||||
|
||||
/// 环境变量名(`THING_AI_<ID>_KEY`)。
|
||||
fn env_name(id: &str) -> String {
|
||||
let sanitized: String = id
|
||||
.trim()
|
||||
.to_uppercase()
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
|
||||
.collect();
|
||||
format!("THING_AI_{sanitized}_KEY")
|
||||
}
|
||||
|
||||
/// settings.yaml 路径(`$DSH_HOME/settings.yaml`)。
|
||||
pub fn dsh_settings_path(&self) -> std::path::PathBuf {
|
||||
self.home_dir().join("settings.yaml")
|
||||
}
|
||||
|
||||
/// 当前将被映射的供应商列表(enabled 且 baseUrl 非空)。
|
||||
pub fn ai_providers(&self) -> Vec<DshAiProvider> {
|
||||
let settings = crate::ai::AiManager::load_settings_sync(&self.data_dir);
|
||||
settings
|
||||
.providers
|
||||
.iter()
|
||||
.filter(|p| p.enabled && !p.base_url.trim().is_empty() && !p.model.trim().is_empty())
|
||||
.map(|p| DshAiProvider {
|
||||
id: p.id.clone(),
|
||||
name: p.name.clone(),
|
||||
env_name: Self::env_name(&p.id),
|
||||
base_url: p.base_url.clone(),
|
||||
model: p.model.clone(),
|
||||
has_key: !crate::ai::provider_api_key(&p.id).is_empty(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 构造本模块管理的配置片段(`llm-pi-ai.providers` + `agent-default-model`)。
|
||||
fn build_patch(&self) -> (Mapping, Value, Option<String>, Option<String>) {
|
||||
let settings = crate::ai::AiManager::load_settings_sync(&self.data_dir);
|
||||
let mut providers = Mapping::new();
|
||||
let mut default_pair: Option<(String, String)> = None;
|
||||
let wanted = self.load_settings().provider_id;
|
||||
|
||||
for p in settings.providers.iter() {
|
||||
if !p.enabled || p.base_url.trim().is_empty() || p.model.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let dsh_id = Self::dsh_provider_id(&p.id);
|
||||
let mut entry = Mapping::new();
|
||||
entry.insert(
|
||||
Value::String("displayName".into()),
|
||||
Value::String(if p.name.trim().is_empty() {
|
||||
p.id.clone()
|
||||
} else {
|
||||
p.name.clone()
|
||||
}),
|
||||
);
|
||||
entry.insert(
|
||||
Value::String("api".into()),
|
||||
Value::String("openai-completions".into()),
|
||||
);
|
||||
entry.insert(
|
||||
Value::String("baseURL".into()),
|
||||
Value::String(p.base_url.trim().trim_end_matches('/').to_string()),
|
||||
);
|
||||
entry.insert(
|
||||
Value::String("apiKeyEnv".into()),
|
||||
Value::String(Self::env_name(&p.id)),
|
||||
);
|
||||
// 模型目录:当前模型 + 常见上下文窗口(字段名以 dsh 的 catalog 为准,
|
||||
// 这里只写最稳定的 id/name,避免写错字段导致 dsh 拒绝配置)
|
||||
let mut model = Mapping::new();
|
||||
model.insert(Value::String("id".into()), Value::String(p.model.clone()));
|
||||
model.insert(Value::String("name".into()), Value::String(p.model.clone()));
|
||||
entry.insert(
|
||||
Value::String("models".into()),
|
||||
Value::Sequence(vec![Value::Mapping(model)]),
|
||||
);
|
||||
providers.insert(Value::String(dsh_id.clone()), Value::Mapping(entry));
|
||||
|
||||
let is_wanted = p.id == wanted || (wanted.is_empty() && default_pair.is_none());
|
||||
if is_wanted {
|
||||
default_pair = Some((dsh_id, p.model.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
let default_value = match &default_pair {
|
||||
Some((provider, model)) => {
|
||||
let mut m = Mapping::new();
|
||||
m.insert(Value::String("provider".into()), Value::String(provider.clone()));
|
||||
m.insert(Value::String("model".into()), Value::String(model.clone()));
|
||||
Value::Mapping(m)
|
||||
}
|
||||
None => Value::Null,
|
||||
};
|
||||
let default_provider = default_pair.as_ref().map(|(p, _)| p.clone());
|
||||
let default_model = default_pair.map(|(_, m)| m);
|
||||
(providers, default_value, default_provider, default_model)
|
||||
}
|
||||
|
||||
/// 预览将要写入的 YAML(不含明文密钥)。
|
||||
pub fn ai_preview(&self) -> DshAiPreview {
|
||||
let (providers, default_value, default_provider, default_model) = self.build_patch();
|
||||
let mut root = Mapping::new();
|
||||
if !default_value.is_null() {
|
||||
root.insert(Value::String(DEFAULT_MODEL_SECTION.into()), default_value);
|
||||
}
|
||||
let mut llm = Mapping::new();
|
||||
llm.insert(Value::String("providers".into()), Value::Mapping(providers));
|
||||
root.insert(Value::String(LLM_SECTION.into()), Value::Mapping(llm));
|
||||
|
||||
let yaml = serde_yaml::to_string(&Value::Mapping(root))
|
||||
.unwrap_or_else(|e| format!("# 生成预览失败: {e}"));
|
||||
DshAiPreview {
|
||||
yaml,
|
||||
providers: self.ai_providers(),
|
||||
default_provider,
|
||||
default_model,
|
||||
settings_path: self.dsh_settings_path().to_string_lossy().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 生成/合并 `$DSH_HOME/settings.yaml`(写盘前备份旧文件)。
|
||||
pub fn ai_sync(&self, _app: &AppHandle) -> Result<(), String> {
|
||||
let (providers, default_value, _, _) = self.build_patch();
|
||||
let path = self.dsh_settings_path();
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建 $DSH_HOME 失败: {e}"))?;
|
||||
}
|
||||
|
||||
// 读现有文档(缺失/非映射时用空映射起步)
|
||||
let existing = std::fs::read_to_string(&path).ok();
|
||||
let mut doc = existing
|
||||
.as_deref()
|
||||
.and_then(|t| serde_yaml::from_str::<Value>(t).ok())
|
||||
.filter(|v| v.is_mapping())
|
||||
.unwrap_or_else(|| Value::Mapping(Mapping::new()));
|
||||
let root = doc.as_mapping_mut().ok_or_else(|| "settings.yaml 结构非法".to_string())?;
|
||||
|
||||
// 备份
|
||||
if existing.is_some() {
|
||||
std::fs::write(path.with_extension("yaml.bak"), existing.as_deref().unwrap_or_default())
|
||||
.map_err(|e| format!("备份 settings.yaml 失败: {e}"))?;
|
||||
}
|
||||
|
||||
// llm-pi-ai.providers:只替换本模块管理的 thing-* 键
|
||||
let llm_key = Value::String(LLM_SECTION.into());
|
||||
let llm_entry = root
|
||||
.entry(llm_key)
|
||||
.or_insert_with(|| Value::Mapping(Mapping::new()));
|
||||
if !llm_entry.is_mapping() {
|
||||
*llm_entry = Value::Mapping(Mapping::new());
|
||||
}
|
||||
let llm_map = llm_entry.as_mapping_mut().expect("已保证为映射");
|
||||
let providers_key = Value::String("providers".into());
|
||||
let providers_entry = llm_map
|
||||
.entry(providers_key)
|
||||
.or_insert_with(|| Value::Mapping(Mapping::new()));
|
||||
if !providers_entry.is_mapping() {
|
||||
*providers_entry = Value::Mapping(Mapping::new());
|
||||
}
|
||||
let providers_map = providers_entry.as_mapping_mut().expect("已保证为映射");
|
||||
// 先清掉上一次由本模块写入的键(用户自建的其它键保留)
|
||||
let stale: Vec<Value> = providers_map
|
||||
.keys()
|
||||
.filter(|k| {
|
||||
k.as_str()
|
||||
.map(|s| s.starts_with(PROVIDER_PREFIX))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
for key in stale {
|
||||
providers_map.remove(&key);
|
||||
}
|
||||
for (key, value) in providers.iter() {
|
||||
providers_map.insert(key.clone(), value.clone());
|
||||
}
|
||||
|
||||
// agent-default-model
|
||||
if default_value.is_null() {
|
||||
root.remove(&Value::String(DEFAULT_MODEL_SECTION.into()));
|
||||
} else {
|
||||
root.insert(Value::String(DEFAULT_MODEL_SECTION.into()), default_value);
|
||||
}
|
||||
|
||||
let text = serde_yaml::to_string(&doc).map_err(|e| format!("序列化 settings.yaml 失败: {e}"))?;
|
||||
std::fs::write(&path, text).map_err(|e| format!("写入 settings.yaml 失败: {e}"))?;
|
||||
crate::logger::log_info(
|
||||
"dsh",
|
||||
&format!("已同步 AI 供应商到 {}", path.display()),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 启动服务时注入的环境变量(供应商密钥 + DeepSeek 官方变量兜底)。
|
||||
pub fn ai_env_vars(&self) -> Vec<(String, String)> {
|
||||
let settings = crate::ai::AiManager::load_settings_sync(&self.data_dir);
|
||||
let mut vars: Vec<(String, String)> = Vec::new();
|
||||
for p in settings.providers.iter() {
|
||||
if !p.enabled || p.base_url.trim().is_empty() || p.model.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let key = crate::ai::provider_api_key(&p.id);
|
||||
if key.is_empty() {
|
||||
continue;
|
||||
}
|
||||
vars.push((Self::env_name(&p.id), key.clone()));
|
||||
// DeepSeek 官方通道:dsh 内置 provider 直接读 DEEPSEEK_API_KEY
|
||||
let is_deepseek = p.id.eq_ignore_ascii_case("deepseek")
|
||||
|| p.preset.eq_ignore_ascii_case("deepseek")
|
||||
|| p.base_url.contains("api.deepseek.com");
|
||||
if is_deepseek {
|
||||
vars.push(("DEEPSEEK_API_KEY".into(), key));
|
||||
}
|
||||
}
|
||||
vars
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! dsh 模块的 Tauri 命令层。
|
||||
//!
|
||||
//! 前端统一经 `@/lib/bindings` 的 `commands.dsh*` 调用。
|
||||
//! 进度事件 `dsh-install-progress`、状态事件 `dsh-server-state` 见
|
||||
//! `crate::constants::events`(与 `src/lib/constants.ts` 的 `EVENTS` 对应)。
|
||||
|
||||
use tauri::Manager;
|
||||
use tauri::{AppHandle, State};
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
|
||||
use super::types::{
|
||||
DshAiPreview, DshEnvStatus, DshInstallStatus, DshNpmRegistryInfo, DshServerStatus, DshSettings,
|
||||
DshUpdateInfo, NodeStatus,
|
||||
};
|
||||
use super::DshManager;
|
||||
|
||||
/// 环境总览:Node / dsh / 服务状态 + 模块设置(模块首屏一次拿全)。
|
||||
///
|
||||
/// 声明为 `async`:Tauri 的**同步**命令在主线程执行,而本命令要跑
|
||||
/// `node --version` 子进程探测,放主线程会造成界面卡顿。
|
||||
/// (async 命令带 `State<'_>` 引用参数时必须返回 `Result`,故这里包一层 Ok。)
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_env_status(state: State<'_, DshManager>) -> Result<DshEnvStatus, String> {
|
||||
Ok(DshEnvStatus {
|
||||
node: state.node_status(),
|
||||
dsh: state.install_status(),
|
||||
server: state.server_status(),
|
||||
settings: state.load_settings(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 重新探测 Node(系统 PATH + 托管目录)。同样因执行 `node --version` 而用 async。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_node_detect(state: State<'_, DshManager>) -> Result<NodeStatus, String> {
|
||||
Ok(state.node_status())
|
||||
}
|
||||
|
||||
/// 下载并安装便携 Node(`version` 为空 = 自动取满足要求的最新版)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_node_install(
|
||||
app: AppHandle,
|
||||
state: State<'_, DshManager>,
|
||||
version: Option<String>,
|
||||
) -> Result<NodeStatus, String> {
|
||||
state.node_install(&app, version).await
|
||||
}
|
||||
|
||||
/// 安装 dsh(`version` 为空 = latest)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_install(
|
||||
app: AppHandle,
|
||||
state: State<'_, DshManager>,
|
||||
version: Option<String>,
|
||||
) -> Result<DshInstallStatus, String> {
|
||||
state.install(&app, version).await
|
||||
}
|
||||
|
||||
/// 更新 dsh 到 latest(更新前停止服务,避免文件被占用)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_update(
|
||||
app: AppHandle,
|
||||
state: State<'_, DshManager>,
|
||||
) -> Result<DshInstallStatus, String> {
|
||||
state.stop_server(&app);
|
||||
state.install(&app, None).await
|
||||
}
|
||||
|
||||
/// 卸载 dsh(停止服务并删除包目录;保留设置与 $DSH_HOME)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn dsh_uninstall(app: AppHandle, state: State<'_, DshManager>) -> Result<(), String> {
|
||||
state.uninstall(&app)
|
||||
}
|
||||
|
||||
/// 取消进行中的下载 / 安装。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn dsh_cancel_install(state: State<'_, DshManager>) {
|
||||
state.request_cancel();
|
||||
}
|
||||
|
||||
/// 查询 npm 上的可用版本。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_check_update(state: State<'_, DshManager>) -> Result<DshUpdateInfo, String> {
|
||||
state.check_update().await
|
||||
}
|
||||
|
||||
/// 读取「本次安装实际使用的 npm 源」及其来源。
|
||||
///
|
||||
/// 设置为空时 npm 会用自己配置链里的源(含系统 Node 的 `~/.npmrc`),
|
||||
/// 这里把解析结果回给前端展示,让用户能看出「到底走的是哪个源」。
|
||||
/// async:内部要跑 `node <npm-cli.js> config get registry` 子进程。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_npm_registry_info(
|
||||
state: State<'_, DshManager>,
|
||||
) -> Result<DshNpmRegistryInfo, String> {
|
||||
Ok(state.npm_registry_info())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn dsh_get_settings(state: State<'_, DshManager>) -> DshSettings {
|
||||
state.load_settings()
|
||||
}
|
||||
|
||||
/// 保存设置(即时生效;端口等改动在下次启动服务时生效)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn dsh_save_settings(
|
||||
state: State<'_, DshManager>,
|
||||
settings: DshSettings,
|
||||
) -> Result<DshSettings, String> {
|
||||
state.save_settings(settings)
|
||||
}
|
||||
|
||||
/// 启动 dsh Web 服务。async:内部要 spawn 子进程 + 读凭据 + 写 settings.yaml,
|
||||
/// 同步命令会在主线程执行从而卡住界面。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_start(app: AppHandle, state: State<'_, DshManager>) -> Result<DshServerStatus, String> {
|
||||
state.start_server(&app)
|
||||
}
|
||||
|
||||
/// 停止 dsh Web 服务。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_stop(app: AppHandle, state: State<'_, DshManager>) -> Result<DshServerStatus, String> {
|
||||
state.stop_server(&app);
|
||||
Ok(state.server_status())
|
||||
}
|
||||
|
||||
/// 重启 dsh Web 服务。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_restart(app: AppHandle, state: State<'_, DshManager>) -> Result<DshServerStatus, String> {
|
||||
state.stop_server(&app);
|
||||
// Windows 上端口释放有延迟,稍等再起,避免 bind 预检误判占用
|
||||
// (用异步 sleep:同步命令在主线程执行,阻塞 500ms 会冻界面)
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
state.start_server(&app)
|
||||
}
|
||||
|
||||
/// 预览将写入 `$DSH_HOME/settings.yaml` 的内容(不含明文密钥)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn dsh_ai_preview(state: State<'_, DshManager>) -> DshAiPreview {
|
||||
state.ai_preview()
|
||||
}
|
||||
|
||||
/// 执行 AI 配置同步(合并写入 settings.yaml,写前备份)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn dsh_ai_sync(app: AppHandle, state: State<'_, DshManager>) -> Result<DshAiPreview, String> {
|
||||
state.ai_sync(&app)?;
|
||||
Ok(state.ai_preview())
|
||||
}
|
||||
|
||||
/// 读取服务日志尾部。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn dsh_log_tail(state: State<'_, DshManager>, lines: u32) -> String {
|
||||
state.log_tail(lines as usize)
|
||||
}
|
||||
|
||||
/// 读取 dsh 安装输出(npm 的 stdout/stderr 尾部)。
|
||||
///
|
||||
/// 只存在内存里(每次安装开始时清空),供「安装引导 → dsh 本体」页临时展示,
|
||||
/// **不写应用日志、不落盘**。前端在安装进行中轮询这个命令。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn dsh_install_log(state: State<'_, DshManager>) -> String {
|
||||
state.install_log()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn dsh_log_clear(state: State<'_, DshManager>) {
|
||||
state.clear_log();
|
||||
}
|
||||
|
||||
/// 在资源管理器中打开 dsh 模块目录。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn dsh_open_dir(app: AppHandle, state: State<'_, DshManager>) -> Result<(), String> {
|
||||
app.opener()
|
||||
.open_path(state.root().to_string_lossy().to_string(), None::<&str>)
|
||||
.map_err(|e| format!("打开目录失败: {e}"))
|
||||
}
|
||||
|
||||
/// 注册(或切换)「打开 dsh 独立窗口」全局快捷键;传空字符串则注销。
|
||||
///
|
||||
/// 按下时只 emit `dsh-open-window` 事件,**窗口由前端创建**:前端才持有带令牌的
|
||||
/// 启动地址,也能用 label 判重复用已开窗口(与截图模块「快捷键 → 事件 → 前端开窗」同构)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_register_shortcut(app: AppHandle, shortcut: String) -> Result<(), String> {
|
||||
crate::shortcut::register_shortcut(&app, "dsh", &shortcut, |a| {
|
||||
use tauri::Emitter;
|
||||
let _ = a.emit(crate::constants::events::DSH_OPEN_WINDOW, ());
|
||||
})
|
||||
}
|
||||
|
||||
/// 注销「打开 dsh 独立窗口」全局快捷键。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dsh_unregister_shortcut(app: AppHandle) -> Result<(), String> {
|
||||
crate::shortcut::unregister_shortcut(&app, "dsh");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 供 `setup.rs` 在应用启动时按设置自启服务。
|
||||
pub fn autostart_if_enabled(app: &AppHandle) {
|
||||
let manager = app.state::<DshManager>();
|
||||
let settings = manager.load_settings();
|
||||
if !settings.auto_start {
|
||||
return;
|
||||
}
|
||||
if !manager.install_status().installed {
|
||||
crate::logger::log_warn("dsh", "设置了自动启动,但 dsh 尚未安装,跳过");
|
||||
return;
|
||||
}
|
||||
if let Err(e) = manager.start_server(app) {
|
||||
crate::logger::log_warn("dsh", &format!("自动启动 dsh 服务失败: {e}"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
//! dsh 本体的安装 / 更新 / 卸载与版本查询。
|
||||
//!
|
||||
//! 安装方式:用当前解析出的 Node 自带的 npm,把 `@deepseek-ai/dsh` 装进模块目录
|
||||
//! (`npm install --prefix {app_data}/dsh`)。好处是版本可锁、可配镜像源、可复用
|
||||
//! 已下载的依赖,且启动时直接 `node <bin 入口>`,不依赖 PATH 上的全局 shim。
|
||||
//!
|
||||
//! npm 调用形态:`node <npm-cli.js> install ...`(不走 npm.cmd,理由见 `node.rs`)。
|
||||
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
use tauri::{AppHandle, Emitter};
|
||||
|
||||
use super::node::NODE_CANCELLED;
|
||||
use super::types::{DshInstallProgress, DshInstallStatus, DshNpmRegistryInfo, DshUpdateInfo, DSH_PACKAGE};
|
||||
use super::DshManager;
|
||||
|
||||
impl DshManager {
|
||||
/// dsh 包目录
|
||||
fn package_dir(&self) -> PathBuf {
|
||||
self.install_root()
|
||||
.join("node_modules")
|
||||
.join("@deepseek-ai")
|
||||
.join("dsh")
|
||||
}
|
||||
|
||||
/// 已安装版本(读 package.json,不起进程)
|
||||
pub fn installed_version(&self) -> Option<String> {
|
||||
let text = std::fs::read_to_string(self.package_dir().join("package.json")).ok()?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
value
|
||||
.get("version")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
}
|
||||
|
||||
/// dsh bin 入口(`package.json` 的 `bin.dsh`),启动服务时直接 `node <入口>`。
|
||||
pub fn bin_entry(&self) -> Option<PathBuf> {
|
||||
let dir = self.package_dir();
|
||||
let text = std::fs::read_to_string(dir.join("package.json")).ok()?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
let rel = match value.get("bin") {
|
||||
Some(serde_json::Value::String(s)) => s.clone(),
|
||||
Some(serde_json::Value::Object(map)) => map.get("dsh")?.as_str()?.to_string(),
|
||||
_ => return None,
|
||||
};
|
||||
let entry = dir.join(rel);
|
||||
entry.exists().then_some(entry)
|
||||
}
|
||||
|
||||
/// 安装状态
|
||||
pub fn install_status(&self) -> DshInstallStatus {
|
||||
let version = self.installed_version();
|
||||
let entry = self.bin_entry();
|
||||
DshInstallStatus {
|
||||
installed: version.is_some() && entry.is_some(),
|
||||
version,
|
||||
entry: entry.map(|p| p.to_string_lossy().to_string()),
|
||||
dir: self.install_root().to_string_lossy().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 模块设置里**显式**填写的 npm 源(空 = 未指定,交给 npm 自己解析)。
|
||||
///
|
||||
/// 与 [`Self::npm_registry_info`] 的区别:这里只认模块设置。安装时只在
|
||||
/// 显式填写的情况下才传 `--registry`,其余情况让 npm 走自己的配置链
|
||||
/// (环境变量 > 安装目录 `.npmrc` > 用户 `~/.npmrc` > 内置),
|
||||
/// 这样「系统 node 以前配过的镜像」会被自动沿用。
|
||||
fn registry_setting(&self) -> String {
|
||||
self.load_settings()
|
||||
.npm_registry
|
||||
.trim()
|
||||
.trim_end_matches('/')
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// npm 自身解析出的源(`node <npm-cli.js> config get registry`)。
|
||||
///
|
||||
/// 未检测到 Node/npm、或 npm 执行失败时为 None。cwd 取安装目录——
|
||||
/// npm 的「项目级配置」来自 cwd 下的 `.npmrc`,要与真实安装保持一致。
|
||||
pub fn npm_config_registry(&self) -> Option<String> {
|
||||
let env = self.resolve_node_env()?;
|
||||
let npm = env.npm?;
|
||||
let mut cmd = std::process::Command::new(&env.node_exe);
|
||||
cmd.arg(&npm).args(["config", "get", "registry"]);
|
||||
// 安装目录可能还没创建(首次安装):退回模块目录,保证能起来
|
||||
let install_root = self.install_root();
|
||||
cmd.current_dir(if install_root.exists() {
|
||||
install_root
|
||||
} else {
|
||||
self.root.clone()
|
||||
});
|
||||
cmd.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.stdin(std::process::Stdio::null());
|
||||
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||
let out = cmd.output().ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
text.lines()
|
||||
.map(|l| l.trim())
|
||||
.find(|l| !l.is_empty())
|
||||
.map(|l| l.trim_end_matches('/').to_string())
|
||||
}
|
||||
|
||||
/// 本次安装/查询实际使用的源 + 来源(供 UI 展示与快捷切换)。
|
||||
pub fn npm_registry_info(&self) -> DshNpmRegistryInfo {
|
||||
let setting = self.registry_setting();
|
||||
let npm_registry = self.npm_config_registry();
|
||||
let (effective, source) = if !setting.is_empty() {
|
||||
(setting.clone(), "setting")
|
||||
} else if let Some(npm) = npm_registry.as_ref() {
|
||||
(npm.clone(), "npm")
|
||||
} else {
|
||||
("https://registry.npmjs.org".to_string(), "fallback")
|
||||
};
|
||||
DshNpmRegistryInfo {
|
||||
effective,
|
||||
source: source.to_string(),
|
||||
npm_registry,
|
||||
setting,
|
||||
}
|
||||
}
|
||||
|
||||
/// 版本查询(reqwest)用的源:与安装保持一致(设置 → npm 配置 → 官方源)。
|
||||
///
|
||||
/// 之前这里在设置为空时硬编码官方源,导致「安装走国内镜像、检查更新却直连
|
||||
/// npmjs.org」的不一致。
|
||||
fn registry_for_query(&self) -> String {
|
||||
self.npm_registry_info().effective
|
||||
}
|
||||
|
||||
/// 查询 npm 上的可用版本(`dist-tags.latest` + 版本列表)。
|
||||
pub async fn check_update(&self) -> Result<DshUpdateInfo, String> {
|
||||
let url = format!("{}/{DSH_PACKAGE}", self.registry_for_query());
|
||||
let resp = self
|
||||
.http_client(30)
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("查询 npm 版本失败: {e}"))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("查询 npm 版本失败: HTTP {}", resp.status().as_u16()));
|
||||
}
|
||||
let value: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("解析 npm 响应失败: {e}"))?;
|
||||
|
||||
let latest = value
|
||||
.get("dist-tags")
|
||||
.and_then(|t| t.get("latest"))
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "npm 响应缺少 dist-tags.latest".to_string())?
|
||||
.to_string();
|
||||
|
||||
let mut versions: Vec<String> = value
|
||||
.get("versions")
|
||||
.and_then(|v| v.as_object())
|
||||
.map(|m| m.keys().cloned().collect())
|
||||
.unwrap_or_default();
|
||||
// 取尾部若干(近似按发布顺序),再反转成最新在前
|
||||
if versions.len() > 20 {
|
||||
versions = versions.split_off(versions.len() - 20);
|
||||
}
|
||||
versions.reverse();
|
||||
|
||||
let current = self.installed_version();
|
||||
Ok(DshUpdateInfo {
|
||||
has_update: current.as_deref() != Some(latest.as_str()),
|
||||
current,
|
||||
latest,
|
||||
versions,
|
||||
})
|
||||
}
|
||||
|
||||
/// 安装 / 更新 dsh(`version` 为空 = 装 latest)。
|
||||
pub async fn install(&self, app: &AppHandle, version: Option<String>) -> Result<DshInstallStatus, String> {
|
||||
self.cancel.store(false, Ordering::SeqCst);
|
||||
// 每次安装开始清空上一次的输出缓冲
|
||||
self.clear_install_log();
|
||||
let result = self.install_inner(app, version).await;
|
||||
self.cancel.store(false, Ordering::SeqCst);
|
||||
if let Err(ref e) = result {
|
||||
if e != NODE_CANCELLED {
|
||||
self.push_install_log(&format!("[错误] {e}"));
|
||||
self.emit_progress(app, "error", 0, 0, None, e);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn install_inner(&self, app: &AppHandle, version: Option<String>) -> Result<DshInstallStatus, String> {
|
||||
let env = self
|
||||
.resolve_node_env()
|
||||
.ok_or_else(|| "未找到可用的 Node,请先完成第 1 步".to_string())?;
|
||||
if !super::satisfies_node_requirement(&env.version) {
|
||||
return Err(format!(
|
||||
"当前 Node {} 不满足 dsh 要求({}),请先安装合规的 Node",
|
||||
env.version,
|
||||
super::NODE_REQUIRED
|
||||
));
|
||||
}
|
||||
let npm = env
|
||||
.npm
|
||||
.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(|| format!("{DSH_PACKAGE}@latest"));
|
||||
|
||||
let install_dir = self.install_root();
|
||||
// npm 的 prefix 目录不存在时由 npm 自己创建;这里先建一次,避免
|
||||
// 自定义到新盘符目录时 npm 因父级缺失报 ENOENT
|
||||
std::fs::create_dir_all(&install_dir)
|
||||
.map_err(|e| format!("创建安装目录失败({}): {e}", install_dir.display()))?;
|
||||
let mut args: Vec<String> = vec![
|
||||
npm.to_string_lossy().to_string(),
|
||||
"install".into(),
|
||||
"--prefix".into(),
|
||||
install_dir.to_string_lossy().to_string(),
|
||||
spec.clone(),
|
||||
"--no-fund".into(),
|
||||
"--no-audit".into(),
|
||||
"--loglevel".into(),
|
||||
"info".into(),
|
||||
];
|
||||
let registry = self.registry_setting();
|
||||
if !registry.is_empty() {
|
||||
// 只在显式指定时才覆盖 npm 自己的配置链
|
||||
args.push("--registry".into());
|
||||
args.push(registry);
|
||||
}
|
||||
|
||||
self.emit_progress(
|
||||
app,
|
||||
"installing",
|
||||
0,
|
||||
0,
|
||||
None,
|
||||
&format!("正在安装 {spec}(依赖较多,请稍候)..."),
|
||||
);
|
||||
|
||||
// npm 不输出百分比:percent 恒为 0(前端按不确定进度展示),
|
||||
// message 跟随 npm 自身的汇总行(`added N packages` 等)更新。
|
||||
//
|
||||
// 逐行输出**只进内存缓冲**(安装引导页临时展示),不写应用日志:
|
||||
// npm 的 72 个依赖会刷出上千行,进应用日志只会淹没真正的运行日志。
|
||||
let progress_app = app.clone();
|
||||
let install_ring = self.install_ring_handle();
|
||||
let on_line = Arc::new(move |line: &str| {
|
||||
super::push_bounded(&install_ring, super::INSTALL_RING_CAPACITY, line);
|
||||
let trimmed = line.trim();
|
||||
if trimmed.starts_with("added ")
|
||||
|| trimmed.starts_with("changed ")
|
||||
|| trimmed.starts_with("removed ")
|
||||
|| trimmed.starts_with("up to date")
|
||||
{
|
||||
let _ = progress_app.emit(
|
||||
crate::constants::events::DSH_INSTALL_PROGRESS,
|
||||
DshInstallProgress {
|
||||
stage: "installing".into(),
|
||||
percent: 0,
|
||||
downloaded_bytes: 0,
|
||||
total_bytes: None,
|
||||
message: trimmed.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
let node_exe = env.node_exe.clone();
|
||||
let pid_ref = self.install_pid.clone();
|
||||
let result = tauri::async_runtime::spawn_blocking(move || {
|
||||
run_npm(node_exe, args, install_dir, pid_ref, on_line)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("安装任务执行失败: {e}"))?;
|
||||
self.install_pid.store(0, Ordering::SeqCst);
|
||||
|
||||
if self.cancel.load(Ordering::SeqCst) {
|
||||
return Err(NODE_CANCELLED.into());
|
||||
}
|
||||
result?;
|
||||
|
||||
let status = self.install_status();
|
||||
if !status.installed {
|
||||
return Err("npm 安装结束,但未找到 dsh 入口(请查看日志)".into());
|
||||
}
|
||||
self.emit_progress(
|
||||
app,
|
||||
"done",
|
||||
100,
|
||||
0,
|
||||
None,
|
||||
&format!(
|
||||
"dsh {} 安装完成",
|
||||
status.version.as_deref().unwrap_or("unknown")
|
||||
),
|
||||
);
|
||||
crate::logger::log_info(
|
||||
"dsh",
|
||||
&format!(
|
||||
"dsh 安装完成: {}",
|
||||
status.version.as_deref().unwrap_or("unknown")
|
||||
),
|
||||
);
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
/// 卸载 dsh:停止服务并删除包目录(保留设置与 $DSH_HOME)。
|
||||
pub fn uninstall(&self, app: &AppHandle) -> Result<(), String> {
|
||||
self.stop_server(app);
|
||||
let dir = self.package_dir();
|
||||
if dir.exists() {
|
||||
std::fs::remove_dir_all(&dir).map_err(|e| format!("删除 dsh 目录失败: {e}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 同步执行 npm(阻塞线程内),逐行读输出交给 `on_line`;pid 记录供取消时 taskkill。
|
||||
fn run_npm(
|
||||
node_exe: PathBuf,
|
||||
args: Vec<String>,
|
||||
cwd: PathBuf,
|
||||
pid_ref: Arc<std::sync::atomic::AtomicU64>,
|
||||
on_line: Arc<dyn Fn(&str) + Send + Sync>,
|
||||
) -> Result<(), String> {
|
||||
let mut cmd = std::process::Command::new(&node_exe);
|
||||
cmd.args(&args);
|
||||
cmd.current_dir(&cwd);
|
||||
cmd.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.stdin(std::process::Stdio::null());
|
||||
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||
|
||||
let mut child = cmd
|
||||
.spawn()
|
||||
.map_err(|e| format!("启动 npm 失败({}): {e}", node_exe.display()))?;
|
||||
let pid = child.id();
|
||||
pid_ref.store(pid as u64, Ordering::SeqCst);
|
||||
|
||||
let stdout = child.stdout.take();
|
||||
let stderr = child.stderr.take();
|
||||
|
||||
// 末 40 行留作失败时的错误摘要
|
||||
let tail = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
|
||||
let mut handles = Vec::new();
|
||||
let pipes: [Option<Box<dyn std::io::Read + Send>>; 2] = [
|
||||
stdout.map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
|
||||
stderr.map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
|
||||
];
|
||||
for pipe in pipes.into_iter().flatten() {
|
||||
let on_line = on_line.clone();
|
||||
let tail = tail.clone();
|
||||
handles.push(std::thread::spawn(move || {
|
||||
let reader = BufReader::new(pipe);
|
||||
for line in reader.lines().map_while(Result::ok) {
|
||||
on_line(&line);
|
||||
if let Ok(mut t) = tail.lock() {
|
||||
if t.len() >= 40 {
|
||||
t.remove(0);
|
||||
}
|
||||
t.push(line);
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
let status = child.wait();
|
||||
for h in handles {
|
||||
let _ = h.join();
|
||||
}
|
||||
pid_ref.store(0, Ordering::SeqCst);
|
||||
|
||||
let status = status.map_err(|e| format!("等待 npm 结束失败: {e}"))?;
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let text = tail.lock().map(|t| t.join("\n")).unwrap_or_default();
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let skip = chars.len().saturating_sub(800);
|
||||
Err(format!(
|
||||
"npm 退出码 {}: {}",
|
||||
status.code().unwrap_or(-1),
|
||||
chars[skip..].iter().collect::<String>()
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
//! dsh 模块(DeepSeek Harness 外壳)。
|
||||
//!
|
||||
//! 模块定位:为 DeepSeek Harness(npm 包 `@deepseek-ai/dsh`)做安装、更新与
|
||||
//! 生命周期管理,并把主设置里的 AI 供应商(含 DeepSeek API Key)装载给 dsh。
|
||||
//! 模块页不内嵌浏览器,dsh 的 Web UI 通过独立窗口 / 系统浏览器打开。
|
||||
//!
|
||||
//! 目录布局(`{app_data_dir}/dsh`):
|
||||
//! ```text
|
||||
//! settings.json 模块自身设置(版本号 + 自愈)
|
||||
//! node/ 便携 Node(仅系统 Node 不可用时)
|
||||
//! node_modules/ @deepseek-ai/dsh 本地安装(npm --prefix)
|
||||
//! home/ $DSH_HOME(settings.yaml / profiles / 会话)
|
||||
//! workspace/ 默认工作区(dsh 进程的启动目录)
|
||||
//! logs/web.log dsh 服务输出
|
||||
//! ```
|
||||
//!
|
||||
//! 安全姿态:模块设置不含任何密钥;API Key 只在 spawn 子进程时以环境变量注入
|
||||
//! (明文来自系统凭据管理器,见 [`crate::secrets`]),不写 dsh 的
|
||||
//! `.credentials.yaml`、不落日志、不过前端。
|
||||
|
||||
mod ai_sync;
|
||||
mod commands;
|
||||
mod install;
|
||||
mod node;
|
||||
mod server;
|
||||
mod types;
|
||||
|
||||
pub use commands::{
|
||||
dsh_ai_preview, dsh_ai_sync, dsh_cancel_install, dsh_check_update, dsh_env_status,
|
||||
dsh_get_settings, dsh_install, dsh_install_log, dsh_log_clear, dsh_log_tail,
|
||||
dsh_node_detect, dsh_node_install, dsh_npm_registry_info, dsh_open_dir,
|
||||
dsh_register_shortcut, dsh_restart, dsh_save_settings, dsh_start, dsh_stop,
|
||||
dsh_uninstall, dsh_unregister_shortcut, dsh_update,
|
||||
};
|
||||
pub use commands::autostart_if_enabled;
|
||||
// 仅重导出模块自身与子模块会经 `super::` 用到的类型(其余由各子模块直接从 types 取)
|
||||
pub use types::{DshInstallProgress, DshSettings, NODE_REQUIRED};
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Child;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tauri::AppHandle;
|
||||
|
||||
/// 设置内存缓存有效期(与其他模块的 500ms 一致)。
|
||||
const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500);
|
||||
/// 日志环形缓冲保留的最大行数(供「日志」页签快速读取)。
|
||||
const LOG_RING_CAPACITY: usize = 500;
|
||||
/// 安装输出缓冲保留的最大行数(npm 输出较啰嗦,只留最近一段)。
|
||||
const INSTALL_RING_CAPACITY: usize = 200;
|
||||
|
||||
/// 服务进程条目(自管 stdio,不走 ProcessManager)。
|
||||
pub(crate) struct ServerEntry {
|
||||
pub child: Child,
|
||||
pub pid: u32,
|
||||
pub port: u16,
|
||||
/// 启动时间(unix 秒)
|
||||
pub started_at: i64,
|
||||
}
|
||||
|
||||
struct SettingsCacheEntry {
|
||||
read_at: Instant,
|
||||
settings: DshSettings,
|
||||
}
|
||||
|
||||
/// 解析出的 Node 运行环境。
|
||||
pub(crate) struct NodeEnv {
|
||||
/// system | managed
|
||||
pub source: &'static str,
|
||||
pub node_exe: PathBuf,
|
||||
/// npm 入口(`node_modules/npm/bin/npm-cli.js`,用 `node <此路径>` 调用)
|
||||
pub npm: Option<PathBuf>,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
/// dsh 模块管理器(Tauri State)。
|
||||
pub struct DshManager {
|
||||
/// 应用数据目录(`{app_data_dir}`)
|
||||
data_dir: PathBuf,
|
||||
/// 模块根目录(`{app_data_dir}/dsh`)
|
||||
root: PathBuf,
|
||||
settings_cache: Mutex<Option<SettingsCacheEntry>>,
|
||||
/// 安装/下载取消标志
|
||||
cancel: Arc<AtomicBool>,
|
||||
/// 安装子进程 pid(取消时 taskkill /T)
|
||||
install_pid: Arc<AtomicU64>,
|
||||
/// 服务进程
|
||||
server: Mutex<Option<ServerEntry>>,
|
||||
/// 启动串行化锁(防并发双开)
|
||||
start_lock: Mutex<()>,
|
||||
/// HTTP 就绪标志
|
||||
ready: Arc<AtomicBool>,
|
||||
/// 本次进程的「带 token 启动地址」(从 dsh stdout 抓取)。
|
||||
/// dsh web 的浏览器鉴权靠它首次访问换取 cookie,没它就只会拿到 401。
|
||||
launch_url: Arc<Mutex<Option<String>>>,
|
||||
/// 最近一次启动错误(端口占用 / 进程立即退出)
|
||||
server_error: Mutex<Option<String>>,
|
||||
/// 日志环形缓冲
|
||||
log_ring: Arc<Mutex<VecDeque<String>>>,
|
||||
/// 安装(npm)输出缓冲:只在模块页临时展示,**不落应用日志、不落盘**
|
||||
install_ring: Arc<Mutex<VecDeque<String>>>,
|
||||
}
|
||||
|
||||
impl DshManager {
|
||||
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||
let root = app_data_dir.join("dsh");
|
||||
for d in ["node", "logs", "home", "workspace"] {
|
||||
std::fs::create_dir_all(root.join(d)).ok();
|
||||
}
|
||||
Self {
|
||||
data_dir: app_data_dir,
|
||||
root,
|
||||
settings_cache: Mutex::new(None),
|
||||
cancel: Arc::new(AtomicBool::new(false)),
|
||||
install_pid: Arc::new(AtomicU64::new(0)),
|
||||
server: Mutex::new(None),
|
||||
start_lock: Mutex::new(()),
|
||||
ready: Arc::new(AtomicBool::new(false)),
|
||||
launch_url: Arc::new(Mutex::new(None)),
|
||||
server_error: Mutex::new(None),
|
||||
log_ring: Arc::new(Mutex::new(VecDeque::with_capacity(LOG_RING_CAPACITY))),
|
||||
install_ring: Arc::new(Mutex::new(VecDeque::with_capacity(INSTALL_RING_CAPACITY))),
|
||||
}
|
||||
}
|
||||
|
||||
/// 模块根目录(「在文件夹中打开」用)
|
||||
pub fn root(&self) -> &PathBuf {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// 便携 Node 目录
|
||||
pub fn node_dir(&self) -> PathBuf {
|
||||
self.root.join("node")
|
||||
}
|
||||
|
||||
/// dsh 本体的安装根目录(npm `--prefix` 目标)。
|
||||
///
|
||||
/// 设置留空 = 模块目录。自定义时**只有 dsh 本体与它的 node_modules 跟随**,
|
||||
/// 便携 Node / `$DSH_HOME` / 日志 / 模块设置仍留在应用数据目录——自定义路径
|
||||
/// 若被移动或卸载,至少配置与日志还读得到,排障不会失联。
|
||||
pub fn install_root(&self) -> PathBuf {
|
||||
let raw = self.load_settings().install_dir;
|
||||
let raw = raw.trim();
|
||||
if raw.is_empty() {
|
||||
self.root.clone()
|
||||
} else {
|
||||
PathBuf::from(raw)
|
||||
}
|
||||
}
|
||||
|
||||
/// `$DSH_HOME`
|
||||
pub fn home_dir(&self) -> PathBuf {
|
||||
let settings = self.load_settings();
|
||||
if settings.dsh_home_mode == "user" {
|
||||
dirs::home_dir()
|
||||
.map(|h| h.join(".dsh"))
|
||||
.unwrap_or_else(|| self.root.join("home"))
|
||||
} else {
|
||||
self.root.join("home")
|
||||
}
|
||||
}
|
||||
|
||||
/// dsh 进程的启动目录(工作区)
|
||||
pub fn workspace_dir(&self) -> PathBuf {
|
||||
let settings = self.load_settings();
|
||||
let raw = settings.workspace.trim();
|
||||
let dir = if raw.is_empty() {
|
||||
self.root.join("workspace")
|
||||
} else {
|
||||
PathBuf::from(raw)
|
||||
};
|
||||
std::fs::create_dir_all(&dir).ok();
|
||||
dir
|
||||
}
|
||||
|
||||
pub fn log_path(&self) -> PathBuf {
|
||||
self.root.join("logs").join("web.log")
|
||||
}
|
||||
|
||||
pub fn settings_path(&self) -> PathBuf {
|
||||
self.root.join("settings.json")
|
||||
}
|
||||
|
||||
// ---------- 设置 ----------
|
||||
|
||||
pub fn load_settings(&self) -> DshSettings {
|
||||
if let Ok(cache) = self.settings_cache.lock() {
|
||||
if let Some(entry) = cache.as_ref() {
|
||||
if entry.read_at.elapsed() < SETTINGS_CACHE_TTL {
|
||||
return entry.settings.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut settings = std::fs::read_to_string(self.settings_path())
|
||||
.ok()
|
||||
.and_then(|t| serde_json::from_str::<DshSettings>(&t).ok())
|
||||
.unwrap_or_default();
|
||||
let changed = settings.heal();
|
||||
if changed {
|
||||
self.write_settings(&settings).ok();
|
||||
}
|
||||
if let Ok(mut cache) = self.settings_cache.lock() {
|
||||
*cache = Some(SettingsCacheEntry {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
pub fn save_settings(&self, mut settings: DshSettings) -> Result<DshSettings, String> {
|
||||
// 自定义安装目录必须是绝对路径:npm 的 --prefix 用相对路径会落到
|
||||
// 进程当前目录(开发期即仓库根目录),这种"看起来生效其实装错地方"最难排查
|
||||
let custom = settings.install_dir.trim();
|
||||
if !custom.is_empty() && !std::path::Path::new(custom).is_absolute() {
|
||||
return Err("dsh 安装目录必须是绝对路径(如 D:/Thing/dsh)".to_string());
|
||||
}
|
||||
settings.heal();
|
||||
self.write_settings(&settings)?;
|
||||
if let Ok(mut cache) = self.settings_cache.lock() {
|
||||
*cache = Some(SettingsCacheEntry {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
fn write_settings(&self, settings: &DshSettings) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(settings)
|
||||
.map_err(|e| format!("序列化 dsh 设置失败: {e}"))?;
|
||||
std::fs::write(self.settings_path(), json).map_err(|e| format!("写入 dsh 设置失败: {e}"))
|
||||
}
|
||||
|
||||
// ---------- 日志 ----------
|
||||
|
||||
/// 追加一行到环形缓冲 + 落盘(服务输出走这里)。
|
||||
pub(crate) fn push_log(&self, line: &str) {
|
||||
push_log_shared(&self.log_ring, &self.log_path(), line);
|
||||
}
|
||||
|
||||
/// 读取日志:优先环形缓冲;为空时回落到文件尾部。
|
||||
pub fn log_tail(&self, lines: usize) -> String {
|
||||
let lines = lines.clamp(1, LOG_RING_CAPACITY);
|
||||
if let Ok(ring) = self.log_ring.lock() {
|
||||
if !ring.is_empty() {
|
||||
let skip = ring.len().saturating_sub(lines);
|
||||
return ring
|
||||
.iter()
|
||||
.skip(skip)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
}
|
||||
}
|
||||
let text = std::fs::read_to_string(self.log_path()).unwrap_or_default();
|
||||
let all: Vec<&str> = text.lines().collect();
|
||||
let skip = all.len().saturating_sub(lines);
|
||||
all[skip..].join("\n")
|
||||
}
|
||||
|
||||
pub fn clear_log(&self) {
|
||||
if let Ok(mut ring) = self.log_ring.lock() {
|
||||
ring.clear();
|
||||
}
|
||||
std::fs::write(self.log_path(), b"").ok();
|
||||
}
|
||||
|
||||
// ---------- 安装输出(仅内存,供安装引导页临时展示) ----------
|
||||
|
||||
/// 追加一行安装输出(已过滤疑似密钥)。
|
||||
pub(crate) fn push_install_log(&self, line: &str) {
|
||||
push_bounded(&self.install_ring, INSTALL_RING_CAPACITY, line);
|
||||
}
|
||||
|
||||
/// 读取当前安装输出(每次安装开始时清空)。
|
||||
pub fn install_log(&self) -> String {
|
||||
self.install_ring
|
||||
.lock()
|
||||
.map(|r| r.iter().cloned().collect::<Vec<_>>().join("\n"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn clear_install_log(&self) {
|
||||
if let Ok(mut ring) = self.install_ring.lock() {
|
||||
ring.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// 安装输出缓冲句柄(阻塞线程内的 on_line 闭包持有;'static 需要)。
|
||||
pub(crate) fn install_ring_handle(
|
||||
&self,
|
||||
) -> Arc<Mutex<VecDeque<String>>> {
|
||||
self.install_ring.clone()
|
||||
}
|
||||
|
||||
// ---------- 代理 ----------
|
||||
|
||||
/// 按设置解析代理地址(mihomo mixed 端口)。返回 None 表示直连。
|
||||
///
|
||||
/// 只读代理模块设置文件里的 mixedPort,并用一次 300ms TCP 探测确认内核在线;
|
||||
/// 内核没起来时静默直连(与 download_engine / translate 的降级姿态一致)。
|
||||
pub(crate) fn proxy_url(&self) -> Option<String> {
|
||||
if !self.load_settings().use_proxy {
|
||||
return None;
|
||||
}
|
||||
let text = std::fs::read_to_string(self.data_dir.join("proxy").join("settings.json")).ok()?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
let port = value.get("mixedPort").and_then(|v| v.as_u64())?;
|
||||
if port == 0 || port > u16::MAX as u64 {
|
||||
return None;
|
||||
}
|
||||
let port = port as u16;
|
||||
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
|
||||
if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(300)).is_err() {
|
||||
return None;
|
||||
}
|
||||
Some(format!("http://127.0.0.1:{port}"))
|
||||
}
|
||||
|
||||
// ---------- 事件 ----------
|
||||
|
||||
/// 推送安装/下载进度(stage: download | extracting | installing | done | error)。
|
||||
pub(crate) fn emit_progress(
|
||||
&self,
|
||||
app: &AppHandle,
|
||||
stage: &str,
|
||||
percent: u8,
|
||||
downloaded_bytes: u64,
|
||||
total_bytes: Option<u64>,
|
||||
message: &str,
|
||||
) {
|
||||
use tauri::Emitter;
|
||||
let _ = app.emit(
|
||||
crate::constants::events::DSH_INSTALL_PROGRESS,
|
||||
DshInstallProgress {
|
||||
stage: stage.into(),
|
||||
percent,
|
||||
downloaded_bytes,
|
||||
total_bytes,
|
||||
message: message.into(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// 推送服务状态(启动/停止/就绪变化时)。
|
||||
pub(crate) fn emit_server_state(&self, app: &AppHandle) {
|
||||
use tauri::Emitter;
|
||||
let status = self.server_status();
|
||||
let _ = app.emit(crate::constants::events::DSH_SERVER_STATE, status);
|
||||
}
|
||||
|
||||
/// 构造 reqwest 客户端:按代理设置决定是否走 mihomo。
|
||||
pub(crate) fn http_client(&self, timeout_secs: u64) -> reqwest::Client {
|
||||
let mut builder = reqwest::Client::builder()
|
||||
.user_agent("thing-app")
|
||||
.timeout(Duration::from_secs(timeout_secs));
|
||||
if let Some(proxy) = self.proxy_url() {
|
||||
if let Ok(p) = reqwest::Proxy::all(&proxy) {
|
||||
builder = builder.proxy(p);
|
||||
}
|
||||
}
|
||||
builder.build().unwrap_or_else(|_| reqwest::Client::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// 过滤日志行里的疑似密钥(`sk-` 形态)与 URL 里的会话令牌。
|
||||
pub(crate) fn sanitize_log_line(line: &str) -> String {
|
||||
let line = mask_token_in_url(line);
|
||||
let mut out = String::with_capacity(line.len());
|
||||
for token in line.split_inclusive(char::is_whitespace) {
|
||||
let trimmed = token.trim_end();
|
||||
if trimmed.starts_with("sk-") && trimmed.len() > 12 {
|
||||
out.push_str("sk-***");
|
||||
out.push_str(&token[trimmed.len()..]);
|
||||
} else {
|
||||
out.push_str(token);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 掩码 URL 里的 `token=` 取值(`?token=xxx` → `?token=***`)。
|
||||
///
|
||||
/// dsh web 的浏览器会话令牌等同于「对该 loopback 服务(能执行代码)的完全访问权」,
|
||||
/// 不该落进应用日志与 logs/web.log;真正的带令牌地址经 IPC 单独给前端使用。
|
||||
fn mask_token_in_url(line: &str) -> String {
|
||||
const NEEDLE: &str = "token=";
|
||||
let mut out = String::with_capacity(line.len());
|
||||
let mut cursor = 0usize;
|
||||
while let Some(rel) = line[cursor..].find(NEEDLE) {
|
||||
let start = cursor + rel + NEEDLE.len();
|
||||
out.push_str(&line[cursor..start]);
|
||||
let after = &line[start..];
|
||||
let end = after
|
||||
.find(|c: char| c.is_whitespace() || matches!(c, ')' | ',' | '"' | '\'' | '&'))
|
||||
.unwrap_or(after.len());
|
||||
out.push_str("***");
|
||||
cursor = start + end;
|
||||
}
|
||||
out.push_str(&line[cursor..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// 从 dsh 输出行里解析「带 token 的启动地址」。
|
||||
///
|
||||
/// `dsh web` 就绪后会打印(见 dsh-web-app 的 announceReady):
|
||||
/// `dsh web: http://127.0.0.1:3080/?token=<随机令牌> (LAN: http://<lan>:3080/?token=<...>)`
|
||||
///
|
||||
/// 浏览器鉴权靠这个地址首次访问换取签名 cookie(dsh-client-connection 的 BrowserAuth);
|
||||
/// 令牌是**每次进程随机生成**的,无法推导,只能从输出里取。
|
||||
/// 取第一个(loopback)地址,忽略随后的 LAN 地址。
|
||||
pub(crate) fn parse_launch_url(line: &str) -> Option<String> {
|
||||
let start = line.find("http://").or_else(|| line.find("https://"))?;
|
||||
let rest = &line[start..];
|
||||
let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
|
||||
let url = rest[..end].trim_end_matches(|c: char| c == ')' || c == ',');
|
||||
url.contains("token=").then(|| url.to_string())
|
||||
}
|
||||
|
||||
/// 共享的日志写入(服务 stdout/stderr reader 线程与探测线程用)。
|
||||
///
|
||||
/// reader 线程拿不到 `&DshManager`(需要 'static),因此把环形缓冲与日志路径
|
||||
/// 单独传进来。
|
||||
pub(crate) fn push_log_shared(
|
||||
ring: &Arc<Mutex<VecDeque<String>>>,
|
||||
log_path: &PathBuf,
|
||||
line: &str,
|
||||
) {
|
||||
let line = push_bounded(ring, LOG_RING_CAPACITY, line);
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(log_path)
|
||||
{
|
||||
use std::io::Write;
|
||||
let _ = writeln!(f, "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// 有界环形缓冲追加(**不落盘**),返回写入后的文本。
|
||||
///
|
||||
/// 安装输出走这里:只要内存,不写应用日志、不写文件——用户明确要求安装日志
|
||||
/// 仅在安装引导页临时展示(npm 输出啰嗦,进应用日志只会淹没真正的运行日志)。
|
||||
pub(crate) fn push_bounded(
|
||||
ring: &Arc<Mutex<VecDeque<String>>>,
|
||||
capacity: usize,
|
||||
line: &str,
|
||||
) -> String {
|
||||
let line = sanitize_log_line(line);
|
||||
if let Ok(mut r) = ring.lock() {
|
||||
if r.len() >= capacity {
|
||||
r.pop_front();
|
||||
}
|
||||
r.push_back(line.clone());
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// 解析 "v24.9.0" / "24.9.0" → (24, 9, 0)
|
||||
pub(crate) fn parse_version(raw: &str) -> Option<(u32, u32, u32)> {
|
||||
let cleaned = raw.trim().trim_start_matches('v');
|
||||
let core = cleaned.split('-').next().unwrap_or(cleaned);
|
||||
let mut it = core.split('.');
|
||||
let major = it.next()?.parse::<u32>().ok()?;
|
||||
let minor = it.next().unwrap_or("0").parse::<u32>().ok()?;
|
||||
let patch = it.next().unwrap_or("0").parse::<u32>().ok()?;
|
||||
Some((major, minor, patch))
|
||||
}
|
||||
|
||||
/// 是否满足 dsh 的要求:`^22.19.0 || >=24.0.0`
|
||||
pub(crate) fn satisfies_node_requirement(raw: &str) -> bool {
|
||||
let Some((major, minor, patch)) = parse_version(raw) else {
|
||||
return false;
|
||||
};
|
||||
match major {
|
||||
22 => (minor, patch) >= (19, 0),
|
||||
24.. => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
//! Node 运行环境:探测系统 Node / 下载并解压便携 Node。
|
||||
//!
|
||||
//! dsh 要求 Node `^22.19.0 || >=24.0.0`。策略(用户已确认):
|
||||
//! 优先复用 PATH 上的系统 Node,版本不满足或缺失时才下载官方便携版到
|
||||
//! `{app_data}/dsh/node`(官方 zip 内含 npm/npx,因此托管 Node 自带 npm)。
|
||||
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use tauri::AppHandle;
|
||||
|
||||
use super::types::{NodeStatus, NODE_REQUIRED};
|
||||
use super::{satisfies_node_requirement, DshManager, NodeEnv};
|
||||
|
||||
/// 用户取消时返回的错误信息(前端静默处理,不弹错误 toast)。
|
||||
pub(crate) const NODE_CANCELLED: &str = "已取消";
|
||||
|
||||
impl DshManager {
|
||||
/// 系统 PATH 上的 node.exe
|
||||
pub fn system_node(&self) -> Option<PathBuf> {
|
||||
which_node()
|
||||
}
|
||||
|
||||
/// 托管便携 Node 的 node.exe
|
||||
pub fn managed_node(&self) -> Option<PathBuf> {
|
||||
let exe = self.node_dir().join(if cfg!(windows) { "node.exe" } else { "bin/node" });
|
||||
exe.exists().then_some(exe)
|
||||
}
|
||||
|
||||
/// 解析实际使用的 Node 环境(按 nodeSource 设置)。
|
||||
pub fn resolve_node_env(&self) -> Option<NodeEnv> {
|
||||
let settings = self.load_settings();
|
||||
let system = self.system_node();
|
||||
let managed = self.managed_node();
|
||||
|
||||
let system_ok = system
|
||||
.as_ref()
|
||||
.and_then(|p| node_version(p))
|
||||
.map(|v| satisfies_node_requirement(&v))
|
||||
.unwrap_or(false);
|
||||
|
||||
// 选定 (是否托管, 可执行文件)
|
||||
let chosen: Option<(bool, PathBuf)> = match settings.node_source.as_str() {
|
||||
"system" => system.map(|p| (false, p)),
|
||||
"managed" => managed.map(|p| (true, p)),
|
||||
// auto:系统满足即复用,否则回落托管;两者都没有时退回系统 Node 仅用于展示版本
|
||||
_ => {
|
||||
if system_ok {
|
||||
system.map(|p| (false, p))
|
||||
} else {
|
||||
managed
|
||||
.map(|p| (true, p))
|
||||
.or_else(|| system.map(|p| (false, p)))
|
||||
}
|
||||
}
|
||||
};
|
||||
let (is_managed, exe) = chosen?;
|
||||
|
||||
let version = node_version(&exe).unwrap_or_default();
|
||||
let npm = npm_cli_js(&exe);
|
||||
Some(NodeEnv {
|
||||
source: if is_managed { "managed" } else { "system" },
|
||||
node_exe: exe,
|
||||
npm,
|
||||
version,
|
||||
})
|
||||
}
|
||||
|
||||
/// 当前 Node 状态(供 UI 首屏展示)。
|
||||
pub fn node_status(&self) -> NodeStatus {
|
||||
match self.resolve_node_env() {
|
||||
Some(env) => {
|
||||
let satisfies = satisfies_node_requirement(&env.version);
|
||||
NodeStatus {
|
||||
source: if env.source == "managed" { "managed".into() } else { "system".into() },
|
||||
path: Some(env.node_exe.to_string_lossy().to_string()),
|
||||
version: Some(env.version),
|
||||
satisfies,
|
||||
required: NODE_REQUIRED.into(),
|
||||
}
|
||||
}
|
||||
None => NodeStatus {
|
||||
source: "none".into(),
|
||||
path: None,
|
||||
version: None,
|
||||
satisfies: false,
|
||||
required: NODE_REQUIRED.into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// 下载并安装便携 Node(进度经 `dsh-install-progress` 推送)。
|
||||
///
|
||||
/// `version` 为空时自动解析满足要求的最新版本(优先 LTS)。
|
||||
pub async fn node_install(&self, app: &AppHandle, version: Option<String>) -> Result<NodeStatus, String> {
|
||||
if !cfg!(windows) {
|
||||
return Err("便携 Node 安装仅支持 Windows,请改用系统 Node(nodeSource = system)".into());
|
||||
}
|
||||
self.cancel.store(false, Ordering::SeqCst);
|
||||
let result = self.node_install_inner(app, version).await;
|
||||
self.cancel.store(false, Ordering::SeqCst);
|
||||
if let Err(ref e) = result {
|
||||
if e != NODE_CANCELLED {
|
||||
self.emit_progress(app, "error", 0, 0, None, e);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn node_install_inner(&self, app: &AppHandle, version: Option<String>) -> Result<NodeStatus, String> {
|
||||
let base = self.node_mirror_base();
|
||||
let version = match version.filter(|v| !v.trim().is_empty()) {
|
||||
Some(v) => normalize_version(&v),
|
||||
None => {
|
||||
self.emit_progress(app, "download", 0, 0, None, "正在解析 Node 版本...");
|
||||
let requested = self.load_settings().managed_node_version;
|
||||
if requested.trim().is_empty() {
|
||||
self.resolve_latest_node_version(&base).await?
|
||||
} else {
|
||||
normalize_version(&requested)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let arch = platform_arch();
|
||||
let url = format!("{base}/{version}/node-{version}-{arch}.zip");
|
||||
let zip_path = self.node_dir().join("node-download.zip");
|
||||
self.emit_progress(
|
||||
app,
|
||||
"download",
|
||||
1,
|
||||
0,
|
||||
None,
|
||||
&format!("正在下载 Node {version}..."),
|
||||
);
|
||||
self.download_to_file(app, &url, &zip_path, "正在下载 Node").await?;
|
||||
|
||||
if self.cancel.load(Ordering::SeqCst) {
|
||||
let _ = fs::remove_file(&zip_path);
|
||||
return Err(NODE_CANCELLED.into());
|
||||
}
|
||||
|
||||
// 解压:官方 zip 顶层是 node-vX-win-x64/,剥掉这一层直接落到 node/
|
||||
self.emit_progress(app, "extracting", 92, 0, None, "正在解压...");
|
||||
let dest = self.node_dir();
|
||||
if dest.exists() {
|
||||
fs::remove_dir_all(&dest).map_err(|e| format!("清理旧 Node 目录失败: {e}"))?;
|
||||
}
|
||||
fs::create_dir_all(&dest).map_err(|e| format!("创建 Node 目录失败: {e}"))?;
|
||||
if let Err(e) = extract_zip_strip_top(&zip_path, &dest) {
|
||||
let _ = fs::remove_file(&zip_path);
|
||||
return Err(format!("解压 Node 失败: {e}"));
|
||||
}
|
||||
let _ = fs::remove_file(&zip_path);
|
||||
|
||||
let exe = dest.join("node.exe");
|
||||
if !exe.exists() {
|
||||
return Err("解压后未找到 node.exe".into());
|
||||
}
|
||||
let actual = node_version(&exe).unwrap_or(version.clone());
|
||||
self.emit_progress(app, "done", 100, 0, None, &format!("Node {actual} 安装完成"));
|
||||
crate::logger::log_info("dsh", &format!("便携 Node 安装完成: {actual} ({})", exe.display()));
|
||||
Ok(self.node_status())
|
||||
}
|
||||
|
||||
/// 托管 Node 的镜像基址(`{base}/{version}/node-{version}-win-x64.zip`)。
|
||||
fn node_mirror_base(&self) -> String {
|
||||
let mirror = self.load_settings().node_mirror;
|
||||
let mirror = mirror.trim().trim_end_matches('/');
|
||||
if mirror.is_empty() {
|
||||
"https://nodejs.org/dist".to_string()
|
||||
} else {
|
||||
mirror.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析满足要求的最新 Node 版本(优先 LTS)。
|
||||
async fn resolve_latest_node_version(&self, base: &str) -> Result<String, String> {
|
||||
let url = format!("{base}/index.json");
|
||||
let resp = self
|
||||
.http_client(30)
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("获取 Node 版本列表失败: {e}"))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("获取 Node 版本列表失败: HTTP {}", resp.status().as_u16()));
|
||||
}
|
||||
let list: Vec<serde_json::Value> = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("解析 Node 版本列表失败: {e}"))?;
|
||||
|
||||
let mut latest_lts: Option<(u32, u32, u32, String)> = None;
|
||||
let mut latest_any: Option<(u32, u32, u32, String)> = None;
|
||||
for item in list {
|
||||
let Some(version) = item.get("version").and_then(|v| v.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
if !satisfies_node_requirement(version) {
|
||||
continue;
|
||||
}
|
||||
let Some(parsed) = super::parse_version(version) else {
|
||||
continue;
|
||||
};
|
||||
let is_lts = item.get("lts").map(|l| !l.is_null() && l != false).unwrap_or(false);
|
||||
if latest_any.as_ref().map(|(maj, min, pat, _)| (parsed.0, parsed.1, parsed.2) > (*maj, *min, *pat)).unwrap_or(true) {
|
||||
latest_any = Some((parsed.0, parsed.1, parsed.2, version.to_string()));
|
||||
}
|
||||
if is_lts
|
||||
&& latest_lts
|
||||
.as_ref()
|
||||
.map(|(maj, min, pat, _)| (parsed.0, parsed.1, parsed.2) > (*maj, *min, *pat))
|
||||
.unwrap_or(true)
|
||||
{
|
||||
latest_lts = Some((parsed.0, parsed.1, parsed.2, version.to_string()));
|
||||
}
|
||||
}
|
||||
latest_lts
|
||||
.or(latest_any)
|
||||
.map(|(_, _, _, v)| v)
|
||||
.ok_or_else(|| "未找到满足 dsh 要求的 Node 版本".to_string())
|
||||
}
|
||||
|
||||
/// 流式下载到文件(带取消 + 进度事件,percent 0-90)。
|
||||
pub(crate) async fn download_to_file(
|
||||
&self,
|
||||
app: &AppHandle,
|
||||
url: &str,
|
||||
dest: &Path,
|
||||
label: &str,
|
||||
) -> Result<(), String> {
|
||||
let resp = self
|
||||
.http_client(1800)
|
||||
.get(url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("请求下载失败({url}): {e}"))?;
|
||||
let status = resp.status();
|
||||
if !status.is_success() {
|
||||
return Err(format!("下载返回 HTTP {}", status.as_u16()));
|
||||
}
|
||||
let total = resp.content_length();
|
||||
let mut file = fs::File::create(dest).map_err(|e| format!("创建文件失败: {e}"))?;
|
||||
let mut stream = resp.bytes_stream();
|
||||
let mut downloaded: u64 = 0;
|
||||
let mut last_percent: u8 = 0;
|
||||
while let Some(chunk) = stream.next().await {
|
||||
if self.cancel.load(Ordering::SeqCst) {
|
||||
drop(file);
|
||||
fs::remove_file(dest).ok();
|
||||
return Err(NODE_CANCELLED.into());
|
||||
}
|
||||
let chunk = chunk.map_err(|e| format!("下载中断: {e}"))?;
|
||||
file.write_all(&chunk).map_err(|e| format!("写入文件失败: {e}"))?;
|
||||
downloaded += chunk.len() as u64;
|
||||
let percent = total
|
||||
.filter(|t| *t > 0)
|
||||
.map(|t| ((downloaded as f64 / t as f64) * 90.0) as u8)
|
||||
.unwrap_or(0)
|
||||
.min(90);
|
||||
if percent >= last_percent + 1 {
|
||||
last_percent = percent;
|
||||
self.emit_progress(
|
||||
app,
|
||||
"download",
|
||||
percent,
|
||||
downloaded,
|
||||
total,
|
||||
&format!("{label} {:.1} MB", downloaded as f64 / 1048576.0),
|
||||
);
|
||||
}
|
||||
}
|
||||
file.flush().ok();
|
||||
self.emit_progress(app, "download", 90, downloaded, total, "下载完成");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 请求取消(下载 / 安装 / 解压均轮询此标志)。
|
||||
pub(crate) fn request_cancel(&self) {
|
||||
self.cancel.store(true, Ordering::SeqCst);
|
||||
let pid = self.install_pid.load(Ordering::SeqCst);
|
||||
if pid > 0 {
|
||||
taskkill_tree(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 官方分发包的平台标识(Windows x64 / arm64)。
|
||||
fn platform_arch() -> &'static str {
|
||||
match std::env::consts::ARCH {
|
||||
"aarch64" => "win-arm64",
|
||||
_ => "win-x64",
|
||||
}
|
||||
}
|
||||
|
||||
/// PATH 上查找 node 可执行文件。
|
||||
fn which_node() -> Option<PathBuf> {
|
||||
let name = if cfg!(windows) { "node.exe" } else { "node" };
|
||||
let path_var = std::env::var_os("PATH")?;
|
||||
for dir in std::env::split_paths(&path_var) {
|
||||
let candidate = dir.join(name);
|
||||
if candidate.is_file() {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 取 node 目录下的 npm 入口(`node_modules/npm/bin/npm-cli.js`)。
|
||||
///
|
||||
/// 直接 `node npm-cli.js` 而不是 `npm.cmd`:`.cmd` 在 Windows 上无法被
|
||||
/// CreateProcess 直接执行(需经 `cmd /C`,而 cmd 的引号规则易踩坑),
|
||||
/// 且批处理 shim 会多出一层进程影响取消时的进程树清理。
|
||||
fn npm_cli_js(node_exe: &Path) -> Option<PathBuf> {
|
||||
let dir = node_exe.parent()?;
|
||||
let candidates = [
|
||||
dir.join("node_modules").join("npm").join("bin").join("npm-cli.js"),
|
||||
dir.join("lib").join("node_modules").join("npm").join("bin").join("npm-cli.js"),
|
||||
];
|
||||
candidates.into_iter().find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// 执行 `node --version` 取版本号。
|
||||
fn node_version(node_exe: &Path) -> Option<String> {
|
||||
let mut cmd = std::process::Command::new(node_exe);
|
||||
cmd.arg("--version");
|
||||
cmd.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.stdin(std::process::Stdio::null());
|
||||
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||
let out = cmd.output().ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
(!text.is_empty()).then_some(text)
|
||||
}
|
||||
|
||||
/// 规范化版本号:补上 `v` 前缀。
|
||||
fn normalize_version(raw: &str) -> String {
|
||||
let t = raw.trim();
|
||||
if t.starts_with('v') {
|
||||
t.to_string()
|
||||
} else {
|
||||
format!("v{t}")
|
||||
}
|
||||
}
|
||||
|
||||
/// 解压 zip 并剥掉顶层目录(Node 官方分发包顶层是 `node-vX-win-x64/`)。
|
||||
pub(crate) fn extract_zip_strip_top(zip_path: &Path, dest: &Path) -> Result<(), String> {
|
||||
let file = fs::File::open(zip_path).map_err(|e| format!("打开 zip 失败: {e}"))?;
|
||||
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("读取 zip 失败: {e}"))?;
|
||||
for i in 0..archive.len() {
|
||||
let mut entry = archive.by_index(i).map_err(|e| format!("读取条目失败: {e}"))?;
|
||||
let Some(name) = entry.enclosed_name() else {
|
||||
continue;
|
||||
};
|
||||
// 剥掉第一层目录;顶层目录条目本身(只有一个组件)跳过
|
||||
let mut comps = name.components();
|
||||
comps.next();
|
||||
let rel: PathBuf = comps.map(|c| c.as_os_str()).collect();
|
||||
if rel.as_os_str().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let outpath = dest.join(&rel);
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(&outpath).map_err(|e| e.to_string())?;
|
||||
} else {
|
||||
if let Some(parent) = outpath.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let mut outfile = fs::File::create(&outpath).map_err(|e| e.to_string())?;
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
let n = entry.read(&mut buf).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
outfile.write_all(&buf[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 强杀进程树(安装子进程取消用)。
|
||||
pub(crate) fn taskkill_tree(pid: u64) {
|
||||
let mut cmd = std::process::Command::new("taskkill");
|
||||
cmd.args(["/F", "/T", "/PID", &pid.to_string()])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.stdin(std::process::Stdio::null());
|
||||
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||
let _ = cmd.status();
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
//! dsh 服务进程生命周期:spawn(自管 stdio)→ 就绪探测 → 日志落盘 → 停止。
|
||||
//!
|
||||
//! 进程形态参照 `music/bridge.rs` 的长驻子进程:stdout/stderr 各起一个 reader 线程,
|
||||
//! 逐行写入日志环形缓冲与 `logs/web.log`;子进程加入 Job Object,应用退出时由
|
||||
//! 系统自动回收。启动命令为 `node <dsh bin 入口> web --port <端口> --no-open`:
|
||||
//! `--no-open` 让 dsh 不要自己弹出系统浏览器(由本模块的按钮决定何时打开)。
|
||||
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{SocketAddr, TcpListener, TcpStream};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tauri::AppHandle;
|
||||
|
||||
use super::types::DshServerStatus;
|
||||
use super::{DshManager, ServerEntry};
|
||||
|
||||
/// 就绪探测总时长上限。
|
||||
const READY_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
impl DshManager {
|
||||
/// 进程是否存活。
|
||||
fn server_running(&self) -> bool {
|
||||
let mut guard = match self.server.lock() {
|
||||
Ok(g) => g,
|
||||
Err(_) => return false,
|
||||
};
|
||||
match guard.as_mut() {
|
||||
Some(entry) => entry
|
||||
.child
|
||||
.try_wait()
|
||||
.ok()
|
||||
.map(|w| w.is_none())
|
||||
.unwrap_or(false),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前服务状态。
|
||||
pub fn server_status(&self) -> DshServerStatus {
|
||||
let running = self.server_running();
|
||||
// 运行中一律用**进程实际使用的端口**(设置可能在启动后被改过,
|
||||
// 此时 UI 展示的地址必须仍是真正监听的那个)
|
||||
let entry = self
|
||||
.server
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|g| g.as_ref().map(|e| (e.pid, e.port, e.started_at)));
|
||||
let (pid, port, started_at) = match (running, entry) {
|
||||
(true, Some((pid, port, started_at))) => (Some(pid), port, Some(started_at)),
|
||||
_ => (None, self.load_settings().port, None),
|
||||
};
|
||||
DshServerStatus {
|
||||
running,
|
||||
ready: running && self.ready.load(Ordering::SeqCst),
|
||||
pid,
|
||||
port,
|
||||
url: format!("http://127.0.0.1:{port}"),
|
||||
launch_url: if running {
|
||||
self.launch_url.lock().ok().and_then(|g| g.clone())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
started_at,
|
||||
error: self.server_error.lock().ok().and_then(|g| g.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 启动 dsh Web 服务(幂等:已在运行直接返回当前状态)。
|
||||
pub fn start_server(&self, app: &AppHandle) -> Result<DshServerStatus, String> {
|
||||
if self.server_running() {
|
||||
return Ok(self.server_status());
|
||||
}
|
||||
let _guard = self.start_lock.lock().map_err(|e| e.to_string())?;
|
||||
if self.server_running() {
|
||||
return Ok(self.server_status());
|
||||
}
|
||||
// 清理可能残留的旧条目
|
||||
if let Ok(mut g) = self.server.lock() {
|
||||
g.take();
|
||||
}
|
||||
self.ready.store(false, Ordering::SeqCst);
|
||||
if let Ok(mut g) = self.server_error.lock() {
|
||||
*g = None;
|
||||
}
|
||||
// 上一进程的令牌必须清掉:沿用旧令牌会让新进程的首次访问仍然 401
|
||||
if let Ok(mut g) = self.launch_url.lock() {
|
||||
*g = None;
|
||||
}
|
||||
|
||||
let settings = self.load_settings();
|
||||
let port = settings.port;
|
||||
let env = self
|
||||
.resolve_node_env()
|
||||
.ok_or_else(|| "未找到可用的 Node,请先完成环境安装".to_string())?;
|
||||
if !super::satisfies_node_requirement(&env.version) {
|
||||
return Err(format!(
|
||||
"当前 Node {} 不满足 dsh 要求({})",
|
||||
env.version,
|
||||
super::NODE_REQUIRED
|
||||
));
|
||||
}
|
||||
let entry = self
|
||||
.bin_entry()
|
||||
.ok_or_else(|| "未安装 dsh,请先完成安装".to_string())?;
|
||||
|
||||
// 端口预检:dsh 自身在端口占用时的报错不够直观,这里提前给出可读错误
|
||||
if let Err(e) = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], port))) {
|
||||
let msg = format!("端口 {port} 不可用({e}),请在配置中更换端口");
|
||||
self.set_server_error(&msg);
|
||||
return Err(msg);
|
||||
}
|
||||
|
||||
// 同步 AI 供应商配置(写 settings.yaml + 收集环境变量)
|
||||
if settings.ai_sync {
|
||||
if let Err(e) = self.ai_sync(app) {
|
||||
// 同步失败不阻塞启动,只记日志(用户可在 dsh 内手动配置)
|
||||
crate::logger::log_warn("dsh", &format!("AI 配置同步失败(继续启动): {e}"));
|
||||
}
|
||||
}
|
||||
let env_vars = self.ai_env_vars();
|
||||
|
||||
let mut cmd = Command::new(&env.node_exe);
|
||||
cmd.arg(&entry)
|
||||
.arg("web")
|
||||
.arg("--port")
|
||||
.arg(port.to_string())
|
||||
.arg("--no-open");
|
||||
cmd.current_dir(self.workspace_dir());
|
||||
cmd.env("DSH_HOME", self.home_dir());
|
||||
for (key, value) in env_vars {
|
||||
cmd.env(key, value);
|
||||
}
|
||||
cmd.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.stdin(Stdio::null());
|
||||
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||
|
||||
let mut child = cmd.spawn().map_err(|e| {
|
||||
let msg = format!("启动 dsh 失败({}): {e}", env.node_exe.display());
|
||||
self.set_server_error(&msg);
|
||||
msg
|
||||
})?;
|
||||
let pid = child.id();
|
||||
crate::process_manager::assign_to_job(&child);
|
||||
|
||||
let stdout = child.stdout.take();
|
||||
let stderr = child.stderr.take();
|
||||
if let Ok(mut g) = self.server.lock() {
|
||||
*g = Some(ServerEntry {
|
||||
child,
|
||||
pid,
|
||||
port,
|
||||
started_at: chrono::Utc::now().timestamp(),
|
||||
});
|
||||
}
|
||||
|
||||
// 输出 → 日志。stdout 额外承担「抓取带令牌启动地址」的职责:
|
||||
// dsh 就绪后打印 `dsh web: http://127.0.0.1:<port>/?token=<令牌>`,
|
||||
// 浏览器鉴权靠这个地址换 cookie(我们传了 --no-open,没别人替它换)。
|
||||
let ring = self.log_ring_handle();
|
||||
let log_path = self.log_path();
|
||||
if let Some(out) = stdout {
|
||||
spawn_stdout_reader(out, ring.clone(), log_path.clone(), self.launch_url.clone(), app.clone());
|
||||
}
|
||||
if let Some(err) = stderr {
|
||||
spawn_log_reader(err, ring, log_path);
|
||||
}
|
||||
|
||||
crate::logger::log_info(
|
||||
"dsh",
|
||||
&format!("dsh 服务已启动 (pid: {pid}, 端口: {port})"),
|
||||
);
|
||||
self.emit_server_state(app);
|
||||
|
||||
// 就绪探测(后台线程,不阻塞启动返回)
|
||||
self.spawn_ready_probe(app.clone(), port);
|
||||
Ok(self.server_status())
|
||||
}
|
||||
|
||||
/// 停止 dsh 服务(kill 快速返回,wait 移到后台线程)。
|
||||
pub fn stop_server(&self, app: &AppHandle) {
|
||||
let entry = self.server.lock().ok().and_then(|mut g| g.take());
|
||||
self.ready.store(false, Ordering::SeqCst);
|
||||
if let Ok(mut g) = self.launch_url.lock() {
|
||||
*g = None;
|
||||
}
|
||||
if let Some(mut entry) = entry {
|
||||
// 先杀进程树(dsh 可能派生子进程),再关本进程句柄
|
||||
super::node::taskkill_tree(entry.pid as u64);
|
||||
let _ = entry.child.kill();
|
||||
std::thread::spawn(move || {
|
||||
let _ = entry.child.wait();
|
||||
});
|
||||
crate::logger::log_info("dsh", &format!("dsh 服务已停止 (pid: {})", entry.pid));
|
||||
}
|
||||
self.emit_server_state(app);
|
||||
}
|
||||
|
||||
fn set_server_error(&self, message: &str) {
|
||||
if let Ok(mut g) = self.server_error.lock() {
|
||||
*g = Some(message.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// 就绪探测:轮询 HTTP,成功置 ready;进程提前退出则记录错误原因。
|
||||
fn spawn_ready_probe(&self, app: AppHandle, port: u16) {
|
||||
std::thread::spawn(move || {
|
||||
use tauri::Manager;
|
||||
let deadline = Instant::now() + READY_TIMEOUT;
|
||||
loop {
|
||||
{
|
||||
let manager = app.state::<DshManager>();
|
||||
if http_probe(port) {
|
||||
manager.ready.store(true, Ordering::SeqCst);
|
||||
manager.emit_server_state(&app);
|
||||
return;
|
||||
}
|
||||
if !manager.server_running() {
|
||||
// 进程已退出:不必等到超时
|
||||
let line = "dsh 服务进程已退出,未能就绪(详见日志)".to_string();
|
||||
manager.push_log(&line);
|
||||
manager.set_server_error(&line);
|
||||
crate::logger::log_warn("dsh", &line);
|
||||
manager.emit_server_state(&app);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
let manager = app.state::<DshManager>();
|
||||
manager.emit_server_state(&app);
|
||||
});
|
||||
}
|
||||
|
||||
/// 日志环形缓冲句柄(reader/探测线程持有)。
|
||||
pub(crate) fn log_ring_handle(&self) -> std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<String>>> {
|
||||
self.log_ring.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// 起一个 reader 线程把子进程输出逐行写进日志(stdout 与 stderr 类型不同,故泛型化)。
|
||||
fn spawn_log_reader<R: Read + Send + 'static>(
|
||||
pipe: R,
|
||||
ring: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<String>>>,
|
||||
log_path: std::path::PathBuf,
|
||||
) {
|
||||
std::thread::spawn(move || {
|
||||
let reader = BufReader::new(pipe);
|
||||
for line in reader.lines().map_while(Result::ok) {
|
||||
super::push_log_shared(&ring, &log_path, &line);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// stdout reader:写日志之外,还从 `dsh web: ...?token=<令牌>` 行里抓取启动地址。
|
||||
///
|
||||
/// 抓到后置入 `launch_url` 并推送状态事件,前端据此启用「独立窗口 / 浏览器打开」。
|
||||
/// 注意锁的粒度:先算好是否需要通知再释放锁——`emit_server_state` 会读
|
||||
/// `launch_url`,持锁调用会自锁。
|
||||
fn spawn_stdout_reader<R: Read + Send + 'static>(
|
||||
pipe: R,
|
||||
ring: std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<String>>>,
|
||||
log_path: std::path::PathBuf,
|
||||
launch_url: std::sync::Arc<std::sync::Mutex<Option<String>>>,
|
||||
app: tauri::AppHandle,
|
||||
) {
|
||||
std::thread::spawn(move || {
|
||||
let reader = BufReader::new(pipe);
|
||||
for line in reader.lines().map_while(Result::ok) {
|
||||
// 先解析原文(落日志时 token 会被掩码)
|
||||
let parsed = super::parse_launch_url(&line);
|
||||
if let Some(url) = parsed {
|
||||
let changed = match launch_url.lock() {
|
||||
Ok(mut slot) => {
|
||||
let changed = slot.as_deref() != Some(url.as_str());
|
||||
if changed {
|
||||
*slot = Some(url);
|
||||
}
|
||||
changed
|
||||
}
|
||||
Err(_) => false,
|
||||
};
|
||||
if changed {
|
||||
use tauri::Manager;
|
||||
if let Some(manager) = app.try_state::<DshManager>() {
|
||||
manager.emit_server_state(&app);
|
||||
}
|
||||
}
|
||||
}
|
||||
super::push_log_shared(&ring, &log_path, &line);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 极简 HTTP 探测:TCP 连上并收到以 `HTTP/` 开头的响应即视为就绪。
|
||||
fn http_probe(port: u16) -> bool {
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], port));
|
||||
let Ok(mut stream) = TcpStream::connect_timeout(&addr, Duration::from_millis(500)) else {
|
||||
return false;
|
||||
};
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_millis(800)));
|
||||
let req = format!("GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
|
||||
if stream.write_all(req.as_bytes()).is_err() {
|
||||
return false;
|
||||
}
|
||||
let mut buf = [0u8; 16];
|
||||
match stream.read(&mut buf) {
|
||||
Ok(n) if n >= 5 => &buf[..5] == b"HTTP/",
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
//! dsh 模块(DeepSeek Harness 外壳)的数据类型。
|
||||
//!
|
||||
//! 全部走 specta 导出到 `src/lib/bindings.ts`,字段 camelCase。
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// dsh 对 Node 的版本要求(`^22.19.0 || >=24.0.0`)。
|
||||
pub const NODE_REQUIRED: &str = "^22.19.0 || >=24.0.0";
|
||||
/// dsh npm 包名。
|
||||
pub const DSH_PACKAGE: &str = "@deepseek-ai/dsh";
|
||||
/// 默认 Web UI 端口。
|
||||
pub const DEFAULT_PORT: u16 = 3080;
|
||||
/// 默认「打开独立窗口」全局快捷键(与 quickpanel/截图等同为全局快捷键,格式见
|
||||
/// `keyboard-types` 的 `Modifiers+Code`:修饰键名大小写不敏感,数字键名即 `5`)。
|
||||
pub const DEFAULT_SHORTCUT: &str = "Alt+D";
|
||||
|
||||
/// 模块设置(`{app_data}/dsh/settings.json`)。
|
||||
///
|
||||
/// 独立文件,**不写** `thing_app_settings`(appStore 的 SETTINGS_VERSION 迁移会清空用户设置)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct DshSettings {
|
||||
/// 结构版本号;变更时按版本校正字段
|
||||
pub version: u32,
|
||||
/// Node 来源偏好:auto(系统优先,缺失回落托管)| system | managed
|
||||
pub node_source: String,
|
||||
/// 指定下载的 Node 版本(空 = 自动取满足要求的最新版)
|
||||
pub managed_node_version: String,
|
||||
/// Node 分发包镜像前缀(空 = 官方 nodejs.org;国内可用 npmmirror)
|
||||
pub node_mirror: String,
|
||||
/// npm registry(空 = 官方源)
|
||||
pub npm_registry: String,
|
||||
/// 下载 Node / npm 安装是否走代理模块(mihomo mixed 端口)
|
||||
pub use_proxy: bool,
|
||||
/// Web UI 端口(dsh 的 `--port` 参数)
|
||||
pub port: u16,
|
||||
/// 应用启动时自动拉起 dsh 服务
|
||||
pub auto_start: bool,
|
||||
/// 全局快捷键:打开 dsh Web 独立窗口(空 = 未启用)
|
||||
pub shortcut: String,
|
||||
/// $DSH_HOME 模式:managed({app_data}/dsh/home)| user(~/.dsh)
|
||||
pub dsh_home_mode: String,
|
||||
/// 工作区目录(空 = {app_data}/dsh/workspace),即 dsh 进程的启动目录
|
||||
pub workspace: String,
|
||||
/// dsh 本体的安装目录(npm `--prefix` 目标,即 node_modules 所在位置)。
|
||||
/// 空 = {app_data}/dsh。
|
||||
/// 只有 dsh 本体与它的 node_modules 跟随此设置;便携 Node、$DSH_HOME、
|
||||
/// 日志与模块设置仍固定在应用数据目录,避免自定义路径失效时连配置都读不到。
|
||||
pub install_dir: String,
|
||||
/// 映射为 dsh 默认模型的 Thing AI 供应商 id
|
||||
pub provider_id: String,
|
||||
/// 启动前自动同步 settings.yaml
|
||||
pub ai_sync: bool,
|
||||
}
|
||||
|
||||
impl Default for DshSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: 1,
|
||||
node_source: "auto".into(),
|
||||
managed_node_version: String::new(),
|
||||
node_mirror: String::new(),
|
||||
npm_registry: String::new(),
|
||||
use_proxy: true,
|
||||
port: DEFAULT_PORT,
|
||||
auto_start: false,
|
||||
shortcut: DEFAULT_SHORTCUT.into(),
|
||||
dsh_home_mode: "managed".into(),
|
||||
workspace: String::new(),
|
||||
install_dir: String::new(),
|
||||
provider_id: "deepseek".into(),
|
||||
ai_sync: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DshSettings {
|
||||
/// 自愈:非法/越界字段夹回默认;版本推进。返回是否发生变更。
|
||||
pub fn heal(&mut self) -> bool {
|
||||
let mut changed = false;
|
||||
if !matches!(self.node_source.as_str(), "auto" | "system" | "managed") {
|
||||
self.node_source = "auto".into();
|
||||
changed = true;
|
||||
}
|
||||
if !matches!(self.dsh_home_mode.as_str(), "managed" | "user") {
|
||||
self.dsh_home_mode = "managed".into();
|
||||
changed = true;
|
||||
}
|
||||
if self.port == 0 {
|
||||
self.port = DEFAULT_PORT;
|
||||
changed = true;
|
||||
}
|
||||
if self.version < 1 {
|
||||
self.version = 1;
|
||||
changed = true;
|
||||
}
|
||||
// v1 → v2:默认「打开独立窗口」快捷键从 Ctrl+5 改为 Alt+D。
|
||||
// 仍等于旧默认值 = 用户没改过,直接迁移;改过(或清空禁用)的原样保留 ——
|
||||
// 版本号已推进,之后即使再改回旧键位也不会被改写(同 translate 的 heal 约定)。
|
||||
if self.version < 2 {
|
||||
if self.shortcut.trim().eq_ignore_ascii_case("ctrl+5") {
|
||||
self.shortcut = DEFAULT_SHORTCUT.to_string();
|
||||
}
|
||||
self.version = 2;
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
/// Node 运行环境状态。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NodeStatus {
|
||||
/// system | managed | none
|
||||
pub source: String,
|
||||
/// node.exe 路径
|
||||
pub path: Option<String>,
|
||||
/// 版本号(如 v24.9.0)
|
||||
pub version: Option<String>,
|
||||
/// 是否满足 dsh 的版本要求
|
||||
pub satisfies: bool,
|
||||
/// 版本要求文案(供 UI 展示)
|
||||
pub required: String,
|
||||
}
|
||||
|
||||
/// dsh 本体安装状态。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DshInstallStatus {
|
||||
pub installed: bool,
|
||||
pub version: Option<String>,
|
||||
/// bin 入口(dist/bin.js 绝对路径)
|
||||
pub entry: Option<String>,
|
||||
/// 安装目录
|
||||
pub dir: String,
|
||||
}
|
||||
|
||||
/// dsh 服务进程状态。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DshServerStatus {
|
||||
/// 进程存活
|
||||
pub running: bool,
|
||||
/// HTTP 端口已可访问
|
||||
pub ready: bool,
|
||||
pub pid: Option<u32>,
|
||||
pub port: u16,
|
||||
/// 规范地址(不含令牌,用于界面展示)
|
||||
pub url: String,
|
||||
/// 带令牌的启动地址(**用于打开界面**)。
|
||||
///
|
||||
/// dsh web 的浏览器鉴权是「进程级随机令牌 → 首次访问换 cookie」:
|
||||
/// 直接访问 [`Self::url`] 只会拿到 401。令牌每次启动都不同,只能从
|
||||
/// dsh 的输出里抓取,因此进程刚起来时这里可能为 None(等它打印)。
|
||||
pub launch_url: Option<String>,
|
||||
/// 启动时间(unix 秒)
|
||||
pub started_at: Option<i64>,
|
||||
/// 启动失败原因(端口占用 / 进程立即退出等)
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// 模块首屏环境总览。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DshEnvStatus {
|
||||
pub node: NodeStatus,
|
||||
pub dsh: DshInstallStatus,
|
||||
pub server: DshServerStatus,
|
||||
pub settings: DshSettings,
|
||||
}
|
||||
|
||||
/// 安装/下载进度事件载荷(与 kernel/music 同构)。
|
||||
/// stage: download | extracting | installing | done | error
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DshInstallProgress {
|
||||
pub stage: String,
|
||||
pub percent: u8,
|
||||
#[specta(type = f64)]
|
||||
pub downloaded_bytes: u64,
|
||||
#[specta(type = Option<f64>)]
|
||||
pub total_bytes: Option<u64>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// dsh 版本更新信息。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DshUpdateInfo {
|
||||
pub current: Option<String>,
|
||||
pub latest: String,
|
||||
pub has_update: bool,
|
||||
/// 可选版本(倒序,最多 20 个)
|
||||
pub versions: Vec<String>,
|
||||
}
|
||||
|
||||
/// npm 源信息(安装引导页展示「本次实际用哪个源」并提供快捷切换)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DshNpmRegistryInfo {
|
||||
/// 本次安装/查询实际会使用的源(已去掉末尾 `/`)
|
||||
pub effective: String,
|
||||
/// effective 的来源:setting(模块设置显式指定)| npm(npm 自身配置链)| fallback(默认官方源)
|
||||
pub source: String,
|
||||
/// npm 自身解析出的源(环境变量 > 安装目录 .npmrc > 用户 ~/.npmrc > 内置),
|
||||
/// 未检测到 Node/npm 时为 None
|
||||
pub npm_registry: Option<String>,
|
||||
/// 模块设置里显式填写的值(空 = 未指定,交给 npm 解析)
|
||||
pub setting: String,
|
||||
}
|
||||
|
||||
/// AI 供应商映射结果(预览用,不含明文密钥)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DshAiProvider {
|
||||
/// Thing 侧供应商 id
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// 写入 settings.yaml 的 apiKeyEnv 变量名
|
||||
pub env_name: String,
|
||||
pub base_url: String,
|
||||
pub model: String,
|
||||
/// 凭据管理器中是否已配置密钥
|
||||
pub has_key: bool,
|
||||
}
|
||||
|
||||
/// settings.yaml 同步预览。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DshAiPreview {
|
||||
/// 将被写入的 YAML 文本(密钥位置只有环境变量名)
|
||||
pub yaml: String,
|
||||
pub providers: Vec<DshAiProvider>,
|
||||
pub default_provider: Option<String>,
|
||||
pub default_model: Option<String>,
|
||||
pub settings_path: String,
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
//! 「用 Thing 打开」的参数解析与事件投递。
|
||||
//!
|
||||
//! # 两条入口,同一份逻辑
|
||||
//!
|
||||
//! 1. **冷启动**:安装器注册的文件关联让 Windows 用 `thing.exe <文件路径>` 启动本应用;
|
||||
//! 资源管理器右键菜单(`HKCU\...\shell\ThingEditor`)同样以参数形式传入文件/文件夹;
|
||||
//! 2. **热启动**:应用已在运行时再次打开,会起第二个进程,由
|
||||
//! `tauri-plugin-single-instance` 把它的命令行参数转交给第一个实例。
|
||||
//!
|
||||
//! 两条路径的输入形态完全一样(都是命令行参数),因此共用 [`open_target_from_args`]。
|
||||
//! 解析成功后统一发事件(文件走 `editor-open-file`、文件夹走 `editor-open-folder`),
|
||||
//! **窗口由前端创建** —— Rust 侧不持有窗口 label 策略。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
/// 一个待打开目标(文件或文件夹)。
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum OpenTarget {
|
||||
File(PathBuf),
|
||||
/// 文件夹:由编辑器「本地目录」面板承载
|
||||
Folder(PathBuf),
|
||||
}
|
||||
|
||||
impl OpenTarget {
|
||||
pub fn path(&self) -> &Path {
|
||||
match self {
|
||||
Self::File(p) | Self::Folder(p) => p,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
Self::File(_) => "file",
|
||||
Self::Folder(_) => "folder",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 回传给前端的待打开目标。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OpenTargetPayload {
|
||||
/// 绝对路径
|
||||
pub path: String,
|
||||
/// `"file"` | `"folder"`
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
impl From<&OpenTarget> for OpenTargetPayload {
|
||||
fn from(target: &OpenTarget) -> Self {
|
||||
Self {
|
||||
path: target.path().to_string_lossy().to_string(),
|
||||
kind: target.kind().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 「启动时命令行指定的目标」缓存。
|
||||
///
|
||||
/// # 为什么需要缓存而不是启动时直接 `emit`
|
||||
///
|
||||
/// 冷启动的顺序是:`setup` 跑完 → 创建主窗口 → WebView 加载前端 → 前端注册监听。
|
||||
/// 在 `setup` 里 `emit` 时前端还没开始监听,事件**直接丢掉**了 —— 表现是
|
||||
/// 「双击 .md 打开了应用,但笔记没打开」。
|
||||
///
|
||||
/// 因此这里把目标存下来,由前端在注册完监听后**主动取一次**
|
||||
/// (`editor_take_pending_file`)。取走即清空,避免下次打开窗口时又被翻出来。
|
||||
static PENDING: std::sync::OnceLock<Mutex<Option<OpenTarget>>> = std::sync::OnceLock::new();
|
||||
|
||||
fn pending_slot() -> &'static Mutex<Option<OpenTarget>> {
|
||||
PENDING.get_or_init(|| Mutex::new(None))
|
||||
}
|
||||
|
||||
/// 记下「启动时想打开的目标」(由 `setup` 调用)。
|
||||
pub fn remember_pending_target(target: OpenTarget) {
|
||||
if let Ok(mut slot) = pending_slot().lock() {
|
||||
*slot = Some(target);
|
||||
}
|
||||
}
|
||||
|
||||
/// 取出并清空待打开目标(由 `editor_take_pending_file` 命令调用)。
|
||||
pub fn take_pending_target() -> Option<OpenTargetPayload> {
|
||||
pending_slot()
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut slot| slot.take())
|
||||
.map(|target| OpenTargetPayload::from(&target))
|
||||
}
|
||||
|
||||
/// 从一组命令行参数里挑出「看起来是要打开的路径」。
|
||||
///
|
||||
/// 只认「**存在**的路径」,其余一律忽略 —— 宁可漏开一个窗口,也不要因为一个开关
|
||||
/// 参数把主窗口的启动逻辑搞乱。目录优先(右键文件夹的场景)。
|
||||
pub fn open_target_from_args<I: IntoIterator<Item = String>>(args: I) -> Option<OpenTarget> {
|
||||
for arg in args {
|
||||
let trimmed = arg.trim().trim_matches('"');
|
||||
if trimmed.is_empty() || trimmed.starts_with('-') {
|
||||
continue;
|
||||
}
|
||||
let path = PathBuf::from(trimmed);
|
||||
if path.is_dir() {
|
||||
return Some(OpenTarget::Folder(path));
|
||||
}
|
||||
if path.is_file() {
|
||||
return Some(OpenTarget::File(path));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 从一组命令行参数里挑出「看起来是笔记文件」的那个路径(仅 `.md`/`.markdown`/`.mdx`)。
|
||||
///
|
||||
/// 实际启动路径用的是 [`open_target_from_args`](接受任意文件与文件夹,以支持资源
|
||||
/// 管理器右键菜单);这个更严格的入口现在**只服务于单测**,故仅测试构建时编译。
|
||||
#[cfg(test)]
|
||||
pub fn note_path_from_args<I: IntoIterator<Item = String>>(args: I) -> Option<PathBuf> {
|
||||
for arg in args {
|
||||
let trimmed = arg.trim().trim_matches('"');
|
||||
if trimmed.is_empty() || trimmed.starts_with('-') {
|
||||
continue;
|
||||
}
|
||||
let lower = trimmed.to_ascii_lowercase();
|
||||
let is_note_ext =
|
||||
lower.ends_with(".md") || lower.ends_with(".markdown") || lower.ends_with(".mdx");
|
||||
if !is_note_ext {
|
||||
continue;
|
||||
}
|
||||
let path = PathBuf::from(trimmed);
|
||||
if path.is_file() {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 通知前端「要打开这个目标」(窗口由前端创建)。
|
||||
pub fn emit_open_target(app: &tauri::AppHandle, target: &OpenTarget) {
|
||||
use tauri::Emitter;
|
||||
let payload = serde_json::json!({ "path": target.path().to_string_lossy() });
|
||||
let event = match target {
|
||||
OpenTarget::File(_) => crate::constants::events::EDITOR_OPEN_FILE,
|
||||
OpenTarget::Folder(_) => crate::constants::events::EDITOR_OPEN_FOLDER,
|
||||
};
|
||||
if let Err(e) = app.emit(event, payload) {
|
||||
crate::logger::log_warn("editor", &format!("发出打开目标事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_note(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("thing-notes-args-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, "# x").unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_markdown_path_and_ignores_flags() {
|
||||
let note = temp_note("会议.md");
|
||||
let args = vec![
|
||||
"--some-flag".to_string(),
|
||||
"not-a-file".to_string(),
|
||||
note.to_string_lossy().to_string(),
|
||||
];
|
||||
assert_eq!(note_path_from_args(args), Some(note.clone()));
|
||||
|
||||
let _ = std::fs::remove_file(¬e);
|
||||
let _ = std::fs::remove_dir_all(note.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_markdown_and_mdx_too() {
|
||||
let note = temp_note("a.markdown");
|
||||
assert_eq!(
|
||||
note_path_from_args(vec![note.to_string_lossy().to_string()]),
|
||||
Some(note.clone())
|
||||
);
|
||||
let _ = std::fs::remove_file(¬e);
|
||||
let _ = std::fs::remove_dir_all(note.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_markdown_and_missing_files() {
|
||||
// 非笔记扩展名
|
||||
assert_eq!(note_path_from_args(vec!["C:\\a\\b.txt".to_string()]), None);
|
||||
// 不存在的 .md:静默忽略(否则会开一个空窗口)
|
||||
assert_eq!(
|
||||
note_path_from_args(vec!["C:\\definitely\\missing\\x.md".to_string()]),
|
||||
None
|
||||
);
|
||||
// 空参数与开关
|
||||
assert_eq!(
|
||||
note_path_from_args(vec!["".to_string(), "-v".to_string()]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_surrounding_quotes() {
|
||||
let note = temp_note("带 空格.md");
|
||||
let quoted = format!("\"{}\"", note.to_string_lossy());
|
||||
assert_eq!(note_path_from_args(vec![quoted]), Some(note.clone()));
|
||||
let _ = std::fs::remove_file(¬e);
|
||||
let _ = std::fs::remove_dir_all(note.parent().unwrap());
|
||||
}
|
||||
|
||||
/// 右键菜单:任意扩展名的文件都要被接受(不只 .md)。
|
||||
#[test]
|
||||
fn open_target_accepts_any_file_and_folder() {
|
||||
let file = temp_note("plain.txt");
|
||||
match open_target_from_args(vec![file.to_string_lossy().to_string()]) {
|
||||
Some(OpenTarget::File(p)) => assert_eq!(p, file),
|
||||
other => panic!("应识别为文件: {other:?}"),
|
||||
}
|
||||
let dir = file.parent().unwrap().to_path_buf();
|
||||
match open_target_from_args(vec![dir.to_string_lossy().to_string()]) {
|
||||
Some(OpenTarget::Folder(p)) => assert_eq!(p, dir),
|
||||
other => panic!("应识别为文件夹: {other:?}"),
|
||||
}
|
||||
let _ = std::fs::remove_file(&file);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
//! zip 快照备份:整库打包上传 + 远端轮转 + 恢复。
|
||||
//!
|
||||
//! # 为什么「快照」比「双向同步」更该先做
|
||||
//!
|
||||
//! 规划 §3.6 的判断:对「只是要个备份」的用户,一次上传一个完整 zip 比双向同步
|
||||
//! **可靠得多** —— 同步要考虑冲突、删除传播、时钟偏差;快照只有一个动作(上传),
|
||||
//! 失败就是失败,不会在半途产生「一半新一半旧」的库。
|
||||
//!
|
||||
//! 因此本模块与 `webdav/sync.rs` 是两条独立路径,用的是同一个客户端。
|
||||
//!
|
||||
//! # 打包内容
|
||||
//!
|
||||
//! 库内全部 `.md` 与 `assets/` 下的附件,外加一份 `thing-notes-manifest.json`
|
||||
//! (记录快照时间、文件数、格式版本)。**不打包 `.editor/`**:里面是索引与同步基线,
|
||||
//! 属于本机私有数据,跟着快照跑到另一台机器上只会误导那边的基线判断。
|
||||
//!
|
||||
//! # 轮转
|
||||
//!
|
||||
//! 上传后列出远端 `backups/` 下的快照,按**文件名里的时间戳**倒序保留
|
||||
//! [`WebdavSettings::backup_keep`] 份,其余删除。用文件名排序而不是远端 mtime:
|
||||
//! 各家服务端的 mtime 精度与时钟都不一致,而文件名是我们自己写的、单调递增。
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use super::webdav::client::WebdavClient;
|
||||
use crate::editor::library;
|
||||
use crate::editor::types::{BackupReport, BackupSnapshot, WebdavSettings};
|
||||
|
||||
/// 远端存放快照的目录(相对远端根)。
|
||||
pub const BACKUP_DIR: &str = "backups";
|
||||
/// 快照文件名前缀。
|
||||
const SNAPSHOT_PREFIX: &str = "thing-notes-";
|
||||
/// 清单文件名(打包进 zip,供恢复时校验)。
|
||||
const MANIFEST_NAME: &str = "thing-notes-manifest.json";
|
||||
|
||||
/// 快照清单。
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SnapshotManifest {
|
||||
version: u32,
|
||||
created_at: String,
|
||||
files: u32,
|
||||
}
|
||||
|
||||
/// 打包库根为 zip 字节流(不触网,便于单测)。
|
||||
pub fn build_snapshot(root: &Path) -> Result<(Vec<u8>, u32), String> {
|
||||
library::ensure_library(root)?;
|
||||
let cursor = std::io::Cursor::new(Vec::new());
|
||||
let mut writer = zip::ZipWriter::new(cursor);
|
||||
let options: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated);
|
||||
|
||||
let mut files = 0u32;
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let rel = library::rel_string(root, entry.path());
|
||||
if rel.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// `.editor/` 是本机私有数据(索引 + 同步基线),不进快照
|
||||
if rel.split('/').any(|part| part.starts_with('.')) {
|
||||
continue;
|
||||
}
|
||||
let bytes = match std::fs::read(entry.path()) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
crate::logger::log_warn("editor", &format!("快照跳过 {rel}(读取失败: {e})"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
writer
|
||||
.start_file(rel.clone(), options)
|
||||
.map_err(|e| format!("写入快照条目失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
.map_err(|e| format!("写入快照内容失败: {e}"))?;
|
||||
files += 1;
|
||||
}
|
||||
|
||||
// 清单最后写:它要记录真实打包到的文件数
|
||||
let manifest = SnapshotManifest {
|
||||
version: 1,
|
||||
created_at: chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
|
||||
files,
|
||||
};
|
||||
let manifest_bytes = serde_json::to_vec_pretty(&manifest)
|
||||
.map_err(|e| format!("序列化快照清单失败: {e}"))?;
|
||||
writer
|
||||
.start_file(MANIFEST_NAME, options)
|
||||
.map_err(|e| format!("写入快照清单失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&manifest_bytes)
|
||||
.map_err(|e| format!("写入快照清单内容失败: {e}"))?;
|
||||
|
||||
let cursor = writer.finish().map_err(|e| format!("完成快照打包失败: {e}"))?;
|
||||
Ok((cursor.into_inner(), files))
|
||||
}
|
||||
|
||||
/// 上传一份快照并做轮转。返回备份报告。
|
||||
pub fn upload_snapshot(
|
||||
root: &Path,
|
||||
settings: &WebdavSettings,
|
||||
client: &WebdavClient,
|
||||
) -> Result<BackupReport, String> {
|
||||
let (bytes, files) = build_snapshot(root)?;
|
||||
let name = format!(
|
||||
"{SNAPSHOT_PREFIX}{}.zip",
|
||||
chrono::Local::now().format("%Y%m%d-%H%M%S")
|
||||
);
|
||||
let remote_path = format!("{BACKUP_DIR}/{name}");
|
||||
client.put(&remote_path, bytes.clone())?;
|
||||
|
||||
let pruned = prune_snapshots(client, settings.backup_keep)?;
|
||||
Ok(BackupReport {
|
||||
name,
|
||||
bytes: bytes.len() as u64,
|
||||
files,
|
||||
pruned,
|
||||
})
|
||||
}
|
||||
|
||||
/// 轮转:只保留最新的 `keep` 份。
|
||||
pub fn prune_snapshots(client: &WebdavClient, keep: u32) -> Result<Vec<String>, String> {
|
||||
let keep = keep.max(1) as usize;
|
||||
let mut snapshots = list_snapshots(client)?;
|
||||
if snapshots.len() <= keep {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// 文件名里的时间戳是 `%Y%m%d-%H%M%S`,字典序即时间序
|
||||
snapshots.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
let outdated = snapshots.len() - keep;
|
||||
let mut pruned = Vec::new();
|
||||
for snapshot in snapshots.into_iter().take(outdated) {
|
||||
if let Err(e) = client.delete(&format!("{BACKUP_DIR}/{}", snapshot.name)) {
|
||||
crate::logger::log_warn("editor", &format!("删除旧快照 {} 失败: {e}", snapshot.name));
|
||||
continue;
|
||||
}
|
||||
pruned.push(snapshot.name);
|
||||
}
|
||||
Ok(pruned)
|
||||
}
|
||||
|
||||
/// 列出远端已有的快照。
|
||||
pub fn list_snapshots(client: &WebdavClient) -> Result<Vec<BackupSnapshot>, String> {
|
||||
let entries = client.list(BACKUP_DIR)?;
|
||||
let Some(entries) = entries else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter(|entry| !entry.is_dir)
|
||||
.filter(|entry| {
|
||||
entry
|
||||
.rel_path
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.map(|name| name.starts_with(SNAPSHOT_PREFIX) && name.ends_with(".zip"))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.map(|entry| BackupSnapshot {
|
||||
name: entry
|
||||
.rel_path
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
size: entry.size,
|
||||
modified: entry.modified,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 从快照恢复(**不覆盖已存在的本地文件**)。
|
||||
///
|
||||
/// 保守策略的理由:恢复的典型场景是「换机器」或「误删了几篇」。前者的本地基本是空的,
|
||||
/// 后者的本地有用户最近的工作 —— 覆盖会把「误删之前写的东西」一起冲掉。
|
||||
/// 需要时用户可以先在资源管理器里移走旧库,再恢复。
|
||||
pub fn restore_snapshot(
|
||||
root: &Path,
|
||||
client: &WebdavClient,
|
||||
name: &str,
|
||||
) -> Result<(u32, u32), String> {
|
||||
if name.contains('/') || name.contains('\\') || name.contains("..") {
|
||||
return Err("快照名不合法".to_string());
|
||||
}
|
||||
let bytes = client.get(&format!("{BACKUP_DIR}/{name}"))?;
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes))
|
||||
.map_err(|e| format!("读取快照失败: {e}"))?;
|
||||
|
||||
let mut written = 0u32;
|
||||
let mut kept = 0u32;
|
||||
for index in 0..archive.len() {
|
||||
let mut file = archive
|
||||
.by_index(index)
|
||||
.map_err(|e| format!("读取快照条目失败: {e}"))?;
|
||||
let Some(entry_path) = file.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
// `enclosed_name` 会拒绝 `..` 与绝对路径 —— 恶意快照不能写到库外
|
||||
crate::logger::log_warn("editor", "快照里有越界路径,已跳过");
|
||||
continue;
|
||||
};
|
||||
let rel = entry_path.to_string_lossy().replace('\\', "/");
|
||||
if rel == MANIFEST_NAME || file.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let target = library::safe_join(root, &rel)?;
|
||||
if target.exists() {
|
||||
kept += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
std::io::Read::read_to_end(&mut file, &mut out)
|
||||
.map_err(|e| format!("读取快照内容失败: {e}"))?;
|
||||
std::fs::write(&target, out).map_err(|e| format!("写入 {rel} 失败: {e}"))?;
|
||||
written += 1;
|
||||
}
|
||||
Ok((written, kept))
|
||||
}
|
||||
|
||||
/// 一次完整的「同步 + 备份」会话入口(命令层用)。
|
||||
///
|
||||
/// 返回(同步报告, 可选备份报告)。`with_backup` 为真时在同步之后追加一次快照 ——
|
||||
/// 「先同步再备份」的顺序是刻意的:备份应当是**同步之后的一致状态**,
|
||||
/// 而不是把一次半途失败的同步结果定格下来。
|
||||
pub fn sync_then_backup(
|
||||
root: &Path,
|
||||
settings: &WebdavSettings,
|
||||
client: &WebdavClient,
|
||||
app: &tauri::AppHandle,
|
||||
with_backup: bool,
|
||||
) -> Result<(super::webdav::sync::SyncReport, Option<BackupReport>), String> {
|
||||
let (plan, mut state, remote) = super::webdav::sync::build_plan(root, settings, client)?;
|
||||
let runner = super::webdav::sync::SyncRunner::new(client, root, app, plan.actions.len());
|
||||
let report = runner.run(&plan, &mut state, &remote);
|
||||
|
||||
// 只有「没有失败」时才推进基线:失败的一轮如果把基线写下去,
|
||||
// 那些没传成功的文件会被当成「已同步」,下次同步就静默漏掉了
|
||||
if report.failed == 0 {
|
||||
state.last_sync = chrono::Local::now().timestamp_millis().max(0) as u64;
|
||||
if let Err(e) = state.save(root) {
|
||||
crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}"));
|
||||
}
|
||||
} else {
|
||||
crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!("本轮有 {} 条失败,不推进同步基线", report.failed),
|
||||
);
|
||||
// 仍然保存「成功的那些」:SyncState 是按条更新的,未处理的条目保持旧基线,
|
||||
// 于是下一轮会把它们重新算作差异并重试
|
||||
if let Err(e) = state.save(root) {
|
||||
crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
let backup = if with_backup {
|
||||
Some(upload_snapshot(root, settings, client)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok((report, backup))
|
||||
}
|
||||
|
||||
/// 本地临时快照目录(供「导出快照到本地」与调试用)。
|
||||
///
|
||||
/// 与 [`upload_snapshot`] 共用 [`build_snapshot`],区别只是落盘而不是上传 ——
|
||||
/// 「我要一份备份,但不想连远端」是个很常见的诉求(比如先手动拷到网盘)。
|
||||
pub fn snapshot_to_file(root: &Path, dest: &Path) -> Result<u64, String> {
|
||||
let (bytes, _) = build_snapshot(root)?;
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
std::fs::write(dest, &bytes).map_err(|e| format!("写入快照失败: {e}"))?;
|
||||
Ok(bytes.len() as u64)
|
||||
}
|
||||
|
||||
/// 库根的默认快照落点(用户点「导出快照到本地」时用)。
|
||||
pub fn default_snapshot_path(root: &Path) -> PathBuf {
|
||||
root.join(format!(
|
||||
"{SNAPSHOT_PREFIX}{}.zip",
|
||||
chrono::Local::now().format("%Y%m%d-%H%M%S")
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_root(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-backup-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_excludes_private_dir() {
|
||||
let root = temp_root("build");
|
||||
std::fs::write(root.join("a.md"), "# A").unwrap();
|
||||
std::fs::create_dir_all(root.join("sub")).unwrap();
|
||||
std::fs::write(root.join("sub/b.md"), "# B").unwrap();
|
||||
std::fs::write(root.join("assets/pic.png"), [1u8, 2, 3]).unwrap();
|
||||
std::fs::create_dir_all(root.join(".editor")).unwrap();
|
||||
std::fs::write(root.join(".editor/editor.db"), "索引不该进快照").unwrap();
|
||||
|
||||
let (bytes, files) = build_snapshot(&root).unwrap();
|
||||
assert_eq!(files, 3, "两篇笔记 + 一个附件");
|
||||
assert!(!bytes.is_empty());
|
||||
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let names: Vec<String> = (0..archive.len())
|
||||
.map(|i| archive.by_index(i).unwrap().name().to_string())
|
||||
.collect();
|
||||
assert!(names.contains(&"a.md".to_string()), "{names:?}");
|
||||
assert!(names.contains(&"sub/b.md".to_string()), "{names:?}");
|
||||
assert!(names.contains(&"assets/pic.png".to_string()), "{names:?}");
|
||||
assert!(names.contains(&MANIFEST_NAME.to_string()), "{names:?}");
|
||||
assert!(
|
||||
!names.iter().any(|n| n.starts_with(".editor")),
|
||||
"私有目录不该进快照: {names:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_does_not_overwrite_existing_files() {
|
||||
let root = temp_root("restore");
|
||||
std::fs::write(root.join("a.md"), "新版").unwrap();
|
||||
std::fs::write(root.join("b.md"), "旧版").unwrap();
|
||||
let (bytes, _) = build_snapshot(&root).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("a.md"), "本机已有内容").unwrap();
|
||||
|
||||
// 直接走「解包到库根」的那段逻辑(用本地 zip 代替远端下载)
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut kept = 0u32;
|
||||
for index in 0..archive.len() {
|
||||
let mut file = archive.by_index(index).unwrap();
|
||||
let Some(path) = file.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
continue;
|
||||
};
|
||||
let rel = path.to_string_lossy().replace('\\', "/");
|
||||
if rel == MANIFEST_NAME || file.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let target = library::safe_join(&root, &rel).unwrap();
|
||||
if target.exists() {
|
||||
kept += 1;
|
||||
continue;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
std::io::Read::read_to_end(&mut file, &mut out).unwrap();
|
||||
std::fs::write(&target, out).unwrap();
|
||||
}
|
||||
assert_eq!(kept, 1, "已存在的 a.md 应被跳过");
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.md")).unwrap(), "本机已有内容");
|
||||
assert_eq!(std::fs::read_to_string(root.join("b.md")).unwrap(), "旧版");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_file_writing() {
|
||||
let root = temp_root("to-file");
|
||||
std::fs::write(root.join("a.md"), "# A").unwrap();
|
||||
let dest = root.join("out.zip");
|
||||
let size = snapshot_to_file(&root, &dest).unwrap();
|
||||
assert!(size > 0);
|
||||
assert!(dest.is_file());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,977 @@
|
||||
//! 笔记模块 Tauri 命令层。
|
||||
//!
|
||||
//! 所有库操作都经 [`super::library`] 的路径安全校验、所有库外文件操作都经
|
||||
//! [`super::files`] 的授权白名单、所有 WebDAV 操作都经 [`super::webdav`] 的会话层;
|
||||
//! 命令本身只做几件事:解析当前库根 → 调下层 → 标记「本应用刚写过」→ 发事件。
|
||||
//!
|
||||
//! # 为什么每条命令都要先 `retarget`
|
||||
//!
|
||||
//! 索引服务是常驻 worker,它记着「自己挂在哪个库根上」。库根可以在设置里改,
|
||||
//! 而 worker 不知道这件事 —— 若命令层不主动告知,就会出现「侧栏显示新库、
|
||||
//! 搜索却在新库的旧索引里查」这种最难查的错。`retarget` 在库根未变时是两次
|
||||
//! 比较,成本可忽略。
|
||||
//!
|
||||
//! # 网络类命令为什么是异步的
|
||||
//!
|
||||
//! `tests_webdav` / `sync_now` / `backup_now` 会真的发 HTTP 请求(同步一个几百篇的
|
||||
//! 库可能跑几分钟)。Tauri 的同步命令会占住调用线程,因此这几个一律 `async` 并用
|
||||
//! `spawn_blocking` 把阻塞的 reqwest 调用挪到专用线程池 —— 既不卡 UI,也不卡
|
||||
//! Tauri 的命令线程池。
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
|
||||
use super::backup;
|
||||
use super::export;
|
||||
use super::files;
|
||||
use super::import;
|
||||
use super::index::{
|
||||
NoteBacklinks, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery,
|
||||
};
|
||||
use super::index_service::{self, IndexService, NoteIndexReport};
|
||||
use super::library;
|
||||
use super::templates::{self, NoteTemplate};
|
||||
use super::types::{
|
||||
BackupReport, BackupSnapshot, ImportReport, LibraryEntry, LibraryInfo, NoteDoc, EditorSettings,
|
||||
SyncProgress,
|
||||
};
|
||||
use super::webdav::{self, WebdavTestResult};
|
||||
use super::EditorManager;
|
||||
use crate::constants::events;
|
||||
|
||||
/// 通知各窗口「库内容已变更」(新建/保存/重命名/删除/切换库根后)。
|
||||
fn emit_library_changed(app: &AppHandle) {
|
||||
if let Err(e) = app.emit(events::EDITOR_LIBRARY_CHANGED, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出库变更事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 通知各窗口「设置已变更」(跨窗口同步,范式同 terminal-settings)。
|
||||
fn emit_settings_changed(app: &AppHandle) {
|
||||
if let Err(e) = app.emit(events::EDITOR_SETTINGS, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出设置变更事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前库根(按设置解析),并确保目录存在。
|
||||
fn current_root(state: &EditorManager) -> PathBuf {
|
||||
let settings = state.load_settings();
|
||||
library::resolve_library_root(state.module_dir(), &settings)
|
||||
}
|
||||
|
||||
/// 取索引服务并把它的库根对齐到当前设置。
|
||||
fn indexed<'a>(app: &AppHandle, state: &EditorManager) -> Result<&'a IndexService, String> {
|
||||
let root = current_root(state);
|
||||
let service = index_service::service(app);
|
||||
service.retarget(root)?;
|
||||
Ok(service)
|
||||
}
|
||||
|
||||
/// 组装库状态概览。
|
||||
fn library_info(state: &EditorManager) -> Result<LibraryInfo, String> {
|
||||
let settings = state.load_settings();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
let entries = library::scan(&root)?;
|
||||
Ok(LibraryInfo {
|
||||
root: root.to_string_lossy().to_string(),
|
||||
is_custom: settings
|
||||
.library_root
|
||||
.as_deref()
|
||||
.map(|s| !s.trim().is_empty())
|
||||
.unwrap_or(false),
|
||||
note_count: library::count_notes(&entries),
|
||||
})
|
||||
}
|
||||
|
||||
/// 标记「本应用刚**批量**写过」,随后把库同步进索引。
|
||||
///
|
||||
/// 用于导入 / WebDAV 同步 / 恢复 / 模板导出这类**无法逐路径枚举**的操作:写完之后
|
||||
/// 在抑制窗口内的一切文件事件都当作自己写的。
|
||||
///
|
||||
/// 顺序重要:先标记(抑制窗口从写入那一刻算起),再同步。这里走全库增量同步而不是
|
||||
/// 「只索引这一篇」的快路径:单文件快路径要额外拼一份 wikilink 的 `stems` 映射,
|
||||
/// 而不完整的映射会让 `[[某笔记]]` 解析到错误位置;全量同步靠 (mtime,size) 跳过
|
||||
/// 未变文件,万篇规模也是毫秒级,用一点开销换「索引永远自洽」。
|
||||
fn mark_written_then_index(app: &AppHandle, state: &EditorManager) {
|
||||
match indexed(app, state) {
|
||||
Ok(service) => {
|
||||
service.mark_write_all();
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("保存后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// 写入前登记「本应用即将写这一篇笔记」(按库内相对路径)。
|
||||
///
|
||||
/// **必须在 `library::write_note` 之前调用**:notify 的 Modify 事件可能与写入几乎
|
||||
/// 同时到达索引 worker,晚于写盘再登记就会漏过 —— 前端便会把自家的保存当成
|
||||
/// 「外部修改」,进而重载文档、把光标弹回第一行。
|
||||
fn mark_pending_note_write(app: &AppHandle, state: &EditorManager, rel_path: &str) {
|
||||
match indexed(app, state) {
|
||||
Ok(service) => service.mark_write_path(rel_path),
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// 把库同步进索引(不登记自我写入 —— 调用方已在写入前按路径登记过)。
|
||||
fn sync_index_after_write(app: &AppHandle, state: &EditorManager) {
|
||||
match indexed(app, state) {
|
||||
Ok(service) => {
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("保存后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 设置与库 =====
|
||||
|
||||
/// 读取笔记模块设置。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_get_settings(state: State<'_, EditorManager>) -> Result<EditorSettings, String> {
|
||||
Ok(state.load_settings())
|
||||
}
|
||||
|
||||
/// 临时草稿文件的存放目录(`{app_data_dir}/editor/scratch`),不存在则创建,返回绝对路径。
|
||||
///
|
||||
/// 「新建临时文件(草稿)」用它:**不随应用退出删除** —— 用户可能还没决定存哪儿,
|
||||
/// 收尾交给「关闭该文件时选择保存 / 删除」。
|
||||
///
|
||||
/// # 为什么不放在**安装目录**
|
||||
///
|
||||
/// 安装目录(`Program Files` 之类)对普通用户通常不可写,装到系统盘就必然失败;
|
||||
/// 而 `app_data_dir` 本来就是本模块放设置与默认库的地方,是「应用自己的可写目录」的
|
||||
/// 标准位置,且卸载时随程序数据一起清理。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_scratch_dir(state: State<'_, EditorManager>) -> Result<String, String> {
|
||||
let dir = state.module_dir().join("scratch");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建临时目录失败:{e}"))?;
|
||||
Ok(dir.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 保存笔记模块设置(自愈后落盘,并广播给各窗口)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_save_settings(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
settings: EditorSettings,
|
||||
) -> Result<EditorSettings, String> {
|
||||
let mut next = settings;
|
||||
next.heal();
|
||||
state.save_settings(&next)?;
|
||||
// 全局快捷键可能刚被改了:就地重注册(`register_shortcut` 会先注销本模块的旧键,
|
||||
// 因此「清空快捷键」也能通过传空串生效)
|
||||
state.init_on_launch(&app);
|
||||
emit_settings_changed(&app);
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// 当前库状态概览(库根 / 是否自定义 / 笔记数)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_library_info(state: State<'_, EditorManager>) -> Result<LibraryInfo, String> {
|
||||
library_info(&state)
|
||||
}
|
||||
|
||||
/// 设置库根(`None` 或空串 = 恢复默认库根)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_set_library_root(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
root: Option<String>,
|
||||
) -> Result<LibraryInfo, String> {
|
||||
let cleaned = root.and_then(|r| {
|
||||
let trimmed = r.trim().to_string();
|
||||
if trimmed.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(trimmed)
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(path) = &cleaned {
|
||||
let p = std::path::Path::new(path);
|
||||
if !p.exists() {
|
||||
return Err(format!("目录不存在:{path}"));
|
||||
}
|
||||
if !p.is_dir() {
|
||||
return Err("请选择一个文件夹作为笔记库".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = state.load_settings();
|
||||
settings.library_root = cleaned;
|
||||
state.save_settings(&settings)?;
|
||||
|
||||
emit_settings_changed(&app);
|
||||
let info = library_info(&state)?;
|
||||
emit_library_changed(&app);
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// 扫描库,返回扁平条目列表(前端组树)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_scan_library(state: State<'_, EditorManager>) -> Result<Vec<LibraryEntry>, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
library::scan(&root)
|
||||
}
|
||||
|
||||
/// 读取一篇笔记。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_note(state: State<'_, EditorManager>, rel_path: String) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
library::read_note(&root, &rel_path)
|
||||
}
|
||||
|
||||
/// 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_save_note(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
content: String,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
// 先登记「即将写这一篇」,再落盘:notify 的事件可能与写入同时抵达 worker
|
||||
mark_pending_note_write(&app, &state, &rel_path);
|
||||
let doc = library::write_note(&root, &rel_path, &content)?;
|
||||
sync_index_after_write(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 新建笔记(自动补 `.md`、重名加序号),返回新文档。
|
||||
///
|
||||
/// `template_id` 为空时用默认模板;找不到该模板时同样回退默认模板(不报错 ——
|
||||
/// 模板文件被删掉不该让「新建笔记」这个核心动作失败)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_note(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
dir_rel: String,
|
||||
name: String,
|
||||
template_id: Option<String>,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
let template = template_id.unwrap_or_default();
|
||||
// 模板为空时走「不读模板目录」的那条路径:模板目录被删/损坏也要能新建笔记
|
||||
let doc = if template.trim().is_empty() {
|
||||
library::create_note(&root, &dir_rel, &name)?
|
||||
} else {
|
||||
library::create_note_with_template(&root, &dir_rel, &name, &template)?
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 打开(或创建)今天的日记:`日记/YYYY-MM-DD.md`。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_daily_note(app: AppHandle, state: State<'_, EditorManager>) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
let name = templates::daily_note_name();
|
||||
let dir = "日记";
|
||||
let rel = format!("{dir}/{name}.md");
|
||||
let path = library::safe_join(&root, &rel)?;
|
||||
let doc = if path.is_file() {
|
||||
library::read_note(&root, &rel)?
|
||||
} else {
|
||||
// 日记用同名内置模板;没有则回退默认(模板可被用户改名,这里不能假定存在)
|
||||
let template = if templates::body_of(&root, "builtin:日记").is_some() {
|
||||
"builtin:日记"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
library::create_note_with_template(&root, dir, &name, template)?
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 新建文件夹。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_folder(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
dir_rel: String,
|
||||
name: String,
|
||||
) -> Result<(), String> {
|
||||
let root = current_root(&state);
|
||||
library::create_folder(&root, &dir_rel, &name)?;
|
||||
emit_library_changed(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 重命名条目,返回新相对路径。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_rename_entry(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
new_name: String,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
let next = library::rename_entry(&root, &rel_path, &new_name)?;
|
||||
// 改名在索引里是「旧路径消失 + 新路径出现」:增量同步一次比手工删+插更稳
|
||||
if let Ok(service) = indexed(&app, &state) {
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("改名后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
emit_library_changed(&app);
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// 删除条目(目录递归删除)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_delete_entry(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
) -> Result<(), String> {
|
||||
let root = current_root(&state);
|
||||
library::delete_entry(&root, &rel_path)?;
|
||||
if let Ok(service) = indexed(&app, &state) {
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("删除后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
emit_library_changed(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ===== 索引与检索 =====
|
||||
|
||||
/// 全量重建索引(设置页「重建索引」)。文件不受影响。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_rebuild_index(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<NoteIndexReport, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let report = service.rebuild()?;
|
||||
Ok(finish_report(service, report))
|
||||
}
|
||||
|
||||
/// 增量同步索引(打开编辑器 / 手动刷新时调用)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_sync_index(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<NoteIndexReport, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let report = service.sync()?;
|
||||
Ok(finish_report(service, report))
|
||||
}
|
||||
|
||||
/// 把同步结果补上「索引里的笔记数」再回传(前端省一次 stats 往返)。
|
||||
fn finish_report(service: &IndexService, report: super::index::NoteSyncReport) -> NoteIndexReport {
|
||||
let note_count = service.stats().map(|s| s.note_count).unwrap_or(0);
|
||||
let mut out: NoteIndexReport = report.into();
|
||||
out.note_count = note_count;
|
||||
out
|
||||
}
|
||||
|
||||
/// 全文检索 / 按标签 / 按目录筛选。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_search_notes(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
query: NoteSearchQuery,
|
||||
) -> Result<NoteSearchPage, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.search(query)
|
||||
}
|
||||
|
||||
/// 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_list_notes(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
limit: Option<i64>,
|
||||
) -> Result<Vec<NoteSearchHit>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.list(limit.unwrap_or(500))
|
||||
}
|
||||
|
||||
/// 标签及计数。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_tags(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<Vec<super::index::NoteTagCount>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.tags()
|
||||
}
|
||||
|
||||
/// 一篇笔记的链接关系(出链 + 入链)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_backlinks(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
) -> Result<NoteBacklinks, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.backlinks(&rel_path)
|
||||
}
|
||||
|
||||
/// 全库链接图(已解析的内部链接边)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_link_graph(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<Vec<LinkEdge>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let edges = service.link_graph()?;
|
||||
Ok(edges
|
||||
.into_iter()
|
||||
.map(|(from, to)| LinkEdge { from, to })
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 链接图的一条边(用 `from`/`to` 而不是元组:元组序列化成数组后前端得按下标取值,
|
||||
/// 改一次顺序就静默错位 —— 与 `terminal/history.rs` 的 `HistorySource` 同一理由)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LinkEdge {
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
}
|
||||
|
||||
/// 索引状态(设置页展示:索引数 / 文件数 / 标签数 / 索引文件路径)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_index_stats(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<NoteIndexStats, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.stats()
|
||||
}
|
||||
|
||||
// ===== 库外任意文件 =====
|
||||
|
||||
/// 把库内图片读成 `data:` URL(供编辑器内联预览)。
|
||||
///
|
||||
/// # 为什么走 data URL 而不是 asset 协议
|
||||
///
|
||||
/// 库根是用户自选目录,可以用 `convertFileSrc` + `assetProtocol.scope` 直接把磁盘路径
|
||||
/// 交给 `<img>`。但那条路要求把「用户选的任意目录」加进 asset 协议的作用域白名单 ——
|
||||
/// 那等于给 WebView 开一个「可以按路径读任意文件」的口子,而笔记模块的整个安全模型
|
||||
/// 是「库根沙箱 + 授权白名单」。走 data URL 则完全在既有沙箱内:路径必须经
|
||||
/// [`library::safe_join`](拒绝 `..` 与绝对路径),且只认图片扩展名。
|
||||
///
|
||||
/// # 为什么必须有大小上限
|
||||
///
|
||||
/// data URL 是 base64,体积约为原文件的 1.34 倍,且会进 JS 堆。一张 20MB 的图片
|
||||
/// 变成 27MB 字符串,多预览几张就能把 WebView 拖垮。超限时**不报错**,返回
|
||||
/// `None` —— 调用方(编辑器)会把该图片节点当作普通文本渲染,用户看到的就是
|
||||
/// 原始 Markdown,不会打断编辑。
|
||||
const MAX_ASSET_BYTES: u64 = 8 * 1024 * 1024;
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_asset(
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
) -> Result<Option<String>, String> {
|
||||
let root = current_root(&state);
|
||||
let path = library::safe_join(&root, &rel_path)?;
|
||||
if !path.is_file() {
|
||||
return Ok(None);
|
||||
}
|
||||
let ext = path
|
||||
.extension()
|
||||
.map(|e| e.to_string_lossy().to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
let mime = match ext.as_str() {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"webp" => "image/webp",
|
||||
"svg" => "image/svg+xml",
|
||||
"bmp" => "image/bmp",
|
||||
"avif" => "image/avif",
|
||||
// 非图片(或未识别):不预览。返回 `None` 而不是报错 —— 正文里写个
|
||||
// `` 不该让编辑器弹错误。
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let meta = std::fs::metadata(&path).map_err(|e| format!("读取附件信息失败: {e}"))?;
|
||||
if meta.len() > MAX_ASSET_BYTES {
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("附件过大,跳过内联预览:{rel_path}({} 字节)", meta.len()),
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
use base64::Engine;
|
||||
let bytes = std::fs::read(&path).map_err(|e| format!("读取附件失败: {e}"))?;
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
|
||||
Ok(Some(format!("data:{mime};base64,{encoded}")))
|
||||
}
|
||||
|
||||
/// 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。
|
||||
///
|
||||
/// 前端在注册完事件监听后调用。**不能靠启动时 `emit`** —— 那时 WebView 还没加载完,
|
||||
/// 事件会直接丢掉(见 `editor/args.rs` 的 `PENDING` 注释)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_take_pending_file() -> Result<Option<super::args::OpenTargetPayload>, String> {
|
||||
Ok(super::args::take_pending_target())
|
||||
}
|
||||
|
||||
/// 打开(读取)库外任意文件。
|
||||
///
|
||||
/// 读取本身不要求预先授权(用户可能刚通过系统对话框选完,也可能带命令行参数),
|
||||
/// 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_open_file(
|
||||
state: State<'_, EditorManager>,
|
||||
path: String,
|
||||
) -> Result<files::FileDoc, String> {
|
||||
let settings = state.load_settings();
|
||||
index_service::read_and_authorize(&path, settings.max_file_size_mb)
|
||||
}
|
||||
|
||||
/// 保存库外任意文件(按前端回传的编码与换行写回)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_write_file(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
path: String,
|
||||
content: String,
|
||||
encoding: String,
|
||||
eol: String,
|
||||
) -> Result<files::FileDoc, String> {
|
||||
let settings = state.load_settings();
|
||||
let doc = files::write_file(&path, &content, &encoding, &eol, settings.max_file_size_mb)?;
|
||||
if let Ok(service) = indexed(&app, &state) {
|
||||
// 库外文件的路径语义与库内相对路径不同,这里退回窗口式抑制;
|
||||
// 真正在库内的 `.md`(被当作普通文件打开)同样受这一窗口保护。
|
||||
service.mark_write_all();
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 以指定编码重新解码磁盘字节(切换编码用;不写回,只换一种解释方式)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_redecode_file(
|
||||
state: State<'_, EditorManager>,
|
||||
path: String,
|
||||
encoding: String,
|
||||
) -> Result<files::FileDoc, String> {
|
||||
let settings = state.load_settings();
|
||||
files::redecode_file(&path, &encoding, settings.max_file_size_mb)
|
||||
}
|
||||
|
||||
/// 显式登记一个路径为「可写」。
|
||||
///
|
||||
/// 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `editor_open_file`,
|
||||
/// 但用户确实是用系统对话框选的,属于「用户显式选择」)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_authorize_file(path: String) -> Result<(), String> {
|
||||
if path.trim().is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
files::authorize(std::path::Path::new(path.trim()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把 base64 图片写进库根的 `assets/`,返回可插入 Markdown 的相对路径。
|
||||
///
|
||||
/// 为什么走 base64 而不是直接给前端一个写文件句柄:粘贴的图片来自剪贴板,
|
||||
/// 前端拿到的本来就是 Blob/DataURL;转一次 base64 比让前端拿到「任意写权限」
|
||||
/// 安全得多(写的位置由后端决定,且只落在 `assets/`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_write_asset(
|
||||
state: State<'_, EditorManager>,
|
||||
file_name: String,
|
||||
ext: String,
|
||||
data_base64: String,
|
||||
) -> Result<String, String> {
|
||||
use base64::Engine;
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let data = base64::engine::general_purpose::STANDARD
|
||||
.decode(data_base64.trim())
|
||||
.map_err(|e| format!("图片数据解析失败: {e}"))?;
|
||||
files::write_asset(&root, &file_name, &data, &ext)
|
||||
}
|
||||
|
||||
// ===== 模板(P2) =====
|
||||
|
||||
/// 列出可用模板(用户模板优先,同名覆盖内置)。
|
||||
///
|
||||
/// 顺带确保库内 `templates/` 目录存在 —— 这样界面上「新建模板」按钮第一次点击
|
||||
/// 就能直接写文件,不需要用户先去资源管理器建目录。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_list_templates(state: State<'_, EditorManager>) -> Result<Vec<NoteTemplate>, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let _ = templates::ensure_dir(&root);
|
||||
Ok(templates::list(&root))
|
||||
}
|
||||
|
||||
/// 把内置模板导出到库内 `templates/`(已存在的不覆盖),返回新写入的名字。
|
||||
///
|
||||
/// 三种用法:
|
||||
/// - 都不传:把全部内置模板导出到 `templates/`(用户想改内置模板时的起点);
|
||||
/// - 传 `name` + `body`:新建一个自定义模板。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_add_template(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
name: Option<String>,
|
||||
body: Option<String>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let root = current_root(&state);
|
||||
let written = match (name, body) {
|
||||
(Some(name), Some(body)) => {
|
||||
let safe = templates::validate_name(&name)?;
|
||||
templates::ensure_dir(&root)?;
|
||||
let path = root.join("templates").join(format!("{safe}.md"));
|
||||
if path.exists() {
|
||||
return Err(format!("模板「{safe}」已存在"));
|
||||
}
|
||||
std::fs::write(&path, body).map_err(|e| format!("写入模板失败: {e}"))?;
|
||||
vec![safe]
|
||||
}
|
||||
// 不带参数 = 导出全部内置模板
|
||||
_ => templates::export_builtin(&root)?,
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// 读取一个模板的正文(界面上「查看 / 编辑模板」用)。
|
||||
///
|
||||
/// 内置模板也返回正文(便于「另存为自定义模板」),但 `path` 为 `None` ——
|
||||
/// 内置模板没有对应的库内文件,前端据此禁掉「直接编辑」。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_template(
|
||||
state: State<'_, EditorManager>,
|
||||
template_id: String,
|
||||
) -> Result<TemplateSource, String> {
|
||||
let root = current_root(&state);
|
||||
let body = templates::body_of(&root, &template_id)
|
||||
.ok_or_else(|| format!("模板不存在:{template_id}"))?;
|
||||
Ok(TemplateSource {
|
||||
body,
|
||||
path: templates::relative_path(&template_id),
|
||||
})
|
||||
}
|
||||
|
||||
/// 模板正文与它在库内的位置(`path` 为 `None` = 内置模板)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TemplateSource {
|
||||
pub body: String,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
// ===== 导入 / 导出(P2) =====
|
||||
|
||||
/// 从磁盘路径导入(文件 / 目录 / zip 自动判别)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_import(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
source: String,
|
||||
dest_dir: String,
|
||||
) -> Result<ImportReport, String> {
|
||||
let root = current_root(&state);
|
||||
let report = import::import_path(&root, &source, &dest_dir)?;
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// 把一篇笔记导出为独立 HTML 文件,返回落盘路径。
|
||||
///
|
||||
/// HTML 的渲染在**前端**(`markdown-it` + `DOMPurify` 都在前端),这里只负责把
|
||||
/// 已经渲染好的字符串写到用户选定的位置 —— 即「后端不碰渲染逻辑,前端不碰文件系统」。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_export_note(
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
html: String,
|
||||
dest: String,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
// 无论导出哪一篇,都要先确认它确实在库内(不接受库外相对路径)
|
||||
library::read_note(&root, &rel_path)?;
|
||||
let target = PathBuf::from(dest.trim());
|
||||
if target.as_os_str().is_empty() {
|
||||
return Err("请选择导出位置".to_string());
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建导出目录失败: {e}"))?;
|
||||
}
|
||||
let bytes = html.into_bytes();
|
||||
std::fs::write(&target, &bytes).map_err(|e| format!("写入导出文件失败: {e}"))?;
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("导出 {} → {}({} 字节)", rel_path, target.display(), bytes.len()),
|
||||
);
|
||||
Ok(target.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 把整库(或某个目录)打包成 zip,返回落盘路径。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_export_zip(
|
||||
state: State<'_, EditorManager>,
|
||||
dest: String,
|
||||
dir_rel: Option<String>,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
let dest_path = PathBuf::from(dest.trim());
|
||||
if dest_path.as_os_str().is_empty() {
|
||||
return Err("请选择导出位置".to_string());
|
||||
}
|
||||
let scope = dir_rel.unwrap_or_default();
|
||||
let (bytes, files) = export::zip_scope(&root, &scope)?;
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建导出目录失败: {e}"))?;
|
||||
}
|
||||
std::fs::write(&dest_path, &bytes).map_err(|e| format!("写入 zip 失败: {e}"))?;
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("导出 zip:{files} 个文件 → {}", dest_path.display()),
|
||||
);
|
||||
Ok(dest_path.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。
|
||||
///
|
||||
/// 与 [`editor_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
|
||||
/// 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为
|
||||
/// 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_export_snapshot_local(
|
||||
state: State<'_, EditorManager>,
|
||||
dest: Option<String>,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let target = match dest.map(|d| d.trim().to_string()) {
|
||||
Some(d) if !d.is_empty() => PathBuf::from(d),
|
||||
_ => backup::default_snapshot_path(&root),
|
||||
};
|
||||
backup::snapshot_to_file(&root, &target)?;
|
||||
Ok(target.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
// ===== WebDAV 同步 / 备份(P2) =====
|
||||
|
||||
/// 当前 WebDAV 配置状态(设置页展示;**密码只回传「是否已保存」**)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_webdav_status(state: State<'_, EditorManager>) -> Result<WebdavStatus, String> {
|
||||
let settings = state.load_settings();
|
||||
let has_password = crate::secrets::secret_read(webdav::KEYRING_PASSWORD)
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|value| !value.is_empty())
|
||||
.unwrap_or(false);
|
||||
Ok(WebdavStatus {
|
||||
configured: settings.webdav.is_configured(),
|
||||
has_password,
|
||||
remote_root: settings.webdav.remote_root.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// WebDAV 配置状态(不包含密码本身)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WebdavStatus {
|
||||
/// 地址与用户名是否已填
|
||||
pub configured: bool,
|
||||
/// keyring 里是否已存密码
|
||||
pub has_password: bool,
|
||||
pub remote_root: String,
|
||||
}
|
||||
|
||||
/// 保存 WebDAV 密码到系统凭据管理器(传空串 = 删除)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_set_webdav_password(password: String) -> Result<(), String> {
|
||||
if password.trim().is_empty() {
|
||||
return crate::secrets::secret_delete(webdav::KEYRING_PASSWORD);
|
||||
}
|
||||
crate::secrets::secret_write(webdav::KEYRING_PASSWORD, password.trim())
|
||||
}
|
||||
|
||||
/// 连接自检(建目录 + 列远端)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_test_webdav(
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<WebdavTestResult, String> {
|
||||
let settings = state.load_settings().webdav;
|
||||
run_blocking(move || webdav::test_connection(&settings)).await
|
||||
}
|
||||
|
||||
/// 立即同步(并按设置决定是否追加一次快照备份)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_sync_now(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<SyncOutcome, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
|
||||
// 让前端先看到「开始同步」(进度事件的第一条由 worker 之外发,总数为 0 表示准备中)
|
||||
let _ = app.emit(
|
||||
events::EDITOR_SYNC_PROGRESS,
|
||||
SyncProgress {
|
||||
done: 0,
|
||||
total: 0,
|
||||
current: String::new(),
|
||||
kind: "prepare".to_string(),
|
||||
message: "正在比对清单…".to_string(),
|
||||
},
|
||||
);
|
||||
|
||||
let app_for_task = app.clone();
|
||||
let outcome = run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
client.ensure_root()?;
|
||||
let (report, backup) = backup::sync_then_backup(&root, &webdav, &client, &app_for_task, true)?;
|
||||
Ok(SyncOutcome {
|
||||
report,
|
||||
backup,
|
||||
})
|
||||
})
|
||||
.await;
|
||||
|
||||
// 同步会改本地文件 → 索引必须跟着更新
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
outcome
|
||||
}
|
||||
|
||||
/// 一次同步的结果(报告 + 可选快照)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncOutcome {
|
||||
pub report: super::webdav::sync::SyncReport,
|
||||
pub backup: Option<BackupReport>,
|
||||
}
|
||||
|
||||
/// 只做一次 zip 快照备份(不上传增量)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_backup_now(
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<BackupReport, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
client.ensure_root()?;
|
||||
backup::upload_snapshot(&root, &webdav, &client)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// 列出远端已有快照。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_list_backups(
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<Vec<BackupSnapshot>, String> {
|
||||
let settings = state.load_settings().webdav;
|
||||
run_blocking(move || {
|
||||
let client = webdav::client_from(&settings)?;
|
||||
backup::list_snapshots(&client)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// 从远端快照恢复(不覆盖本地已有文件)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_restore_backup(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
name: String,
|
||||
) -> Result<ImportReport, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
let result = run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
let (written, kept) = backup::restore_snapshot(&root, &client, &name)?;
|
||||
Ok(ImportReport {
|
||||
imported: written,
|
||||
renamed: 0,
|
||||
skipped: kept,
|
||||
failures: Vec::new(),
|
||||
})
|
||||
})
|
||||
.await;
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
result
|
||||
}
|
||||
|
||||
/// 把阻塞的 WebDAV 调用挪到专用线程池,避免占住 Tauri 的命令线程。
|
||||
///
|
||||
/// `reqwest::blocking` 在 tokio 运行时线程上会 panic(它内部会尝试建一个运行时),
|
||||
/// 因此**必须**走 `spawn_blocking` 而不是直接 `.await` 一个同步函数。
|
||||
async fn run_blocking<T, F>(task: F) -> Result<T, String>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce() -> Result<T, String> + Send + 'static,
|
||||
{
|
||||
match tokio::task::spawn_blocking(task).await {
|
||||
Ok(result) => result,
|
||||
Err(e) => Err(format!("后台任务执行失败: {e}")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! 编辑器「本地目录」命令层:直接操作用户真实文件系统(不进索引、无沙箱)。
|
||||
//!
|
||||
//! # 为什么复用 `terminal::local_fs`
|
||||
//!
|
||||
//! 列举 / 新建目录 / 重命名 / **回收站删除** 在终端模块的「本地栏」已经实现过,
|
||||
//! 且把「目录/文件分流」「不弹系统错误对话框」「拒绝删除盘符根」这些细节处理好了。
|
||||
//! 这里只补它没有的两件事:
|
||||
//! 1. **新建文件**(空文本,终端本地栏只建目录);
|
||||
//! 2. **重名一律报错**——目录树是用户的真实文件系统,静默改名会让人找不到刚建的文件。
|
||||
//!
|
||||
//! # 安全边界(与终端同一姿态)
|
||||
//!
|
||||
//! 路径来自用户自己的浏览/输入,不做「限制在本目录根下」的约束(那是本地文件管理器,
|
||||
//! 限制根只会挡住用户自己)。唯一硬守卫是 **拒绝删除盘符根**(已在
|
||||
//! [`terminal::local_fs::delete`] 内实现),且删除一律走回收站。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
use super::library::validate_name;
|
||||
use crate::terminal::local_fs;
|
||||
|
||||
/// 批量删除结果(回传前端展示「成功 N 项、失败明细」)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeleteReport {
|
||||
/// 成功移入回收站的项数
|
||||
pub removed: u32,
|
||||
/// 失败明细(路径 + 原因)
|
||||
pub failed: Vec<String>,
|
||||
}
|
||||
|
||||
/// 列举本地目录(`path` 为空 = 用户主目录)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_dir(path: String) -> Result<local_fs::LocalDir, String> {
|
||||
local_fs::list_dir(&path)
|
||||
}
|
||||
|
||||
/// 在 `dir` 下新建一个空文本文件。重名报错(不自动加序号)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_file(dir: String, name: String) -> Result<String, String> {
|
||||
let target = resolve_child(&dir, &name)?;
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
std::fs::write(&target, b"").map_err(|e| format!("新建文件失败: {e}"))?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 在 `dir` 下新建一个文件夹。重名报错(不自动加序号)。
|
||||
///
|
||||
/// 命名用 `editor_create_dir` 而不是 `editor_create_folder`:后者已被**库内**建文件夹
|
||||
/// 的命令占用(`editor_create_folder(dir_rel, name)`,走库根沙箱)—— 两者操作对象不同
|
||||
/// (真实文件系统 vs 库内),必须能同时在命令表里存在。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_dir(dir: String, name: String) -> Result<String, String> {
|
||||
let target = resolve_child(&dir, &name)?;
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
local_fs::create_dir(&target.to_string_lossy())?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 同目录内重命名。目标存在则报错。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_rename_path(path: String, new_name: String) -> Result<String, String> {
|
||||
let src = Path::new(path.trim());
|
||||
if !src.exists() {
|
||||
return Err("路径不存在".to_string());
|
||||
}
|
||||
let parent = src.parent().ok_or_else(|| "无法解析父目录".to_string())?;
|
||||
let name = validate_name(&new_name)?;
|
||||
let target = parent.join(&name);
|
||||
if target == src {
|
||||
return Ok(local_fs::display_path(src));
|
||||
}
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
local_fs::rename(&path, &target.to_string_lossy())?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 删除若干本地项(**走系统回收站**,不是永久删除)。
|
||||
///
|
||||
/// 单个失败不中断其余项:用户选中的 10 个文件里有一个正被占用,另外 9 个仍应删掉。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_delete_path(paths: Vec<String>) -> Result<DeleteReport, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let (removed, failed) = local_fs::delete(&paths);
|
||||
DeleteReport {
|
||||
removed: removed as u32,
|
||||
failed,
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("删除任务失败: {e}"))
|
||||
}
|
||||
|
||||
/// 把一个文件 / 文件夹移动到目标目录下(同盘移动;重名报错)。
|
||||
///
|
||||
/// 不允许把文件夹移动到自身或其子目录下 —— 那会把目录搬进自己里面,属数据事故。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_move_path(path: String, dest_dir: String) -> Result<String, String> {
|
||||
let src = Path::new(path.trim());
|
||||
if !src.exists() {
|
||||
return Err("源路径不存在".to_string());
|
||||
}
|
||||
let dest = Path::new(dest_dir.trim());
|
||||
if !dest.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
let name = src
|
||||
.file_name()
|
||||
.ok_or_else(|| "无法解析文件名".to_string())?;
|
||||
let target = dest.join(name);
|
||||
if target == src {
|
||||
return Ok(local_fs::display_path(src));
|
||||
}
|
||||
if target.exists() {
|
||||
return Err(format!("目标目录中已存在「{}」", name.to_string_lossy()));
|
||||
}
|
||||
if src.is_dir() && dest.starts_with(src) {
|
||||
return Err("不能把文件夹移动到自身或子目录中".to_string());
|
||||
}
|
||||
local_fs::rename(&path, &target.to_string_lossy())?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 校验名字并把「目录 + 名字」拼成绝对路径。
|
||||
fn resolve_child(dir: &str, name: &str) -> Result<std::path::PathBuf, String> {
|
||||
let name = validate_name(name)?;
|
||||
let dir = Path::new(dir.trim());
|
||||
if !dir.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
Ok(dir.join(name))
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! 整库 / 目录导出为 zip。
|
||||
//!
|
||||
//! # 与快照备份的区别
|
||||
//!
|
||||
//! `backup.rs` 的 zip 是**给同步服务用的**(固定文件名前缀、上传到远端、轮转),
|
||||
//! 本模块的 zip 是**给用户拿走的**(用户选保存位置、可以只导出某个目录)。
|
||||
//! 两者都打包 `.md` 与 `assets/`,但排除规则不同:用户导出时**包含**点号开头的
|
||||
//! 普通目录(除了 `.editor/`)—— 因为「我库里有 `.foo/` 目录,为什么导出后没了」
|
||||
//! 是个更难解释的问题;而同步必须排除它们(避免把本机私有状态推给别人)。
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use super::library;
|
||||
|
||||
/// 打包范围。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Scope {
|
||||
/// 整个库
|
||||
All,
|
||||
/// 只打包库内某个目录(连同库根的 `assets/`)
|
||||
Dir,
|
||||
}
|
||||
|
||||
/// 按范围打包,返回 `(zip 字节, 文件数)`。
|
||||
pub fn zip_scope(root: &Path, dir_rel: &str) -> Result<(Vec<u8>, u32), String> {
|
||||
let scope = if dir_rel.trim().is_empty() {
|
||||
Scope::All
|
||||
} else {
|
||||
Scope::Dir
|
||||
};
|
||||
// 目录模式下先确认目标目录存在且仍在库内(`safe_join` 拒绝越界)
|
||||
let filter_prefix = if scope == Scope::Dir {
|
||||
let dir = library::safe_join(root, dir_rel)?;
|
||||
if !dir.is_dir() {
|
||||
return Err(format!("目录不存在:{dir_rel}"));
|
||||
}
|
||||
Some(library::rel_string(root, &dir))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let cursor = std::io::Cursor::new(Vec::new());
|
||||
let mut writer = zip::ZipWriter::new(cursor);
|
||||
let options: zip::write::FileOptions<'_, ()> =
|
||||
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
|
||||
let mut files = 0u32;
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let rel = library::rel_string(root, entry.path());
|
||||
if rel.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// 私有目录(索引 + 同步基线)任何情况下都不导出
|
||||
if rel == ".editor" || rel.starts_with(".editor/") {
|
||||
continue;
|
||||
}
|
||||
if let Some(prefix) = &filter_prefix {
|
||||
// 目录模式:只收该目录下的文件,外加库根 assets/
|
||||
let in_scope = rel == *prefix
|
||||
|| rel.starts_with(&format!("{prefix}/"))
|
||||
|| rel.starts_with(&format!("{}/", library::ASSETS_DIR));
|
||||
if !in_scope {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let bytes = match std::fs::read(entry.path()) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
crate::logger::log_warn("editor", &format!("导出跳过 {rel}(读取失败: {e})"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
writer
|
||||
.start_file(rel, options)
|
||||
.map_err(|e| format!("写入 zip 条目失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
.map_err(|e| format!("写入 zip 内容失败: {e}"))?;
|
||||
files += 1;
|
||||
}
|
||||
|
||||
let cursor = writer.finish().map_err(|e| format!("完成 zip 打包失败: {e}"))?;
|
||||
Ok((cursor.into_inner(), files))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn temp_lib(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-export-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
fn names(bytes: Vec<u8>) -> Vec<String> {
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
(0..archive.len())
|
||||
.map(|i| archive.by_index(i).unwrap().name().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_export_skips_private_dir_only() {
|
||||
let root = temp_lib("all");
|
||||
std::fs::create_dir_all(root.join(".editor")).unwrap();
|
||||
std::fs::create_dir_all(root.join(".custom")).unwrap();
|
||||
std::fs::write(root.join("a.md"), "A").unwrap();
|
||||
std::fs::write(root.join(".editor/editor.db"), "x").unwrap();
|
||||
std::fs::write(root.join(".custom/keep.md"), "保留").unwrap();
|
||||
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
|
||||
|
||||
let (bytes, count) = zip_scope(&root, "").unwrap();
|
||||
assert_eq!(count, 3, "a.md + .custom/keep.md + assets/p.png");
|
||||
let list = names(bytes);
|
||||
assert!(list.contains(&"a.md".to_string()), "{list:?}");
|
||||
assert!(
|
||||
list.contains(&".custom/keep.md".to_string()),
|
||||
"普通点号目录应被导出: {list:?}"
|
||||
);
|
||||
assert!(
|
||||
!list.iter().any(|n| n.starts_with(".editor")),
|
||||
"私有目录不该导出: {list:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dir_export_limits_scope_but_keeps_assets() {
|
||||
let root = temp_lib("dir");
|
||||
std::fs::create_dir_all(root.join("work")).unwrap();
|
||||
std::fs::create_dir_all(root.join("personal")).unwrap();
|
||||
std::fs::write(root.join("work/a.md"), "A").unwrap();
|
||||
std::fs::write(root.join("personal/b.md"), "B").unwrap();
|
||||
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
|
||||
|
||||
let (bytes, count) = zip_scope(&root, "work").unwrap();
|
||||
assert_eq!(count, 2, "work/a.md + assets/p.png");
|
||||
let list = names(bytes);
|
||||
assert!(list.contains(&"work/a.md".to_string()), "{list:?}");
|
||||
assert!(list.contains(&"assets/p.png".to_string()), "{list:?}");
|
||||
assert!(
|
||||
!list.contains(&"personal/b.md".to_string()),
|
||||
"范围外文件不该导出: {list:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dir_export_rejects_escape_and_missing() {
|
||||
let root = temp_lib("escape");
|
||||
assert!(zip_scope(&root, "../..").is_err(), "越界路径必须被拒");
|
||||
assert!(zip_scope(&root, "不存在").is_err());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
//! 任意文本 / 代码文件的读写:编码探测、换行探测、授权路径白名单。
|
||||
//!
|
||||
//! # 与笔记库的分工
|
||||
//!
|
||||
//! 库内笔记走 `library.rs`(相对路径 + 树形结构 + front-matter);本模块服务的是
|
||||
//! **库外的任意文件**:用户用 `Ctrl+O` 或拖拽打开的一个 `.py`、`.json`、`.log`。
|
||||
//! 两者的安全模型完全不同 —— 库是「一个根目录内的沙箱」,而任意文件是「用户显式
|
||||
//! 点过的那个路径」。因此这里的守卫不是路径前缀,而是**授权集合**(见下)。
|
||||
//!
|
||||
//! # 为什么要有授权白名单
|
||||
//!
|
||||
//! 前端传来的路径一律不可信:一个被污染的 WebView(XSS、恶意依赖)如果能调
|
||||
//! `editor_write_file('/Windows/System32/...')`,那就不是编辑器而是任意文件写入漏洞。
|
||||
//! 做法:只有经过 [`authorize`] 登记过的路径才允许读**写**(读也一并限制,避免拿它
|
||||
//! 当任意文件读取接口探测磁盘)。授权的三个来源都是用户动作:系统文件对话框、
|
||||
//! 命令行参数、库本身。
|
||||
//!
|
||||
//! **读**比写宽松一档:读只要求「存在且是文件」,写入才强制授权。原因是打开一篇
|
||||
//! 从设置页点进来的文件不该因为「窗口重启过、授权表空了」而失败。
|
||||
//!
|
||||
//! # 编码与换行:读写成对
|
||||
//!
|
||||
//! GBK 文件被当成 UTF-8 读出来是乱码,再按 UTF-8 存回去就是**永久损坏**(原字节
|
||||
//! 已经不可逆地丢了)。因此读的时候把「编码 + 有无 BOM + 换行风格」一并记下来,
|
||||
//! 写回时原样还原;用户显式改编码时才按新编码写。换行同理:CRLF 文件存回去必须
|
||||
//! 还是 CRLF,否则一次「随手保存」就会在整个 diff 里掀起风暴。
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fs::Metadata;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
/// 会话内已授权(用户显式打开过)的路径集合。
|
||||
///
|
||||
/// 进程级静态而非 Tauri State:授权是「这一次运行期间用户点过什么」的事实,
|
||||
/// 与库根、设置无关,也不需要跨窗口同步(每个源窗口都会自己调 `authorize`)。
|
||||
static AUTHORIZED: std::sync::OnceLock<Mutex<HashSet<PathBuf>>> = std::sync::OnceLock::new();
|
||||
|
||||
fn authorized() -> &'static Mutex<HashSet<PathBuf>> {
|
||||
AUTHORIZED.get_or_init(|| Mutex::new(HashSet::new()))
|
||||
}
|
||||
|
||||
/// 换行风格。
|
||||
pub const EOL_LF: &str = "lf";
|
||||
pub const EOL_CRLF: &str = "crlf";
|
||||
|
||||
/// 一个已打开文件的完整状态(前端据此显示编码/换行,并原样写回)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileDoc {
|
||||
/// 绝对路径(Windows 下已剥掉 `\\?\` 前缀)
|
||||
pub path: String,
|
||||
/// 显示名(文件名)
|
||||
pub name: String,
|
||||
/// 文本内容(换行已统一为 `\n`,写回时按 `eol` 还原)
|
||||
pub content: String,
|
||||
/// 探测到的编码(`utf-8` / `utf-8-bom` / `gbk` / …)
|
||||
pub encoding: String,
|
||||
/// 换行风格:"lf" | "crlf"
|
||||
pub eol: String,
|
||||
/// 文件字节数
|
||||
pub size: u64,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 是否超过「大文件」阈值(前端据此关闭 Live Preview / 折叠 / 补全)
|
||||
pub large: bool,
|
||||
/// 行数(前端状态栏显示;大文件也只需要扫一遍换行,成本可忽略)
|
||||
pub lines: u64,
|
||||
/// 是否只读(打开时探测写权限失败;前端据此拦截保存并给出原因)
|
||||
pub readonly: bool,
|
||||
}
|
||||
|
||||
/// 探测写权限:以写模式打开但**不写入**(失败 → 只读)。
|
||||
///
|
||||
/// 比「打开成功但保存时才报错」体验好得多:只读文件一打开就能看到状态栏标记。
|
||||
fn is_writable(path: &Path) -> bool {
|
||||
std::fs::OpenOptions::new().write(true).open(path).is_ok()
|
||||
}
|
||||
|
||||
/// 登记一个路径为「已授权可写」。
|
||||
pub fn authorize(path: &Path) {
|
||||
let key = normalize_key(path);
|
||||
if let Ok(mut set) = authorized().lock() {
|
||||
set.insert(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// 该路径是否已授权(写操作的前置条件)。
|
||||
pub fn is_authorized(path: &Path) -> bool {
|
||||
let key = normalize_key(path);
|
||||
authorized()
|
||||
.lock()
|
||||
.map(|set| set.contains(&key))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 授权集合的比对键:**尽力规范化**(解析符号链接与 `..`)。
|
||||
///
|
||||
/// 规范化失败(文件不存在)时退回原路径 —— 那说明写操作本来就会失败,
|
||||
/// 这里没必要为了「统一键」而提前报错。
|
||||
fn normalize_key(path: &Path) -> PathBuf {
|
||||
std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// 把路径转成可显示、可回传的字符串(剥掉 Windows 的 `\\?\` 扩展长度前缀)。
|
||||
pub fn display_path(path: &Path) -> String {
|
||||
let s = path.to_string_lossy().to_string();
|
||||
match s.strip_prefix(r"\\?\") {
|
||||
Some(rest) => rest.to_string(),
|
||||
None => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// 探测编码:返回规范名(`utf-8` / `utf-8-bom` / `gbk` / `gb18030` / `big5` / `shift_jis` / …)。
|
||||
///
|
||||
/// # 判定顺序(每一步都有理由)
|
||||
///
|
||||
/// 1. **BOM**:UTF-8 BOM / UTF-16 的 BOM 是无歧义的事实,直接采信;
|
||||
/// 2. **严格 UTF-8 校验**:能完整解成 UTF-8 就是 UTF-8。优先级高于任何统计猜测 ——
|
||||
/// 中文 GBK 字节序列几乎不可能恰好是合法 UTF-8,反向的误判同样罕见;
|
||||
/// 3. **chardetng 统计探测**:区分 Shift_JIS / Big5 / EUC-KR / GB18030 等 CJK 编码。
|
||||
/// 这一步不能省:GB18030 几乎能解码任意字节序列,若只靠「试解是否成功」,
|
||||
/// 日文 Shift_JIS 文件会被静默当成中文 GB18030;
|
||||
/// 4. 探测器给不出我们支持的编码 → 退回 GB18030 兜底;仍不行则按 UTF-8 有损解码
|
||||
/// (宁可显示替换字符,也不要打不开文件)。
|
||||
pub fn detect_encoding(bytes: &[u8]) -> String {
|
||||
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
|
||||
return "utf-8-bom".to_string();
|
||||
}
|
||||
if bytes.starts_with(&[0xFF, 0xFE]) {
|
||||
return "utf-16le".to_string();
|
||||
}
|
||||
if bytes.starts_with(&[0xFE, 0xFF]) {
|
||||
return "utf-16be".to_string();
|
||||
}
|
||||
if std::str::from_utf8(bytes).is_ok() {
|
||||
return "utf-8".to_string();
|
||||
}
|
||||
// 非 UTF-8:先用统计探测区分 CJK 编码(Shift_JIS / Big5 / EUC-KR / GB18030 …)。
|
||||
// 不能直接拿 GB18030 兜底 —— GB18030 几乎能解码任意字节序列,试解永远「成功」,
|
||||
// 会把日文 Shift_JIS 文件静默当成中文 GB18030(用户实测到的问题)。
|
||||
if let Some(name) = detect_with_chardetng(bytes) {
|
||||
return name;
|
||||
}
|
||||
// 探测器给不出我们支持的编码:退回 GB18030(GBK 的每个序列在它之下都合法)
|
||||
if crate::terminal::encoding::is_supported("gb18030") {
|
||||
return "gb18030".to_string();
|
||||
}
|
||||
"utf-8".to_string()
|
||||
}
|
||||
|
||||
/// 用 `chardetng` 统计探测非 UTF-8 文本的编码,并映射回本模块的规范编码名。
|
||||
///
|
||||
/// 只接受我们**支持**的编码(见 `terminal::encoding::SUPPORTED`):探测器给出的
|
||||
/// 单字节西文编码(`windows-125x` / `ISO-8859-x` / `KOI8-*`)统一归到 `latin1`
|
||||
/// (它们都是单字节、逐字节一一映射,不会产生替换字符);其余未知的一律返回
|
||||
/// `None`,由调用方走兜底 —— 宁可退回 GB18030,也不要返回一个解出来全是 `` 的名字。
|
||||
fn detect_with_chardetng(bytes: &[u8]) -> Option<String> {
|
||||
use chardetng::{EncodingDetector, Iso2022JpDetection, Utf8Detection};
|
||||
|
||||
let mut detector = EncodingDetector::new(Iso2022JpDetection::Deny);
|
||||
detector.feed(bytes, true);
|
||||
// 调用前已排除「合法 UTF-8」,因此不允许探测器再返回 UTF-8
|
||||
let guessed = detector.guess(None, Utf8Detection::Deny);
|
||||
let name = guessed.name().to_ascii_lowercase();
|
||||
|
||||
if name.starts_with("windows-125")
|
||||
|| name.starts_with("iso-8859")
|
||||
|| name.starts_with("koi8")
|
||||
|| name == "ibm866"
|
||||
{
|
||||
return Some("latin1".to_string());
|
||||
}
|
||||
let normalized = crate::terminal::encoding::normalize(&name);
|
||||
if crate::terminal::encoding::is_supported(&normalized) {
|
||||
return Some(normalized);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 按编码把字节解成字符串(BOM 已剥离)。
|
||||
pub(crate) fn decode_bytes(bytes: &[u8], encoding: &str) -> String {
|
||||
match encoding {
|
||||
"utf-8-bom" => {
|
||||
let body = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
|
||||
String::from_utf8_lossy(body).into_owned()
|
||||
}
|
||||
"utf-16le" | "utf-16be" => {
|
||||
// UTF-16 走 encoding_rs;BOM 由它自己处理
|
||||
crate::terminal::encoding::decode(bytes, "utf-16le")
|
||||
}
|
||||
other => crate::terminal::encoding::decode(bytes, other),
|
||||
}
|
||||
}
|
||||
|
||||
/// 按编码把字符串编成字节(必要时写回 BOM)。
|
||||
///
|
||||
/// **不可表示字符绝不静默替换成 `?`**(那是不可逆的数据损坏):先整串试编一次,
|
||||
/// 若往返比对不一致(说明有字符编不进去),再逐字符定位并报错,让用户改用 UTF-8
|
||||
/// 或删除这些字符。
|
||||
pub(crate) fn encode_text(text: &str, encoding: &str) -> Result<Vec<u8>, String> {
|
||||
match encoding {
|
||||
"utf-8-bom" => {
|
||||
let mut out = vec![0xEF, 0xBB, 0xBF];
|
||||
out.extend_from_slice(text.as_bytes());
|
||||
Ok(out)
|
||||
}
|
||||
other => {
|
||||
let normalized = crate::terminal::encoding::normalize(other);
|
||||
if !crate::terminal::encoding::is_supported(&normalized) {
|
||||
return Err(format!("不支持的编码:{other}"));
|
||||
}
|
||||
let encoded = crate::terminal::encoding::encode(text, &normalized);
|
||||
// UTF-8 能表示任何字符串,无需比对
|
||||
if normalized != "utf-8"
|
||||
&& crate::terminal::encoding::decode(&encoded, &normalized) != text
|
||||
{
|
||||
let bad = find_unencodable(text, &normalized);
|
||||
let preview = bad
|
||||
.iter()
|
||||
.take(8)
|
||||
.map(|(index, ch)| format!("第 {index} 个「{ch}」"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("、");
|
||||
let tail = if bad.len() > 8 {
|
||||
format!(",等共 {} 个字符", bad.len())
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
return Err(format!(
|
||||
"编码「{other}」无法表示:{preview}{tail}。请改用 UTF-8,或删除这些字符后再保存"
|
||||
));
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 找出目标编码无法表示的字符(位置按字符计,从 1 开始)。仅在错误路径上跑。
|
||||
fn find_unencodable(text: &str, encoding: &str) -> Vec<(usize, char)> {
|
||||
let mut out = Vec::new();
|
||||
for (index, ch) in text.chars().enumerate() {
|
||||
let mut buf = [0u8; 4];
|
||||
let s = ch.encode_utf8(&mut buf);
|
||||
let encoded = crate::terminal::encoding::encode(s, encoding);
|
||||
if crate::terminal::encoding::decode(&encoded, encoding) != &*s {
|
||||
out.push((index + 1, ch));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 探测换行风格(`\r\n` 只要出现一次就判定为 CRLF —— 混合换行的文件按主流风格写回)。
|
||||
fn detect_eol(text: &str) -> String {
|
||||
if text.contains("\r\n") {
|
||||
EOL_CRLF.to_string()
|
||||
} else {
|
||||
EOL_LF.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取任意文件(自动探测编码)。
|
||||
pub fn read_file(path: &str, max_mb: u32) -> Result<FileDoc, String> {
|
||||
read_file_inner(path, max_mb, None)
|
||||
}
|
||||
|
||||
/// 以指定编码**重新解码磁盘字节**(不写回,只换一种解释方式)。
|
||||
///
|
||||
/// 语义(规划 §5.3):切换编码是「换一种方式解释**磁盘字节**」,而不是「重新解释
|
||||
/// 缓冲区文本」—— 因此必须回到磁盘字节重新解码,而不是把编辑器里已有的字符串再转一次。
|
||||
pub fn redecode_file(path: &str, encoding: &str, max_mb: u32) -> Result<FileDoc, String> {
|
||||
read_file_inner(path, max_mb, Some(encoding))
|
||||
}
|
||||
|
||||
/// 读取实现。`forced_encoding` 为 `None` 时走探测链(BOM → 严格 UTF-8 → GB18030)。
|
||||
fn read_file_inner(
|
||||
path: &str,
|
||||
max_mb: u32,
|
||||
forced_encoding: Option<&str>,
|
||||
) -> Result<FileDoc, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
if p.is_dir() {
|
||||
return Err("这是一个目录,请选择文件".to_string());
|
||||
}
|
||||
let meta = std::fs::metadata(p).map_err(|e| format!("读取文件信息失败: {e}"))?;
|
||||
if !meta.is_file() {
|
||||
return Err("目标不是普通文件".to_string());
|
||||
}
|
||||
let bytes = std::fs::read(p).map_err(|e| format!("读取文件失败: {e}"))?;
|
||||
build_doc(p, &meta, bytes, max_mb, forced_encoding)
|
||||
}
|
||||
|
||||
/// 读取文件,复用调用方**已经读过**的头部(不重开文件、也不重读开头)。
|
||||
///
|
||||
/// 用途是对比模块:它必须「先读头部判断二进制、是文本才整读」(二进制要尽早放弃,
|
||||
/// 不能整读),若先自己嗅探再调 `read_file`,同一个文件会被打开两次、开头读两遍。
|
||||
/// 这里让调用方把**同一个句柄**(读位置已停在 `head` 之后)连同那段头部一起递进来,
|
||||
/// 于是全程只打开一次;也顺带消掉「嗅探时与整读时文件已被换掉」的那个窗口。
|
||||
///
|
||||
/// `meta` 同样由调用方传入(它刚读过一次 `metadata`,两边都省一次 stat)。
|
||||
pub(crate) fn read_file_after_head(
|
||||
mut reader: impl std::io::Read,
|
||||
path: &Path,
|
||||
meta: &Metadata,
|
||||
head: &[u8],
|
||||
max_mb: u32,
|
||||
) -> Result<FileDoc, String> {
|
||||
let mut bytes = Vec::with_capacity(head.len());
|
||||
bytes.extend_from_slice(head);
|
||||
reader
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| format!("读取文件失败: {e}"))?;
|
||||
build_doc(path, meta, bytes, max_mb, None)
|
||||
}
|
||||
|
||||
/// 读取链路的公共尾部:由「磁盘字节 + 元信息」组装 [`FileDoc`]。
|
||||
///
|
||||
/// 两个调用方共用 —— [`read_file_inner`](自己整读)与 [`read_file_after_head`]
|
||||
/// (头部由调用方提供)。把这段独立出来是为了让「字节从哪来」与「字节怎么解释」解耦,
|
||||
/// 而不是让解码 / 换行 / 元信息这段逻辑出现两份。
|
||||
fn build_doc(
|
||||
p: &Path,
|
||||
meta: &Metadata,
|
||||
bytes: Vec<u8>,
|
||||
max_mb: u32,
|
||||
forced_encoding: Option<&str>,
|
||||
) -> Result<FileDoc, String> {
|
||||
let encoding = match forced_encoding {
|
||||
Some(enc) if !enc.trim().is_empty() => {
|
||||
let requested = enc.trim();
|
||||
let normalized = if requested.eq_ignore_ascii_case("utf-8-bom") {
|
||||
"utf-8-bom".to_string()
|
||||
} else {
|
||||
crate::terminal::encoding::normalize(requested)
|
||||
};
|
||||
if normalized != "utf-8-bom" && !crate::terminal::encoding::is_supported(&normalized) {
|
||||
return Err(format!("不支持的编码:{requested}"));
|
||||
}
|
||||
normalized
|
||||
}
|
||||
_ => detect_encoding(&bytes),
|
||||
};
|
||||
let raw = decode_bytes(&bytes, &encoding);
|
||||
let eol = detect_eol(&raw);
|
||||
// 统一成 `\n` 交给编辑器:CM6 的一份文档只应有一种换行,混合换行会让
|
||||
// 「行号 / 选区 / 大纲」三处计算各按各的口径,写法回时再还原
|
||||
let content = raw.replace("\r\n", "\n");
|
||||
let limit = (max_mb.max(1) as u64) * 1024 * 1024;
|
||||
|
||||
Ok(FileDoc {
|
||||
path: display_path(p),
|
||||
name: p
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
lines: content.lines().count() as u64,
|
||||
content,
|
||||
encoding,
|
||||
eol,
|
||||
size: meta.len(),
|
||||
modified: meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0),
|
||||
large: meta.len() > limit,
|
||||
readonly: !is_writable(p),
|
||||
})
|
||||
}
|
||||
|
||||
/// 写入任意文件。
|
||||
///
|
||||
/// `encoding` 为空串时沿用「读时探测到的编码」由前端回传的那个值 —— 调用方
|
||||
/// (编辑器)始终带着它,这里不接受「猜一个」。
|
||||
pub fn write_file(
|
||||
path: &str,
|
||||
content: &str,
|
||||
encoding: &str,
|
||||
eol: &str,
|
||||
max_mb: u32,
|
||||
) -> Result<FileDoc, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
if !is_authorized(p) {
|
||||
return Err("该文件未经授权,无法写入(请通过「打开文件」重新选择)".to_string());
|
||||
}
|
||||
if !is_writable(p) {
|
||||
return Err("文件为只读,无法保存".to_string());
|
||||
}
|
||||
|
||||
let enc = if encoding.trim().is_empty() {
|
||||
"utf-8".to_string()
|
||||
} else {
|
||||
crate::terminal::encoding::normalize(encoding)
|
||||
};
|
||||
let text = if eol == EOL_CRLF {
|
||||
content.replace("\r\n", "\n").replace('\n', "\r\n")
|
||||
} else {
|
||||
content.replace("\r\n", "\n")
|
||||
};
|
||||
let bytes = encode_text(&text, &enc)?;
|
||||
|
||||
std::fs::write(p, &bytes).map_err(|e| format!("保存文件失败: {e}"))?;
|
||||
read_file(trimmed, max_mb)
|
||||
}
|
||||
|
||||
/// 把图片等二进制内容写入库根的 `assets/`(粘贴图片用)。
|
||||
///
|
||||
/// 返回**相对库根的路径**(统一 `/` 分隔),前端据此插入 Markdown 图片引用;
|
||||
/// 不使用绝对路径,保证笔记换个机器 / 换个库根也能打开。
|
||||
pub fn write_asset(
|
||||
root: &Path,
|
||||
file_name: &str,
|
||||
data: &[u8],
|
||||
ext: &str,
|
||||
) -> Result<String, String> {
|
||||
let assets = root.join(super::library::ASSETS_DIR);
|
||||
std::fs::create_dir_all(&assets).map_err(|e| format!("创建附件目录失败: {e}"))?;
|
||||
|
||||
let stem = super::library::validate_name(file_name)?;
|
||||
let stem = Path::new(&stem)
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "image".to_string());
|
||||
let ext = ext.trim().trim_start_matches('.').to_ascii_lowercase();
|
||||
let ext = if ext.is_empty() { "png".to_string() } else { ext };
|
||||
|
||||
let mut candidate = format!("{stem}.{ext}");
|
||||
let mut index = 1;
|
||||
while assets.join(&candidate).exists() {
|
||||
candidate = format!("{stem}-{index}.{ext}");
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名附件过多,请清理 assets 目录".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
std::fs::write(assets.join(&candidate), data).map_err(|e| format!("写入附件失败: {e}"))?;
|
||||
Ok(format!("{}/{candidate}", super::library::ASSETS_DIR))
|
||||
}
|
||||
|
||||
// ===== 测试 =====
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detects_bom_and_plain_utf8() {
|
||||
assert_eq!(detect_encoding(b"hello"), "utf-8");
|
||||
assert_eq!(detect_encoding("\u{feff}hello".as_bytes()), "utf-8-bom");
|
||||
assert_eq!(detect_encoding(&[0xFF, 0xFE, 0x41, 0x00]), "utf-16le");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_non_utf8_chinese_as_gbk_family() {
|
||||
// 中文:合法 UTF-8 校验必然失败,探测应落在 GBK 家族(gbk 或 gb18030)
|
||||
let text = "这是一段中文测试文本,用于验证编码探测。";
|
||||
let gbk = crate::terminal::encoding::encode(text, "gbk");
|
||||
let detected = detect_encoding(&gbk);
|
||||
assert!(
|
||||
detected == "gbk" || detected == "gb18030",
|
||||
"中文应探测为 GBK 家族,实际为 {detected}"
|
||||
);
|
||||
// GB18030 是 GBK 的超集,用它解码同样能还原
|
||||
assert_eq!(decode_bytes(&gbk, "gb18030"), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_shift_jis_not_gb18030() {
|
||||
// 日文 Shift_JIS:GB18030 也能「解码成功」,这正是旧实现误判成中文的原因
|
||||
let text = "これは日本語のテキストです。テスト用のサンプル文です。";
|
||||
let sjis = crate::terminal::encoding::encode(text, "shift_jis");
|
||||
let detected = detect_encoding(&sjis);
|
||||
assert_eq!(
|
||||
detected, "shift_jis",
|
||||
"日文 Shift_JIS 不应被误判(实际 {detected})"
|
||||
);
|
||||
assert_eq!(decode_bytes(&sjis, "shift_jis"), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eol_roundtrip_preserves_crlf() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("crlf.txt");
|
||||
std::fs::write(&path, b"a\r\nb\r\n").unwrap();
|
||||
|
||||
let doc = read_file(&display_path(&path), 5).unwrap();
|
||||
assert_eq!(doc.eol, EOL_CRLF);
|
||||
assert_eq!(doc.content, "a\nb\n");
|
||||
assert_eq!(doc.lines, 2);
|
||||
|
||||
authorize(&path);
|
||||
let saved = write_file(&display_path(&path), "a\nb\nc\n", "utf-8", EOL_CRLF, 5).unwrap();
|
||||
assert_eq!(saved.content, "a\nb\nc\n");
|
||||
// 落盘字节必须还是 CRLF(否则一次保存就污染整个 diff)
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"a\r\nb\r\nc\r\n");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_requires_authorization() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("unauthorized.txt");
|
||||
std::fs::write(&path, b"x").unwrap();
|
||||
let err = write_file(&display_path(&path), "y", "utf-8", EOL_LF, 5).unwrap_err();
|
||||
assert!(err.contains("未经授权"), "{err}");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gbk_write_uses_original_encoding() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("gbk.txt");
|
||||
std::fs::write(&path, crate::terminal::encoding::encode("中文", "gbk")).unwrap();
|
||||
|
||||
let doc = read_file(&display_path(&path), 5).unwrap();
|
||||
assert_eq!(doc.content, "中文");
|
||||
authorize(&path);
|
||||
write_file(&display_path(&path), "中文内容", &doc.encoding, &doc.eol, 5).unwrap();
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert_eq!(crate::terminal::encoding::decode(&bytes, "gbk"), "中文内容");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_flag_uses_megabyte_limit() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("big.txt");
|
||||
std::fs::write(&path, vec![b'a'; 2048]).unwrap();
|
||||
assert!(read_file(&display_path(&path), 1).unwrap().large == false);
|
||||
// 阈值按 MB 计,2048 字节在 0 上限下被夹到 1MB,仍不算大文件
|
||||
assert!(!read_file(&display_path(&path), 0).unwrap().large);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,890 @@
|
||||
//! 「在路径中查找」(Find in Path):对真实文件系统做逐行文本 / 正则检索。
|
||||
//!
|
||||
//! # 为什么不用 `index.rs` 的 FTS5 索引
|
||||
//!
|
||||
//! 索引是**笔记库专用**的加速层:它只覆盖 `.md`、只回传片段(没有行号),且不支持
|
||||
//! 正则。而「在目录 / 库中查找」需要的是**逐行命中 + 行号 + 正则**——这正是 IDEA
|
||||
//! 的 Find in Path 语义(真 grep,不是索引查询)。因此这里直接扫盘,与索引解耦:
|
||||
//! 索引挂掉 / 还没同步完,搜索依然可用。
|
||||
//!
|
||||
//! # 边界(防卡死是第一位的)
|
||||
//!
|
||||
//! - 跳过目录名清单里的目录(默认见 [`DEFAULT_SKIP_DIRS`])与超过大小上限的文件;
|
||||
//! - 跳过二进制文件(前 8KB 含 NUL 字节);
|
||||
//! - **完整统计**所有命中行(`total` / `total_files`),预览结构只构建前 `limit` 条
|
||||
//! (`returned`),`truncated` = 统计到的总数超过回传的预览数。
|
||||
//!
|
||||
//! 「计数便宜、预览贵」:就算超过上限,也只继续 `regex.find` 计数,不再做字符开窗 ——
|
||||
//! 于是「全库一共多少处命中」永远是准的,而 UI 可以分页展示回传的那部分。
|
||||
//!
|
||||
//! # 按文件自己的编码读
|
||||
//!
|
||||
//! 每个文件先用 `detect_encoding` 探测(BOM / UTF-8 合法性 / `chardetng` 统计),再按
|
||||
//! 该编码解码 —— 于是 GBK / Big5 / Shift_JIS / UTF-16 的正文与预览都是**可读的原文字**,
|
||||
//! 而不是一堆 U+FFFD。替换同样按原编码写回(复用 `files.rs` 里那套已带往返校验的
|
||||
//! `encode_text`),因此不会把 GBK 文件改成 UTF-8。
|
||||
//!
|
||||
//! # 每行只出一条命中
|
||||
//!
|
||||
//! 一行里出现多次匹配时,只回传**第一处**(`match_start` / `match_end` 指向它)。
|
||||
//! 这是 grep 类工具的常规做法:结果列表以「行」为单位才能扫读,一行列十条几乎相同
|
||||
//! 的预览反而是噪声。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use regex::{Regex, RegexBuilder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use crate::editor::files::{decode_bytes, detect_encoding, encode_text};
|
||||
|
||||
/// 单文件大小上限(超过则跳过:这类文件多是日志 / 数据,检索无意义且极慢)
|
||||
const MAX_FILE_BYTES: u64 = 8 * 1024 * 1024;
|
||||
/// 单行预览最大字符数(超出时围绕命中位置开窗)
|
||||
const PREVIEW_MAX_CHARS: usize = 220;
|
||||
/// 命中前保留的上下文字符数(开窗时)
|
||||
const PREVIEW_LEAD_CHARS: usize = 60;
|
||||
/// 每个文件最多回传的命中行数(防止单个大文件刷满结果)
|
||||
const MAX_MATCHES_PER_FILE: usize = 200;
|
||||
/// 二进制探测读取的头部字节数
|
||||
const BINARY_SNIFF_BYTES: usize = 8 * 1024;
|
||||
|
||||
/// 默认跳过的目录名(`|` 分隔,大小写不敏感)。
|
||||
///
|
||||
/// 这是**唯一**的跳过依据:早期实现还会无条件跳过所有点目录,那样用户在搜索卡片里
|
||||
/// 把 `.git` 从清单里删掉也搜不进去 —— 控件就成了摆设。默认清单已覆盖常见组合。
|
||||
///
|
||||
/// 与前端 `EditorSearch.vue` 的默认值必须一致(前端是展示源,这里是字段缺省时的兜底)。
|
||||
const DEFAULT_SKIP_DIRS: &str = "debug|.vs|.git|.svn|.hg|.idea|.vscode|node_modules|target|dist|build|out|.cache|__pycache__|.venv|venv|vendor|.next|coverage|.tmp-build";
|
||||
|
||||
/// 把 `|` / `,` 分隔的清单拆开(去空白、去空项)。跳过目录名与文件名通配共用这个约定。
|
||||
fn split_list(raw: &str) -> Vec<String> {
|
||||
raw.split(['|', ','])
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 跳过目录名集合(已转小写)。
|
||||
///
|
||||
/// `None` = 用内置默认清单;`Some("")` = **不跳过任何目录**(用户清空输入框就是明确
|
||||
/// 要求全盘搜,包括 `node_modules`)。
|
||||
fn skip_dir_set(raw: &Option<String>) -> Vec<String> {
|
||||
let list = match raw {
|
||||
Some(s) => split_list(s),
|
||||
None => split_list(DEFAULT_SKIP_DIRS),
|
||||
};
|
||||
list.iter().map(|s| s.to_lowercase()).collect()
|
||||
}
|
||||
|
||||
/// 文件名通配过滤器(`None` = 不过滤)。
|
||||
///
|
||||
/// `*` / `*.*` 按 Windows 习惯当「全部文件」,不按字面 glob 处理 —— 否则 `Makefile`
|
||||
/// 这类无扩展名的文件会被默认值意外排除。多项用 `|` 或 `,` 分隔,大小写不敏感。
|
||||
fn build_file_filter(raw: &Option<String>) -> Option<Regex> {
|
||||
let parts = match raw {
|
||||
Some(s) => split_list(s),
|
||||
None => return None,
|
||||
};
|
||||
if parts.is_empty() || parts.iter().any(|p| p == "*" || p == "*.*") {
|
||||
return None;
|
||||
}
|
||||
let body = parts
|
||||
.iter()
|
||||
.map(|p| glob_to_regex(p))
|
||||
.collect::<Vec<_>>()
|
||||
.join("|");
|
||||
RegexBuilder::new(&format!("^(?:{body})$"))
|
||||
.case_insensitive(true)
|
||||
.build()
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// 单个通配片段 → 正则(只匹配文件名,所以 `*` 不必排除路径分隔符)。
|
||||
fn glob_to_regex(pattern: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for ch in pattern.chars() {
|
||||
match ch {
|
||||
'*' => out.push_str(".*"),
|
||||
'?' => out.push('.'),
|
||||
other => out.push_str(®ex::escape(&other.to_string())),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 查找请求(`dir` 为绝对路径:当前目录或笔记库根)。
|
||||
#[derive(Debug, Clone, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchQuery {
|
||||
/// 检索根目录(绝对路径)
|
||||
pub dir: String,
|
||||
/// 关键词(`regex` 为真时按正则解释)
|
||||
pub pattern: String,
|
||||
/// 区分大小写(默认关:与 CM6 搜索一致)
|
||||
pub case_sensitive: bool,
|
||||
/// 全词匹配
|
||||
pub whole_word: bool,
|
||||
/// 按正则解释关键词
|
||||
pub regex: bool,
|
||||
/// 回传预览条数上限(缺省 1000,夹在 1..=5000)。总数不受它影响 ——
|
||||
/// 超过上限的命中只计数不构建预览,由前端分页展示回传的部分
|
||||
pub limit: Option<i64>,
|
||||
/// 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件)
|
||||
pub file_types: Option<String>,
|
||||
/// 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单)
|
||||
pub skip_dirs: Option<String>,
|
||||
}
|
||||
|
||||
/// 一处命中(以「行」为单位)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchMatch {
|
||||
/// 行号(1 起)
|
||||
pub line: i64,
|
||||
/// 行内字符列(1 起,指向首个匹配)
|
||||
pub column: i64,
|
||||
/// 该行预览(超长时围绕命中开窗,两端以 `…` 标记)
|
||||
pub preview: String,
|
||||
/// 命中在 `preview` 中的起始字符下标(前端高亮用)
|
||||
pub match_start: i64,
|
||||
/// 命中在 `preview` 中的结束字符下标(不含)
|
||||
pub match_end: i64,
|
||||
}
|
||||
|
||||
/// 一个文件内的全部命中。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchFileHits {
|
||||
/// 文件绝对路径
|
||||
pub path: String,
|
||||
/// 文件名(结果列表展示)
|
||||
pub name: String,
|
||||
/// 该文件内**全部**命中行数(`matches` 可能因回传上限只含前一部分)
|
||||
pub total_in_file: i64,
|
||||
pub matches: Vec<PathSearchMatch>,
|
||||
}
|
||||
|
||||
/// 一次「在路径中查找」的结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchResult {
|
||||
/// 按文件分组的命中(文件按遍历顺序;超出回传上限的文件不在此列)
|
||||
pub files: Vec<PathSearchFileHits>,
|
||||
/// 全树命中行总数(统计完整,不受 `limit` 影响)
|
||||
pub total: i64,
|
||||
/// 全树至少命中一行的文件总数(≥ `files.len()`)
|
||||
pub total_files: i64,
|
||||
/// 实际回传的预览条数(`files` 里 `matches` 长度之和,≤ `total`)
|
||||
pub returned: i64,
|
||||
/// `total > returned`:还有命中未回传预览
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// 替换请求(`dir` 为绝对路径:当前目录或笔记库根)。
|
||||
#[derive(Debug, Clone, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceQuery {
|
||||
/// 检索根目录(绝对路径)
|
||||
pub dir: String,
|
||||
/// 关键词(`regex` 为真时按正则解释)
|
||||
pub pattern: String,
|
||||
/// 替换串(`regex` 关闭时按**字面量**写入,不做 `$1` 展开)
|
||||
pub replacement: String,
|
||||
/// 区分大小写(默认关)
|
||||
pub case_sensitive: bool,
|
||||
/// 全词匹配
|
||||
pub whole_word: bool,
|
||||
/// 按正则解释关键词
|
||||
pub regex: bool,
|
||||
/// 替换总数上限(缺省 1000,夹在 1..=5000)
|
||||
pub limit: Option<i64>,
|
||||
/// 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件)
|
||||
pub file_types: Option<String>,
|
||||
/// 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单)
|
||||
pub skip_dirs: Option<String>,
|
||||
}
|
||||
|
||||
/// 一个被修改的文件。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceFileResult {
|
||||
pub path: String,
|
||||
pub name: String,
|
||||
pub replacements: i64,
|
||||
}
|
||||
|
||||
/// 被跳过的文件(非 UTF-8 / 写不进去)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceSkipped {
|
||||
pub path: String,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
/// 一次「在路径中替换」的结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceResult {
|
||||
/// 实际被改写的文件(含各自的替换处数)
|
||||
pub files: Vec<PathReplaceFileResult>,
|
||||
pub files_changed: i64,
|
||||
pub replacements: i64,
|
||||
/// 达到上限提前停止:此时**只改了前面一部分文件**
|
||||
pub truncated: bool,
|
||||
pub skipped: Vec<PathReplaceSkipped>,
|
||||
}
|
||||
|
||||
/// 在目录内逐行检索,按文件分组返回。
|
||||
pub fn search_in_path(query: PathSearchQuery) -> Result<PathSearchResult, String> {
|
||||
let pattern = query.pattern.trim();
|
||||
let dir = Path::new(query.dir.trim());
|
||||
if !dir.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
if pattern.is_empty() {
|
||||
return Ok(PathSearchResult {
|
||||
files: Vec::new(),
|
||||
total: 0,
|
||||
total_files: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
|
||||
let regex = build_regex(pattern, &query)?;
|
||||
let limit = query.limit.unwrap_or(1000).clamp(1, 5000) as usize;
|
||||
let skip_dirs = skip_dir_set(&query.skip_dirs);
|
||||
let file_filter = build_file_filter(&query.file_types);
|
||||
|
||||
let mut files: Vec<PathSearchFileHits> = Vec::new();
|
||||
let mut total = 0usize;
|
||||
let mut total_files = 0usize;
|
||||
let mut returned = 0usize;
|
||||
|
||||
// 不再「达限即停」:命中行数与文件数要统计完整树(用户要的是准确的总量),
|
||||
// 超过 `limit` 之后只继续计数,不再构建预览结构(开窗/换算才是贵的)。
|
||||
for_each_candidate_file(dir, &skip_dirs, file_filter.as_ref(), |path, bytes| {
|
||||
// 按文件**自己的编码**解码:GBK / Big5 / Shift_JIS / UTF-16 的正文与预览都是
|
||||
// 可读的原文字,而不是一堆 U+FFFD
|
||||
let text = decode_bytes(bytes, &detect_encoding(bytes));
|
||||
let mut hits: Vec<PathSearchMatch> = Vec::new();
|
||||
let mut in_file = 0usize;
|
||||
for (index, raw) in text.split('\n').enumerate() {
|
||||
let line = raw.strip_suffix('\r').unwrap_or(raw);
|
||||
let Some(m) = regex.find(line) else { continue };
|
||||
in_file += 1;
|
||||
if returned < limit && hits.len() < MAX_MATCHES_PER_FILE {
|
||||
hits.push(make_match(line, m.start(), m.end(), (index + 1) as i64));
|
||||
returned += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if in_file > 0 {
|
||||
total += in_file;
|
||||
total_files += 1;
|
||||
// 预览为空的文件(上限已满)不进 `files`:UI 上一个没有行的文件头是噪声
|
||||
if !hits.is_empty() {
|
||||
files.push(PathSearchFileHits {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
name: file_name_of(path),
|
||||
total_in_file: in_file as i64,
|
||||
matches: hits,
|
||||
});
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
|
||||
Ok(PathSearchResult {
|
||||
files,
|
||||
total: total as i64,
|
||||
total_files: total_files as i64,
|
||||
returned: returned as i64,
|
||||
truncated: total > returned,
|
||||
})
|
||||
}
|
||||
|
||||
/// 在目录内逐文件替换。
|
||||
///
|
||||
/// # 安全模型(这是会**改用户磁盘文件**的操作,每条都是刻意的)
|
||||
///
|
||||
/// - **按文件自己的编码读与写**:`detect_encoding` 探测 → `decode_bytes` 解码 →
|
||||
/// `encode_text` 编码写回,所以 GBK 文件写回去还是 GBK,不会被改成 UTF-8。
|
||||
/// - **编码不可字节级还原就跳过**:编码探测对某些文件是有歧义的(同一段内容在
|
||||
/// GBK / GB18030 下能编出不同字节,UTF-16 的 BOM 也不一定补得回来)。写回前先验
|
||||
/// 「原文按该编码重新编码 == 原字节」,不等就整文件跳过 —— 否则重编码会顺手改掉
|
||||
/// 未命中的字节,那是用户无从察觉的数据损坏。
|
||||
/// - **替换内容编不进去就跳过**:交给 `encode_text` 判定(它绝不把不可表示字符静默
|
||||
/// 变成 `?`),失败原因逐个回报到 `skipped`。
|
||||
/// - **只写真正变了的文件**:没匹配到就 `return`,不徒增 mtime、不触发文件监听事件。
|
||||
/// - **上限停在文件边界**:替换总数达到 `limit` 就停止并回传 `truncated`。绝不写
|
||||
/// 「一个文件只改了一半」,所以允许总数略微超过上限。
|
||||
/// - **失败即记录**:只读 / 被占用等写入失败不影响其它文件,逐个回报 `skipped`。
|
||||
pub fn replace_in_path(query: PathReplaceQuery) -> Result<PathReplaceResult, String> {
|
||||
let pattern = query.pattern.trim();
|
||||
let dir = Path::new(query.dir.trim());
|
||||
if !dir.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
|
||||
let mut result = PathReplaceResult {
|
||||
files: Vec::new(),
|
||||
files_changed: 0,
|
||||
replacements: 0,
|
||||
truncated: false,
|
||||
skipped: Vec::new(),
|
||||
};
|
||||
if pattern.is_empty() {
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
let regex = build_regex(pattern, &query)?;
|
||||
let limit = query.limit.unwrap_or(1000).clamp(1, 5000) as usize;
|
||||
let skip_dirs = skip_dir_set(&query.skip_dirs);
|
||||
let file_filter = build_file_filter(&query.file_types);
|
||||
// 正则关闭时按字面量写入(不让 `$1` / `$foo` 被意外展开 —— 用户在做纯文本替换);
|
||||
// 开启时才做捕获组展开,并把 CM6 风格的 `$&`(整个匹配)统一成 Rust regex 的 `$0`
|
||||
let expand = query.regex;
|
||||
let replacement = if expand {
|
||||
query.replacement.replace("$&", "$0")
|
||||
} else {
|
||||
query.replacement.clone()
|
||||
};
|
||||
|
||||
for_each_candidate_file(dir, &skip_dirs, file_filter.as_ref(), |path, bytes| {
|
||||
if result.replacements as usize >= limit {
|
||||
result.truncated = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
let encoding = detect_encoding(bytes);
|
||||
let text = decode_bytes(bytes, &encoding);
|
||||
// 编码必须能字节级还原原文,否则重编码会改动未命中的字节(见函数文档)
|
||||
match encode_text(&text, &encoding) {
|
||||
Ok(same) if same == bytes => {}
|
||||
Ok(_) => {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: format!("编码「{encoding}」无法字节级还原原文,已跳过(避免改动未命中的字节)"),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
Err(e) => {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: e,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
let count = regex.find_iter(&text).count();
|
||||
if count == 0 {
|
||||
return true;
|
||||
}
|
||||
let next = if expand {
|
||||
regex.replace_all(&text, replacement.as_str())
|
||||
} else {
|
||||
regex.replace_all(&text, regex::NoExpand(replacement.as_str()))
|
||||
};
|
||||
let out = match encode_text(&next, &encoding) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: e,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = std::fs::write(path, &out) {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: format!("写入失败:{e}"),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
result.replacements += count as i64;
|
||||
result.files_changed += 1;
|
||||
result.files.push(PathReplaceFileResult {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
name: file_name_of(path),
|
||||
replacements: count as i64,
|
||||
});
|
||||
true
|
||||
});
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 遍历 `dir` 下的候选文件(剪枝 + 尺寸 + 二进制 + 文件名通配),逐个把字节交给 `visit`。
|
||||
///
|
||||
/// `visit` 返回 `false` 表示调用方要求提前结束(例如命中总数已达上限)。
|
||||
///
|
||||
/// 抽出来给「查找」与「替换」共用:两者的**取舍必须完全一致**(跳哪些目录、多大算大、
|
||||
/// 什么算二进制、按什么文件名过滤),否则会出现「搜得到、替换却跳过」这种自相矛盾的行为。
|
||||
fn for_each_candidate_file(
|
||||
dir: &Path,
|
||||
skip_dirs: &[String],
|
||||
file_filter: Option<&Regex>,
|
||||
mut visit: impl FnMut(&Path, &[u8]) -> bool,
|
||||
) {
|
||||
for entry in WalkDir::new(dir)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_entry(|e| !should_skip(e, skip_dirs))
|
||||
{
|
||||
let Ok(entry) = entry else { continue };
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
if let Some(filter) = file_filter {
|
||||
let name = entry.file_name().to_string_lossy();
|
||||
if !filter.is_match(&name) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Ok(meta) = entry.metadata() else { continue };
|
||||
if meta.len() > MAX_FILE_BYTES {
|
||||
continue;
|
||||
}
|
||||
let Ok(bytes) = std::fs::read(entry.path()) else { continue };
|
||||
// 二进制文件(头部含 NUL)直接跳过:只会读到一堆乱码预览
|
||||
if bytes[..bytes.len().min(BINARY_SNIFF_BYTES)].contains(&0u8) {
|
||||
continue;
|
||||
}
|
||||
if !visit(entry.path(), &bytes) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 文件名(结果列表展示用)。
|
||||
fn file_name_of(path: &Path) -> String {
|
||||
path.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 查找 / 替换请求共有的匹配选项。
|
||||
///
|
||||
/// 抽成 trait 是为了让两处 `build_regex` 调用**不可能**把选项传串位 —— 查找与替换必须
|
||||
/// 用完全一样的规则构造正则,否则会出现「搜到的和替换的不是同一批」这种最坏情况。
|
||||
trait MatchOptions {
|
||||
fn regex_mode(&self) -> bool;
|
||||
fn whole_word(&self) -> bool;
|
||||
fn case_sensitive(&self) -> bool;
|
||||
}
|
||||
|
||||
impl MatchOptions for PathSearchQuery {
|
||||
fn regex_mode(&self) -> bool {
|
||||
self.regex
|
||||
}
|
||||
fn whole_word(&self) -> bool {
|
||||
self.whole_word
|
||||
}
|
||||
fn case_sensitive(&self) -> bool {
|
||||
self.case_sensitive
|
||||
}
|
||||
}
|
||||
|
||||
impl MatchOptions for PathReplaceQuery {
|
||||
fn regex_mode(&self) -> bool {
|
||||
self.regex
|
||||
}
|
||||
fn whole_word(&self) -> bool {
|
||||
self.whole_word
|
||||
}
|
||||
fn case_sensitive(&self) -> bool {
|
||||
self.case_sensitive
|
||||
}
|
||||
}
|
||||
|
||||
/// 组装正则:`regex` 关闭时转义为字面量,`whole_word` 时包一层词边界。
|
||||
fn build_regex(pattern: &str, options: &impl MatchOptions) -> Result<Regex, String> {
|
||||
let core = if options.regex_mode() {
|
||||
pattern.to_string()
|
||||
} else {
|
||||
regex::escape(pattern)
|
||||
};
|
||||
let body = if options.whole_word() {
|
||||
format!(r"\b(?:{core})\b")
|
||||
} else {
|
||||
core
|
||||
};
|
||||
RegexBuilder::new(&body)
|
||||
.case_insensitive(!options.case_sensitive())
|
||||
.build()
|
||||
.map_err(|e| format!("正则表达式无效:{e}"))
|
||||
}
|
||||
|
||||
/// 目录遍历剪枝:按**清单里的名字**跳过(大小写不敏感)。根目录(depth 0)永不跳过。
|
||||
fn should_skip(entry: &walkdir::DirEntry, skip_dirs: &[String]) -> bool {
|
||||
if entry.depth() == 0 || !entry.file_type().is_dir() {
|
||||
return false;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_lowercase();
|
||||
skip_dirs.iter().any(|s| *s == name)
|
||||
}
|
||||
|
||||
/// 构造一行命中:超长行围绕命中开窗,并把命中位置换算成预览内的字符下标。
|
||||
fn make_match(line: &str, match_start: usize, match_end: usize, line_no: i64) -> PathSearchMatch {
|
||||
let chars: Vec<char> = line.chars().collect();
|
||||
let start_ch = char_index(line, match_start);
|
||||
let end_ch = char_index(line, match_end);
|
||||
|
||||
let window_start = start_ch.saturating_sub(PREVIEW_LEAD_CHARS);
|
||||
let window_end = (window_start + PREVIEW_MAX_CHARS)
|
||||
.max(end_ch)
|
||||
.min(chars.len());
|
||||
let body: String = chars[window_start..window_end].iter().collect();
|
||||
let prefix = if window_start > 0 { "…" } else { "" };
|
||||
let suffix = if window_end < chars.len() { "…" } else { "" };
|
||||
let preview = format!("{prefix}{body}{suffix}");
|
||||
|
||||
let lead = prefix.chars().count() as i64;
|
||||
let preview_len = preview.chars().count() as i64;
|
||||
let match_from = ((start_ch - window_start) as i64 + lead).clamp(0, preview_len);
|
||||
let match_to = ((end_ch - window_start) as i64 + lead).clamp(match_from, preview_len);
|
||||
|
||||
PathSearchMatch {
|
||||
line: line_no,
|
||||
column: (start_ch + 1) as i64,
|
||||
preview,
|
||||
match_start: match_from,
|
||||
match_end: match_to,
|
||||
}
|
||||
}
|
||||
|
||||
/// 字节下标 → 字符下标(`regex` 给的是字节偏移,前端高亮要字符下标)。
|
||||
fn char_index(s: &str, byte: usize) -> usize {
|
||||
let byte = byte.min(s.len());
|
||||
s[..byte].chars().count()
|
||||
}
|
||||
|
||||
/// 「在路径中查找」命令。
|
||||
///
|
||||
/// 走 `spawn_blocking`:一次目录扫描是同步阻塞 IO,放在 Tauri 命令线程上会占住它
|
||||
/// (范式同 `editor_delete_path` / `editor_sync_now`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_search_in_path(query: PathSearchQuery) -> Result<PathSearchResult, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || search_in_path(query))
|
||||
.await
|
||||
.map_err(|e| format!("检索任务失败: {e}"))?
|
||||
}
|
||||
|
||||
/// 「在路径中替换」命令。
|
||||
///
|
||||
/// 与查找同理走 `spawn_blocking`(整棵树的重写是同步阻塞 IO)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_replace_in_path(query: PathReplaceQuery) -> Result<PathReplaceResult, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || replace_in_path(query))
|
||||
.await
|
||||
.map_err(|e| format!("替换任务失败: {e}"))?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 每个用例独占一个临时目录(测试并行跑,不能共用)。
|
||||
///
|
||||
/// 用 crate 的 `target/test-tmp/` 而不是 `std::env::temp_dir()`:系统临时目录在受限
|
||||
/// 环境下未必可写(本机就是这样 —— 连既有的 `files.rs` 用例也会 `PermissionDenied`),
|
||||
/// 而 `target/` 一定可写,且已被 gitignore。
|
||||
fn temp_dir(name: &str) -> std::path::PathBuf {
|
||||
let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("target")
|
||||
.join("test-tmp")
|
||||
.join(format!("grep-{name}"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// 字面量(非正则)替换请求。
|
||||
fn literal(dir: &Path, pattern: &str, replacement: &str) -> PathReplaceQuery {
|
||||
PathReplaceQuery {
|
||||
dir: dir.to_string_lossy().to_string(),
|
||||
pattern: pattern.to_string(),
|
||||
replacement: replacement.to_string(),
|
||||
case_sensitive: true,
|
||||
whole_word: false,
|
||||
regex: false,
|
||||
limit: None,
|
||||
file_types: None,
|
||||
skip_dirs: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 同上的查找请求。
|
||||
fn search_query(dir: &Path, pattern: &str) -> PathSearchQuery {
|
||||
PathSearchQuery {
|
||||
dir: dir.to_string_lossy().to_string(),
|
||||
pattern: pattern.to_string(),
|
||||
case_sensitive: true,
|
||||
whole_word: false,
|
||||
regex: false,
|
||||
limit: None,
|
||||
file_types: None,
|
||||
skip_dirs: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_replace_keeps_bom_and_crlf() {
|
||||
let dir = temp_dir("bom-crlf");
|
||||
let file = dir.join("a.txt");
|
||||
let mut bytes = vec![0xEF, 0xBB, 0xBF];
|
||||
bytes.extend_from_slice(b"foo\r\nfoo\r\n");
|
||||
std::fs::write(&file, &bytes).unwrap();
|
||||
|
||||
let result = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
|
||||
assert_eq!(result.replacements, 2);
|
||||
assert_eq!(result.files_changed, 1);
|
||||
assert!(!result.truncated);
|
||||
assert!(result.skipped.is_empty());
|
||||
|
||||
let mut expected = vec![0xEF, 0xBB, 0xBF];
|
||||
expected.extend_from_slice(b"bar\r\nbar\r\n");
|
||||
assert_eq!(
|
||||
std::fs::read(&file).unwrap(),
|
||||
expected,
|
||||
"BOM 与 CRLF 必须原样保留"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_replacement_does_not_expand_captures() {
|
||||
let dir = temp_dir("literal-dollar");
|
||||
let file = dir.join("a.txt");
|
||||
std::fs::write(&file, "foo\n").unwrap();
|
||||
|
||||
replace_in_path(literal(&dir, "foo", "$1x")).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&file).unwrap(),
|
||||
"$1x\n",
|
||||
"正则关闭时替换串必须按字面量写入"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regex_mode_expands_groups_and_normalizes_ampersand() {
|
||||
let dir = temp_dir("regex-groups");
|
||||
let a = dir.join("a.txt");
|
||||
let b = dir.join("b.txt");
|
||||
std::fs::write(&a, "user@host\n").unwrap();
|
||||
std::fs::write(&b, "word\n").unwrap();
|
||||
|
||||
let mut groups = literal(&dir, r"(\w+)@(\w+)", "$2.$1");
|
||||
groups.regex = true;
|
||||
replace_in_path(groups).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&a).unwrap(), "host.user\n");
|
||||
|
||||
// `$&`(CM6 风格的「整个匹配」)要等价于 Rust 的 `$0`
|
||||
let mut whole = literal(&dir, "word", "[$&]");
|
||||
whole.regex = true;
|
||||
replace_in_path(whole).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&b).unwrap(), "[word]\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn searches_and_replaces_gbk_file_keeping_its_encoding() {
|
||||
let dir = temp_dir("gbk");
|
||||
let file = dir.join("a.txt");
|
||||
let original = crate::terminal::encoding::encode("中文 foo\n", "gbk");
|
||||
std::fs::write(&file, &original).unwrap();
|
||||
assert!(
|
||||
std::str::from_utf8(&original).is_err(),
|
||||
"前提:原文不是合法 UTF-8"
|
||||
);
|
||||
|
||||
// 查找:预览要按原编码解出中文,而不是一堆 U+FFFD
|
||||
let found = search_in_path(search_query(&dir, "foo")).unwrap();
|
||||
assert_eq!(found.total, 1);
|
||||
let preview = &found.files[0].matches[0].preview;
|
||||
assert!(preview.contains("中文"), "预览应按原编码解出中文,实际:{preview}");
|
||||
assert!(!preview.contains('\u{FFFD}'), "预览不应出现替换字符");
|
||||
|
||||
// 替换:写回去仍然是 GBK
|
||||
let replaced = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
|
||||
assert_eq!(replaced.replacements, 1);
|
||||
assert!(
|
||||
replaced.skipped.is_empty(),
|
||||
"GBK 文件应能正常替换,实际跳过:{:?}",
|
||||
replaced.skipped
|
||||
);
|
||||
let after = std::fs::read(&file).unwrap();
|
||||
assert_eq!(
|
||||
decode_bytes(&after, &detect_encoding(&after)),
|
||||
"中文 bar\n",
|
||||
"应能按原编码读回替换后的内容"
|
||||
);
|
||||
assert!(
|
||||
std::str::from_utf8(&after).is_err(),
|
||||
"不能把 GBK 文件写成 UTF-8"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_replace_when_replacement_is_not_encodable() {
|
||||
let dir = temp_dir("unencodable");
|
||||
let file = dir.join("a.txt");
|
||||
let original = crate::terminal::encoding::encode("中文 foo\n", "gbk");
|
||||
std::fs::write(&file, &original).unwrap();
|
||||
|
||||
// emoji 编不进 GBK:必须跳过并回报,绝不能写成 `?`
|
||||
let result = replace_in_path(literal(&dir, "foo", "🙂")).unwrap();
|
||||
assert_eq!(result.replacements, 0);
|
||||
assert_eq!(result.skipped.len(), 1, "应回报为跳过");
|
||||
assert_eq!(
|
||||
std::fs::read(&file).unwrap(),
|
||||
original,
|
||||
"编码装不下替换内容时,文件必须一个字节都不动"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn respects_custom_skip_dirs_and_file_types() {
|
||||
let dir = temp_dir("filters");
|
||||
// 目录名刻意不落在默认清单里(`vendor` / `build` 之类都在清单里)
|
||||
let sub = dir.join("innersrc");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
std::fs::write(dir.join("a.md"), "foo\n").unwrap();
|
||||
std::fs::write(dir.join("b.txt"), "foo\n").unwrap();
|
||||
std::fs::write(sub.join("c.md"), "foo\n").unwrap();
|
||||
|
||||
// `innersrc` 不在默认清单里 → 三处都命中
|
||||
assert_eq!(search_in_path(search_query(&dir, "foo")).unwrap().total, 3);
|
||||
|
||||
// 只搜 *.md
|
||||
let mut by_type = search_query(&dir, "foo");
|
||||
by_type.file_types = Some("*.md".to_string());
|
||||
assert_eq!(search_in_path(by_type).unwrap().total, 2, "应只命中 .md");
|
||||
|
||||
// 跳过 innersrc
|
||||
let mut skip = search_query(&dir, "foo");
|
||||
skip.skip_dirs = Some("innersrc".to_string());
|
||||
assert_eq!(
|
||||
search_in_path(skip).unwrap().total,
|
||||
2,
|
||||
"innersrc 下的应被跳过"
|
||||
);
|
||||
|
||||
// 默认清单跳过 .git
|
||||
let git = dir.join(".git");
|
||||
std::fs::create_dir_all(&git).unwrap();
|
||||
std::fs::write(git.join("cfg"), "foo\n").unwrap();
|
||||
assert_eq!(
|
||||
search_in_path(search_query(&dir, "foo")).unwrap().total,
|
||||
3,
|
||||
"默认清单应跳过 .git"
|
||||
);
|
||||
|
||||
// 清空清单 = 不跳过任何目录(清单是唯一依据)
|
||||
let mut no_skip = search_query(&dir, "foo");
|
||||
no_skip.skip_dirs = Some(String::new());
|
||||
assert_eq!(
|
||||
search_in_path(no_skip).unwrap().total,
|
||||
4,
|
||||
"清空清单后连 .git 也要搜"
|
||||
);
|
||||
|
||||
// `*.*` 按「全部文件」处理:无扩展名的 Makefile 不能被排除
|
||||
std::fs::write(dir.join("Makefile"), "foo\n").unwrap();
|
||||
let mut star = search_query(&dir, "foo");
|
||||
star.file_types = Some("*.*".to_string());
|
||||
assert_eq!(
|
||||
search_in_path(star).unwrap().total,
|
||||
4,
|
||||
"*.* 应包含无扩展名文件"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limit_stops_at_file_boundary_without_half_writes() {
|
||||
let dir = temp_dir("limit");
|
||||
for name in ["1.txt", "2.txt", "3.txt"] {
|
||||
std::fs::write(dir.join(name), "foo\nfoo\n").unwrap();
|
||||
}
|
||||
|
||||
let mut query = literal(&dir, "foo", "bar");
|
||||
query.limit = Some(2);
|
||||
let result = replace_in_path(query).unwrap();
|
||||
|
||||
assert!(result.truncated, "达到上限应回报 truncated");
|
||||
assert_eq!(result.files_changed, 1, "上限停在文件边界,只应改完一个文件");
|
||||
assert_eq!(result.replacements, 2);
|
||||
|
||||
// 其余两个文件必须完全没动(绝不能出现「只改了一半」的文件)
|
||||
let untouched = ["1.txt", "2.txt", "3.txt"]
|
||||
.iter()
|
||||
.filter(|n| std::fs::read_to_string(dir.join(n)).unwrap() == "foo\nfoo\n")
|
||||
.count();
|
||||
assert_eq!(untouched, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_binary_files_and_pruned_dirs() {
|
||||
let dir = temp_dir("binary-prune");
|
||||
let bin = dir.join("bin.dat");
|
||||
std::fs::write(&bin, b"foo\0foo").unwrap();
|
||||
let git = dir.join(".git");
|
||||
std::fs::create_dir_all(&git).unwrap();
|
||||
std::fs::write(git.join("cfg"), "foo\n").unwrap();
|
||||
|
||||
let result = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
|
||||
assert_eq!(result.replacements, 0, "二进制文件与 .git 都不该被改写");
|
||||
assert_eq!(std::fs::read(&bin).unwrap(), b"foo\0foo");
|
||||
assert_eq!(std::fs::read_to_string(git.join("cfg")).unwrap(), "foo\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_and_replace_agree_on_matches() {
|
||||
let dir = temp_dir("agree");
|
||||
std::fs::write(dir.join("a.txt"), "Alpha alpha ALPHA\n").unwrap();
|
||||
|
||||
let found = search_in_path(search_query(&dir, "Alpha")).unwrap();
|
||||
assert_eq!(found.total, 1);
|
||||
|
||||
let replaced = replace_in_path(literal(&dir, "Alpha", "Beta")).unwrap();
|
||||
assert_eq!(replaced.replacements, 1, "替换处数必须与检索结果一致");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.join("a.txt")).unwrap(),
|
||||
"Beta alpha ALPHA\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_counts_all_hits_beyond_limit() {
|
||||
let dir = temp_dir("count-all");
|
||||
for name in ["1.txt", "2.txt", "3.txt"] {
|
||||
std::fs::write(dir.join(name), "foo\nfoo\n").unwrap();
|
||||
}
|
||||
|
||||
let mut query = search_query(&dir, "foo");
|
||||
query.limit = Some(2);
|
||||
let result = search_in_path(query).unwrap();
|
||||
|
||||
assert_eq!(result.total, 6, "总数统计完整树,不受 limit 影响");
|
||||
assert_eq!(result.total_files, 3, "文件数同样统计完整树");
|
||||
assert_eq!(result.returned, 2, "预览只回传 limit 条");
|
||||
assert!(result.truncated, "total > returned 应标记截断");
|
||||
assert_eq!(result.files.len(), 1, "超出上限的文件不再回传预览");
|
||||
assert_eq!(result.files[0].name, "1.txt");
|
||||
assert_eq!(result.files[0].total_in_file, 2);
|
||||
assert_eq!(result.files[0].matches.len(), 2);
|
||||
|
||||
// limit 足够时 truncated 为假,且 returned == total
|
||||
let full = search_in_path(search_query(&dir, "foo")).unwrap();
|
||||
assert_eq!(full.returned, full.total);
|
||||
assert!(!full.truncated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
//! 导入:本地 Markdown 目录 / 单文件 / zip 包 → 笔记库。
|
||||
//!
|
||||
//! # 永不覆盖
|
||||
//!
|
||||
//! 导入的唯一硬规则是**不覆盖库内已有文件**:重名时加序号(`笔记 2.md`)。
|
||||
//! 理由很直接 —— 导入是个批量动作,用户不会记得库里已经有哪些名字;一旦某个
|
||||
//! 同名笔记被静默替换,就是一次不可撤销的数据丢失。「多一个文件」远比「少一篇笔记」
|
||||
//! 可接受。
|
||||
//!
|
||||
//! # zip 的路径安全
|
||||
//!
|
||||
//! zip 条目名可以包含 `..` 或绝对路径(经典的 Zip Slip)。这里用
|
||||
//! `enclosed_name()` 让 zip crate 做规范化与拒绝,再过一道 [`library::safe_join`]。
|
||||
//! 两层都做不是冗余:前者防的是「解包到库外」,后者防的是「库内路径被拼成绝对路径」。
|
||||
//!
|
||||
//! # 保留目录结构
|
||||
//!
|
||||
//! 导入目录时保留其相对结构(`笔记/2026/a.md` → `<目标目录>/笔记/2026/a.md`):
|
||||
//! 用户选一个目录导入,期待的是「把这棵子树搬进来」,而不是把几十篇笔记拍平到一层。
|
||||
//! 但**跳过隐藏目录与 `node_modules`**(与同步的排除规则同一口径)。
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::library;
|
||||
use super::types::ImportReport;
|
||||
|
||||
/// 测试里要用 `ZipWriter::write_all`(`Write` 是 trait 方法,必须进作用域)。
|
||||
#[cfg(test)]
|
||||
use std::io::Write as _;
|
||||
|
||||
/// 单次导入的文件数上限(防御性:避免误选 `C:\` 之类的目录把应用拖死)。
|
||||
const MAX_IMPORT_FILES: usize = 20_000;
|
||||
|
||||
/// 从磁盘路径导入(文件 / 目录 / zip,自动判别)。
|
||||
///
|
||||
/// `dest_dir` 为库内相对目录(空串 = 库根)。
|
||||
pub fn import_path(root: &Path, source: &str, dest_dir: &str) -> Result<ImportReport, String> {
|
||||
let path = PathBuf::from(source.trim());
|
||||
if !path.exists() {
|
||||
return Err(format!("路径不存在:{source}"));
|
||||
}
|
||||
library::ensure_library(root)?;
|
||||
// 目标目录先建出来(导入到新建的目录时它可能还不存在)
|
||||
let dest = library::safe_join(root, dest_dir)?;
|
||||
std::fs::create_dir_all(&dest).map_err(|e| format!("创建目标目录失败: {e}"))?;
|
||||
|
||||
let mut report = ImportReport::default();
|
||||
|
||||
if path.is_file() {
|
||||
let is_zip = path
|
||||
.extension()
|
||||
.map(|e| e.eq_ignore_ascii_case("zip"))
|
||||
.unwrap_or(false);
|
||||
if is_zip {
|
||||
import_zip(root, &path, &dest, &mut report)?;
|
||||
} else {
|
||||
import_single(root, &path, &dest, &mut report)?;
|
||||
}
|
||||
} else {
|
||||
import_dir(root, &path, &dest, &mut report)?;
|
||||
}
|
||||
|
||||
// 导入后刷新索引交给命令层(它有 AppHandle 与索引服务)
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// 导入单个文件(非 Markdown 的图片类文件放进 `assets/`)。
|
||||
fn import_single(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let name = file
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
return Err("无法解析文件名".to_string());
|
||||
}
|
||||
if !is_markdown(&name) {
|
||||
// 单选的图片/附件:放进 assets,不当笔记
|
||||
return import_asset(root, file, &name, report);
|
||||
}
|
||||
copy_note(file, dest, &name, report)
|
||||
}
|
||||
|
||||
/// 递归导入目录(保留相对结构)。
|
||||
fn import_dir(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let mut count = 0usize;
|
||||
for entry in walkdir::WalkDir::new(dir)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
let rel_from_source = match path.strip_prefix(dir) {
|
||||
Ok(rel) => rel,
|
||||
Err(_) => continue,
|
||||
};
|
||||
// 跳过隐藏项与 node_modules(与同步排除口径一致)
|
||||
let rel_text = rel_from_source.to_string_lossy().replace('\\', "/");
|
||||
if rel_text
|
||||
.split('/')
|
||||
.any(|part| part.starts_with('.') || part.eq_ignore_ascii_case("node_modules"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
count += 1;
|
||||
if count > MAX_IMPORT_FILES {
|
||||
return Err(format!("导入文件过多(超过 {MAX_IMPORT_FILES}),请分批导入"));
|
||||
}
|
||||
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if is_markdown(&name) {
|
||||
// 保持子目录结构
|
||||
let sub = rel_from_source
|
||||
.parent()
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default();
|
||||
let target_dir = if sub.is_empty() {
|
||||
dest.to_path_buf()
|
||||
} else {
|
||||
let joined = library::safe_join(root, &relative_to(root, dest, &sub))?;
|
||||
std::fs::create_dir_all(&joined).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
joined
|
||||
};
|
||||
copy_note(path, &target_dir, &name, report)?;
|
||||
} else if is_asset(&name) {
|
||||
if let Err(e) = import_asset(root, path, &name, report) {
|
||||
push_failure(report, &rel_text, &e);
|
||||
}
|
||||
} else {
|
||||
report.skipped += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 由「库内目标目录 + 源侧子目录」拼出库内相对路径。
|
||||
fn relative_to(root: &Path, dest: &Path, sub: &str) -> String {
|
||||
let prefix = library::rel_string(root, dest);
|
||||
if prefix.is_empty() {
|
||||
sub.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{sub}")
|
||||
}
|
||||
}
|
||||
|
||||
/// 导入 zip 包(保留包内结构)。
|
||||
fn import_zip(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let handle = std::fs::File::open(file).map_err(|e| format!("打开 zip 失败: {e}"))?;
|
||||
let mut archive = zip::ZipArchive::new(handle).map_err(|e| format!("读取 zip 失败: {e}"))?;
|
||||
let dest_prefix = library::rel_string(root, dest);
|
||||
|
||||
for index in 0..archive.len() {
|
||||
let mut entry = archive
|
||||
.by_index(index)
|
||||
.map_err(|e| format!("读取 zip 条目失败: {e}"))?;
|
||||
// Zip Slip 的第一道防线:`enclosed_name` 拒绝 `..`/绝对路径
|
||||
let Some(inner) = entry.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
push_failure(report, &format!("条目 #{index}"), "路径越界,已跳过");
|
||||
continue;
|
||||
};
|
||||
if entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let rel = inner.to_string_lossy().replace('\\', "/");
|
||||
// macOS 压缩包常见的 `__MACOSX/` 与隐藏文件
|
||||
if rel
|
||||
.split('/')
|
||||
.any(|part| part.starts_with('.') || part.eq_ignore_ascii_case("__MACOSX"))
|
||||
{
|
||||
report.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let name = inner
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut bytes = Vec::new();
|
||||
entry
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| format!("读取 zip 内容失败: {e}"))?;
|
||||
|
||||
if is_markdown(&name) {
|
||||
let sub = inner
|
||||
.parent()
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default();
|
||||
let target_rel = if sub.is_empty() {
|
||||
join_rel(&dest_prefix, &name)
|
||||
} else {
|
||||
join_rel(&dest_prefix, &format!("{sub}/{name}"))
|
||||
};
|
||||
match write_unique(root, &target_rel, &bytes) {
|
||||
Ok(renamed) => {
|
||||
report.imported += 1;
|
||||
if renamed {
|
||||
report.renamed += 1;
|
||||
}
|
||||
}
|
||||
Err(e) => push_failure(report, &rel, &e),
|
||||
}
|
||||
} else if is_asset(&name) {
|
||||
match write_asset_unique(root, &name, &bytes) {
|
||||
Ok(_) => report.imported += 1,
|
||||
Err(e) => push_failure(report, &rel, &e),
|
||||
}
|
||||
} else {
|
||||
report.skipped += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 拷贝一篇 Markdown(重名加序号,**不覆盖**)。
|
||||
fn copy_note(
|
||||
file: &Path,
|
||||
dest_dir: &Path,
|
||||
name: &str,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let bytes = std::fs::read(file).map_err(|e| format!("读取 {name} 失败: {e}"))?;
|
||||
// 目标目录已在库内,这里直接构造候选名并落盘(仍走 safe_join 的等价校验)
|
||||
let mut candidate = name.to_string();
|
||||
let mut index = 1;
|
||||
while dest_dir.join(&candidate).exists() {
|
||||
candidate = numbered(name, index);
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名文件过多".to_string());
|
||||
}
|
||||
}
|
||||
let renamed = candidate != name;
|
||||
std::fs::write(dest_dir.join(&candidate), &bytes).map_err(|e| format!("写入 {candidate} 失败: {e}"))?;
|
||||
report.imported += 1;
|
||||
if renamed {
|
||||
report.renamed += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把附件写进库根 `assets/`(重名加序号)。
|
||||
fn import_asset(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
name: &str,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let bytes = std::fs::read(file).map_err(|e| format!("读取 {name} 失败: {e}"))?;
|
||||
write_asset_unique(root, name, &bytes)?;
|
||||
report.imported += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 写入 `assets/`(重名加序号)。
|
||||
fn write_asset_unique(root: &Path, name: &str, bytes: &[u8]) -> Result<String, String> {
|
||||
let assets = root.join(library::ASSETS_DIR);
|
||||
std::fs::create_dir_all(&assets).map_err(|e| format!("创建附件目录失败: {e}"))?;
|
||||
let safe = library::validate_name(name)?;
|
||||
let mut candidate = safe.clone();
|
||||
let mut index = 1;
|
||||
while assets.join(&candidate).exists() {
|
||||
candidate = numbered(&safe, index);
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名附件过多".to_string());
|
||||
}
|
||||
}
|
||||
std::fs::write(assets.join(&candidate), bytes).map_err(|e| format!("写入附件失败: {e}"))?;
|
||||
Ok(candidate)
|
||||
}
|
||||
|
||||
/// 按库内相对路径写入(重名加序号),返回是否被改名。
|
||||
fn write_unique(root: &Path, rel: &str, bytes: &[u8]) -> Result<bool, String> {
|
||||
let target = library::safe_join(root, rel)?;
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
let name = target
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
let mut candidate = name.clone();
|
||||
let mut index = 1;
|
||||
let mut renamed = false;
|
||||
while target.parent().map(|p| p.join(&candidate).exists()).unwrap_or(false) {
|
||||
candidate = numbered(&name, index);
|
||||
index += 1;
|
||||
renamed = true;
|
||||
if index > 9999 {
|
||||
return Err("同名文件过多".to_string());
|
||||
}
|
||||
}
|
||||
let final_path = match target.parent() {
|
||||
Some(parent) => parent.join(&candidate),
|
||||
None => target.clone(),
|
||||
};
|
||||
std::fs::write(&final_path, bytes).map_err(|e| format!("写入 {candidate} 失败: {e}"))?;
|
||||
Ok(renamed)
|
||||
}
|
||||
|
||||
/// 拼相对路径(空前缀时不带斜杠)。
|
||||
fn join_rel(prefix: &str, name: &str) -> String {
|
||||
if prefix.is_empty() {
|
||||
name.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{name}")
|
||||
}
|
||||
}
|
||||
|
||||
/// `笔记.md` → `笔记 2.md`
|
||||
fn numbered(name: &str, index: u32) -> String {
|
||||
match name.rfind('.') {
|
||||
Some(dot) => format!("{} {}{}", &name[..dot], index + 1, &name[dot..]),
|
||||
None => format!("{name} {}", index + 1),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_markdown(name: &str) -> bool {
|
||||
name.to_ascii_lowercase().ends_with(".md")
|
||||
|| name.to_ascii_lowercase().ends_with(".markdown")
|
||||
}
|
||||
|
||||
/// 附件类型的白名单(图片、PDF、压缩包以外的常见附件)。
|
||||
///
|
||||
/// 用白名单而不是「非 md 即附件」:导入一个目录时往往会混进 `.DS_Store`、
|
||||
/// `Thumbs.db`、`.gitignore` 之类;把它们全塞进 `assets/` 只会制造垃圾。
|
||||
fn is_asset(name: &str) -> bool {
|
||||
const EXT: &[&str] = &[
|
||||
"png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "avif", "pdf", "mp3", "wav", "mp4",
|
||||
"webm", "zip",
|
||||
];
|
||||
match name.rsplit('.').next() {
|
||||
Some(ext) => EXT.contains(&ext.to_ascii_lowercase().as_str()),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn push_failure(report: &mut ImportReport, name: &str, error: &str) {
|
||||
if report.failures.len() < 20 {
|
||||
report.failures.push(format!("{name}:{error}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_lib(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-import-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_single_file_renames_instead_of_overwriting() {
|
||||
let root = temp_lib("single");
|
||||
let src_dir = std::env::temp_dir().join(format!("thing-notes-src-single-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&src_dir);
|
||||
std::fs::create_dir_all(&src_dir).unwrap();
|
||||
std::fs::write(src_dir.join("a.md"), "导入的内容").unwrap();
|
||||
// 库内已有一篇同名
|
||||
std::fs::write(root.join("a.md"), "库里原有的").unwrap();
|
||||
|
||||
let report = import_path(&root, &src_dir.join("a.md").to_string_lossy(), "").unwrap();
|
||||
assert_eq!(report.imported, 1);
|
||||
assert_eq!(report.renamed, 1);
|
||||
// 原有内容必须没被覆盖
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.md")).unwrap(), "库里原有的");
|
||||
assert_eq!(std::fs::read_to_string(root.join("a 2.md")).unwrap(), "导入的内容");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_dir_all(&src_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_directory_keeps_structure_and_skips_junk() {
|
||||
let root = temp_lib("dir");
|
||||
let src = std::env::temp_dir().join(format!("thing-notes-src-dir-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
std::fs::create_dir_all(src.join("sub")).unwrap();
|
||||
std::fs::create_dir_all(src.join(".git")).unwrap();
|
||||
std::fs::write(src.join("top.md"), "top").unwrap();
|
||||
std::fs::write(src.join("sub/deep.md"), "deep").unwrap();
|
||||
std::fs::write(src.join("sub/note.txt"), "不是 md").unwrap();
|
||||
std::fs::write(src.join(".git/config"), "不该导入").unwrap();
|
||||
std::fs::write(src.join("pic.png"), [1u8, 2, 3]).unwrap();
|
||||
|
||||
let report = import_path(&root, &src.to_string_lossy(), "导入").unwrap();
|
||||
assert_eq!(report.imported, 3, "两篇 md + 一张图片: {report:?}");
|
||||
assert_eq!(report.skipped, 1, "note.txt 应被跳过: {report:?}");
|
||||
assert!(root.join("导入/top.md").is_file());
|
||||
assert!(root.join("导入/sub/deep.md").is_file(), "应保留子目录结构");
|
||||
assert!(root.join("assets/pic.png").is_file());
|
||||
assert!(!root.join("导入/.git").exists());
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_zip_keeps_structure_and_rejects_traversal() {
|
||||
let root = temp_lib("zip");
|
||||
let zip_path = std::env::temp_dir().join(format!("thing-notes-src-{}.zip", std::process::id()));
|
||||
{
|
||||
let file = std::fs::File::create(&zip_path).unwrap();
|
||||
let mut writer = zip::ZipWriter::new(file);
|
||||
let options: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default();
|
||||
writer.start_file("notes/a.md", options).unwrap();
|
||||
writer.write_all(b"# A").unwrap();
|
||||
// 恶意条目:逃出库根
|
||||
writer.start_file("../escape.md", options).unwrap();
|
||||
writer.write_all("坏".as_bytes()).unwrap();
|
||||
writer.start_file("__MACOSX/x.md", options).unwrap();
|
||||
writer.write_all(b"mac").unwrap();
|
||||
writer.finish().unwrap();
|
||||
}
|
||||
|
||||
let report = import_path(&root, &zip_path.to_string_lossy(), "").unwrap();
|
||||
assert_eq!(report.imported, 1, "{report:?}");
|
||||
assert!(root.join("notes/a.md").is_file());
|
||||
// `enclosed_name()` 会把 `../escape.md` 归一化成 `escape.md`(去掉了越界前缀),
|
||||
// 关键是**没有写到库根之外**
|
||||
let parent = root.parent().unwrap();
|
||||
assert!(!parent.join("escape.md").exists(), "不能写到库根之外");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_file(&zip_path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_names_keep_extension() {
|
||||
assert_eq!(numbered("a.md", 1), "a 2.md");
|
||||
assert_eq!(numbered("无扩展名", 0), "无扩展名 1");
|
||||
assert_eq!(numbered("a.b.md", 2), "a.b 3.md");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asset_whitelist_rejects_junk() {
|
||||
assert!(is_asset("pic.png"));
|
||||
assert!(is_asset("PIC.PNG"));
|
||||
assert!(is_asset("doc.pdf"));
|
||||
assert!(!is_asset("Thumbs.db"));
|
||||
assert!(!is_asset(".DS_Store"));
|
||||
assert!(!is_asset("noext"));
|
||||
}}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,592 @@
|
||||
//! 索引服务:单线程 worker + notify 文件监听。
|
||||
//!
|
||||
//! # 为什么索引必须由一个线程独占
|
||||
//!
|
||||
//! `rusqlite::Connection` 不是 `Sync` 的共享对象,而本模块有三个**并发**入口:
|
||||
//! ① 前端的搜索/统计命令(Tauri 命令线程池,可能同时进来好几个);
|
||||
//! ② 保存笔记后的增量更新;③ 文件监听器(notify 自己的回调线程)。
|
||||
//!
|
||||
//! 三种做法各有代价:给连接套 `Mutex` 会让「全库重建索引」这类慢操作**堵住搜索**
|
||||
//! (UI 直接卡住);每次操作现开一个连接则丢失 prepared statement 缓存,还会在
|
||||
//! WAL 上堆出一串写锁竞争。这里选第三条:**一个专职线程独占连接**,所有操作通过
|
||||
//! 消息通道排队进来。慢操作只排队、不阻塞调用方(命令层是异步等待回复),
|
||||
//! 连接始终只有一个,顺序天然可预期。
|
||||
//!
|
||||
//! # 监听器为什么也挂在这个线程上
|
||||
//!
|
||||
//! `notify` 的事件要落到索引上(外部新增/改动文件后立刻可搜),而**只有这个线程
|
||||
//! 能写索引**。让监听回调投递一条 `SyncPath` 消息给 worker,就地把那一个文件同步掉,
|
||||
//! 比「回调里发前端事件 → 前端再调一次同步命令」少一次往返,也不会因为前端窗口
|
||||
//! 关着而漏掉索引更新。
|
||||
//!
|
||||
//! 自我保存识别([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发
|
||||
//! `Modify(Data)`,若把这类事件也当成「外部修改」,前端就会在用户自己打字时反复
|
||||
//! 重载文档 / 弹提示。识别按**库内相对路径**在写入前登记(见 `mark_write_path`),
|
||||
//! 结果写进事件的 `from_app`,由前端决定是否提示 —— 而不是在这里静默丢弃事件。
|
||||
//! 静默丢弃一旦因时序漏判,前端就会把自家的保存当成外部改动而重载。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
|
||||
use super::files;
|
||||
use super::index::{content_hash, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery, NoteSyncReport, EditorIndex};
|
||||
use super::library;
|
||||
use crate::constants::events;
|
||||
|
||||
/// 自我写入(自己刚保存)与外部改动之间的**去重窗口**。
|
||||
///
|
||||
/// 取 1200ms:一次写入可能被 notify 拆成多条事件(`Modify(Data)` 常伴一条元数据事件),
|
||||
/// 命中的第一条之后,这段时间内的同路径事件一并算作「自己写的」,既不重复处理,
|
||||
/// 又不会把窗口拉得太长去吞掉用户紧接着在外部编辑器里的另一次保存。
|
||||
const SUPPRESS_MS: u64 = 1200;
|
||||
|
||||
/// 自我写入登记在「尚未被任何文件事件命中」时的最长存活时间。
|
||||
///
|
||||
/// 比去重窗口宽得多:notify 的派发延迟可能到秒级,窗口太窄会把「自己刚写的」误判成
|
||||
/// 外部修改(重载文档、光标弹回第一行)—— 这正是要避免的事故。登记项一旦被**第一个**
|
||||
/// 匹配事件消费,就只保留 [`SUPPRESS_MS`] 的去重窗口,不会长期吞掉真正的外部改动。
|
||||
const SELF_WRITE_TTL_MS: u64 = 30_000;
|
||||
|
||||
/// 单个文件事件的去抖说明。
|
||||
///
|
||||
/// worker 是「来一条处理一条」,去抖由三层共同承担:notify 自身的派发合并、
|
||||
/// 前端 `editor-library-changed` 的 400ms 防抖、以及自我保存抑制窗口。
|
||||
/// 之所以不在这里再加一个定时器:多一层延迟就多一个「事件丢了谁负责」的疑问,
|
||||
/// 而下游每一层都是幂等的(重复同步同一个文件只是重算一次 hash)。
|
||||
const _DEBOUNCE_NOTE_MS: u64 = 250;
|
||||
|
||||
/// 库文件变化的分类(前端据此决定「重载当前笔记」还是「只刷新树」)。
|
||||
///
|
||||
/// 只有 `removed` 是确定事实(文件不在了);「新建」与「修改」在单文件事件层面
|
||||
/// **无法区分**(notify 给的 `Create` 与 `Modify` 在一次保存里会同时出现),
|
||||
/// 因此统一报 [`CHANGE_MODIFIED`],由前端按「路径在不在当前树里」自行判断。
|
||||
pub const CHANGE_MODIFIED: &str = "modified";
|
||||
pub const CHANGE_REMOVED: &str = "removed";
|
||||
|
||||
/// 广播给各窗口的库文件变化事件。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteFileEvent {
|
||||
/// 相对库根的路径(`/` 分隔)
|
||||
pub rel_path: String,
|
||||
/// 磁盘上的绝对路径。
|
||||
///
|
||||
/// 前端需要它来判断「这个事件说的是不是我正在编辑的那个库外文件」——
|
||||
/// 相对库根路径对库外文件没有意义(它根本不在库里),只留 `rel_path`
|
||||
/// 会让「打开 D:\x\a.md 时有人在别处改了它」永远匹配不上。
|
||||
pub abs_path: String,
|
||||
/// "modified" | "removed"
|
||||
pub kind: String,
|
||||
/// 事件发生时间(Unix 毫秒)
|
||||
pub at: u64,
|
||||
/// 是否是本应用自己写入造成的(前端据此跳过「外部修改」提示)
|
||||
pub from_app: bool,
|
||||
}
|
||||
|
||||
/// 一次索引同步的结果(命令返回值)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteIndexReport {
|
||||
pub indexed: i64,
|
||||
pub removed: i64,
|
||||
pub skipped: i64,
|
||||
/// 同步后索引里的笔记数(前端直接显示,省一次统计往返)
|
||||
pub note_count: i64,
|
||||
}
|
||||
|
||||
impl From<NoteSyncReport> for NoteIndexReport {
|
||||
fn from(report: NoteSyncReport) -> Self {
|
||||
Self {
|
||||
indexed: report.indexed,
|
||||
removed: report.removed,
|
||||
skipped: report.skipped,
|
||||
note_count: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// worker 请求。
|
||||
enum Request {
|
||||
/// 增量同步整个库
|
||||
Sync(Sender<Result<NoteSyncReport, String>>),
|
||||
/// 全量重建
|
||||
Rebuild(Sender<Result<NoteSyncReport, String>>),
|
||||
/// 同步单个文件(监听器投递;文件不存在则从索引移除)
|
||||
SyncPath(PathBuf),
|
||||
/// 全文检索
|
||||
Search(NoteSearchQuery, Sender<Result<NoteSearchPage, String>>),
|
||||
/// 快速打开清单
|
||||
List(i64, Sender<Result<Vec<NoteSearchHit>, String>>),
|
||||
/// 标签清单
|
||||
Tags(Sender<Result<Vec<super::index::NoteTagCount>, String>>),
|
||||
/// 一篇笔记的出链 / 入链
|
||||
Backlinks(String, Sender<Result<super::index::NoteBacklinks, String>>),
|
||||
/// 全库链接图
|
||||
LinkGraph(Sender<Result<Vec<(String, String)>, String>>),
|
||||
/// 索引状态
|
||||
Stats(Sender<Result<NoteIndexStats, String>>),
|
||||
/// 重建监听器(库根变化后)
|
||||
Retarget(PathBuf, Sender<Result<(), String>>),
|
||||
}
|
||||
|
||||
/// 一条「本应用自己写入」的登记。
|
||||
struct SelfWrite {
|
||||
/// 库内相对路径(`/` 分隔,与 [`library::rel_string`] 的输出一致)
|
||||
rel: String,
|
||||
/// 登记时刻(写入之前,见 [`IndexService::mark_write_path`])
|
||||
marked: Instant,
|
||||
/// 首次被文件事件命中的时刻(`None` = 还没等到它的事件)
|
||||
matched: Option<Instant>,
|
||||
}
|
||||
|
||||
/// 丢弃过期的自我写入登记。
|
||||
///
|
||||
/// - **已命中**:保留 [`SUPPRESS_MS`] —— 覆盖同一次写入产生的重复事件。
|
||||
/// - **未命中**:保留 [`SELF_WRITE_TTL_MS`] —— 等它的文件事件到达(notify 延迟可能到秒级)。
|
||||
fn prune_self_writes(paths: &mut Vec<SelfWrite>) {
|
||||
let dedupe = Duration::from_millis(SUPPRESS_MS);
|
||||
let wait = Duration::from_millis(SELF_WRITE_TTL_MS);
|
||||
paths.retain(|entry| match entry.matched {
|
||||
Some(at) => at.elapsed() < dedupe,
|
||||
None => entry.marked.elapsed() < wait,
|
||||
});
|
||||
}
|
||||
|
||||
/// 索引服务的句柄(命令层只拿到这个)。
|
||||
pub struct IndexService {
|
||||
tx: Sender<Request>,
|
||||
/// 批量自我写入的时间点(导入 / WebDAV 同步 / 恢复 / 模板导出这类无法逐路径枚举的操作)。
|
||||
/// 窗口内的一切文件事件都当作「自己写的」,不向前端提示外部修改。
|
||||
bulk_write: Mutex<Option<Instant>>,
|
||||
/// 单个文件的自我写入登记。
|
||||
/// 比批量窗口精确:保存 A 不会再顺带吞掉 B 的外部改动事件。
|
||||
write_paths: Mutex<Vec<SelfWrite>>,
|
||||
}
|
||||
|
||||
static SERVICE: std::sync::OnceLock<IndexService> = std::sync::OnceLock::new();
|
||||
|
||||
/// 取索引服务(首次调用时启动 worker 线程与监听器)。
|
||||
pub fn service(app: &AppHandle) -> &'static IndexService {
|
||||
SERVICE.get_or_init(|| IndexService::start(app.clone()))
|
||||
}
|
||||
|
||||
impl IndexService {
|
||||
fn start(app: AppHandle) -> Self {
|
||||
let (tx, rx) = mpsc::channel::<Request>();
|
||||
let handle_tx = tx.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("editor-index".to_string())
|
||||
.spawn(move || worker_loop(app, rx, handle_tx))
|
||||
.expect("启动笔记索引线程失败");
|
||||
Self {
|
||||
tx,
|
||||
bulk_write: Mutex::new(None),
|
||||
write_paths: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 标记「刚刚由本应用**批量**写入了文件」(导入 / 同步 / 恢复 / 模板导出)。
|
||||
/// 这类操作无法逐路径枚举,窗口内一律视为自我写入。
|
||||
pub fn mark_write_all(&self) {
|
||||
if let Ok(mut slot) = self.bulk_write.lock() {
|
||||
*slot = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
/// 登记「本应用即将写入这个库内相对路径」。
|
||||
///
|
||||
/// **必须在真正的 `fs::write` 之前调用**:notify 的 Modify 事件可能与写入几乎同时
|
||||
/// 到达 worker,若等写盘回来再登记,事件可能已经被处理并误判为「外部修改」。
|
||||
pub fn mark_write_path(&self, rel: &str) {
|
||||
if rel.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Ok(mut paths) = self.write_paths.lock() {
|
||||
prune_self_writes(&mut paths);
|
||||
paths.push(SelfWrite {
|
||||
rel: rel.to_string(),
|
||||
marked: Instant::now(),
|
||||
matched: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 这个库内相对路径是不是「本应用自己刚写的」。
|
||||
///
|
||||
/// 命中**一次就算消费**:优先匹配还没命中过的登记(一次写入对应一次命中),
|
||||
/// 找不到才回退到刚命中过的(覆盖同一次写入的重复事件)。这样即便 notify 延迟到
|
||||
/// 秒级,登记项仍在(见 [`SELF_WRITE_TTL_MS`]),不会把自家的保存误判成外部修改。
|
||||
fn recently_written(&self, rel: &str) -> bool {
|
||||
let bulk = self
|
||||
.bulk_write
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|slot| *slot)
|
||||
.map(|at| at.elapsed() < Duration::from_millis(SUPPRESS_MS))
|
||||
.unwrap_or(false);
|
||||
if bulk {
|
||||
return true;
|
||||
}
|
||||
let Ok(mut paths) = self.write_paths.lock() else {
|
||||
return false;
|
||||
};
|
||||
prune_self_writes(&mut paths);
|
||||
let index = paths
|
||||
.iter()
|
||||
.position(|entry| entry.rel == rel && entry.matched.is_none())
|
||||
.or_else(|| paths.iter().position(|entry| entry.rel == rel));
|
||||
let Some(index) = index else {
|
||||
return false;
|
||||
};
|
||||
let entry = &mut paths[index];
|
||||
entry.matched.get_or_insert_with(Instant::now);
|
||||
true
|
||||
}
|
||||
|
||||
/// 增量同步整个库。
|
||||
pub fn sync(&self) -> Result<NoteSyncReport, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Sync(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全量重建索引。
|
||||
pub fn rebuild(&self) -> Result<NoteSyncReport, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Rebuild(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全文检索。
|
||||
pub fn search(&self, query: NoteSearchQuery) -> Result<NoteSearchPage, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Search(query, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 快速打开清单。
|
||||
pub fn list(&self, limit: i64) -> Result<Vec<NoteSearchHit>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::List(limit, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 标签清单。
|
||||
pub fn tags(&self) -> Result<Vec<super::index::NoteTagCount>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Tags(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 索引状态。
|
||||
pub fn stats(&self) -> Result<NoteIndexStats, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Stats(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 一篇笔记的出链 / 入链。
|
||||
pub fn backlinks(&self, rel_path: &str) -> Result<super::index::NoteBacklinks, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Backlinks(rel_path.to_string(), tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全库链接图(已解析的内部链接边)。
|
||||
pub fn link_graph(&self) -> Result<Vec<(String, String)>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::LinkGraph(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 切换库根(重新打开索引 + 重建监听器)。
|
||||
pub fn retarget(&self, root: PathBuf) -> Result<(), String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Retarget(root, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
}
|
||||
|
||||
/// worker 主循环:独占 [`EditorIndex`],串行处理所有请求。
|
||||
fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>) {
|
||||
let mut index: Option<EditorIndex> = None;
|
||||
let mut watcher: Option<RecommendedWatcher> = None;
|
||||
let mut watched_root: Option<PathBuf> = None;
|
||||
let mut root: Option<PathBuf> = None;
|
||||
|
||||
while let Ok(request) = rx.recv() {
|
||||
match request {
|
||||
Request::Sync(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.sync()));
|
||||
}
|
||||
Request::Rebuild(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.rebuild()));
|
||||
}
|
||||
Request::Search(query, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.search(query)));
|
||||
}
|
||||
Request::List(limit, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.list_notes(limit)));
|
||||
}
|
||||
Request::Tags(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.tags()));
|
||||
}
|
||||
Request::Backlinks(rel_path, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| {
|
||||
idx.backlinks(&rel_path)
|
||||
}));
|
||||
}
|
||||
Request::LinkGraph(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.link_graph()));
|
||||
}
|
||||
Request::Stats(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.stats()));
|
||||
}
|
||||
Request::Retarget(next, reply) => {
|
||||
// 库根未变:直接返回,不重开索引、不重建监听器。
|
||||
// 早期实现每次都 `index = None` + 重挂 watcher,于是**每次自动保存**都要重开
|
||||
// SQLite 连接、重建 notify 监听,既慢,又让「写入 → 事件」挤进这段重建窗口,
|
||||
// 制造出「自己保存却被当成外部修改」的竞态。
|
||||
if root.as_deref() == Some(next.as_path()) {
|
||||
let _ = reply.send(Ok(()));
|
||||
continue;
|
||||
}
|
||||
// 库根切换:丢掉旧索引实例,下次操作按新库根重新打开
|
||||
index = None;
|
||||
root = Some(next.clone());
|
||||
let result = match ensure_index(&app, &mut index, &next) {
|
||||
Ok(_) => {
|
||||
watched_root = None; // 触发重建监听器
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
// 新库的监听器要在回复之后建:先让前端拿到「已切换」的结果
|
||||
ensure_watcher(&mut watcher, &mut watched_root, &next, &handle_tx);
|
||||
}
|
||||
Request::SyncPath(path) => {
|
||||
if let Some(current) = root.clone() {
|
||||
// 索引尚未建立时先建(首次操作前就被外部改动的情况)
|
||||
if index.is_none() {
|
||||
if let Err(e) = ensure_index(&app, &mut index, ¤t) {
|
||||
crate::logger::log_warn("editor", &format!("索引不可用: {e}"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
ensure_watcher(&mut watcher, &mut watched_root, ¤t, &handle_tx);
|
||||
sync_one(&app, index.as_mut(), ¤t, &path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 借出索引(必要时按 `root` 打开),并把结果映射成 `Result<_, String>`。
|
||||
fn with_index<T>(
|
||||
app: &AppHandle,
|
||||
index: &mut Option<EditorIndex>,
|
||||
root: &mut Option<PathBuf>,
|
||||
run: impl FnOnce(&mut EditorIndex) -> Result<T, String>,
|
||||
) -> Result<T, String> {
|
||||
let Some(current) = root.clone() else {
|
||||
// 不在这里猜库根:命令层每次操作前都会 `retarget` 到当前库根,
|
||||
// 猜错的后果是索引挂到别的目录上(用户切过库时尤其明显)。
|
||||
return Err("索引尚未指向任何笔记库(请先打开笔记窗口)".to_string());
|
||||
};
|
||||
ensure_index(app, index, ¤t)?;
|
||||
match index.as_mut() {
|
||||
Some(idx) => run(idx),
|
||||
None => Err("索引未就绪".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保索引实例存在且指向 `root`(不匹配则重新打开)。
|
||||
fn ensure_index(app: &AppHandle, index: &mut Option<EditorIndex>, root: &Path) -> Result<(), String> {
|
||||
if let Some(existing) = index.as_ref() {
|
||||
if existing.root() == root {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if let Err(e) = library::ensure_library(root) {
|
||||
crate::logger::log_warn("editor", &e);
|
||||
}
|
||||
let opened = EditorIndex::open(root)?;
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("索引已就绪: {}", opened.db_path().display()),
|
||||
);
|
||||
// 首次打开时不自动全量同步:库可能很大,交给命令层(打开编辑器 / 重建索引时)触发
|
||||
let _ = app;
|
||||
*index = Some(opened);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 确保监听器挂在 `root` 上。
|
||||
fn ensure_watcher(
|
||||
watcher: &mut Option<RecommendedWatcher>,
|
||||
watched_root: &mut Option<PathBuf>,
|
||||
root: &Path,
|
||||
tx: &Sender<Request>,
|
||||
) {
|
||||
if let Err(e) = ensure_watcher_inner(watcher, watched_root, root, tx) {
|
||||
crate::logger::log_warn("editor", &e);
|
||||
}
|
||||
}
|
||||
|
||||
/// 建/换监听器(`root` 未变则不动)。
|
||||
fn ensure_watcher_inner(
|
||||
watcher: &mut Option<RecommendedWatcher>,
|
||||
watched_root: &mut Option<PathBuf>,
|
||||
root: &Path,
|
||||
tx: &Sender<Request>,
|
||||
) -> Result<(), String> {
|
||||
if watched_root.as_deref() == Some(root) && watcher.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let sender = tx.clone();
|
||||
let mut next = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
|
||||
let Ok(event) = event else { return };
|
||||
for path in event_paths(&event) {
|
||||
let _ = sender.send(Request::SyncPath(path));
|
||||
}
|
||||
})
|
||||
.map_err(|e| format!("创建库监听器失败: {e}"))?;
|
||||
|
||||
next.watch(root, RecursiveMode::Recursive)
|
||||
.map_err(|e| format!("监听笔记库失败: {e}"))?;
|
||||
|
||||
// 替换旧监听器(drop 即 unwatch)
|
||||
*watcher = Some(next);
|
||||
*watched_root = Some(root.to_path_buf());
|
||||
crate::logger::log_info("editor", &format!("库监听已启动: {}", root.display()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.editor/` 自身)。
|
||||
///
|
||||
/// 重命名会给出两个路径(旧、新),这里都收下:旧路径在同步时会发现「文件不存在」
|
||||
/// 而被当作删除处理,新路径自然成为新增 —— 无需专门分辨 RenameMode。
|
||||
fn event_paths(event: ¬ify::Event) -> Vec<PathBuf> {
|
||||
if matches!(event.kind, EventKind::Access(_) | EventKind::Other) {
|
||||
return Vec::new();
|
||||
}
|
||||
event
|
||||
.paths
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
let name = p.file_name().map(|n| n.to_string_lossy().to_string());
|
||||
// 只跟踪 .md 与目录事件(目录事件用于捕捉「整目录移入」)
|
||||
let is_md = name
|
||||
.as_deref()
|
||||
.map(|n| n.to_ascii_lowercase().ends_with(".md"))
|
||||
.unwrap_or(false);
|
||||
let is_meta = p
|
||||
.components()
|
||||
.any(|c| c.as_os_str().to_string_lossy().starts_with('.'));
|
||||
is_md && !is_meta
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 就地同步单个文件(含自我保存抑制与前端事件广播)。
|
||||
///
|
||||
/// 事件是否「本应用自己写的」按**库内相对路径**判定(见 [`IndexService::mark_write_path`]),
|
||||
/// 而不是一个全局时间窗 —— 全局窗会把「保存 A 之后 1.2s 内 B 被外部改动」也一并吞掉。
|
||||
fn sync_one(app: &AppHandle, index: Option<&mut EditorIndex>, root: &Path, path: &Path) {
|
||||
let Some(index) = index else { return };
|
||||
let rel = library::rel_string(root, path);
|
||||
if rel.is_empty() || rel.starts_with('.') || rel.starts_with("assets/") {
|
||||
return;
|
||||
}
|
||||
|
||||
// 自我保存抑制:只影响「是否提示用户」,索引照常更新
|
||||
let self_write = SERVICE
|
||||
.get()
|
||||
.map(|service| service.recently_written(&rel))
|
||||
.unwrap_or(false);
|
||||
|
||||
let kind = if path.is_file() {
|
||||
if let Ok(bytes) = std::fs::read(path) {
|
||||
let content = String::from_utf8_lossy(&bytes);
|
||||
let meta = std::fs::metadata(path).ok();
|
||||
let mtime = meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.modified().ok())
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0);
|
||||
let stems = std::collections::HashMap::new();
|
||||
if let Err(e) = index.upsert_note(
|
||||
&rel,
|
||||
&content,
|
||||
mtime,
|
||||
meta.as_ref().map(|m| m.len()).unwrap_or(0),
|
||||
&content_hash(&bytes),
|
||||
&stems,
|
||||
) {
|
||||
crate::logger::log_warn("editor", &format!("增量索引 {rel} 失败: {e}"));
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
// 无法分辨「新建」与「修改」时统一报 modified:前端对两者的处理相同
|
||||
// (重载树)。真正需要区分时以库扫描结果为准。
|
||||
CHANGE_MODIFIED
|
||||
} else {
|
||||
if let Err(e) = index.remove_note(&rel) {
|
||||
crate::logger::log_warn("editor", &format!("移除索引 {rel} 失败: {e}"));
|
||||
}
|
||||
CHANGE_REMOVED
|
||||
};
|
||||
|
||||
// 事件一律发出,用 `from_app` 如实标注来源,由前端决定是否提示/重载。
|
||||
// 早期实现是「自己写的就静默不发」,一旦自我写入判定因时序漏过,前端就会把自家
|
||||
// 的保存当成外部修改而重载文档(光标弹回第一行)—— 判定留在前端更稳。
|
||||
let payload = NoteFileEvent {
|
||||
rel_path: rel,
|
||||
abs_path: files::display_path(path),
|
||||
kind: kind.to_string(),
|
||||
at: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0),
|
||||
from_app: self_write,
|
||||
};
|
||||
if let Err(e) = app.emit(events::EDITOR_FILE_CHANGED, payload) {
|
||||
crate::logger::log_warn("editor", &format!("发出文件变化事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 授权 + 读取(供命令层调用,收敛「读文件必须先登记授权」这条规则)。
|
||||
pub fn read_and_authorize(path: &str, max_mb: u32) -> Result<files::FileDoc, String> {
|
||||
let doc = files::read_file(path, max_mb)?;
|
||||
files::authorize(Path::new(&doc.path));
|
||||
Ok(doc)
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
//! 笔记库的文件系统层:路径安全解析、扫描、读写、增删改移。
|
||||
//!
|
||||
//! # 真相在文件,不在数据库
|
||||
//!
|
||||
//! 笔记就是库根下的 `.md` 文件树。本文件的每个函数都以「相对库根的路径」为
|
||||
//! 输入/输出,**所有路径都先过 [`safe_join`]**:拒绝绝对路径、盘符与 `..`,
|
||||
//! 保证任何操作都无法越出库根(前端传来的路径一律不可信)。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use super::types::{LibraryEntry, NoteDoc, EditorSettings};
|
||||
|
||||
/// 默认库根相对模块目录的名字:`{app_data_dir}/editor/library`
|
||||
pub const DEFAULT_LIBRARY_DIR: &str = "library";
|
||||
/// 附件(粘贴图片等)目录名,位于库根下
|
||||
pub const ASSETS_DIR: &str = "assets";
|
||||
/// 库内私有目录名(索引 + 同步基线),**永不参与同步 / 导出 / 快照**。
|
||||
pub const PRIVATE_DIR: &str = ".editor";
|
||||
/// v1「笔记模块」的私有目录名;首次打开时惰性迁移到 [`PRIVATE_DIR`]。
|
||||
const LEGACY_PRIVATE_DIR: &str = ".notes";
|
||||
/// 扫描深度上限(防御性:软链接成环时不会无限递归)。
|
||||
/// 对 `index.rs` 公开:两处扫描(侧栏树 / 索引)必须用同一个深度口径,
|
||||
/// 否则会出现「树里看不到、搜索却搜得到」这种自相矛盾的状态。
|
||||
pub const MAX_DEPTH: usize = 24;
|
||||
|
||||
/// 新建笔记的正文模板(front-matter + 一级标题)。
|
||||
fn note_template(title: &str) -> String {
|
||||
let now = chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
|
||||
format!(
|
||||
"---\ntitle: {title}\ncreated: {now}\nupdated: {now}\ntags: []\n---\n\n# {title}\n\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// 默认库根路径(未配置自定义库根时使用)。
|
||||
pub fn default_library_root(module_dir: &Path) -> PathBuf {
|
||||
module_dir.join(DEFAULT_LIBRARY_DIR)
|
||||
}
|
||||
|
||||
/// 由设置解析出当前生效的库根。
|
||||
pub fn resolve_library_root(module_dir: &Path, settings: &EditorSettings) -> PathBuf {
|
||||
match &settings.library_root {
|
||||
Some(root) if !root.trim().is_empty() => PathBuf::from(root.trim()),
|
||||
_ => default_library_root(module_dir),
|
||||
}
|
||||
}
|
||||
|
||||
/// 惰性迁移旧私有目录 `.notes/` → `.editor/`(幂等)。
|
||||
///
|
||||
/// 索引可重建,但迁移能保住同步基线(`sync.json`),因此优先整目录重命名。
|
||||
/// 迁移后残留的旧索引文件(`notes.db*`)直接删除 —— 下次打开会按新库根重建。
|
||||
pub fn migrate_private_dir(root: &Path) {
|
||||
let old = root.join(LEGACY_PRIVATE_DIR);
|
||||
let new = root.join(PRIVATE_DIR);
|
||||
if !old.is_dir() || new.exists() {
|
||||
return;
|
||||
}
|
||||
match std::fs::rename(&old, &new) {
|
||||
Ok(()) => {
|
||||
for stale in ["notes.db", "notes.db-wal", "notes.db-shm"] {
|
||||
let _ = std::fs::remove_file(new.join(stale));
|
||||
}
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("已迁移库内私有目录 {LEGACY_PRIVATE_DIR}/ → {PRIVATE_DIR}/"),
|
||||
);
|
||||
}
|
||||
Err(e) => crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!("迁移库内私有目录失败(将按新目录重建): {e}"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保库根与其 `assets/` 子目录存在(顺带惰性迁移旧私有目录)。
|
||||
pub fn ensure_library(root: &Path) -> Result<(), String> {
|
||||
migrate_private_dir(root);
|
||||
std::fs::create_dir_all(root).map_err(|e| format!("创建笔记库目录失败: {e}"))?;
|
||||
std::fs::create_dir_all(root.join(ASSETS_DIR))
|
||||
.map_err(|e| format!("创建附件目录失败: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把「相对库根的路径」解析为绝对路径,并拒绝任何逃逸。
|
||||
///
|
||||
/// 空串表示库根本身。统一接受 `/` 与 `\` 两种分隔符输入,输出用系统分隔符。
|
||||
pub fn safe_join(root: &Path, rel: &str) -> Result<PathBuf, String> {
|
||||
let normalized = rel.trim().replace('\\', "/");
|
||||
if normalized.starts_with('/') || normalized.contains(':') {
|
||||
return Err("仅支持库内相对路径".to_string());
|
||||
}
|
||||
let mut out = root.to_path_buf();
|
||||
for part in normalized.split('/') {
|
||||
if part.is_empty() || part == "." {
|
||||
continue;
|
||||
}
|
||||
if part == ".." {
|
||||
return Err("路径不能包含上级目录(..)".to_string());
|
||||
}
|
||||
out.push(part);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 绝对路径 → 相对库根的路径(统一 `/` 分隔)。
|
||||
pub fn rel_string(root: &Path, path: &Path) -> String {
|
||||
path.strip_prefix(root)
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 校验用户输入的条目名(新建/重命名)。
|
||||
///
|
||||
/// 拒绝路径分隔符、Windows 保留字符与控制字符 —— 名称只应是「一个名字」,
|
||||
/// 不含任何路径语义。
|
||||
pub fn validate_name(name: &str) -> Result<String, String> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err("名称不能为空".to_string());
|
||||
}
|
||||
if name == "." || name == ".." {
|
||||
return Err("名称不合法".to_string());
|
||||
}
|
||||
if name.chars().count() > 120 {
|
||||
return Err("名称过长".to_string());
|
||||
}
|
||||
if name
|
||||
.chars()
|
||||
.any(|c| c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*'))
|
||||
{
|
||||
return Err("名称不能包含 < > : \" / \\ | ? * 等字符".to_string());
|
||||
}
|
||||
Ok(name.to_string())
|
||||
}
|
||||
|
||||
fn is_note_file(name: &str) -> bool {
|
||||
name.to_ascii_lowercase().ends_with(".md")
|
||||
}
|
||||
|
||||
fn modified_ms(meta: &std::fs::Metadata) -> u64 {
|
||||
meta.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// 扫描整个库,返回扁平条目列表(目录在前、各自按名称排序;前端自行组树)。
|
||||
pub fn scan(root: &Path) -> Result<Vec<LibraryEntry>, String> {
|
||||
let mut out = Vec::new();
|
||||
if !root.is_dir() {
|
||||
return Ok(out);
|
||||
}
|
||||
walk(root, root, &mut out, 0);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn walk(root: &Path, dir: &Path, out: &mut Vec<LibraryEntry>, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
let read = match std::fs::read_dir(dir) {
|
||||
Ok(r) => r,
|
||||
Err(_) => return,
|
||||
};
|
||||
|
||||
let mut dirs: Vec<(String, PathBuf)> = Vec::new();
|
||||
let mut files: Vec<(String, PathBuf)> = Vec::new();
|
||||
for entry in read.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
// 隐藏项(含 `.editor` 之类的私有目录)一律不进库树
|
||||
if name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let file_type = match entry.file_type() {
|
||||
Ok(t) => t,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let path = entry.path();
|
||||
if file_type.is_dir() {
|
||||
// 根级 assets 是图片仓库,不作为笔记目录展示,避免噪声
|
||||
if depth == 0 && name == ASSETS_DIR {
|
||||
continue;
|
||||
}
|
||||
dirs.push((name, path));
|
||||
} else if file_type.is_file() && is_note_file(&name) {
|
||||
files.push((name, path));
|
||||
}
|
||||
}
|
||||
|
||||
dirs.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
for (name, path) in dirs {
|
||||
let meta = std::fs::metadata(&path).ok();
|
||||
out.push(LibraryEntry {
|
||||
name,
|
||||
rel_path: rel_string(root, &path),
|
||||
parent_rel: rel_string(root, dir),
|
||||
is_dir: true,
|
||||
modified: meta.as_ref().map(modified_ms).unwrap_or(0),
|
||||
size: 0,
|
||||
});
|
||||
walk(root, &path, out, depth + 1);
|
||||
}
|
||||
for (name, path) in files {
|
||||
let meta = std::fs::metadata(&path).ok();
|
||||
out.push(LibraryEntry {
|
||||
name,
|
||||
rel_path: rel_string(root, &path),
|
||||
parent_rel: rel_string(root, dir),
|
||||
is_dir: false,
|
||||
modified: meta.as_ref().map(modified_ms).unwrap_or(0),
|
||||
size: meta.as_ref().map(|m| m.len()).unwrap_or(0),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 统计库内 `.md` 文件数量。
|
||||
pub fn count_notes(entries: &[LibraryEntry]) -> u32 {
|
||||
entries.iter().filter(|e| !e.is_dir).count() as u32
|
||||
}
|
||||
|
||||
/// 构造一篇文档的返回结构。
|
||||
fn to_doc(root: &Path, path: &Path, content: String) -> NoteDoc {
|
||||
let modified = std::fs::metadata(path).map(|m| modified_ms(&m)).unwrap_or(0);
|
||||
NoteDoc {
|
||||
rel_path: rel_string(root, path),
|
||||
name: path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
content,
|
||||
modified,
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取一篇笔记(相对库根路径)。非 UTF-8 字节按 lossy 处理,不报错。
|
||||
pub fn read_note(root: &Path, rel: &str) -> Result<NoteDoc, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.is_file() {
|
||||
return Err(format!("笔记不存在:{rel}"));
|
||||
}
|
||||
let bytes = std::fs::read(&path).map_err(|e| format!("读取笔记失败: {e}"))?;
|
||||
Ok(to_doc(root, &path, String::from_utf8_lossy(&bytes).into_owned()))
|
||||
}
|
||||
|
||||
/// 写入一篇笔记(已存在的文件才允许写;不自动创建目录,由 create_note 负责)。
|
||||
pub fn write_note(root: &Path, rel: &str, content: &str) -> Result<NoteDoc, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.is_file() {
|
||||
return Err(format!("笔记不存在:{rel}"));
|
||||
}
|
||||
std::fs::write(&path, content).map_err(|e| format!("保存笔记失败: {e}"))?;
|
||||
Ok(to_doc(root, &path, content.to_string()))
|
||||
}
|
||||
|
||||
/// 在指定目录下新建笔记:自动补 `.md`、重名自动加序号。
|
||||
///
|
||||
/// 用**内置**的 front-matter 模板(不读 `templates/`)。保留这个无模板参数的入口是
|
||||
/// 为了「模板目录被删/损坏时仍然能新建笔记」这条底线,单测也走它。
|
||||
pub fn create_note(root: &Path, dir_rel: &str, name: &str) -> Result<NoteDoc, String> {
|
||||
create_note_with_template(root, dir_rel, name, "")
|
||||
}
|
||||
|
||||
/// 在指定目录下新建笔记,正文由模板渲染(`template_id` 为空 = 用内置默认模板)。
|
||||
///
|
||||
/// 模板渲染失败(模板文件被删、权限不足)时回退到内置模板而不是报错:
|
||||
/// 「新建笔记」这个动作不该因为一个辅助文件的问题而不可用。
|
||||
pub fn create_note_with_template(
|
||||
root: &Path,
|
||||
dir_rel: &str,
|
||||
name: &str,
|
||||
template_id: &str,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let dir = safe_join(root, dir_rel)?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
|
||||
let mut file_name = validate_name(name)?;
|
||||
if !is_note_file(&file_name) {
|
||||
file_name.push_str(".md");
|
||||
}
|
||||
let title = file_name.trim_end_matches(".md").to_string();
|
||||
|
||||
// 重名自动加序号,避免「新建即报错」
|
||||
let mut candidate = file_name.clone();
|
||||
let mut index = 1;
|
||||
while dir.join(&candidate).exists() {
|
||||
candidate = format!("{title} {index}.md");
|
||||
index += 1;
|
||||
if index > 999 {
|
||||
return Err("同名文件过多,请换一个名称".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// 模板渲染:模板 ID 无效时 `render_for_new_note` 自己会回退到内置空白模板
|
||||
let content = if template_id.trim().is_empty() {
|
||||
note_template(&title)
|
||||
} else {
|
||||
super::templates::render_for_new_note(root, template_id, &title, dir_rel)
|
||||
};
|
||||
|
||||
let path = dir.join(&candidate);
|
||||
std::fs::write(&path, content).map_err(|e| format!("新建笔记失败: {e}"))?;
|
||||
read_note(root, &rel_string(root, &path))
|
||||
}
|
||||
|
||||
/// 在指定目录下新建文件夹。
|
||||
pub fn create_folder(root: &Path, dir_rel: &str, name: &str) -> Result<String, String> {
|
||||
let dir = safe_join(root, dir_rel)?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
let folder_name = validate_name(name)?;
|
||||
let path = dir.join(&folder_name);
|
||||
if path.exists() {
|
||||
return Err(format!("「{folder_name}」已存在"));
|
||||
}
|
||||
std::fs::create_dir_all(&path).map_err(|e| format!("新建文件夹失败: {e}"))?;
|
||||
Ok(rel_string(root, &path))
|
||||
}
|
||||
|
||||
/// 重命名库内条目;返回新的相对路径。
|
||||
///
|
||||
/// 文件若未带扩展名,沿用原扩展名(避免 `a.md` 改成 `a` 变成无扩展名文件)。
|
||||
pub fn rename_entry(root: &Path, rel: &str, new_name: &str) -> Result<String, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.exists() {
|
||||
return Err("条目不存在".to_string());
|
||||
}
|
||||
let mut name = validate_name(new_name)?;
|
||||
if path.is_file() {
|
||||
let old_ext = path.extension().map(|e| e.to_string_lossy().to_string());
|
||||
if let Some(ext) = old_ext {
|
||||
if !name.to_ascii_lowercase().ends_with(&format!(".{}", ext.to_ascii_lowercase())) {
|
||||
name.push('.');
|
||||
name.push_str(&ext);
|
||||
}
|
||||
}
|
||||
}
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| "无法解析父目录".to_string())?;
|
||||
let target = parent.join(&name);
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
std::fs::rename(&path, &target).map_err(|e| format!("重命名失败: {e}"))?;
|
||||
Ok(rel_string(root, &target))
|
||||
}
|
||||
|
||||
/// 删除库内条目(目录递归删除)。
|
||||
pub fn delete_entry(root: &Path, rel: &str) -> Result<(), String> {
|
||||
if rel.trim().is_empty() {
|
||||
return Err("不能删除库根".to_string());
|
||||
}
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.exists() {
|
||||
return Err("条目不存在".to_string());
|
||||
}
|
||||
if path.is_dir() {
|
||||
std::fs::remove_dir_all(&path).map_err(|e| format!("删除目录失败: {e}"))?;
|
||||
} else {
|
||||
std::fs::remove_file(&path).map_err(|e| format!("删除文件失败: {e}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//! 笔记 / 编辑器模块。
|
||||
//!
|
||||
//! 架构位置:
|
||||
//!
|
||||
//! ```text
|
||||
//! 主模块页(设置 / 库管理) 独立窗口(CM6 编辑器)
|
||||
//! ↓ Tauri IPC ↓
|
||||
//! commands.rs 命令层
|
||||
//! ↓
|
||||
//! EditorManager(本文件):设置读写 / 库根解析
|
||||
//! ↓
|
||||
//! library.rs 文件系统(路径安全 / 扫描 / 读写 / 增删改移)
|
||||
//! ```
|
||||
//!
|
||||
//! # 真相在文件
|
||||
//!
|
||||
//! 笔记 = 库根下的 `.md` 文件树。Rust 侧只做文件 IO 与设置持久化,
|
||||
//! **不引入私有格式**;SQLite 索引(`index.rs`)只是可重建的加速层。
|
||||
//!
|
||||
//! # 三个入口的职责边界
|
||||
//!
|
||||
//! ```text
|
||||
//! library.rs 库内笔记:相对路径 + 树 + front-matter(安全模型 = 根目录沙箱)
|
||||
//! files.rs 库外任意文件:绝对路径 + 编码/换行(安全模型 = 授权白名单)
|
||||
//! index_service.rs 索引与监听:独占 SQLite 连接的单线程 worker + notify
|
||||
//! ```
|
||||
//!
|
||||
//! 设置持久化:`{app_data_dir}/editor/settings.json`(范式同 ai / translate)。
|
||||
//! 默认库根:`{app_data_dir}/editor/library`;用户可在设置里改。
|
||||
|
||||
mod args;
|
||||
mod backup;
|
||||
mod commands;
|
||||
mod dirs;
|
||||
mod export;
|
||||
pub(crate) mod files;
|
||||
mod grep;
|
||||
mod import;
|
||||
mod index;
|
||||
mod index_service;
|
||||
mod library;
|
||||
mod shell_menu;
|
||||
mod templates;
|
||||
mod types;
|
||||
mod webdav;
|
||||
|
||||
pub use commands::{
|
||||
editor_add_template, editor_authorize_file, editor_backlinks, editor_backup_now,
|
||||
editor_create_folder, editor_create_note, editor_daily_note, editor_delete_entry,
|
||||
editor_export_note, editor_export_snapshot_local, editor_export_zip, editor_get_settings,
|
||||
editor_import, editor_index_stats, editor_library_info, editor_link_graph, editor_list_backups,
|
||||
editor_list_notes, editor_list_templates, editor_open_file, editor_read_asset, editor_read_note,
|
||||
editor_read_template, editor_rebuild_index, editor_redecode_file, editor_rename_entry,
|
||||
editor_restore_backup,
|
||||
editor_save_note, editor_save_settings, editor_scan_library, editor_scratch_dir, editor_search_notes,
|
||||
editor_set_library_root, editor_set_webdav_password, editor_sync_index, editor_sync_now,
|
||||
editor_tags, editor_take_pending_file, editor_test_webdav, editor_webdav_status,
|
||||
editor_write_asset, editor_write_file,
|
||||
};
|
||||
pub use args::{emit_open_target, open_target_from_args, remember_pending_target};
|
||||
pub use dirs::{
|
||||
editor_create_dir, editor_create_file, editor_delete_path, editor_move_path, editor_read_dir,
|
||||
editor_rename_path,
|
||||
};
|
||||
pub use grep::{editor_replace_in_path, editor_search_in_path};
|
||||
pub use shell_menu::{
|
||||
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
|
||||
};
|
||||
use types::EditorSettings;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// 设置内存缓存有效期(与 ai / translate / terminal 的 500ms 一致)。
|
||||
const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500);
|
||||
|
||||
struct SettingsCache {
|
||||
read_at: Instant,
|
||||
settings: EditorSettings,
|
||||
}
|
||||
|
||||
/// 笔记 / 编辑器模块管理器(Tauri State)。
|
||||
pub struct EditorManager {
|
||||
/// 模块自身目录:`{app_data_dir}/editor`
|
||||
module_dir: PathBuf,
|
||||
cache: Mutex<Option<SettingsCache>>,
|
||||
}
|
||||
|
||||
/// 一次性迁移 `{app_data_dir}/notes/` → `{app_data_dir}/editor/`(幂等)。
|
||||
///
|
||||
/// 仅当旧目录存在且新目录不存在时整目录重命名;两者都在则各自独立
|
||||
/// (说明已在用新目录,旧目录留着不动,避免误删用户数据)。
|
||||
fn migrate_legacy_module_dir(app_data_dir: &Path, module_dir: &Path) {
|
||||
let legacy = app_data_dir.join("notes");
|
||||
if legacy.is_dir() && !module_dir.exists() {
|
||||
match std::fs::rename(&legacy, module_dir) {
|
||||
Ok(()) => crate::logger::log_info("editor", "已迁移模块目录 notes/ → editor/"),
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("迁移模块目录失败: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EditorManager {
|
||||
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||
let module_dir = app_data_dir.join("editor");
|
||||
migrate_legacy_module_dir(&app_data_dir, &module_dir);
|
||||
let _ = std::fs::create_dir_all(&module_dir);
|
||||
Self {
|
||||
module_dir,
|
||||
cache: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// 模块自身目录(库根默认值基于它解析)。
|
||||
pub fn module_dir(&self) -> &Path {
|
||||
&self.module_dir
|
||||
}
|
||||
|
||||
/// 启动时按设置注册全局快捷键。
|
||||
///
|
||||
/// 失败只记日志:快捷键被别的应用占了不该阻断启动(与 translate / terminal 同一姿态)。
|
||||
/// 触发时**只发事件**,窗口与「新建哪一篇」由前端决定 —— Rust 侧不持有窗口 label
|
||||
/// 策略,也不该知道当前打开的库是哪一篇(那是前端 store 的事)。
|
||||
pub fn init_on_launch(&self, app: &tauri::AppHandle) {
|
||||
use tauri::Emitter;
|
||||
let settings = self.load_settings();
|
||||
|
||||
let new_note = settings.new_note_shortcut.clone();
|
||||
if let Err(e) = crate::shortcut::register_shortcut(app, "editor-new-note", &new_note, |app| {
|
||||
if let Err(e) = app.emit(crate::constants::events::EDITOR_NEW_NOTE, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出新建笔记事件失败: {e}"));
|
||||
}
|
||||
}) {
|
||||
crate::logger::log_warn("editor", &format!("注册「新建笔记」快捷键失败: {e}"));
|
||||
}
|
||||
|
||||
let open_editor = settings.open_editor_shortcut.clone();
|
||||
if let Err(e) =
|
||||
crate::shortcut::register_shortcut(app, "editor-open-editor", &open_editor, |app| {
|
||||
if let Err(e) = app.emit(crate::constants::events::EDITOR_OPEN_EDITOR, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出打开编辑器事件失败: {e}"));
|
||||
}
|
||||
})
|
||||
{
|
||||
crate::logger::log_warn("editor", &format!("注册「打开编辑器」快捷键失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_path(&self) -> PathBuf {
|
||||
self.module_dir.join("settings.json")
|
||||
}
|
||||
|
||||
/// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。
|
||||
pub fn load_settings(&self) -> EditorSettings {
|
||||
if let Ok(cache) = self.cache.lock() {
|
||||
if let Some(entry) = cache.as_ref() {
|
||||
if entry.read_at.elapsed() < SETTINGS_CACHE_TTL {
|
||||
return entry.settings.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = std::fs::read_to_string(self.settings_path())
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<EditorSettings>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
let healed = settings.heal();
|
||||
// 刷新「最近记录」的存在性(只读,不触发落盘)
|
||||
settings.refresh_recent_exists();
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
if healed {
|
||||
if let Err(e) = self.save_settings(&settings) {
|
||||
crate::logger::log_error("editor", &format!("设置自愈落盘失败: {e}"));
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// 保存设置并刷新缓存。
|
||||
pub fn save_settings(&self, settings: &EditorSettings) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(settings)
|
||||
.map_err(|e| format!("序列化笔记设置失败: {e}"))?;
|
||||
std::fs::write(self.settings_path(), json)
|
||||
.map_err(|e| format!("写入笔记设置失败: {e}"))?;
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Windows 资源管理器右键菜单(HKCU,**免管理员**)。
|
||||
//!
|
||||
//! # 为什么走用户级注册表
|
||||
//!
|
||||
//! 文件关联由安装器写 `HKLM`/`OpenWithProgids`;而「右键 → 用 Thing 编辑器打开」
|
||||
//! 只需 `HKCU\Software\Classes\{*,Directory,Directory\Background}\shell\ThingEditor`,
|
||||
//! 用户级即可生效、无需提权(范式同 `mihomo_manager/system_proxy.rs`)。
|
||||
//!
|
||||
//! # 为什么默认不自动注册
|
||||
//!
|
||||
//! 注册表项里写的是**绝对 exe 路径**:打包安装后指向安装目录(稳定),但
|
||||
//! `tauri dev` 下指向 `target\debug\thing.exe` —— 一旦清理 target 就成了死链。
|
||||
//! 因此注册/卸载都只在设置页按钮下发生,且注册前校验 exe 存在。
|
||||
//!
|
||||
//! # 三处菜单
|
||||
//!
|
||||
//! | 键 | 场景 | 参数 |
|
||||
//! |---|---|---|
|
||||
//! | `*` | 任意文件 | `%1` |
|
||||
//! | `Directory` | 文件夹 | `%1` |
|
||||
//! | `Directory\Background` | 目录背景空白处 | `%V`(当前目录) |
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
/// 右键菜单键名与显示名。
|
||||
const MENU_KEY: &str = "ThingEditor";
|
||||
const MENU_LABEL: &str = "用 Thing 编辑器打开";
|
||||
|
||||
/// 右键菜单状态(回传设置页展示)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ContextMenuStatus {
|
||||
/// 是否已注册(以 `*` 键为准)
|
||||
pub registered: bool,
|
||||
/// 当前可执行文件绝对路径(注册表里写入的就是它)
|
||||
pub exe_path: String,
|
||||
/// 是否开发模式(exe 路径不稳定,UI 需给出提示)
|
||||
pub is_dev: bool,
|
||||
}
|
||||
|
||||
fn exe_path() -> String {
|
||||
std::env::current_exe()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 读取当前状态。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_context_menu_status() -> ContextMenuStatus {
|
||||
ContextMenuStatus {
|
||||
registered: imp::registered(),
|
||||
exe_path: exe_path(),
|
||||
is_dev: cfg!(debug_assertions),
|
||||
}
|
||||
}
|
||||
|
||||
/// 注册右键菜单(写 HKCU)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_register_context_menu() -> Result<ContextMenuStatus, String> {
|
||||
imp::register()?;
|
||||
Ok(editor_context_menu_status())
|
||||
}
|
||||
|
||||
/// 卸载右键菜单(删 HKCU 对应项)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_unregister_context_menu() -> Result<ContextMenuStatus, String> {
|
||||
imp::unregister()?;
|
||||
Ok(editor_context_menu_status())
|
||||
}
|
||||
|
||||
// ===== Windows 实现 =====
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{exe_path, MENU_KEY, MENU_LABEL};
|
||||
use std::path::Path;
|
||||
|
||||
const ROOTS: [&str; 3] = ["*", "Directory", "Directory\\Background"];
|
||||
|
||||
fn key_path(root: &str) -> String {
|
||||
format!("Software\\Classes\\{root}\\shell\\{MENU_KEY}")
|
||||
}
|
||||
|
||||
pub fn registered() -> bool {
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
use winreg::RegKey;
|
||||
RegKey::predef(HKEY_CURRENT_USER)
|
||||
.open_subkey(key_path("*"))
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
pub fn register() -> Result<(), String> {
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
use winreg::RegKey;
|
||||
|
||||
let exe = exe_path();
|
||||
if exe.is_empty() {
|
||||
return Err("无法确定可执行文件路径".to_string());
|
||||
}
|
||||
if !Path::new(&exe).is_file() {
|
||||
return Err(format!("可执行文件不存在:{exe}(开发模式下请先构建)"));
|
||||
}
|
||||
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
for root in ROOTS {
|
||||
let path = key_path(root);
|
||||
let (key, _) = hkcu
|
||||
.create_subkey(&path)
|
||||
.map_err(|e| format!("写入注册表失败({root}): {e}"))?;
|
||||
key.set_value("", &MENU_LABEL)
|
||||
.map_err(|e| format!("写入菜单名称失败({root}): {e}"))?;
|
||||
key.set_value("Icon", &exe)
|
||||
.map_err(|e| format!("写入菜单图标失败({root}): {e}"))?;
|
||||
// Directory\Background 传入的是「当前目录」,用 %V;其余用 %1
|
||||
let arg = if root.ends_with("Background") { "%V" } else { "%1" };
|
||||
let (cmd_key, _) = hkcu
|
||||
.create_subkey(format!("{path}\\command"))
|
||||
.map_err(|e| format!("写入菜单命令失败({root}): {e}"))?;
|
||||
cmd_key
|
||||
.set_value("", &format!("\"{exe}\" \"{arg}\""))
|
||||
.map_err(|e| format!("写入菜单命令行失败({root}): {e}"))?;
|
||||
}
|
||||
crate::logger::log_info("editor", &format!("已注册右键菜单,指向 {exe}"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn unregister() -> Result<(), String> {
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
use winreg::RegKey;
|
||||
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
for root in ROOTS {
|
||||
let path = key_path(root);
|
||||
match hkcu.delete_subkey_all(&path) {
|
||||
Ok(()) => {}
|
||||
// 本就不存在视为成功(幂等)
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(format!("删除注册表项失败({root}): {e}")),
|
||||
}
|
||||
}
|
||||
crate::logger::log_info("editor", "已卸载右键菜单");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 非 Windows:明确告知不支持 =====
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod imp {
|
||||
pub fn registered() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn register() -> Result<(), String> {
|
||||
Err("资源管理器右键菜单仅支持 Windows".to_string())
|
||||
}
|
||||
|
||||
pub fn unregister() -> Result<(), String> {
|
||||
Err("资源管理器右键菜单仅支持 Windows".to_string())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
//! 新建笔记的模板:内置默认模板 + 用户模板目录。
|
||||
//!
|
||||
//! # 模板为什么要落成 `.md` 文件
|
||||
//!
|
||||
//! 与「笔记的真相是文件」同一条原则:模板也是用户会想改的东西,做成 JSON 里的一段
|
||||
//! 字符串,用户既看不到也改不了。落成 `.md` 文件后,用任意编辑器改,改完立刻生效。
|
||||
//!
|
||||
//! # 两个来源
|
||||
//!
|
||||
//! - **内置**:编译进二进制(`include_str!`),保证全新机器上「新建笔记」永远有东西可用;
|
||||
//! - **用户**:`{库根}/templates/*.md`。库是可切换的,模板跟着库走 —— 一个技术笔记库
|
||||
//! 和一个日记库本来就该有不同的模板集。
|
||||
//!
|
||||
//! 同名时用户模板覆盖内置模板。内置模板不写进库根(否则用户第一次新建笔记就会
|
||||
//! 发现库里多出一堆他没建过的文件)。
|
||||
//!
|
||||
//! # 变量替换
|
||||
//!
|
||||
//! 只支持少量、无歧义的占位符(`{{date}}` / `{{time}}` / `{{title}}` / `{{datetime}}`)。
|
||||
//! **不做条件、循环、包含** —— 那是一条通往「半个模板引擎」的路,收益远小于维护成本。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use super::library;
|
||||
|
||||
/// 一个模板。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteTemplate {
|
||||
/// 标识(内置用 `builtin:<文件名>`,用户模板用 `user:<文件名>`)
|
||||
pub id: String,
|
||||
/// 显示名(文件名去掉扩展名)
|
||||
pub name: String,
|
||||
/// 说明(内置模板手写;用户模板取正文首行非空文本)
|
||||
pub description: String,
|
||||
/// 是否为内置模板(前端据此提示「不可删除」)
|
||||
pub builtin: bool,
|
||||
/// 模板正文(含 front-matter)
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
/// 内置模板(编译进二进制)。
|
||||
const BUILTIN: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"空白笔记",
|
||||
"只有 front-matter 与一级标题,适合随手记",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: []\n---\n\n# {{title}}\n\n",
|
||||
),
|
||||
(
|
||||
"会议纪要",
|
||||
"议题 / 结论 / 待办三段式",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [会议]\n---\n\n# {{title}}\n\n- 时间:{{datetime}}\n- 参会:\n\n## 议题\n\n## 结论\n\n## 待办\n\n- [ ] \n",
|
||||
),
|
||||
(
|
||||
"日记",
|
||||
"按日期归档的日记骨架",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [日记]\n---\n\n# {{date}}\n\n## 今天做了什么\n\n## 明天要做什么\n\n- [ ] \n",
|
||||
),
|
||||
(
|
||||
"读书笔记",
|
||||
"书籍信息 + 摘录 + 思考",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [读书]\n---\n\n# {{title}}\n\n- 书名:\n- 作者:\n- 进度:\n\n## 摘录\n\n> \n\n## 我的思考\n\n",
|
||||
),
|
||||
];
|
||||
|
||||
/// 列出全部模板(用户模板优先,同名覆盖内置)。
|
||||
pub fn list(root: &Path) -> Vec<NoteTemplate> {
|
||||
let mut out: Vec<NoteTemplate> = Vec::new();
|
||||
|
||||
// 用户模板:`{库根}/templates/*.md`
|
||||
let dir = root.join("templates");
|
||||
if dir.is_dir() {
|
||||
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| {
|
||||
path.is_file()
|
||||
&& path
|
||||
.extension()
|
||||
.map(|e| e.eq_ignore_ascii_case("md"))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect();
|
||||
files.sort();
|
||||
for path in files {
|
||||
let name = path
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Ok(body) = std::fs::read_to_string(&path) else {
|
||||
continue;
|
||||
};
|
||||
out.push(NoteTemplate {
|
||||
id: format!("user:{name}"),
|
||||
description: first_meaningful_line(&body),
|
||||
name,
|
||||
builtin: false,
|
||||
body,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 内置模板:跳过已被用户模板同名的
|
||||
for (name, description, body) in BUILTIN {
|
||||
if out.iter().any(|item| item.name == *name) {
|
||||
continue;
|
||||
}
|
||||
out.push(NoteTemplate {
|
||||
id: format!("builtin:{name}"),
|
||||
name: name.to_string(),
|
||||
description: description.to_string(),
|
||||
builtin: true,
|
||||
body: body.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// 取模板 ID 对应的正文;找不到返回 `None`(调用方回退到默认模板)。
|
||||
pub fn body_of(root: &Path, id: &str) -> Option<String> {
|
||||
list(root).into_iter().find(|t| t.id == id).map(|t| t.body)
|
||||
}
|
||||
|
||||
/// 把模板正文渲染成一篇新笔记的内容。
|
||||
///
|
||||
/// `parent_dir` 是笔记所在的库内目录(用于 `{{date}}` 之类不受影响,但保留参数
|
||||
/// 以便将来加入「所在目录」变量)。
|
||||
pub fn render(body: &str, title: &str, _parent_dir: &str) -> String {
|
||||
let now = chrono::Local::now();
|
||||
body.replace("{{title}}", title)
|
||||
.replace("{{date}}", &now.format("%Y-%m-%d").to_string())
|
||||
.replace("{{time}}", &now.format("%H:%M").to_string())
|
||||
.replace("{{datetime}}", &now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
|
||||
}
|
||||
|
||||
/// 日记的默认文件名(`2026-09-30`),供「今日日记」入口用。
|
||||
pub fn daily_note_name() -> String {
|
||||
chrono::Local::now().format("%Y-%m-%d").to_string()
|
||||
}
|
||||
|
||||
/// 默认模板的 ID(新建笔记时未选模板就用它)。
|
||||
pub fn default_template_id() -> String {
|
||||
"builtin:空白笔记".to_string()
|
||||
}
|
||||
|
||||
/// 正文里第一行有意义的文本(用户模板的说明用)。
|
||||
fn first_meaningful_line(body: &str) -> String {
|
||||
for line in body.lines() {
|
||||
let text = line.trim();
|
||||
if text.is_empty() || text == "---" || text.starts_with('#') || text.starts_with("title:") {
|
||||
continue;
|
||||
}
|
||||
return text.chars().take(40).collect();
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// 为「新建笔记」渲染正文:`template_id` 为空或找不到时用默认模板。
|
||||
pub fn render_for_new_note(root: &Path, template_id: &str, title: &str, dir_rel: &str) -> String {
|
||||
let id = if template_id.trim().is_empty() {
|
||||
default_template_id()
|
||||
} else {
|
||||
template_id.to_string()
|
||||
};
|
||||
match body_of(root, &id) {
|
||||
Some(body) => render(&body, title, dir_rel),
|
||||
None => {
|
||||
// 兜底:内置空白模板(即使模板目录被清空也能新建)
|
||||
let fallback = BUILTIN
|
||||
.first()
|
||||
.map(|(_, _, body)| *body)
|
||||
.unwrap_or("---\ntitle: {{title}}\n---\n\n# {{title}}\n\n");
|
||||
render(fallback, title, dir_rel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保库里的 `templates/` 目录存在(用户想自定义模板时不用自己新建目录)。
|
||||
pub fn ensure_dir(root: &Path) -> Result<(), String> {
|
||||
std::fs::create_dir_all(root.join("templates")).map_err(|e| format!("创建模板目录失败: {e}"))
|
||||
}
|
||||
|
||||
/// 把内置模板写进库内 `templates/`(供「导出内置模板」按钮用;已存在的不覆盖)。
|
||||
pub fn export_builtin(root: &Path) -> Result<Vec<String>, String> {
|
||||
ensure_dir(root)?;
|
||||
let dir = root.join("templates");
|
||||
let mut written = Vec::new();
|
||||
for (name, _, body) in BUILTIN {
|
||||
let path = dir.join(format!("{name}.md"));
|
||||
if path.exists() {
|
||||
continue;
|
||||
}
|
||||
std::fs::write(&path, body).map_err(|e| format!("写入模板 {name} 失败: {e}"))?;
|
||||
written.push(name.to_string());
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// 模板文件在库内的相对路径(前端「编辑模板」用;内置模板返回 `None`)。
|
||||
pub fn relative_path(id: &str) -> Option<String> {
|
||||
id.strip_prefix("user:")
|
||||
.map(|name| format!("templates/{name}.md"))
|
||||
}
|
||||
|
||||
/// 校验模板名(新建模板时用)。
|
||||
pub fn validate_name(name: &str) -> Result<String, String> {
|
||||
library::validate_name(name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_root(tag: &str) -> std::path::PathBuf {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("thing-notes-tpl-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_templates_are_available_without_files() {
|
||||
let root = temp_root("builtin");
|
||||
let templates = list(&root);
|
||||
assert!(templates.len() >= 4, "{templates:?}");
|
||||
assert!(templates.iter().all(|t| t.builtin));
|
||||
assert!(templates.iter().any(|t| t.name == "日记"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_template_overrides_builtin_with_same_name() {
|
||||
let root = temp_root("override");
|
||||
ensure_dir(&root).unwrap();
|
||||
std::fs::write(root.join("templates/空白笔记.md"), "用户自己的模板 {{title}}").unwrap();
|
||||
let templates = list(&root);
|
||||
let blank = templates.iter().find(|t| t.name == "空白笔记").unwrap();
|
||||
assert!(!blank.builtin, "同名时用户模板应覆盖内置");
|
||||
assert!(blank.body.contains("用户自己的模板"));
|
||||
assert_eq!(
|
||||
templates.iter().filter(|t| t.name == "空白笔记").count(),
|
||||
1,
|
||||
"不该出现两份同名模板"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_substitutes_variables() {
|
||||
let out = render("---\ntitle: {{title}}\ncreated: {{datetime}}\n---\n\n# {{title}} {{date}}\n", "周会", "");
|
||||
assert!(out.contains("title: 周会"));
|
||||
assert!(out.contains("# 周会 "));
|
||||
assert!(!out.contains("{{"), "所有占位符都应被替换: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_for_new_note_falls_back_to_blank() {
|
||||
let root = temp_root("fallback");
|
||||
let out = render_for_new_note(&root, "user:不存在", "标题", "");
|
||||
assert!(out.contains("标题"));
|
||||
assert!(!out.contains("{{"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_builtin_does_not_overwrite() {
|
||||
let root = temp_root("export");
|
||||
ensure_dir(&root).unwrap();
|
||||
std::fs::write(root.join("templates/日记.md"), "我的日记模板").unwrap();
|
||||
let written = export_builtin(&root).unwrap();
|
||||
assert!(!written.contains(&"日记".to_string()), "{written:?}");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join("templates/日记.md")).unwrap(),
|
||||
"我的日记模板"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_path_only_for_user_templates() {
|
||||
assert_eq!(
|
||||
relative_path("user:会议纪要"),
|
||||
Some("templates/会议纪要.md".to_string())
|
||||
);
|
||||
assert_eq!(relative_path("builtin:日记"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_note_name_is_date_shaped() {
|
||||
let name = daily_note_name();
|
||||
assert_eq!(name.len(), 10, "{name}");
|
||||
assert_eq!(name.matches('-').count(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
//! 笔记模块的数据模型。
|
||||
//!
|
||||
//! 持久化位置:`{app_data_dir}/editor/settings.json`(与 ai / translate / terminal 同一范式)。
|
||||
//! 容器级 `#[serde(default)]`:新增字段对旧配置文件向后兼容(缺字段取
|
||||
//! `Default::default()` 的对应值,而不是让整份设置反序列化失败)。
|
||||
//!
|
||||
//! 笔记正文**不在这里**:它以 `.md` 文件为准(见 `library.rs`),
|
||||
//! 本结构只保存「库根 + 编辑器偏好」这类模块级设置。
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// 结构版本号。字段增减时递增,由 [`EditorSettings::heal`] 推进。
|
||||
pub const EDITOR_SETTINGS_VERSION: u32 = 5;
|
||||
|
||||
/// 最近文件 / 文件夹各自的保留上限(超出淘汰最旧)。
|
||||
pub const RECENT_LIMIT: usize = 20;
|
||||
|
||||
/// 同步方向。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SyncDirection {
|
||||
/// 双向同步(默认)
|
||||
Bidirectional,
|
||||
/// 只上传(本地覆盖远端)—— 等价于「推送到远端备份」
|
||||
Upload,
|
||||
/// 只下载(远端覆盖本地)—— 换机器恢复时用
|
||||
Download,
|
||||
}
|
||||
|
||||
impl Default for SyncDirection {
|
||||
fn default() -> Self {
|
||||
Self::Bidirectional
|
||||
}
|
||||
}
|
||||
|
||||
/// 两侧都改动时的冲突策略。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ConflictPolicy {
|
||||
/// 保留较新的(mtime 大的一方;无法判定时保守选本地)
|
||||
Newer,
|
||||
/// 本地覆盖远端
|
||||
LocalWins,
|
||||
/// 远端覆盖本地
|
||||
RemoteWins,
|
||||
/// 两侧都留(本地改名成 `*.sync-conflict-<时间>.md`,再把远端那份下载到原路径)
|
||||
KeepBoth,
|
||||
}
|
||||
|
||||
impl Default for ConflictPolicy {
|
||||
fn default() -> Self {
|
||||
// 默认「都留」:冲突时最保守的选择,绝不丢数据(规划 §7 R6)
|
||||
Self::KeepBoth
|
||||
}
|
||||
}
|
||||
|
||||
/// WebDAV 设置(密码**不在这里** —— 它进 keyring,见 `webdav/mod.rs`)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct WebdavSettings {
|
||||
/// 服务地址(`https://dav.jianguoyun.com/dav`)
|
||||
pub url: String,
|
||||
pub username: String,
|
||||
/// 远端根目录(相对 `url`;空串 = 直接用 `url` 指向的目录)
|
||||
pub remote_root: String,
|
||||
pub direction: SyncDirection,
|
||||
pub conflict: ConflictPolicy,
|
||||
/// 应用启动后自动同步一次
|
||||
pub auto_sync_on_launch: bool,
|
||||
/// 保留的 zip 快照份数(上传备份时轮转)
|
||||
pub backup_keep: u32,
|
||||
}
|
||||
|
||||
impl Default for WebdavSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
url: String::new(),
|
||||
username: String::new(),
|
||||
remote_root: "thing-notes".to_string(),
|
||||
direction: SyncDirection::Bidirectional,
|
||||
conflict: ConflictPolicy::KeepBoth,
|
||||
auto_sync_on_launch: false,
|
||||
backup_keep: 7,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WebdavSettings {
|
||||
/// 是否已经填了连接信息(决定设置页显示「未配置」还是「已配置」)。
|
||||
pub fn is_configured(&self) -> bool {
|
||||
!self.url.trim().is_empty() && !self.username.trim().is_empty()
|
||||
}
|
||||
|
||||
/// 填写是否足以发起请求。
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.url.trim().is_empty() {
|
||||
return Err("请先填写 WebDAV 地址".to_string());
|
||||
}
|
||||
if !self.url.starts_with("http://") && !self.url.starts_with("https://") {
|
||||
return Err("WebDAV 地址必须以 http:// 或 https:// 开头".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 同步进度(事件 `editor-sync-progress` 的负载)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncProgress {
|
||||
/// 已完成条数
|
||||
pub done: u32,
|
||||
/// 总条数
|
||||
pub total: u32,
|
||||
/// 当前处理的相对路径
|
||||
pub current: String,
|
||||
/// 动作类型(`upload` / `download` / …,见 `webdav::sync::SyncActionKind::as_str`)
|
||||
pub kind: String,
|
||||
/// 附加说明(如「正在打包快照」)
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// 一份远端备份快照。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BackupSnapshot {
|
||||
/// 远端文件名(`thing-notes-20260930-1530.zip`)
|
||||
pub name: String,
|
||||
pub size: u64,
|
||||
pub modified: u64,
|
||||
}
|
||||
|
||||
/// 备份结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BackupReport {
|
||||
/// 上传的快照名
|
||||
pub name: String,
|
||||
/// 快照字节数
|
||||
pub bytes: u64,
|
||||
/// 打包的笔记数
|
||||
pub files: u32,
|
||||
/// 因超出保留份数而被删除的旧快照
|
||||
pub pruned: Vec<String>,
|
||||
}
|
||||
|
||||
/// 导入结果。
|
||||
#[derive(Debug, Clone, Default, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ImportReport {
|
||||
/// 导入的笔记数
|
||||
pub imported: u32,
|
||||
/// 因重名而被改名的数量
|
||||
pub renamed: u32,
|
||||
/// 跳过的非 Markdown 文件数
|
||||
pub skipped: u32,
|
||||
/// 失败明细(最多若干条)
|
||||
pub failures: Vec<String>,
|
||||
}
|
||||
|
||||
/// 最近打开的一个文件 / 文件夹。
|
||||
///
|
||||
/// `exists` 在每次读取设置时刷新(不依赖前端探测),供 UI 灰显失效项。
|
||||
/// 与笔记库**解耦**:库可以换 / 删,历史不该跟着丢(规划 §3.5)。
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct RecentEntry {
|
||||
/// 绝对路径(文件或文件夹)
|
||||
pub path: String,
|
||||
/// 显示名(文件名 / 文件夹名)
|
||||
pub name: String,
|
||||
/// 最近打开时间(Unix 毫秒)
|
||||
pub opened_at: u64,
|
||||
/// 该路径当前是否仍存在(读取设置时刷新)
|
||||
pub exists: bool,
|
||||
}
|
||||
|
||||
/// 笔记 / 编辑器设置根结构。
|
||||
///
|
||||
/// 字段取值必须与前端 `src/modules/notes/editor/themes.ts` 的 key 保持一致,
|
||||
/// 否则用户选了主题却回落默认(静默失效,终端模块踩过这个坑)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct EditorSettings {
|
||||
/// 结构版本号
|
||||
pub version: u32,
|
||||
/// 自定义库根(`None` = 用默认 `{app_data_dir}/editor/library`)
|
||||
pub library_root: Option<String>,
|
||||
/// 编辑器配色方案 key(`"system"` / `"vscode-dark"` / `"vscode-light"` / …)
|
||||
pub editor_theme: String,
|
||||
/// 编辑器**窗口**是否跟随主应用主题(开:整体跟随应用;关:由 `editor_theme` 决定,
|
||||
/// 窗口外壳与编辑区保持同一深浅)
|
||||
pub follow_app_theme: bool,
|
||||
/// 编辑器字体族(空串 = 用内置等宽字体栈)
|
||||
pub font_family: String,
|
||||
/// 字号(px)
|
||||
pub font_size: u32,
|
||||
/// 行高倍数
|
||||
pub line_height: f64,
|
||||
/// 是否启用字体连字(ligatures)
|
||||
pub ligatures: bool,
|
||||
/// Tab 宽度(空格数)
|
||||
pub tab_size: u32,
|
||||
/// 是否启用「所见即所得」Live Preview(关闭则纯 Markdown 源码 + 高亮)
|
||||
pub live_preview: bool,
|
||||
/// 自动保存防抖(毫秒;0 = 关闭自动保存,仅手动 Ctrl+S)
|
||||
pub autosave_ms: u32,
|
||||
/// 默认视图:"wysiwyg" | "source"
|
||||
pub default_view: String,
|
||||
/// 是否显示行号
|
||||
pub show_line_numbers: bool,
|
||||
/// 是否显示大纲侧栏(P1)
|
||||
pub show_outline: bool,
|
||||
/// 是否启用代码自动补全 / 括号闭合(P1;大文件会强制关闭)
|
||||
pub autocomplete: bool,
|
||||
/// 单文件大小上限(MB)。超过则编辑器降级为「纯高亮 + 行号」,
|
||||
/// 关闭 Live Preview / 折叠 / 补全等重扩展(见 §7 R2)。
|
||||
pub max_file_size_mb: u32,
|
||||
/// 是否识别 `[[wikilink]]`(P1,仅影响高亮与后续反链)
|
||||
pub wikilink: bool,
|
||||
/// 多窗口是否复用同一文档的窗口(P1;关闭则每次新建窗口)
|
||||
pub reuse_window: bool,
|
||||
/// WebDAV 备份 / 同步设置(P2)
|
||||
pub webdav: WebdavSettings,
|
||||
/// 新建笔记时是否弹出模板选择(P2)
|
||||
pub show_template_picker: bool,
|
||||
/// 导出 HTML 时是否内联代码高亮样式(P2;关闭则用打印友好的纯黑白)
|
||||
pub export_highlight: bool,
|
||||
/// 全局快捷键:新建笔记(空串 = 不注册)。
|
||||
///
|
||||
/// 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译同一套),
|
||||
/// 触发时只发 `editor-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
|
||||
pub new_note_shortcut: String,
|
||||
/// 全局快捷键:打开编辑器窗口(空串 = 不注册)
|
||||
pub open_editor_shortcut: String,
|
||||
/// 最近打开的文件(与笔记库解耦;上限 [`RECENT_LIMIT`])
|
||||
pub recent_files: Vec<RecentEntry>,
|
||||
/// 最近打开的文件夹(与笔记库解耦;上限 [`RECENT_LIMIT`])
|
||||
pub recent_folders: Vec<RecentEntry>,
|
||||
}
|
||||
|
||||
impl Default for EditorSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: EDITOR_SETTINGS_VERSION,
|
||||
library_root: None,
|
||||
editor_theme: "system".to_string(),
|
||||
follow_app_theme: false,
|
||||
font_family: String::new(),
|
||||
font_size: 14,
|
||||
line_height: 1.7,
|
||||
ligatures: false,
|
||||
tab_size: 2,
|
||||
live_preview: true,
|
||||
// 自动保存默认关闭:800ms 一保存会让「保存按钮 / 标签 * 号 / 侧栏」跟着
|
||||
// 闪烁,干扰正常编辑。需要的人可在设置里显式开启(见 heal 的 v4 迁移)。
|
||||
autosave_ms: 0,
|
||||
default_view: "wysiwyg".to_string(),
|
||||
show_line_numbers: true,
|
||||
show_outline: true,
|
||||
autocomplete: true,
|
||||
max_file_size_mb: 5,
|
||||
wikilink: true,
|
||||
reuse_window: true,
|
||||
webdav: WebdavSettings::default(),
|
||||
show_template_picker: true,
|
||||
export_highlight: true,
|
||||
new_note_shortcut: String::new(),
|
||||
open_editor_shortcut: "Alt+E".to_string(),
|
||||
recent_files: Vec::new(),
|
||||
recent_folders: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EditorSettings {
|
||||
/// 自愈:把越界/非法取值夹回合法区间,推进版本号。
|
||||
/// 返回是否发生了变更(由调用方决定是否落盘)。
|
||||
pub fn heal(&mut self) -> bool {
|
||||
let mut changed = false;
|
||||
|
||||
let clamp_u32 = |value: &mut u32, min: u32, max: u32, changed: &mut bool| {
|
||||
let next = (*value).clamp(min, max);
|
||||
if next != *value {
|
||||
*value = next;
|
||||
*changed = true;
|
||||
}
|
||||
};
|
||||
clamp_u32(&mut self.font_size, 10, 32, &mut changed);
|
||||
clamp_u32(&mut self.tab_size, 1, 8, &mut changed);
|
||||
clamp_u32(&mut self.autosave_ms, 0, 10_000, &mut changed);
|
||||
// 上限 100MB:再大就不该用编辑器打开(也不该走 IPC 把全文搬进 WebView)
|
||||
clamp_u32(&mut self.max_file_size_mb, 1, 100, &mut changed);
|
||||
// 快照保留份数:至少 1 份(0 份等于「备份完就删」,显然是误配)
|
||||
clamp_u32(&mut self.webdav.backup_keep, 1, 100, &mut changed);
|
||||
|
||||
if !(1.0..=3.0).contains(&self.line_height) {
|
||||
self.line_height = 1.7;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if self.editor_theme.trim().is_empty() {
|
||||
self.editor_theme = "system".to_string();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if self.default_view != "wysiwyg" && self.default_view != "source" {
|
||||
self.default_view = "wysiwyg".to_string();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if let Some(root) = &self.library_root {
|
||||
if root.trim().is_empty() {
|
||||
self.library_root = None;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// v3:引入「打开编辑器」默认快捷键 Alt+E(用户已显式设过则不覆盖)
|
||||
if self.version < 3 && self.open_editor_shortcut.trim().is_empty() {
|
||||
self.open_editor_shortcut = "Alt+E".to_string();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// v4:自动保存默认从 800ms 改为关闭 —— 仍是 800 说明用户从未改过这个值
|
||||
//(旧默认),此时关闭它;用户显式设过的其他值一律保留。
|
||||
if self.version < 4 && self.autosave_ms == 800 {
|
||||
self.autosave_ms = 0;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// v5:`followAppTheme` 的语义从「配色方案取色基准」改为「编辑器窗口是否跟随主应用
|
||||
// 主题」,默认亦由「跟随」改为「不跟随」。仍是 true 说明用户从未改过这个值(旧默认),
|
||||
// 此时改为不跟随;用户显式关过(false)的保持 false,不做任何覆盖。
|
||||
if self.version < 5 && self.follow_app_theme {
|
||||
self.follow_app_theme = false;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if self.version < EDITOR_SETTINGS_VERSION {
|
||||
self.version = EDITOR_SETTINGS_VERSION;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// 最近记录上限:超出淘汰最旧(列表约定为新在前)
|
||||
if self.recent_files.len() > RECENT_LIMIT {
|
||||
self.recent_files.truncate(RECENT_LIMIT);
|
||||
changed = true;
|
||||
}
|
||||
if self.recent_folders.len() > RECENT_LIMIT {
|
||||
self.recent_folders.truncate(RECENT_LIMIT);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
/// 刷新最近记录的「是否存在」标记(读取设置时调用,供 UI 灰显失效项)。
|
||||
pub fn refresh_recent_exists(&mut self) {
|
||||
for entry in self
|
||||
.recent_files
|
||||
.iter_mut()
|
||||
.chain(self.recent_folders.iter_mut())
|
||||
{
|
||||
entry.exists = !entry.path.trim().is_empty() && std::path::Path::new(&entry.path).exists();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 库内一个条目(文件或目录)的扁平描述。
|
||||
///
|
||||
/// **刻意用扁平列表而不是树**:递归类型在 specta 的 `Type` 派生下容易生成
|
||||
/// 无穷展开的 TS 类型;扁平结构由前端组装成树,更稳也更简单。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LibraryEntry {
|
||||
/// 显示名(不含目录前缀)
|
||||
pub name: String,
|
||||
/// 相对库根的路径,统一用 `/` 分隔(如 `2026/09/meeting.md`)
|
||||
pub rel_path: String,
|
||||
/// 父目录的相对路径(库根为 `""`)
|
||||
pub parent_rel: String,
|
||||
/// 是否目录
|
||||
pub is_dir: bool,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 文件字节数(目录为 0)
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
/// 库状态概览(主模块页横幅与设置页用)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LibraryInfo {
|
||||
/// 当前生效的库根绝对路径
|
||||
pub root: String,
|
||||
/// 是否为用户自定义库根(false = 默认 `{app_data_dir}/editor/library`)
|
||||
pub is_custom: bool,
|
||||
/// `.md` 笔记数量(不含目录)
|
||||
pub note_count: u32,
|
||||
}
|
||||
|
||||
/// 单篇笔记的读取/写入结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteDoc {
|
||||
/// 相对库根的路径(`/` 分隔)
|
||||
pub rel_path: String,
|
||||
/// 显示名(含扩展名)
|
||||
pub name: String,
|
||||
/// 完整文件内容(含 front-matter)
|
||||
pub content: String,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
}
|
||||
Loaded 100 of 499 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user