This commit is contained in:
zhongluofeng committed 2026-10-10 14:29:48 +08:00
1 parent ad987111a3
commit c9e61f38c5
89 files changed
+11775 -3155

No files matched your search

+14 -13
View File
@@ -1694,7 +1694,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users 0.5.2",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -1967,7 +1967,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -2961,7 +2961,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.57.0",
"windows-core 0.61.2",
]
[[package]]
@@ -4127,7 +4127,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.20",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -5378,7 +5378,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -5983,7 +5983,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -6040,7 +6040,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -6621,7 +6621,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -7644,7 +7644,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -7666,6 +7666,7 @@ dependencies = [
"base64 0.22.1",
"bytes",
"cbc 0.1.2",
"chardetng",
"chrono",
"cpal",
"dashmap",
@@ -8114,7 +8115,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.20",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -8167,7 +8168,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -8565,7 +8566,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.48.0",
"windows-sys 0.60.2",
]
[[package]]
@@ -8586,7 +8587,7 @@ dependencies = [
"objc2-foundation",
"objc2-quartz-core",
"raw-window-handle",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
"windows-version",
]
+4
View File
@@ -30,6 +30,10 @@ async-trait = "0.1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
regex = "1"
# 编码统计探测(Firefox 的探测器):判断「非 UTF-8 文件到底是 Shift_JIS 还是
# GB18030」这类问题。GB18030 几乎能解码任意字节序列,「试解是否成功」不可靠,
# 会把日文 Shift_JIS 误判成中文 GB18030。
chardetng = "1.0"
serde_yaml = "0.9"
specta = { version = "=2.0.0-rc.25", features = ["derive", "function", "serde_json"] }
specta-typescript = "0.0.12"
+19
View File
@@ -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"
]
}
@@ -1,8 +1,8 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "notes-window",
"description": "Capability for the notes/editor windows (multi-open, label = notes-window-<n>). Needs the CM6 editor's window controls, events (settings/library sync) and opener.",
"windows": ["notes-window-*"],
"identifier": "editor-window",
"description": "Capability for the editor windows (multi-open, label = editor-window-<n>). Needs the CM6 editor's window controls, events (settings/library sync) and opener.",
"windows": ["editor-window-*"],
"permissions": [
"core:default",
"core:window:allow-show",
+1 -1
View File
@@ -61,7 +61,7 @@ impl SuppressState {
// saturating:异常路径下的多余 end 不应让计数下溢,否则会永久屏蔽
let _ = self
.burst
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| {
.try_update(Ordering::SeqCst, Ordering::SeqCst, |v| {
Some(v.saturating_sub(1))
});
}
+25 -14
View File
@@ -26,9 +26,13 @@ pub mod windows {
/// 因此**不登记 capability**:远端页面不应获得任何 Tauri 权限)。
#[allow(dead_code)]
pub const DSH_WEB: &str = "dsh-web";
/// 笔记 / 编辑器独立窗口前缀,实际 label = `${NOTES_WINDOW}-<n>`(可多开)
/// 笔记 / 编辑器独立窗口前缀,实际 label = `${EDITOR_WINDOW}-<n>`(可多开)
#[allow(dead_code)]
pub const NOTES_WINDOW: &str = "notes-window";
pub const EDITOR_WINDOW: &str = "editor-window";
/// dsh「启动进度」独立窗口(单例,由前端创建)。
/// 服务就绪后由前端打开真正的 [`DSH_WEB`] 窗口并关闭它。
#[allow(dead_code)]
pub const DSH_WINDOW: &str = "dsh-window";
}
/// Tauri 事件名(与前端 constants::EVENTS 对应)
@@ -37,8 +41,12 @@ pub mod events {
pub const TRAY_MENU_SHOW: &str = "tray-menu-show";
pub const TRAY_MENU_STATE_UPDATED: &str = "tray-menu-state-updated";
pub const TRAY_TOGGLE_OSD: &str = "tray:toggle-osd";
pub const TRAY_NEW_DOWNLOAD: &str = "tray:new-download";
pub const TRAY_OPEN_SETTINGS: &str = "tray:open-settings";
/// 托盘菜单「终端」:打开新建终端选择窗口(窗口由前端创建)
pub const TRAY_OPEN_TERMINAL: &str = "tray:open-terminal";
/// 托盘菜单「dsh」:打开 dsh 独立窗口(未启动时先显示启动进度)
pub const TRAY_OPEN_DSH: &str = "tray:open-dsh";
/// 托盘菜单「编辑器」:打开编辑器独立窗口(窗口由前端创建)
pub const TRAY_OPEN_EDITOR: &str = "tray:open-editor";
// 剪贴板
pub const CLIPBOARD_CHANGED: &str = "clipboard-changed";
pub const CLIPBOARD_POPUP_SHOW: &str = "clipboard-popup-show";
@@ -138,23 +146,26 @@ pub mod events {
/// 窗口由前端创建(它持有带令牌的地址与 label 判重),Rust 侧只负责注册快捷键。
pub const DSH_OPEN_WINDOW: &str = "dsh-open-window";
// 笔记模块:设置已保存(无负载)。各窗口据以重读设置,实现跨窗口同步(同 terminal-settings)
pub const NOTES_SETTINGS: &str = "notes-settings";
pub const EDITOR_SETTINGS: &str = "editor-settings";
// 笔记模块:库内容已变更(新建/保存/重命名/删除/切换库根,无负载)
pub const NOTES_LIBRARY_CHANGED: &str = "notes-library-changed";
// 笔记模块:库内某个文件在**应用外**被改动了(负载见 notes::index_service::NoteFileEvent)。
// 与 NOTES_LIBRARY_CHANGED 的区别:那个是「本应用改了,重读即可」,这个是
pub const EDITOR_LIBRARY_CHANGED: &str = "editor-library-changed";
// 笔记模块:库内某个文件在**应用外**被改动了(负载见 editor::index_service::NoteFileEvent)。
// 与 EDITOR_LIBRARY_CHANGED 的区别:那个是「本应用改了,重读即可」,这个是
// 「别人改了,当前打开的文档可能已经过时」——前端据此提示而不是静默覆盖。
pub const NOTES_FILE_CHANGED: &str = "notes-file-changed";
// 笔记模块:WebDAV 同步进度(负载见 notes::types::SyncProgress)。
pub const EDITOR_FILE_CHANGED: &str = "editor-file-changed";
// 笔记模块:WebDAV 同步进度(负载见 editor::types::SyncProgress)。
// 进度事件是高频的,前端按「每 X% 或每 N 条」节流显示即可;Rust 侧逐条发,
// 因为节流放在发送端会让「最后一条」容易被丢掉(进度条停在 98%)。
pub const NOTES_SYNC_PROGRESS: &str = "notes-sync-progress";
pub const EDITOR_SYNC_PROGRESS: &str = "editor-sync-progress";
// 笔记模块:全局快捷键按下「新建笔记」(无负载,窗口由前端创建)
pub const NOTES_NEW_NOTE: &str = "notes-new-note";
pub const EDITOR_NEW_NOTE: &str = "editor-new-note";
// 笔记模块:全局快捷键按下「打开编辑器窗口」(无负载)
pub const NOTES_OPEN_EDITOR: &str = "notes-open-editor";
pub const EDITOR_OPEN_EDITOR: &str = "editor-open-editor";
// 笔记模块:需要打开一个磁盘文件(负载 `{ path }`)。
// 来源有三:① 双击关联的 .md(单实例回调把参数转交过来);② 启动命令行参数;
// ③ 系统「打开方式」。三种都只发事件,窗口由前端创建。
pub const NOTES_OPEN_FILE: &str = "notes-open-file";
pub const EDITOR_OPEN_FILE: &str = "editor-open-file";
// 笔记模块:需要打开一个**文件夹**(负载 `{ path }`)。
// 来源:资源管理器右键「用 Thing 编辑器打开」(目录 / 目录背景)。
pub const EDITOR_OPEN_FOLDER: &str = "editor-open-folder";
}
+8 -1
View File
@@ -210,12 +210,19 @@ impl DshManager {
.clone()
.ok_or_else(|| "未找到 npm(Node 分发中缺少 npm-cli.js)".to_string())?;
// 未指定版本时必须显式写成 `@latest`,**不能**只给裸包名:
// npm 对「裸包名且该包已存在于 prefix 下的 package.json」的语义是
// 「安装满足现有 range 的最新版」,而首次安装时 npm 自己写下的
// `@deepseek-ai/dsh: ^0.1.7-rc.2` 一旦遇到 0.2.x 就永远不满足,
// 于是 `npm install @deepseek-ai/dsh` 只会回一句 "up to date",
// 版本原地不动(这正是「更新到最新」点了没反应的根因)。
// 显式 tag/版本会覆盖 package.json 里的旧 range,npm 才会真正升级。
let spec = version
.as_deref()
.map(|v| v.trim())
.filter(|v| !v.is_empty())
.map(|v| format!("{DSH_PACKAGE}@{v}"))
.unwrap_or_else(|| DSH_PACKAGE.to_string());
.unwrap_or_else(|| format!("{DSH_PACKAGE}@latest"));
let install_dir = self.install_root();
// npm 的 prefix 目录不存在时由 npm 自己创建;这里先建一次,避免
+231
View File
@@ -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(&note);
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(&note);
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(&note);
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);
}
}
@@ -11,7 +11,7 @@
//! # 打包内容
//!
//! 库内全部 `.md` 与 `assets/` 下的附件,外加一份 `thing-notes-manifest.json`
//! (记录快照时间、文件数、格式版本)。**不打包 `.notes/`**:里面是索引与同步基线,
//! (记录快照时间、文件数、格式版本)。**不打包 `.editor/`**:里面是索引与同步基线,
//! 属于本机私有数据,跟着快照跑到另一台机器上只会误导那边的基线判断。
//!
//! # 轮转
@@ -23,8 +23,8 @@
use std::io::Write;
use std::path::{Path, PathBuf};
use super::webdav::client::WebdavClient;
use crate::notes::library;
use crate::notes::types::{BackupReport, BackupSnapshot, WebdavSettings};
use crate::editor::library;
use crate::editor::types::{BackupReport, BackupSnapshot, WebdavSettings};
/// 远端存放快照的目录(相对远端根)。
pub const BACKUP_DIR: &str = "backups";
@@ -63,14 +63,14 @@ pub fn build_snapshot(root: &Path) -> Result<(Vec<u8>, u32), String> {
if rel.is_empty() {
continue;
}
// `.notes/` 是本机私有数据(索引 + 同步基线),不进快照
// `.editor/` 是本机私有数据(索引 + 同步基线),不进快照
if rel.split('/').any(|part| part.starts_with('.')) {
continue;
}
let bytes = match std::fs::read(entry.path()) {
Ok(bytes) => bytes,
Err(e) => {
crate::logger::log_warn("notes", &format!("快照跳过 {rel}(读取失败: {e})"));
crate::logger::log_warn("editor", &format!("快照跳过 {rel}(读取失败: {e})"));
continue;
}
};
@@ -138,7 +138,7 @@ pub fn prune_snapshots(client: &WebdavClient, keep: u32) -> Result<Vec<String>,
let mut pruned = Vec::new();
for snapshot in snapshots.into_iter().take(outdated) {
if let Err(e) = client.delete(&format!("{BACKUP_DIR}/{}", snapshot.name)) {
crate::logger::log_warn("notes", &format!("删除旧快照 {} 失败: {e}", snapshot.name));
crate::logger::log_warn("editor", &format!("删除旧快照 {} 失败: {e}", snapshot.name));
continue;
}
pruned.push(snapshot.name);
@@ -201,7 +201,7 @@ pub fn restore_snapshot(
.map_err(|e| format!("读取快照条目失败: {e}"))?;
let Some(entry_path) = file.enclosed_name().map(|p| p.to_path_buf()) else {
// `enclosed_name` 会拒绝 `..` 与绝对路径 —— 恶意快照不能写到库外
crate::logger::log_warn("notes", "快照里有越界路径,已跳过");
crate::logger::log_warn("editor", "快照里有越界路径,已跳过");
continue;
};
let rel = entry_path.to_string_lossy().replace('\\', "/");
@@ -246,17 +246,17 @@ pub fn sync_then_backup(
if report.failed == 0 {
state.last_sync = chrono::Local::now().timestamp_millis().max(0) as u64;
if let Err(e) = state.save(root) {
crate::logger::log_warn("notes", &format!("保存同步基线失败: {e}"));
crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}"));
}
} else {
crate::logger::log_warn(
"notes",
"editor",
&format!("本轮有 {} 条失败,不推进同步基线", report.failed),
);
// 仍然保存「成功的那些」:SyncState 是按条更新的,未处理的条目保持旧基线,
// 于是下一轮会把它们重新算作差异并重试
if let Err(e) = state.save(root) {
crate::logger::log_warn("notes", &format!("保存同步基线失败: {e}"));
crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}"));
}
}
@@ -301,14 +301,14 @@ mod tests {
}
#[test]
fn snapshot_contains_notes_and_assets_but_not_private_dir() {
fn snapshot_excludes_private_dir() {
let root = temp_root("build");
std::fs::write(root.join("a.md"), "# A").unwrap();
std::fs::create_dir_all(root.join("sub")).unwrap();
std::fs::write(root.join("sub/b.md"), "# B").unwrap();
std::fs::write(root.join("assets/pic.png"), [1u8, 2, 3]).unwrap();
std::fs::create_dir_all(root.join(".notes")).unwrap();
std::fs::write(root.join(".notes/notes.db"), "索引不该进快照").unwrap();
std::fs::create_dir_all(root.join(".editor")).unwrap();
std::fs::write(root.join(".editor/editor.db"), "索引不该进快照").unwrap();
let (bytes, files) = build_snapshot(&root).unwrap();
assert_eq!(files, 3, "两篇笔记 + 一个附件");
@@ -323,7 +323,7 @@ mod tests {
assert!(names.contains(&"assets/pic.png".to_string()), "{names:?}");
assert!(names.contains(&MANIFEST_NAME.to_string()), "{names:?}");
assert!(
!names.iter().any(|n| n.starts_with(".notes")),
!names.iter().any(|n| n.starts_with(".editor")),
"私有目录不该进快照: {names:?}"
);
@@ -33,35 +33,35 @@ use super::index_service::{self, IndexService, NoteIndexReport};
use super::library;
use super::templates::{self, NoteTemplate};
use super::types::{
BackupReport, BackupSnapshot, ImportReport, LibraryEntry, LibraryInfo, NoteDoc, NoteSettings,
BackupReport, BackupSnapshot, ImportReport, LibraryEntry, LibraryInfo, NoteDoc, EditorSettings,
SyncProgress,
};
use super::webdav::{self, WebdavTestResult};
use super::NotesManager;
use super::EditorManager;
use crate::constants::events;
/// 通知各窗口「库内容已变更」(新建/保存/重命名/删除/切换库根后)。
fn emit_library_changed(app: &AppHandle) {
if let Err(e) = app.emit(events::NOTES_LIBRARY_CHANGED, ()) {
crate::logger::log_warn("notes", &format!("发出库变更事件失败: {e}"));
if let Err(e) = app.emit(events::EDITOR_LIBRARY_CHANGED, ()) {
crate::logger::log_warn("editor", &format!("发出库变更事件失败: {e}"));
}
}
/// 通知各窗口「设置已变更」(跨窗口同步,范式同 terminal-settings)。
fn emit_settings_changed(app: &AppHandle) {
if let Err(e) = app.emit(events::NOTES_SETTINGS, ()) {
crate::logger::log_warn("notes", &format!("发出设置变更事件失败: {e}"));
if let Err(e) = app.emit(events::EDITOR_SETTINGS, ()) {
crate::logger::log_warn("editor", &format!("发出设置变更事件失败: {e}"));
}
}
/// 当前库根(按设置解析),并确保目录存在。
fn current_root(state: &NotesManager) -> PathBuf {
fn current_root(state: &EditorManager) -> PathBuf {
let settings = state.load_settings();
library::resolve_library_root(state.module_dir(), &settings)
}
/// 取索引服务并把它的库根对齐到当前设置。
fn indexed<'a>(app: &AppHandle, state: &NotesManager) -> Result<&'a IndexService, String> {
fn indexed<'a>(app: &AppHandle, state: &EditorManager) -> Result<&'a IndexService, String> {
let root = current_root(state);
let service = index_service::service(app);
service.retarget(root)?;
@@ -69,7 +69,7 @@ fn indexed<'a>(app: &AppHandle, state: &NotesManager) -> Result<&'a IndexService
}
/// 组装库状态概览。
fn library_info(state: &NotesManager) -> Result<LibraryInfo, String> {
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)?;
@@ -85,21 +85,48 @@ fn library_info(state: &NotesManager) -> Result<LibraryInfo, String> {
})
}
/// 标记「本应用刚写过」,随后把库同步进索引。
/// 标记「本应用刚**批量**写过」,随后把库同步进索引。
///
/// 用于导入 / WebDAV 同步 / 恢复 / 模板导出这类**无法逐路径枚举**的操作:写完之后
/// 在抑制窗口内的一切文件事件都当作自己写的。
///
/// 顺序重要:先标记(抑制窗口从写入那一刻算起),再同步。这里走全库增量同步而不是
/// 「只索引这一篇」的快路径:单文件快路径要额外拼一份 wikilink 的 `stems` 映射,
/// 而不完整的映射会让 `[[某笔记]]` 解析到错误位置;全量同步靠 (mtime,size) 跳过
/// 未变文件,万篇规模也是毫秒级,用一点开销换「索引永远自洽」。
fn mark_written_then_index(app: &AppHandle, state: &NotesManager) {
fn mark_written_then_index(app: &AppHandle, state: &EditorManager) {
match indexed(app, state) {
Ok(service) => {
service.mark_write();
service.mark_write_all();
if let Err(e) = service.sync() {
crate::logger::log_warn("notes", &format!("保存后同步索引失败: {e}"));
crate::logger::log_warn("editor", &format!("保存后同步索引失败: {e}"));
}
}
Err(e) => crate::logger::log_warn("notes", &format!("索引服务不可用: {e}")),
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
}
}
/// 写入前登记「本应用即将写这一篇笔记」(按库内相对路径)。
///
/// **必须在 `library::write_note` 之前调用**:notify 的 Modify 事件可能与写入几乎
/// 同时到达索引 worker,晚于写盘再登记就会漏过 —— 前端便会把自家的保存当成
/// 「外部修改」,进而重载文档、把光标弹回第一行。
fn mark_pending_note_write(app: &AppHandle, state: &EditorManager, rel_path: &str) {
match indexed(app, state) {
Ok(service) => service.mark_write_path(rel_path),
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
}
}
/// 把库同步进索引(不登记自我写入 —— 调用方已在写入前按路径登记过)。
fn sync_index_after_write(app: &AppHandle, state: &EditorManager) {
match indexed(app, state) {
Ok(service) => {
if let Err(e) = service.sync() {
crate::logger::log_warn("editor", &format!("保存后同步索引失败: {e}"));
}
}
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
}
}
@@ -108,18 +135,36 @@ fn mark_written_then_index(app: &AppHandle, state: &NotesManager) {
/// 读取笔记模块设置。
#[tauri::command]
#[specta::specta]
pub fn notes_get_settings(state: State<'_, NotesManager>) -> Result<NoteSettings, String> {
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 notes_save_settings(
pub fn editor_save_settings(
app: AppHandle,
state: State<'_, NotesManager>,
settings: NoteSettings,
) -> Result<NoteSettings, String> {
state: State<'_, EditorManager>,
settings: EditorSettings,
) -> Result<EditorSettings, String> {
let mut next = settings;
next.heal();
state.save_settings(&next)?;
@@ -133,16 +178,16 @@ pub fn notes_save_settings(
/// 当前库状态概览(库根 / 是否自定义 / 笔记数)。
#[tauri::command]
#[specta::specta]
pub fn notes_library_info(state: State<'_, NotesManager>) -> Result<LibraryInfo, String> {
pub fn editor_library_info(state: State<'_, EditorManager>) -> Result<LibraryInfo, String> {
library_info(&state)
}
/// 设置库根(`None` 或空串 = 恢复默认库根)。
#[tauri::command]
#[specta::specta]
pub fn notes_set_library_root(
pub fn editor_set_library_root(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
root: Option<String>,
) -> Result<LibraryInfo, String> {
let cleaned = root.and_then(|r| {
@@ -177,7 +222,7 @@ pub fn notes_set_library_root(
/// 扫描库,返回扁平条目列表(前端组树)。
#[tauri::command]
#[specta::specta]
pub fn notes_scan_library(state: State<'_, NotesManager>) -> Result<Vec<LibraryEntry>, String> {
pub fn editor_scan_library(state: State<'_, EditorManager>) -> Result<Vec<LibraryEntry>, String> {
let root = current_root(&state);
library::ensure_library(&root)?;
library::scan(&root)
@@ -186,7 +231,7 @@ pub fn notes_scan_library(state: State<'_, NotesManager>) -> Result<Vec<LibraryE
/// 读取一篇笔记。
#[tauri::command]
#[specta::specta]
pub fn notes_read_note(state: State<'_, NotesManager>, rel_path: String) -> Result<NoteDoc, String> {
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)
}
@@ -194,15 +239,17 @@ pub fn notes_read_note(state: State<'_, NotesManager>, rel_path: String) -> Resu
/// 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。
#[tauri::command]
#[specta::specta]
pub fn notes_save_note(
pub fn editor_save_note(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
rel_path: String,
content: String,
) -> Result<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)?;
mark_written_then_index(&app, &state);
sync_index_after_write(&app, &state);
emit_library_changed(&app);
Ok(doc)
}
@@ -213,9 +260,9 @@ pub fn notes_save_note(
/// 模板文件被删掉不该让「新建笔记」这个核心动作失败)。
#[tauri::command]
#[specta::specta]
pub fn notes_create_note(
pub fn editor_create_note(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
dir_rel: String,
name: String,
template_id: Option<String>,
@@ -236,7 +283,7 @@ pub fn notes_create_note(
/// 打开(或创建)今天的日记:`日记/YYYY-MM-DD.md`。
#[tauri::command]
#[specta::specta]
pub fn notes_daily_note(app: AppHandle, state: State<'_, NotesManager>) -> Result<NoteDoc, String> {
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 = "日记";
@@ -261,9 +308,9 @@ pub fn notes_daily_note(app: AppHandle, state: State<'_, NotesManager>) -> Resul
/// 新建文件夹。
#[tauri::command]
#[specta::specta]
pub fn notes_create_folder(
pub fn editor_create_folder(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
dir_rel: String,
name: String,
) -> Result<(), String> {
@@ -276,9 +323,9 @@ pub fn notes_create_folder(
/// 重命名条目,返回新相对路径。
#[tauri::command]
#[specta::specta]
pub fn notes_rename_entry(
pub fn editor_rename_entry(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
rel_path: String,
new_name: String,
) -> Result<String, String> {
@@ -287,7 +334,7 @@ pub fn notes_rename_entry(
// 改名在索引里是「旧路径消失 + 新路径出现」:增量同步一次比手工删+插更稳
if let Ok(service) = indexed(&app, &state) {
if let Err(e) = service.sync() {
crate::logger::log_warn("notes", &format!("改名后同步索引失败: {e}"));
crate::logger::log_warn("editor", &format!("改名后同步索引失败: {e}"));
}
}
emit_library_changed(&app);
@@ -297,16 +344,16 @@ pub fn notes_rename_entry(
/// 删除条目(目录递归删除)。
#[tauri::command]
#[specta::specta]
pub fn notes_delete_entry(
pub fn editor_delete_entry(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
rel_path: String,
) -> Result<(), String> {
let root = current_root(&state);
library::delete_entry(&root, &rel_path)?;
if let Ok(service) = indexed(&app, &state) {
if let Err(e) = service.sync() {
crate::logger::log_warn("notes", &format!("删除后同步索引失败: {e}"));
crate::logger::log_warn("editor", &format!("删除后同步索引失败: {e}"));
}
}
emit_library_changed(&app);
@@ -318,9 +365,9 @@ pub fn notes_delete_entry(
/// 全量重建索引(设置页「重建索引」)。文件不受影响。
#[tauri::command]
#[specta::specta]
pub fn notes_rebuild_index(
pub fn editor_rebuild_index(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<NoteIndexReport, String> {
let service = indexed(&app, &state)?;
let report = service.rebuild()?;
@@ -330,9 +377,9 @@ pub fn notes_rebuild_index(
/// 增量同步索引(打开编辑器 / 手动刷新时调用)。
#[tauri::command]
#[specta::specta]
pub fn notes_sync_index(
pub fn editor_sync_index(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<NoteIndexReport, String> {
let service = indexed(&app, &state)?;
let report = service.sync()?;
@@ -350,9 +397,9 @@ fn finish_report(service: &IndexService, report: super::index::NoteSyncReport) -
/// 全文检索 / 按标签 / 按目录筛选。
#[tauri::command]
#[specta::specta]
pub fn notes_search_notes(
pub fn editor_search_notes(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
query: NoteSearchQuery,
) -> Result<NoteSearchPage, String> {
let service = indexed(&app, &state)?;
@@ -362,9 +409,9 @@ pub fn notes_search_notes(
/// 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。
#[tauri::command]
#[specta::specta]
pub fn notes_list_notes(
pub fn editor_list_notes(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
limit: Option<i64>,
) -> Result<Vec<NoteSearchHit>, String> {
let service = indexed(&app, &state)?;
@@ -374,9 +421,9 @@ pub fn notes_list_notes(
/// 标签及计数。
#[tauri::command]
#[specta::specta]
pub fn notes_tags(
pub fn editor_tags(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<Vec<super::index::NoteTagCount>, String> {
let service = indexed(&app, &state)?;
service.tags()
@@ -385,9 +432,9 @@ pub fn notes_tags(
/// 一篇笔记的链接关系(出链 + 入链)。
#[tauri::command]
#[specta::specta]
pub fn notes_backlinks(
pub fn editor_backlinks(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
rel_path: String,
) -> Result<NoteBacklinks, String> {
let service = indexed(&app, &state)?;
@@ -397,9 +444,9 @@ pub fn notes_backlinks(
/// 全库链接图(已解析的内部链接边)。
#[tauri::command]
#[specta::specta]
pub fn notes_link_graph(
pub fn editor_link_graph(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<Vec<LinkEdge>, String> {
let service = indexed(&app, &state)?;
let edges = service.link_graph()?;
@@ -421,9 +468,9 @@ pub struct LinkEdge {
/// 索引状态(设置页展示:索引数 / 文件数 / 标签数 / 索引文件路径)。
#[tauri::command]
#[specta::specta]
pub fn notes_index_stats(
pub fn editor_index_stats(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<NoteIndexStats, String> {
let service = indexed(&app, &state)?;
service.stats()
@@ -451,8 +498,8 @@ const MAX_ASSET_BYTES: u64 = 8 * 1024 * 1024;
#[tauri::command]
#[specta::specta]
pub fn notes_read_asset(
state: State<'_, NotesManager>,
pub fn editor_read_asset(
state: State<'_, EditorManager>,
rel_path: String,
) -> Result<Option<String>, String> {
let root = current_root(&state);
@@ -479,7 +526,7 @@ pub fn notes_read_asset(
let meta = std::fs::metadata(&path).map_err(|e| format!("读取附件信息失败: {e}"))?;
if meta.len() > MAX_ASSET_BYTES {
crate::logger::log_info(
"notes",
"editor",
&format!("附件过大,跳过内联预览:{rel_path}({} 字节)", meta.len()),
);
return Ok(None);
@@ -493,11 +540,11 @@ pub fn notes_read_asset(
/// 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。
///
/// 前端在注册完事件监听后调用。**不能靠启动时 `emit`** —— 那时 WebView 还没加载完,
/// 事件会直接丢掉(见 `notes/args.rs` 的 `PENDING` 注释)。
/// 事件会直接丢掉(见 `editor/args.rs` 的 `PENDING` 注释)。
#[tauri::command]
#[specta::specta]
pub fn notes_take_pending_file() -> Result<Option<String>, String> {
Ok(super::args::take_pending_file().map(|path| super::files::display_path(&path)))
pub fn editor_take_pending_file() -> Result<Option<super::args::OpenTargetPayload>, String> {
Ok(super::args::take_pending_target())
}
/// 打开(读取)库外任意文件。
@@ -506,8 +553,8 @@ pub fn notes_take_pending_file() -> Result<Option<String>, String> {
/// 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。
#[tauri::command]
#[specta::specta]
pub fn notes_open_file(
state: State<'_, NotesManager>,
pub fn editor_open_file(
state: State<'_, EditorManager>,
path: String,
) -> Result<files::FileDoc, String> {
let settings = state.load_settings();
@@ -517,9 +564,9 @@ pub fn notes_open_file(
/// 保存库外任意文件(按前端回传的编码与换行写回)。
#[tauri::command]
#[specta::specta]
pub fn notes_write_file(
pub fn editor_write_file(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
path: String,
content: String,
encoding: String,
@@ -528,18 +575,32 @@ pub fn notes_write_file(
let settings = state.load_settings();
let doc = files::write_file(&path, &content, &encoding, &eol, settings.max_file_size_mb)?;
if let Ok(service) = indexed(&app, &state) {
service.mark_write();
// 库外文件的路径语义与库内相对路径不同,这里退回窗口式抑制;
// 真正在库内的 `.md`(被当作普通文件打开)同样受这一窗口保护。
service.mark_write_all();
}
Ok(doc)
}
/// 以指定编码重新解码磁盘字节(切换编码用;不写回,只换一种解释方式)。
#[tauri::command]
#[specta::specta]
pub fn editor_redecode_file(
state: State<'_, EditorManager>,
path: String,
encoding: String,
) -> Result<files::FileDoc, String> {
let settings = state.load_settings();
files::redecode_file(&path, &encoding, settings.max_file_size_mb)
}
/// 显式登记一个路径为「可写」。
///
/// 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `notes_open_file`,
/// 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `editor_open_file`,
/// 但用户确实是用系统对话框选的,属于「用户显式选择」)。
#[tauri::command]
#[specta::specta]
pub fn notes_authorize_file(path: String) -> Result<(), String> {
pub fn editor_authorize_file(path: String) -> Result<(), String> {
if path.trim().is_empty() {
return Err("路径为空".to_string());
}
@@ -554,8 +615,8 @@ pub fn notes_authorize_file(path: String) -> Result<(), String> {
/// 安全得多(写的位置由后端决定,且只落在 `assets/`)。
#[tauri::command]
#[specta::specta]
pub fn notes_write_asset(
state: State<'_, NotesManager>,
pub fn editor_write_asset(
state: State<'_, EditorManager>,
file_name: String,
ext: String,
data_base64: String,
@@ -577,7 +638,7 @@ pub fn notes_write_asset(
/// 就能直接写文件,不需要用户先去资源管理器建目录。
#[tauri::command]
#[specta::specta]
pub fn notes_list_templates(state: State<'_, NotesManager>) -> Result<Vec<NoteTemplate>, String> {
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);
@@ -591,9 +652,9 @@ pub fn notes_list_templates(state: State<'_, NotesManager>) -> Result<Vec<NoteTe
/// - 传 `name` + `body`:新建一个自定义模板。
#[tauri::command]
#[specta::specta]
pub fn notes_add_template(
pub fn editor_add_template(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
name: Option<String>,
body: Option<String>,
) -> Result<Vec<String>, String> {
@@ -623,8 +684,8 @@ pub fn notes_add_template(
/// 内置模板没有对应的库内文件,前端据此禁掉「直接编辑」。
#[tauri::command]
#[specta::specta]
pub fn notes_read_template(
state: State<'_, NotesManager>,
pub fn editor_read_template(
state: State<'_, EditorManager>,
template_id: String,
) -> Result<TemplateSource, String> {
let root = current_root(&state);
@@ -649,9 +710,9 @@ pub struct TemplateSource {
/// 从磁盘路径导入(文件 / 目录 / zip 自动判别)。
#[tauri::command]
#[specta::specta]
pub fn notes_import(
pub fn editor_import(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
source: String,
dest_dir: String,
) -> Result<ImportReport, String> {
@@ -668,8 +729,8 @@ pub fn notes_import(
/// 已经渲染好的字符串写到用户选定的位置 —— 即「后端不碰渲染逻辑,前端不碰文件系统」。
#[tauri::command]
#[specta::specta]
pub fn notes_export_note(
state: State<'_, NotesManager>,
pub fn editor_export_note(
state: State<'_, EditorManager>,
rel_path: String,
html: String,
dest: String,
@@ -687,7 +748,7 @@ pub fn notes_export_note(
let bytes = html.into_bytes();
std::fs::write(&target, &bytes).map_err(|e| format!("写入导出文件失败: {e}"))?;
crate::logger::log_info(
"notes",
"editor",
&format!("导出 {} → {}({} 字节)", rel_path, target.display(), bytes.len()),
);
Ok(target.to_string_lossy().to_string())
@@ -696,8 +757,8 @@ pub fn notes_export_note(
/// 把整库(或某个目录)打包成 zip,返回落盘路径。
#[tauri::command]
#[specta::specta]
pub fn notes_export_zip(
state: State<'_, NotesManager>,
pub fn editor_export_zip(
state: State<'_, EditorManager>,
dest: String,
dir_rel: Option<String>,
) -> Result<String, String> {
@@ -713,7 +774,7 @@ pub fn notes_export_zip(
}
std::fs::write(&dest_path, &bytes).map_err(|e| format!("写入 zip 失败: {e}"))?;
crate::logger::log_info(
"notes",
"editor",
&format!("导出 zip:{files} 个文件 → {}", dest_path.display()),
);
Ok(dest_path.to_string_lossy().to_string())
@@ -721,13 +782,13 @@ pub fn notes_export_zip(
/// 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。
///
/// 与 [`notes_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
/// 与 [`editor_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
/// 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为
/// 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。
#[tauri::command]
#[specta::specta]
pub fn notes_export_snapshot_local(
state: State<'_, NotesManager>,
pub fn editor_export_snapshot_local(
state: State<'_, EditorManager>,
dest: Option<String>,
) -> Result<String, String> {
let root = current_root(&state);
@@ -745,7 +806,7 @@ pub fn notes_export_snapshot_local(
/// 当前 WebDAV 配置状态(设置页展示;**密码只回传「是否已保存」**)。
#[tauri::command]
#[specta::specta]
pub fn notes_webdav_status(state: State<'_, NotesManager>) -> Result<WebdavStatus, String> {
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()
@@ -773,7 +834,7 @@ pub struct WebdavStatus {
/// 保存 WebDAV 密码到系统凭据管理器(传空串 = 删除)。
#[tauri::command]
#[specta::specta]
pub fn notes_set_webdav_password(password: String) -> Result<(), String> {
pub fn editor_set_webdav_password(password: String) -> Result<(), String> {
if password.trim().is_empty() {
return crate::secrets::secret_delete(webdav::KEYRING_PASSWORD);
}
@@ -783,8 +844,8 @@ pub fn notes_set_webdav_password(password: String) -> Result<(), String> {
/// 连接自检(建目录 + 列远端)。
#[tauri::command]
#[specta::specta]
pub async fn notes_test_webdav(
state: State<'_, NotesManager>,
pub async fn editor_test_webdav(
state: State<'_, EditorManager>,
) -> Result<WebdavTestResult, String> {
let settings = state.load_settings().webdav;
run_blocking(move || webdav::test_connection(&settings)).await
@@ -793,9 +854,9 @@ pub async fn notes_test_webdav(
/// 立即同步(并按设置决定是否追加一次快照备份)。
#[tauri::command]
#[specta::specta]
pub async fn notes_sync_now(
pub async fn editor_sync_now(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<SyncOutcome, String> {
let settings = state.load_settings();
let webdav = settings.webdav.clone();
@@ -804,7 +865,7 @@ pub async fn notes_sync_now(
// 让前端先看到「开始同步」(进度事件的第一条由 worker 之外发,总数为 0 表示准备中)
let _ = app.emit(
events::NOTES_SYNC_PROGRESS,
events::EDITOR_SYNC_PROGRESS,
SyncProgress {
done: 0,
total: 0,
@@ -843,8 +904,8 @@ pub struct SyncOutcome {
/// 只做一次 zip 快照备份(不上传增量)。
#[tauri::command]
#[specta::specta]
pub async fn notes_backup_now(
state: State<'_, NotesManager>,
pub async fn editor_backup_now(
state: State<'_, EditorManager>,
) -> Result<BackupReport, String> {
let settings = state.load_settings();
let webdav = settings.webdav.clone();
@@ -861,8 +922,8 @@ pub async fn notes_backup_now(
/// 列出远端已有快照。
#[tauri::command]
#[specta::specta]
pub async fn notes_list_backups(
state: State<'_, NotesManager>,
pub async fn editor_list_backups(
state: State<'_, EditorManager>,
) -> Result<Vec<BackupSnapshot>, String> {
let settings = state.load_settings().webdav;
run_blocking(move || {
@@ -875,9 +936,9 @@ pub async fn notes_list_backups(
/// 从远端快照恢复(不覆盖本地已有文件)。
#[tauri::command]
#[specta::specta]
pub async fn notes_restore_backup(
pub async fn editor_restore_backup(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
name: String,
) -> Result<ImportReport, String> {
let settings = state.load_settings();
+147
View File
@@ -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))
}
@@ -5,7 +5,7 @@
//! `backup.rs` 的 zip 是**给同步服务用的**(固定文件名前缀、上传到远端、轮转),
//! 本模块的 zip 是**给用户拿走的**(用户选保存位置、可以只导出某个目录)。
//! 两者都打包 `.md` 与 `assets/`,但排除规则不同:用户导出时**包含**点号开头的
//! 普通目录(除了 `.notes/`)—— 因为「我库里有 `.foo/` 目录,为什么导出后没了」
//! 普通目录(除了 `.editor/`)—— 因为「我库里有 `.foo/` 目录,为什么导出后没了」
//! 是个更难解释的问题;而同步必须排除它们(避免把本机私有状态推给别人)。
use std::io::Write;
@@ -59,7 +59,7 @@ pub fn zip_scope(root: &Path, dir_rel: &str) -> Result<(Vec<u8>, u32), String> {
continue;
}
// 私有目录(索引 + 同步基线)任何情况下都不导出
if rel == ".notes" || rel.starts_with(".notes/") {
if rel == ".editor" || rel.starts_with(".editor/") {
continue;
}
if let Some(prefix) = &filter_prefix {
@@ -74,7 +74,7 @@ pub fn zip_scope(root: &Path, dir_rel: &str) -> Result<(Vec<u8>, u32), String> {
let bytes = match std::fs::read(entry.path()) {
Ok(bytes) => bytes,
Err(e) => {
crate::logger::log_warn("notes", &format!("导出跳过 {rel}(读取失败: {e})"));
crate::logger::log_warn("editor", &format!("导出跳过 {rel}(读取失败: {e})"));
continue;
}
};
@@ -113,10 +113,10 @@ mod tests {
#[test]
fn full_export_skips_private_dir_only() {
let root = temp_lib("all");
std::fs::create_dir_all(root.join(".notes")).unwrap();
std::fs::create_dir_all(root.join(".editor")).unwrap();
std::fs::create_dir_all(root.join(".custom")).unwrap();
std::fs::write(root.join("a.md"), "A").unwrap();
std::fs::write(root.join(".notes/notes.db"), "x").unwrap();
std::fs::write(root.join(".editor/editor.db"), "x").unwrap();
std::fs::write(root.join(".custom/keep.md"), "保留").unwrap();
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
@@ -129,7 +129,7 @@ mod tests {
"普通点号目录应被导出: {list:?}"
);
assert!(
!list.iter().any(|n| n.starts_with(".notes")),
!list.iter().any(|n| n.starts_with(".editor")),
"私有目录不该导出: {list:?}"
);
@@ -10,7 +10,7 @@
//! # 为什么要有授权白名单
//!
//! 前端传来的路径一律不可信:一个被污染的 WebView(XSS、恶意依赖)如果能调
//! `notes_write_file('/Windows/System32/...')`,那就不是编辑器而是任意文件写入漏洞。
//! `editor_write_file('/Windows/System32/...')`,那就不是编辑器而是任意文件写入漏洞。
//! 做法:只有经过 [`authorize`] 登记过的路径才允许读**写**(读也一并限制,避免拿它
//! 当任意文件读取接口探测磁盘)。授权的三个来源都是用户动作:系统文件对话框、
//! 命令行参数、库本身。
@@ -69,6 +69,15 @@ pub struct FileDoc {
pub large: bool,
/// 行数(前端状态栏显示;大文件也只需要扫一遍换行,成本可忽略)
pub lines: u64,
/// 是否只读(打开时探测写权限失败;前端据此拦截保存并给出原因)
pub readonly: bool,
}
/// 探测写权限:以写模式打开但**不写入**(失败 → 只读)。
///
/// 比「打开成功但保存时才报错」体验好得多:只读文件一打开就能看到状态栏标记。
fn is_writable(path: &Path) -> bool {
std::fs::OpenOptions::new().write(true).open(path).is_ok()
}
/// 登记一个路径为「已授权可写」。
@@ -105,16 +114,18 @@ pub fn display_path(path: &Path) -> String {
}
}
/// 探测编码:返回规范名(`utf-8` / `utf-8-bom` / `gbk` / `gb18030` / `big5` / …)。
/// 探测编码:返回规范名(`utf-8` / `utf-8-bom` / `gbk` / `gb18030` / `big5` / `shift_jis` / …)。
///
/// # 判定顺序(每一步都有理由)
///
/// 1. **BOM**:UTF-8 BOM / UTF-16 的 BOM 是无歧义的事实,直接采信;
/// 2. **严格 UTF-8 校验**:能完整解成 UTF-8 就是 UTF-8。这一步的优先级高于任何
/// 统计猜测 —— 中文 GBK 字节序列几乎不可能恰好是合法 UTF-8,反向的误判同样罕见;
/// 3. **GB18030 试解**:GB18030 是 GBK 的超集,用它解 GBK 内容总能成功,
/// 因此作为「非 UTF-8 中文」的兜底(比 GBK 更宽,能覆盖 4 字节生僻字);
/// 4. 都失败则按 UTF-8 有损解码(宁可显示替换字符,也不要打不开文件)。
/// 2. **严格 UTF-8 校验**:能完整解成 UTF-8 就是 UTF-8。优先级高于任何统计猜测 ——
/// 中文 GBK 字节序列几乎不可能恰好是合法 UTF-8,反向的误判同样罕见;
/// 3. **chardetng 统计探测**:区分 Shift_JIS / Big5 / EUC-KR / GB18030 等 CJK 编码。
/// 这一步不能省:GB18030 几乎能解码任意字节序列,若只靠「试解是否成功」,
/// 日文 Shift_JIS 文件会被静默当成中文 GB18030;
/// 4. 探测器给不出我们支持的编码 → 退回 GB18030 兜底;仍不行则按 UTF-8 有损解码
/// (宁可显示替换字符,也不要打不开文件)。
pub fn detect_encoding(bytes: &[u8]) -> String {
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
return "utf-8-bom".to_string();
@@ -128,15 +139,50 @@ pub fn detect_encoding(bytes: &[u8]) -> String {
if std::str::from_utf8(bytes).is_ok() {
return "utf-8".to_string();
}
// 非 UTF-8:交给 GB18030 兜底(GBK 的每个序列在 GB18030 下都合法)
// 非 UTF-8:先用统计探测区分 CJK 编码(Shift_JIS / Big5 / EUC-KR / GB18030 …)。
// 不能直接拿 GB18030 兜底 —— GB18030 几乎能解码任意字节序列,试解永远「成功」,
// 会把日文 Shift_JIS 文件静默当成中文 GB18030(用户实测到的问题)。
if let Some(name) = detect_with_chardetng(bytes) {
return name;
}
// 探测器给不出我们支持的编码:退回 GB18030(GBK 的每个序列在它之下都合法)
if crate::terminal::encoding::is_supported("gb18030") {
return "gb18030".to_string();
}
"utf-8".to_string()
}
/// 用 `chardetng` 统计探测非 UTF-8 文本的编码,并映射回本模块的规范编码名。
///
/// 只接受我们**支持**的编码(见 `terminal::encoding::SUPPORTED`):探测器给出的
/// 单字节西文编码(`windows-125x` / `ISO-8859-x` / `KOI8-*`)统一归到 `latin1`
/// (它们都是单字节、逐字节一一映射,不会产生替换字符);其余未知的一律返回
/// `None`,由调用方走兜底 —— 宁可退回 GB18030,也不要返回一个解出来全是 `` 的名字。
fn detect_with_chardetng(bytes: &[u8]) -> Option<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 已剥离)。
fn decode_bytes(bytes: &[u8], encoding: &str) -> String {
pub(crate) fn decode_bytes(bytes: &[u8], encoding: &str) -> String {
match encoding {
"utf-8-bom" => {
let body = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
@@ -151,7 +197,11 @@ fn decode_bytes(bytes: &[u8], encoding: &str) -> String {
}
/// 按编码把字符串编成字节(必要时写回 BOM)。
fn encode_text(text: &str, encoding: &str) -> Result<Vec<u8>, String> {
///
/// **不可表示字符绝不静默替换成 `?`**(那是不可逆的数据损坏):先整串试编一次,
/// 若往返比对不一致(说明有字符编不进去),再逐字符定位并报错,让用户改用 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];
@@ -163,11 +213,46 @@ fn encode_text(text: &str, encoding: &str) -> Result<Vec<u8>, String> {
if !crate::terminal::encoding::is_supported(&normalized) {
return Err(format!("不支持的编码:{other}"));
}
Ok(crate::terminal::encoding::encode(text, &normalized))
let encoded = crate::terminal::encoding::encode(text, &normalized);
// UTF-8 能表示任何字符串,无需比对
if normalized != "utf-8"
&& crate::terminal::encoding::decode(&encoded, &normalized) != text
{
let bad = find_unencodable(text, &normalized);
let preview = bad
.iter()
.take(8)
.map(|(index, ch)| format!("第 {index} 个「{ch}」"))
.collect::<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") {
@@ -177,8 +262,25 @@ fn detect_eol(text: &str) -> 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());
@@ -193,7 +295,21 @@ pub fn read_file(path: &str, max_mb: u32) -> Result<FileDoc, String> {
}
let bytes = std::fs::read(p).map_err(|e| format!("读取文件失败: {e}"))?;
let encoding = detect_encoding(&bytes);
let encoding = match forced_encoding {
Some(enc) if !enc.trim().is_empty() => {
let requested = enc.trim();
let normalized = if requested.eq_ignore_ascii_case("utf-8-bom") {
"utf-8-bom".to_string()
} else {
crate::terminal::encoding::normalize(requested)
};
if normalized != "utf-8-bom" && !crate::terminal::encoding::is_supported(&normalized) {
return Err(format!("不支持的编码:{requested}"));
}
normalized
}
_ => detect_encoding(&bytes),
};
let raw = decode_bytes(&bytes, &encoding);
let eol = detect_eol(&raw);
// 统一成 `\n` 交给编辑器:CM6 的一份文档只应有一种换行,混合换行会让
@@ -219,6 +335,7 @@ pub fn read_file(path: &str, max_mb: u32) -> Result<FileDoc, String> {
.map(|d| d.as_millis() as u64)
.unwrap_or(0),
large: meta.len() > limit,
readonly: !is_writable(p),
})
}
@@ -241,6 +358,9 @@ pub fn write_file(
if !is_authorized(p) {
return Err("该文件未经授权,无法写入(请通过「打开文件」重新选择)".to_string());
}
if !is_writable(p) {
return Err("文件为只读,无法保存".to_string());
}
let enc = if encoding.trim().is_empty() {
"utf-8".to_string()
@@ -307,11 +427,30 @@ mod tests {
}
#[test]
fn detects_non_utf8_as_gb18030() {
// 「测试」的 GBK 字节:合法 UTF-8 校验必然失败
let gbk = crate::terminal::encoding::encode("测试", "gbk");
assert_eq!(detect_encoding(&gbk), "gb18030");
assert_eq!(decode_bytes(&gbk, "gb18030"), "测试");
fn detects_non_utf8_chinese_as_gbk_family() {
// 中文:合法 UTF-8 校验必然失败,探测应落在 GBK 家族(gbk 或 gb18030)
let text = "这是一段中文测试文本,用于验证编码探测。";
let gbk = crate::terminal::encoding::encode(text, "gbk");
let detected = detect_encoding(&gbk);
assert!(
detected == "gbk" || detected == "gb18030",
"中文应探测为 GBK 家族,实际为 {detected}"
);
// GB18030 是 GBK 的超集,用它解码同样能还原
assert_eq!(decode_bytes(&gbk, "gb18030"), text);
}
#[test]
fn detects_shift_jis_not_gb18030() {
// 日文 Shift_JIS:GB18030 也能「解码成功」,这正是旧实现误判成中文的原因
let text = "これは日本語のテキストです。テスト用のサンプル文です。";
let sjis = crate::terminal::encoding::encode(text, "shift_jis");
let detected = detect_encoding(&sjis);
assert_eq!(
detected, "shift_jis",
"日文 Shift_JIS 不应被误判(实际 {detected})"
);
assert_eq!(decode_bytes(&sjis, "shift_jis"), text);
}
#[test]
+890
View File
@@ -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(&regex::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);
}
}
File renamed without changes.
@@ -3,7 +3,7 @@
//! # 索引不是真相
//!
//! 真相永远是库根下的 `.md` 文件(见 `library.rs`)。本模块只是**可随时丢弃重建**
//! 的加速层:删掉 `{库根}/.notes/notes.db` 的唯一后果是下次搜索前要做一次全量扫描。
//! 的加速层:删掉 `{库根}/.editor/editor.db` 的唯一后果是下次搜索前要做一次全量扫描。
//! 因此这里不写「强一致」逻辑,只保证「一次同步之后索引与文件一致」——
//! 增量同步靠 `(mtime, size)` 快速筛掉未变文件,变了才读内容算 hash。
//!
@@ -13,7 +13,7 @@
//! 不需要维护「库 → 索引文件」的映射;把整个库目录拷走时索引一起走,新机器上
//! 第一次搜索只做增量校验而不是全量重建。
//!
//! 代价是「数据库落在用户看得见的目录里」,所以目录名用点号前缀 `.notes/`:
//! 代价是「数据库落在用户看得见的目录里」,所以目录名用点号前缀 `.editor/`:
//! 库扫描(`library::scan`)本来就跳过点号开头的目录,它不会出现在侧栏树里;
//! P2 的 WebDAV 同步也会按约定排除它。
//!
@@ -398,7 +398,7 @@ pub struct NoteSyncReport {
}
/// 笔记索引(持有 SQLite 连接 + 当前库根)。
pub struct NotesIndex {
pub struct EditorIndex {
conn: Connection,
/// 索引所属的库根(库切换时整个索引实例被替换)
root: PathBuf,
@@ -406,15 +406,17 @@ pub struct NotesIndex {
db_path: PathBuf,
}
impl NotesIndex {
impl EditorIndex {
/// 打开(或创建)某个库根对应的索引。
///
/// 库根切换后由命令层用新库根调用本函数重建实例 —— 索引与库一一对应,
/// 不做「一份索引服务多个库」的多态(那需要为每张表加 root 列,得不偿失)。
pub fn open(root: &Path) -> Result<Self, String> {
let dir = root.join(".notes");
// 惰性迁移旧私有目录(幂等):索引可重建,但同步基线要跟着搬过去
library::migrate_private_dir(root);
let dir = root.join(library::PRIVATE_DIR);
std::fs::create_dir_all(&dir).map_err(|e| format!("创建索引目录失败: {e}"))?;
let db_path = dir.join("notes.db");
let db_path = dir.join("editor.db");
let conn = Connection::open(&db_path).map_err(|e| format!("打开笔记索引失败: {e}"))?;
conn.busy_timeout(std::time::Duration::from_secs(3))
.map_err(|e| format!("设置索引超时失败: {e}"))?;
@@ -450,7 +452,7 @@ impl NotesIndex {
if version != 0 && version != SCHEMA_VERSION {
crate::logger::log_warn(
"notes",
"editor",
&format!("索引结构版本 {version} → {SCHEMA_VERSION},按文件重建索引"),
);
self.drop_all()?;
@@ -563,7 +565,7 @@ impl NotesIndex {
continue;
}
let path = entry.path();
// 跳过点号目录(含 `.notes/` 自身)与根级 assets/
// 跳过点号目录(含 `.editor/` 自身)与根级 assets/
if skip_path(&root, path) {
continue;
}
@@ -626,7 +628,7 @@ impl NotesIndex {
let bytes = match std::fs::read(&path) {
Ok(b) => b,
Err(e) => {
crate::logger::log_warn("notes", &format!("索引读取失败 {rel}: {e}"));
crate::logger::log_warn("editor", &format!("索引读取失败 {rel}: {e}"));
continue;
}
};
@@ -1069,7 +1071,7 @@ fn skip_path(root: &Path, path: &Path) -> bool {
return false;
}
let parts: Vec<&str> = rel.split('/').collect();
// 任何一层是点号开头 → 排除(`.notes/` 索引自身、`.git/` 等)
// 任何一层是点号开头 → 排除(`.editor/` 索引自身、`.git/` 等)
if parts.iter().any(|p| p.starts_with('.')) {
return true;
}
@@ -1294,7 +1296,7 @@ mod tests {
#[test]
fn index_roundtrip_search_tags_and_rebuild() {
let root = std::env::temp_dir().join(format!(
"thing-notes-index-test-{}",
"thing-editor-index-test-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&root);
@@ -1314,9 +1316,9 @@ mod tests {
// 非 .md 与点号目录都不该被索引
std::fs::write(root.join("notes/notes.txt"), "不该被索引").unwrap();
// 先打开索引(顺带创建 `.notes/` 目录),再往里塞一个「不该被索引」的 .md
let mut index = NotesIndex::open(&root).unwrap();
std::fs::write(root.join(".notes/ignored.md"), "也不该被索引").unwrap();
// 先打开索引(顺带创建 `.editor/` 目录),再往里塞一个「不该被索引」的 .md
let mut index = EditorIndex::open(&root).unwrap();
std::fs::write(root.join(".editor/ignored.md"), "也不该被索引").unwrap();
let report = index.sync().unwrap();
assert_eq!(report.indexed, 2, "只应索引两篇 .md");
@@ -1427,7 +1429,7 @@ mod tests {
#[test]
fn front_matter_id_and_dates_are_indexed() {
let root = std::env::temp_dir().join(format!(
"thing-notes-index-fm-{}",
"thing-editor-index-fm-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&root);
@@ -1438,7 +1440,7 @@ mod tests {
)
.unwrap();
let mut index = NotesIndex::open(&root).unwrap();
let mut index = EditorIndex::open(&root).unwrap();
index.sync().unwrap();
let page = index
.search(NoteSearchQuery {
@@ -19,8 +19,11 @@
//! 比「回调里发前端事件 → 前端再调一次同步命令」少一次往返,也不会因为前端窗口
//! 关着而漏掉索引更新。
//!
//! 自我保存抑制([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发
//! `Modify(Data)`,若不抑制,前端就会在用户自己打字时反复弹出「文件已被外部修改」。
//! 自我保存识别([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发
//! `Modify(Data)`,若把这类事件也当成「外部修改」,前端就会在用户自己打字时反复
//! 重载文档 / 弹提示。识别按**库内相对路径**在写入前登记(见 `mark_write_path`),
//! 结果写进事件的 `from_app`,由前端决定是否提示 —— 而不是在这里静默丢弃事件。
//! 静默丢弃一旦因时序漏判,前端就会把自家的保存当成外部改动而重载。
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, Sender};
@@ -33,21 +36,28 @@ use specta::Type;
use tauri::{AppHandle, Emitter};
use super::files;
use super::index::{content_hash, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery, NoteSyncReport, NotesIndex};
use super::index::{content_hash, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery, NoteSyncReport, EditorIndex};
use super::library;
use crate::constants::events;
/// 自我保存抑制窗口:`notes_write_*` 之后这段时间内的文件事件不当作「外部修改」。
/// 自我写入(自己刚保存)与外部改动之间的**去重窗口**。
///
/// 取 1200ms:前端自动保存默认 800ms 防抖,加上写盘与 notify 自身的派发延迟,
/// 这个窗口足够覆盖「自己写的」这一类事件,又短到不会吞掉用户紧接着在外部编辑器
/// 里的另一次保存(那种情况用户本来就刚切过窗口,多等一秒无妨)。
/// 取 1200ms:一次写入可能被 notify 拆成多条事件(`Modify(Data)` 常伴一条元数据事件),
/// 命中的第一条之后,这段时间内的同路径事件一并算作「自己写的」,既不重复处理,
/// 又不会把窗口拉得太长去吞掉用户紧接着在外部编辑器里的另一次保存。
const SUPPRESS_MS: u64 = 1200;
/// 自我写入登记在「尚未被任何文件事件命中」时的最长存活时间。
///
/// 比去重窗口宽得多:notify 的派发延迟可能到秒级,窗口太窄会把「自己刚写的」误判成
/// 外部修改(重载文档、光标弹回第一行)—— 这正是要避免的事故。登记项一旦被**第一个**
/// 匹配事件消费,就只保留 [`SUPPRESS_MS`] 的去重窗口,不会长期吞掉真正的外部改动。
const SELF_WRITE_TTL_MS: u64 = 30_000;
/// 单个文件事件的去抖说明。
///
/// worker 是「来一条处理一条」,去抖由三层共同承担:notify 自身的派发合并、
/// 前端 `notes-library-changed` 的 400ms 防抖、以及自我保存抑制窗口。
/// 前端 `editor-library-changed` 的 400ms 防抖、以及自我保存抑制窗口。
/// 之所以不在这里再加一个定时器:多一层延迟就多一个「事件丢了谁负责」的疑问,
/// 而下游每一层都是幂等的(重复同步同一个文件只是重算一次 hash)。
const _DEBOUNCE_NOTE_MS: u64 = 250;
@@ -109,7 +119,7 @@ enum Request {
/// 全量重建
Rebuild(Sender<Result<NoteSyncReport, String>>),
/// 同步单个文件(监听器投递;文件不存在则从索引移除)
SyncPath(PathBuf, bool),
SyncPath(PathBuf),
/// 全文检索
Search(NoteSearchQuery, Sender<Result<NoteSearchPage, String>>),
/// 快速打开清单
@@ -126,11 +136,38 @@ enum Request {
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>,
/// 自我保存抑制的时间点(`notes_write_*` 写入)
last_write: Mutex<Option<Instant>>,
/// 批量自我写入的时间点(导入 / WebDAV 同步 / 恢复 / 模板导出这类无法逐路径枚举的操作)。
/// 窗口内的一切文件事件都当作「自己写的」,不向前端提示外部修改。
bulk_write: Mutex<Option<Instant>>,
/// 单个文件的自我写入登记。
/// 比批量窗口精确:保存 A 不会再顺带吞掉 B 的外部改动事件。
write_paths: Mutex<Vec<SelfWrite>>,
}
static SERVICE: std::sync::OnceLock<IndexService> = std::sync::OnceLock::new();
@@ -145,29 +182,72 @@ impl IndexService {
let (tx, rx) = mpsc::channel::<Request>();
let handle_tx = tx.clone();
std::thread::Builder::new()
.name("notes-index".to_string())
.name("editor-index".to_string())
.spawn(move || worker_loop(app, rx, handle_tx))
.expect("启动笔记索引线程失败");
Self {
tx,
last_write: Mutex::new(None),
bulk_write: Mutex::new(None),
write_paths: Mutex::new(Vec::new()),
}
}
/// 标记「刚刚由本应用写入了文件」,用于抑制自我触发的「外部修改」提示。
pub fn mark_write(&self) {
if let Ok(mut slot) = self.last_write.lock() {
/// 标记「刚刚由本应用**批量**写入了文件」(导入 / 同步 / 恢复 / 模板导出)。
/// 这类操作无法逐路径枚举,窗口内一律视为自我写入。
pub fn mark_write_all(&self) {
if let Ok(mut slot) = self.bulk_write.lock() {
*slot = Some(Instant::now());
}
}
fn recently_written(&self) -> bool {
self.last_write
/// 登记「本应用即将写入这个库内相对路径」。
///
/// **必须在真正的 `fs::write` 之前调用**:notify 的 Modify 事件可能与写入几乎同时
/// 到达 worker,若等写盘回来再登记,事件可能已经被处理并误判为「外部修改」。
pub fn mark_write_path(&self, rel: &str) {
if rel.is_empty() {
return;
}
if let Ok(mut paths) = self.write_paths.lock() {
prune_self_writes(&mut paths);
paths.push(SelfWrite {
rel: rel.to_string(),
marked: Instant::now(),
matched: None,
});
}
}
/// 这个库内相对路径是不是「本应用自己刚写的」。
///
/// 命中**一次就算消费**:优先匹配还没命中过的登记(一次写入对应一次命中),
/// 找不到才回退到刚命中过的(覆盖同一次写入的重复事件)。这样即便 notify 延迟到
/// 秒级,登记项仍在(见 [`SELF_WRITE_TTL_MS`]),不会把自家的保存误判成外部修改。
fn recently_written(&self, rel: &str) -> bool {
let bulk = self
.bulk_write
.lock()
.ok()
.and_then(|slot| *slot)
.map(|at| at.elapsed() < Duration::from_millis(SUPPRESS_MS))
.unwrap_or(false)
.unwrap_or(false);
if bulk {
return true;
}
let Ok(mut paths) = self.write_paths.lock() else {
return false;
};
prune_self_writes(&mut paths);
let index = paths
.iter()
.position(|entry| entry.rel == rel && entry.matched.is_none())
.or_else(|| paths.iter().position(|entry| entry.rel == rel));
let Some(index) = index else {
return false;
};
let entry = &mut paths[index];
entry.matched.get_or_insert_with(Instant::now);
true
}
/// 增量同步整个库。
@@ -252,9 +332,9 @@ impl IndexService {
}
}
/// worker 主循环:独占 [`NotesIndex`],串行处理所有请求。
/// worker 主循环:独占 [`EditorIndex`],串行处理所有请求。
fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>) {
let mut index: Option<NotesIndex> = None;
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;
@@ -288,6 +368,14 @@ fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.stats()));
}
Request::Retarget(next, reply) => {
// 库根未变:直接返回,不重开索引、不重建监听器。
// 早期实现每次都 `index = None` + 重挂 watcher,于是**每次自动保存**都要重开
// SQLite 连接、重建 notify 监听,既慢,又让「写入 → 事件」挤进这段重建窗口,
// 制造出「自己保存却被当成外部修改」的竞态。
if root.as_deref() == Some(next.as_path()) {
let _ = reply.send(Ok(()));
continue;
}
// 库根切换:丢掉旧索引实例,下次操作按新库根重新打开
index = None;
root = Some(next.clone());
@@ -302,17 +390,17 @@ fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>
// 新库的监听器要在回复之后建:先让前端拿到「已切换」的结果
ensure_watcher(&mut watcher, &mut watched_root, &next, &handle_tx);
}
Request::SyncPath(path, from_app) => {
Request::SyncPath(path) => {
if let Some(current) = root.clone() {
// 索引尚未建立时先建(首次操作前就被外部改动的情况)
if index.is_none() {
if let Err(e) = ensure_index(&app, &mut index, &current) {
crate::logger::log_warn("notes", &format!("索引不可用: {e}"));
crate::logger::log_warn("editor", &format!("索引不可用: {e}"));
continue;
}
}
ensure_watcher(&mut watcher, &mut watched_root, &current, &handle_tx);
sync_one(&app, index.as_mut(), &current, &path, from_app);
sync_one(&app, index.as_mut(), &current, &path);
}
}
}
@@ -322,9 +410,9 @@ fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>
/// 借出索引(必要时按 `root` 打开),并把结果映射成 `Result<_, String>`。
fn with_index<T>(
app: &AppHandle,
index: &mut Option<NotesIndex>,
index: &mut Option<EditorIndex>,
root: &mut Option<PathBuf>,
run: impl FnOnce(&mut NotesIndex) -> Result<T, String>,
run: impl FnOnce(&mut EditorIndex) -> Result<T, String>,
) -> Result<T, String> {
let Some(current) = root.clone() else {
// 不在这里猜库根:命令层每次操作前都会 `retarget` 到当前库根,
@@ -339,18 +427,18 @@ fn with_index<T>(
}
/// 确保索引实例存在且指向 `root`(不匹配则重新打开)。
fn ensure_index(app: &AppHandle, index: &mut Option<NotesIndex>, root: &Path) -> Result<(), String> {
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("notes", &e);
crate::logger::log_warn("editor", &e);
}
let opened = NotesIndex::open(root)?;
let opened = EditorIndex::open(root)?;
crate::logger::log_info(
"notes",
"editor",
&format!("索引已就绪: {}", opened.db_path().display()),
);
// 首次打开时不自动全量同步:库可能很大,交给命令层(打开编辑器 / 重建索引时)触发
@@ -367,7 +455,7 @@ fn ensure_watcher(
tx: &Sender<Request>,
) {
if let Err(e) = ensure_watcher_inner(watcher, watched_root, root, tx) {
crate::logger::log_warn("notes", &e);
crate::logger::log_warn("editor", &e);
}
}
@@ -385,7 +473,7 @@ fn ensure_watcher_inner(
let mut next = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
let Ok(event) = event else { return };
for path in event_paths(&event) {
let _ = sender.send(Request::SyncPath(path, true));
let _ = sender.send(Request::SyncPath(path));
}
})
.map_err(|e| format!("创建库监听器失败: {e}"))?;
@@ -396,11 +484,11 @@ fn ensure_watcher_inner(
// 替换旧监听器(drop 即 unwatch)
*watcher = Some(next);
*watched_root = Some(root.to_path_buf());
crate::logger::log_info("notes", &format!("库监听已启动: {}", root.display()));
crate::logger::log_info("editor", &format!("库监听已启动: {}", root.display()));
Ok(())
}
/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.notes/` 自身)。
/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.editor/` 自身)。
///
/// 重命名会给出两个路径(旧、新),这里都收下:旧路径在同步时会发现「文件不存在」
/// 而被当作删除处理,新路径自然成为新增 —— 无需专门分辨 RenameMode。
@@ -428,13 +516,10 @@ fn event_paths(event: &notify::Event) -> Vec<PathBuf> {
}
/// 就地同步单个文件(含自我保存抑制与前端事件广播)。
fn sync_one(
app: &AppHandle,
index: Option<&mut NotesIndex>,
root: &Path,
path: &Path,
from_app: bool,
) {
///
/// 事件是否「本应用自己写的」按**库内相对路径**判定(见 [`IndexService::mark_write_path`]),
/// 而不是一个全局时间窗 —— 全局窗会把「保存 A 之后 1.2s 内 B 被外部改动」也一并吞掉。
fn sync_one(app: &AppHandle, index: Option<&mut EditorIndex>, root: &Path, path: &Path) {
let Some(index) = index else { return };
let rel = library::rel_string(root, path);
if rel.is_empty() || rel.starts_with('.') || rel.starts_with("assets/") {
@@ -442,8 +527,10 @@ fn sync_one(
}
// 自我保存抑制:只影响「是否提示用户」,索引照常更新
let service = SERVICE.get();
let self_write = from_app && service.map(|s| s.recently_written()).unwrap_or(false);
let self_write = SERVICE
.get()
.map(|service| service.recently_written(&rel))
.unwrap_or(false);
let kind = if path.is_file() {
if let Ok(bytes) = std::fs::read(path) {
@@ -464,7 +551,7 @@ fn sync_one(
&content_hash(&bytes),
&stems,
) {
crate::logger::log_warn("notes", &format!("增量索引 {rel} 失败: {e}"));
crate::logger::log_warn("editor", &format!("增量索引 {rel} 失败: {e}"));
}
} else {
return;
@@ -474,27 +561,26 @@ fn sync_one(
CHANGE_MODIFIED
} else {
if let Err(e) = index.remove_note(&rel) {
crate::logger::log_warn("notes", &format!("移除索引 {rel} 失败: {e}"));
crate::logger::log_warn("editor", &format!("移除索引 {rel} 失败: {e}"));
}
CHANGE_REMOVED
};
if self_write {
// 自己写的:索引已更新,前端无需提示(它的编辑器里本来就是最新内容)
return;
}
// 事件一律发出,用 `from_app` 如实标注来源,由前端决定是否提示/重载。
// 早期实现是「自己写的就静默不发」,一旦自我写入判定因时序漏过,前端就会把自家
// 的保存当成外部修改而重载文档(光标弹回第一行)—— 判定留在前端更稳。
let payload = NoteFileEvent {
rel_path: rel,
abs_path: files::display_path(path),
kind: kind.to_string(), at: std::time::SystemTime::now()
kind: kind.to_string(),
at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0),
from_app: self_write,
};
if let Err(e) = app.emit(events::NOTES_FILE_CHANGED, payload) {
crate::logger::log_warn("notes", &format!("发出文件变化事件失败: {e}"));
if let Err(e) = app.emit(events::EDITOR_FILE_CHANGED, payload) {
crate::logger::log_warn("editor", &format!("发出文件变化事件失败: {e}"));
}
}
@@ -9,12 +9,16 @@
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
use super::types::{LibraryEntry, NoteDoc, NoteSettings};
use super::types::{LibraryEntry, NoteDoc, EditorSettings};
/// 默认库根相对模块目录的名字:`{app_data_dir}/notes/library`
/// 默认库根相对模块目录的名字:`{app_data_dir}/editor/library`
pub const DEFAULT_LIBRARY_DIR: &str = "library";
/// 附件(粘贴图片等)目录名,位于库根下
pub const ASSETS_DIR: &str = "assets";
/// 库内私有目录名(索引 + 同步基线),**永不参与同步 / 导出 / 快照**。
pub const PRIVATE_DIR: &str = ".editor";
/// v1「笔记模块」的私有目录名;首次打开时惰性迁移到 [`PRIVATE_DIR`]。
const LEGACY_PRIVATE_DIR: &str = ".notes";
/// 扫描深度上限(防御性:软链接成环时不会无限递归)。
/// 对 `index.rs` 公开:两处扫描(侧栏树 / 索引)必须用同一个深度口径,
/// 否则会出现「树里看不到、搜索却搜得到」这种自相矛盾的状态。
@@ -34,15 +38,43 @@ pub fn default_library_root(module_dir: &Path) -> PathBuf {
}
/// 由设置解析出当前生效的库根。
pub fn resolve_library_root(module_dir: &Path, settings: &NoteSettings) -> PathBuf {
pub fn resolve_library_root(module_dir: &Path, settings: &EditorSettings) -> PathBuf {
match &settings.library_root {
Some(root) if !root.trim().is_empty() => PathBuf::from(root.trim()),
_ => default_library_root(module_dir),
}
}
/// 确保库根与其 `assets/` 子目录存在。
/// 惰性迁移旧私有目录 `.notes/` → `.editor/`(幂等)。
///
/// 索引可重建,但迁移能保住同步基线(`sync.json`),因此优先整目录重命名。
/// 迁移后残留的旧索引文件(`notes.db*`)直接删除 —— 下次打开会按新库根重建。
pub fn migrate_private_dir(root: &Path) {
let old = root.join(LEGACY_PRIVATE_DIR);
let new = root.join(PRIVATE_DIR);
if !old.is_dir() || new.exists() {
return;
}
match std::fs::rename(&old, &new) {
Ok(()) => {
for stale in ["notes.db", "notes.db-wal", "notes.db-shm"] {
let _ = std::fs::remove_file(new.join(stale));
}
crate::logger::log_info(
"editor",
&format!("已迁移库内私有目录 {LEGACY_PRIVATE_DIR}/ → {PRIVATE_DIR}/"),
);
}
Err(e) => crate::logger::log_warn(
"editor",
&format!("迁移库内私有目录失败(将按新目录重建): {e}"),
),
}
}
/// 确保库根与其 `assets/` 子目录存在(顺带惰性迁移旧私有目录)。
pub fn ensure_library(root: &Path) -> Result<(), String> {
migrate_private_dir(root);
std::fs::create_dir_all(root).map_err(|e| format!("创建笔记库目录失败: {e}"))?;
std::fs::create_dir_all(root.join(ASSETS_DIR))
.map_err(|e| format!("创建附件目录失败: {e}"))?;
@@ -136,7 +168,7 @@ fn walk(root: &Path, dir: &Path, out: &mut Vec<LibraryEntry>, depth: usize) {
let mut files: Vec<(String, PathBuf)> = Vec::new();
for entry in read.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
// 隐藏项(含 `.notes` 之类的私有目录)一律不进库树
// 隐藏项(含 `.editor` 之类的私有目录)一律不进库树
if name.starts_with('.') {
continue;
}
@@ -7,7 +7,7 @@
//! ↓ Tauri IPC ↓
//! commands.rs 命令层
//! ↓
//! NotesManager(本文件):设置读写 / 库根解析
//! EditorManager(本文件):设置读写 / 库根解析
//! ↓
//! library.rs 文件系统(路径安全 / 扫描 / 读写 / 增删改移)
//! ```
@@ -25,36 +25,48 @@
//! index_service.rs 索引与监听:独占 SQLite 连接的单线程 worker + notify
//! ```
//!
//! 设置持久化:`{app_data_dir}/notes/settings.json`(范式同 ai / translate)。
//! 默认库根:`{app_data_dir}/notes/library`;用户可在设置里改。
//! 设置持久化:`{app_data_dir}/editor/settings.json`(范式同 ai / translate)。
//! 默认库根:`{app_data_dir}/editor/library`;用户可在设置里改。
mod args;
mod backup;
mod commands;
mod dirs;
mod export;
mod files;
mod grep;
mod import;
mod index;
mod index_service;
mod library;
mod shell_menu;
mod templates;
mod types;
mod webdav;
pub use commands::{
notes_add_template, notes_authorize_file, notes_backlinks, notes_backup_now,
notes_create_folder, notes_create_note, notes_daily_note, notes_delete_entry,
notes_export_note, notes_export_snapshot_local, notes_export_zip, notes_get_settings,
notes_import, notes_index_stats, notes_library_info, notes_link_graph, notes_list_backups,
notes_list_notes, notes_list_templates, notes_open_file, notes_read_asset, notes_read_note,
notes_read_template, notes_rebuild_index, notes_rename_entry, notes_restore_backup,
notes_save_note, notes_save_settings, notes_scan_library, notes_search_notes,
notes_set_library_root, notes_set_webdav_password, notes_sync_index, notes_sync_now,
notes_tags, notes_take_pending_file, notes_test_webdav, notes_webdav_status,
notes_write_asset, notes_write_file,
editor_add_template, editor_authorize_file, editor_backlinks, editor_backup_now,
editor_create_folder, editor_create_note, editor_daily_note, editor_delete_entry,
editor_export_note, editor_export_snapshot_local, editor_export_zip, editor_get_settings,
editor_import, editor_index_stats, editor_library_info, editor_link_graph, editor_list_backups,
editor_list_notes, editor_list_templates, editor_open_file, editor_read_asset, editor_read_note,
editor_read_template, editor_rebuild_index, editor_redecode_file, editor_rename_entry,
editor_restore_backup,
editor_save_note, editor_save_settings, editor_scan_library, editor_scratch_dir, editor_search_notes,
editor_set_library_root, editor_set_webdav_password, editor_sync_index, editor_sync_now,
editor_tags, editor_take_pending_file, editor_test_webdav, editor_webdav_status,
editor_write_asset, editor_write_file,
};
pub use args::{emit_open_file, note_path_from_args, remember_pending_file};
use types::NoteSettings;
pub use args::{emit_open_target, open_target_from_args, remember_pending_target};
pub use dirs::{
editor_create_dir, editor_create_file, editor_delete_path, editor_move_path, editor_read_dir,
editor_rename_path,
};
pub use grep::{editor_replace_in_path, editor_search_in_path};
pub use shell_menu::{
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
};
use types::EditorSettings;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
@@ -65,19 +77,34 @@ const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500);
struct SettingsCache {
read_at: Instant,
settings: NoteSettings,
settings: EditorSettings,
}
/// 笔记模块管理器(Tauri State)。
pub struct NotesManager {
/// 模块自身目录:`{app_data_dir}/notes`
/// 笔记 / 编辑器模块管理器(Tauri State)。
pub struct EditorManager {
/// 模块自身目录:`{app_data_dir}/editor`
module_dir: PathBuf,
cache: Mutex<Option<SettingsCache>>,
}
impl NotesManager {
/// 一次性迁移 `{app_data_dir}/notes/` → `{app_data_dir}/editor/`(幂等)。
///
/// 仅当旧目录存在且新目录不存在时整目录重命名;两者都在则各自独立
/// (说明已在用新目录,旧目录留着不动,避免误删用户数据)。
fn migrate_legacy_module_dir(app_data_dir: &Path, module_dir: &Path) {
let legacy = app_data_dir.join("notes");
if legacy.is_dir() && !module_dir.exists() {
match std::fs::rename(&legacy, module_dir) {
Ok(()) => crate::logger::log_info("editor", "已迁移模块目录 notes/ → editor/"),
Err(e) => crate::logger::log_warn("editor", &format!("迁移模块目录失败: {e}")),
}
}
}
impl EditorManager {
pub fn new(app_data_dir: PathBuf) -> Self {
let module_dir = app_data_dir.join("notes");
let module_dir = app_data_dir.join("editor");
migrate_legacy_module_dir(&app_data_dir, &module_dir);
let _ = std::fs::create_dir_all(&module_dir);
Self {
module_dir,
@@ -100,23 +127,23 @@ impl NotesManager {
let settings = self.load_settings();
let new_note = settings.new_note_shortcut.clone();
if let Err(e) = crate::shortcut::register_shortcut(app, "notes-new-note", &new_note, |app| {
if let Err(e) = app.emit(crate::constants::events::NOTES_NEW_NOTE, ()) {
crate::logger::log_warn("notes", &format!("发出新建笔记事件失败: {e}"));
if let Err(e) = crate::shortcut::register_shortcut(app, "editor-new-note", &new_note, |app| {
if let Err(e) = app.emit(crate::constants::events::EDITOR_NEW_NOTE, ()) {
crate::logger::log_warn("editor", &format!("发出新建笔记事件失败: {e}"));
}
}) {
crate::logger::log_warn("notes", &format!("注册「新建笔记」快捷键失败: {e}"));
crate::logger::log_warn("editor", &format!("注册「新建笔记」快捷键失败: {e}"));
}
let open_editor = settings.open_editor_shortcut.clone();
if let Err(e) =
crate::shortcut::register_shortcut(app, "notes-open-editor", &open_editor, |app| {
if let Err(e) = app.emit(crate::constants::events::NOTES_OPEN_EDITOR, ()) {
crate::logger::log_warn("notes", &format!("发出打开编辑器事件失败: {e}"));
crate::shortcut::register_shortcut(app, "editor-open-editor", &open_editor, |app| {
if let Err(e) = app.emit(crate::constants::events::EDITOR_OPEN_EDITOR, ()) {
crate::logger::log_warn("editor", &format!("发出打开编辑器事件失败: {e}"));
}
})
{
crate::logger::log_warn("notes", &format!("注册「打开编辑器」快捷键失败: {e}"));
crate::logger::log_warn("editor", &format!("注册「打开编辑器」快捷键失败: {e}"));
}
}
@@ -125,7 +152,7 @@ impl NotesManager {
}
/// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。
pub fn load_settings(&self) -> NoteSettings {
pub fn load_settings(&self) -> EditorSettings {
if let Ok(cache) = self.cache.lock() {
if let Some(entry) = cache.as_ref() {
if entry.read_at.elapsed() < SETTINGS_CACHE_TTL {
@@ -136,9 +163,11 @@ impl NotesManager {
let mut settings = std::fs::read_to_string(self.settings_path())
.ok()
.and_then(|s| serde_json::from_str::<NoteSettings>(&s).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(),
@@ -147,14 +176,14 @@ impl NotesManager {
}
if healed {
if let Err(e) = self.save_settings(&settings) {
crate::logger::log_error("notes", &format!("设置自愈落盘失败: {e}"));
crate::logger::log_error("editor", &format!("设置自愈落盘失败: {e}"));
}
}
settings
}
/// 保存设置并刷新缓存。
pub fn save_settings(&self, settings: &NoteSettings) -> Result<(), String> {
pub fn save_settings(&self, settings: &EditorSettings) -> Result<(), String> {
let json = serde_json::to_string_pretty(settings)
.map_err(|e| format!("序列化笔记设置失败: {e}"))?;
std::fs::write(self.settings_path(), json)
+165
View File
@@ -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())
}
}
File renamed without changes.
@@ -1,6 +1,6 @@
//! 笔记模块的数据模型。
//!
//! 持久化位置:`{app_data_dir}/notes/settings.json`(与 ai / translate / terminal 同一范式)。
//! 持久化位置:`{app_data_dir}/editor/settings.json`(与 ai / translate / terminal 同一范式)。
//! 容器级 `#[serde(default)]`:新增字段对旧配置文件向后兼容(缺字段取
//! `Default::default()` 的对应值,而不是让整份设置反序列化失败)。
//!
@@ -10,8 +10,11 @@
use serde::{Deserialize, Serialize};
use specta::Type;
/// 结构版本号。字段增减时递增,由 [`NoteSettings::heal`] 推进。
pub const NOTES_SETTINGS_VERSION: u32 = 2;
/// 结构版本号。字段增减时递增,由 [`EditorSettings::heal`] 推进。
pub const EDITOR_SETTINGS_VERSION: u32 = 4;
/// 最近文件 / 文件夹各自的保留上限(超出淘汰最旧)。
pub const RECENT_LIMIT: usize = 20;
/// 同步方向。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -101,7 +104,7 @@ impl WebdavSettings {
}
}
/// 同步进度(事件 `notes-sync-progress` 的负载)。
/// 同步进度(事件 `editor-sync-progress` 的负载)。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SyncProgress {
@@ -155,16 +158,33 @@ pub struct ImportReport {
pub failures: Vec<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 NoteSettings {
pub struct EditorSettings {
/// 结构版本号
pub version: u32,
/// 自定义库根(`None` = 用默认 `{app_data_dir}/notes/library`)
/// 自定义库根(`None` = 用默认 `{app_data_dir}/editor/library`)
pub library_root: Option<String>,
/// 编辑器配色方案 key(`"system"` / `"vscode-dark"` / `"vscode-light"` / …)
pub editor_theme: String,
@@ -208,16 +228,20 @@ pub struct NoteSettings {
/// 全局快捷键:新建笔记(空串 = 不注册)。
///
/// 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译同一套),
/// 触发时只发 `notes-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
/// 触发时只发 `editor-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
pub new_note_shortcut: String,
/// 全局快捷键:打开编辑器窗口(空串 = 不注册)
pub open_editor_shortcut: String,
/// 最近打开的文件(与笔记库解耦;上限 [`RECENT_LIMIT`])
pub recent_files: Vec<RecentEntry>,
/// 最近打开的文件夹(与笔记库解耦;上限 [`RECENT_LIMIT`])
pub recent_folders: Vec<RecentEntry>,
}
impl Default for NoteSettings {
impl Default for EditorSettings {
fn default() -> Self {
Self {
version: NOTES_SETTINGS_VERSION,
version: EDITOR_SETTINGS_VERSION,
library_root: None,
editor_theme: "system".to_string(),
follow_app_theme: true,
@@ -227,7 +251,9 @@ impl Default for NoteSettings {
ligatures: false,
tab_size: 2,
live_preview: true,
autosave_ms: 800,
// 自动保存默认关闭:800ms 一保存会让「保存按钮 / 标签 * 号 / 侧栏」跟着
// 闪烁,干扰正常编辑。需要的人可在设置里显式开启(见 heal 的 v4 迁移)。
autosave_ms: 0,
default_view: "wysiwyg".to_string(),
show_line_numbers: true,
show_outline: true,
@@ -239,12 +265,14 @@ impl Default for NoteSettings {
show_template_picker: true,
export_highlight: true,
new_note_shortcut: String::new(),
open_editor_shortcut: String::new(),
open_editor_shortcut: "Alt+E".to_string(),
recent_files: Vec::new(),
recent_folders: Vec::new(),
}
}
}
impl NoteSettings {
impl EditorSettings {
/// 自愈:把越界/非法取值夹回合法区间,推进版本号。
/// 返回是否发生了变更(由调用方决定是否落盘)。
pub fn heal(&mut self) -> bool {
@@ -287,13 +315,47 @@ impl NoteSettings {
}
}
if self.version < NOTES_SETTINGS_VERSION {
self.version = NOTES_SETTINGS_VERSION;
// v3:引入「打开编辑器」默认快捷键 Alt+E(用户已显式设过则不覆盖)
if self.version < 3 && self.open_editor_shortcut.trim().is_empty() {
self.open_editor_shortcut = "Alt+E".to_string();
changed = true;
}
// v4:自动保存默认从 800ms 改为关闭 —— 仍是 800 说明用户从未改过这个值
//(旧默认),此时关闭它;用户显式设过的其他值一律保留。
if self.version < 4 && self.autosave_ms == 800 {
self.autosave_ms = 0;
changed = true;
}
if self.version < EDITOR_SETTINGS_VERSION {
self.version = EDITOR_SETTINGS_VERSION;
changed = true;
}
// 最近记录上限:超出淘汰最旧(列表约定为新在前)
if self.recent_files.len() > RECENT_LIMIT {
self.recent_files.truncate(RECENT_LIMIT);
changed = true;
}
if self.recent_folders.len() > RECENT_LIMIT {
self.recent_folders.truncate(RECENT_LIMIT);
changed = true;
}
changed
}
/// 刷新最近记录的「是否存在」标记(读取设置时调用,供 UI 灰显失效项)。
pub fn refresh_recent_exists(&mut self) {
for entry in self
.recent_files
.iter_mut()
.chain(self.recent_folders.iter_mut())
{
entry.exists = !entry.path.trim().is_empty() && std::path::Path::new(&entry.path).exists();
}
}
}
/// 库内一个条目(文件或目录)的扁平描述。
@@ -323,7 +385,7 @@ pub struct LibraryEntry {
pub struct LibraryInfo {
/// 当前生效的库根绝对路径
pub root: String,
/// 是否为用户自定义库根(false = 默认 `{app_data_dir}/notes/library`)
/// 是否为用户自定义库根(false = 默认 `{app_data_dir}/editor/library`)
pub is_custom: bool,
/// `.md` 笔记数量(不含目录)
pub note_count: u32,
@@ -252,7 +252,7 @@ impl WebdavClient {
if (status == 429 || status == 503) && attempt < BACKOFF_MS.len() {
let wait = BACKOFF_MS[attempt];
crate::logger::log_warn(
"notes",
"editor",
&format!("WebDAV 返回 {status},{wait}ms 后重试(第 {} 次)", attempt + 1),
);
std::thread::sleep(Duration::from_millis(wait));
@@ -265,7 +265,7 @@ impl WebdavClient {
if attempt < BACKOFF_MS.len() {
let wait = BACKOFF_MS[attempt];
crate::logger::log_warn(
"notes",
"editor",
&format!("WebDAV 请求失败({e}),{wait}ms 后重试"),
);
std::thread::sleep(Duration::from_millis(wait));
@@ -373,7 +373,7 @@ impl WebdavClient {
while let Some(dir) = queue.pop() {
depth += 1;
if depth > 4096 {
crate::logger::log_warn("notes", "远端目录过多,提前结束遍历");
crate::logger::log_warn("editor", "远端目录过多,提前结束遍历");
break;
}
let Some(entries) = self.list(&dir)? else {
@@ -664,7 +664,7 @@ fn parse_http_date(value: &str) -> Option<u64> {
/// 该远端路径是否应当排除在同步之外。
///
/// `.notes/` 是本模块的私有目录(索引 + 同步状态),**必须排除**:把索引同步到
/// `.editor/` 是本模块的私有目录(索引 + 同步状态),**必须排除**:把索引同步到
/// 远端毫无意义,且它随每次搜索变化,会让每一次同步都变成全量传输。
pub fn should_skip(rel: &str) -> bool {
let normalized = rel.replace('\\', "/");
@@ -772,7 +772,7 @@ mod tests {
#[test]
fn skip_rules_exclude_private_dir() {
assert!(should_skip(".notes/notes.db"));
assert!(should_skip(".editor/editor.db"));
assert!(should_skip("a/.hidden/b.md"));
assert!(should_skip("node_modules/x.md"));
assert!(!should_skip("notes/a.md"));
@@ -15,11 +15,11 @@ pub mod sync;
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::notes::types::WebdavSettings;
use crate::editor::types::WebdavSettings;
use client::WebdavClient;
/// keyring 里的服务名(与 `secrets.rs` 的约定一致,服务名固定 `"Thing"`)。
pub const KEYRING_PASSWORD: &str = "notes.webdav.password";
pub const KEYRING_PASSWORD: &str = "editor.webdav.password";
/// 连接自检结果(设置页展示)。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
@@ -2,7 +2,7 @@
//!
//! # 状态存在哪、为什么不是「靠时间戳猜」
//!
//! `{库根}/.notes/sync.json` 记录**上次成功同步时**每个文件的两侧指纹:
//! `{库根}/.editor/sync.json` 记录**上次成功同步时**每个文件的两侧指纹:
//! 本地内容的 hash + 本地 mtime,以及远端的 mtime。有了基线才能回答「谁改的」:
//!
//! - 本地 hash ≠ 基线 hash → 本地改了;
@@ -36,11 +36,11 @@ use tauri::{AppHandle, Emitter};
use super::client::{should_skip, WebdavClient};
use crate::constants::events;
use crate::notes::index::content_hash;
use crate::notes::library;
use crate::notes::types::{ConflictPolicy, SyncDirection, WebdavSettings};
use crate::editor::index::content_hash;
use crate::editor::library;
use crate::editor::types::{ConflictPolicy, SyncDirection, WebdavSettings};
/// 同步状态文件名(位于库根 `.notes/` 下,永不参与同步)。
/// 同步状态文件名(位于库根 `.editor/` 下,永不参与同步)。
const SYNC_STATE_FILE: &str = "sync.json";
/// 状态文件结构版本。
const SYNC_STATE_VERSION: u32 = 1;
@@ -73,7 +73,7 @@ pub struct SyncState {
impl SyncState {
/// 从库根读取状态(缺失/损坏都回退空状态 —— 最坏结果是「下次同步当作首次」)。
pub fn load(root: &Path, remote_root: &str) -> Self {
let path = root.join(".notes").join(SYNC_STATE_FILE);
let path = root.join(".editor").join(SYNC_STATE_FILE);
let mut state: SyncState = std::fs::read_to_string(&path)
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
@@ -91,7 +91,7 @@ impl SyncState {
/// 落盘。
pub fn save(&self, root: &Path) -> Result<(), String> {
let dir = root.join(".notes");
let dir = root.join(".editor");
std::fs::create_dir_all(&dir).map_err(|e| format!("创建索引目录失败: {e}"))?;
let text = serde_json::to_string_pretty(self).map_err(|e| format!("序列化同步状态失败: {e}"))?;
std::fs::write(dir.join(SYNC_STATE_FILE), text).map_err(|e| format!("写入同步状态失败: {e}"))
@@ -546,14 +546,14 @@ impl<'a> SyncRunner<'a> {
/// 发进度事件(前端据此画进度条)。
fn progress(&self, done: usize, current: &str, kind: &str) {
let payload = crate::notes::types::SyncProgress {
let payload = crate::editor::types::SyncProgress {
done: done as u32,
total: self.total as u32,
current: current.to_string(),
kind: kind.to_string(),
message: String::new(),
};
let _ = self.app.emit(events::NOTES_SYNC_PROGRESS, payload);
let _ = self.app.emit(events::EDITOR_SYNC_PROGRESS, payload);
}
/// 执行整个计划。
@@ -579,7 +579,7 @@ impl<'a> SyncRunner<'a> {
if report.failures.len() < MAX_FAILURES {
report.failures.push(format!("{}:{e}", item.rel_path));
}
crate::logger::log_warn("notes", &format!("同步 {} 失败: {e}", item.rel_path));
crate::logger::log_warn("editor", &format!("同步 {} 失败: {e}", item.rel_path));
continue;
}
match item.kind {
@@ -1078,10 +1078,10 @@ mod tests {
let root = std::env::temp_dir().join(format!("thing-notes-scan-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("notes")).unwrap();
std::fs::create_dir_all(root.join(".notes")).unwrap();
std::fs::create_dir_all(root.join(".editor")).unwrap();
std::fs::write(root.join("notes/a.md"), "x").unwrap();
std::fs::write(root.join("notes/b.txt"), "x").unwrap();
std::fs::write(root.join(".notes/notes.db"), "x").unwrap();
std::fs::write(root.join(".editor/editor.db"), "x").unwrap();
let map = scan_local(&root).unwrap();
let keys: Vec<&String> = map.keys().collect();
+100 -69
View File
@@ -10,7 +10,7 @@ mod mihomo_manager;
mod monitor_kernel;
pub mod music;
mod network_monitor;
mod notes;
mod editor;
mod osd_window;
mod process_manager;
mod quickpanel;
@@ -38,17 +38,20 @@ use download_engine::{
use logger::{
log_clear, log_info_state, log_list, log_message,
};
use notes::{
notes_add_template, notes_authorize_file, notes_backlinks, notes_backup_now,
notes_create_folder, notes_create_note, notes_daily_note, notes_delete_entry,
notes_export_note, notes_export_snapshot_local, notes_export_zip, notes_get_settings,
notes_import, notes_index_stats, notes_library_info, notes_link_graph, notes_list_backups,
notes_list_notes, notes_list_templates, notes_open_file, notes_read_asset, notes_read_note,
notes_read_template, notes_rebuild_index, notes_rename_entry, notes_restore_backup,
notes_save_note, notes_save_settings, notes_scan_library, notes_search_notes,
notes_set_library_root, notes_set_webdav_password, notes_sync_index, notes_sync_now,
notes_tags, notes_take_pending_file, notes_test_webdav, notes_webdav_status,
notes_write_asset, notes_write_file,
use editor::{
editor_add_template, editor_authorize_file, editor_backlinks, editor_backup_now,
editor_create_folder, editor_create_note, editor_daily_note, editor_delete_entry,
editor_export_note, editor_export_snapshot_local, editor_export_zip, editor_get_settings,
editor_import, editor_index_stats, editor_library_info, editor_link_graph, editor_list_backups,
editor_list_notes, editor_list_templates, editor_open_file, editor_read_asset, editor_read_note,
editor_read_template, editor_rebuild_index, editor_redecode_file, editor_rename_entry, editor_restore_backup,
editor_save_note, editor_save_settings, editor_scan_library, editor_scratch_dir, editor_search_notes,
editor_set_library_root, editor_set_webdav_password, editor_sync_index, editor_sync_now,
editor_tags, editor_take_pending_file, editor_test_webdav, editor_webdav_status,
editor_write_asset, editor_write_file,
editor_read_dir, editor_create_file, editor_create_dir, editor_rename_path, editor_delete_path,
editor_move_path, editor_search_in_path, editor_replace_in_path,
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
};
use mihomo_manager::{
proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy,
@@ -138,7 +141,7 @@ use quickpanel::{
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
quickpanel_show_window, quickpanel_unregister_shortcut, quickpanel_focus_main_window,
};
use tray_menu::{tray_menu_action, tray_menu_hide, tray_menu_ready};
use tray_menu::{tray_menu_action, tray_menu_hide, tray_menu_ready, tray_music_control, tray_music_state};
use terminal::commands::{
terminal_attach_session, terminal_clear_known_hosts, terminal_clear_session,
terminal_close_session, terminal_confirm_host_key, terminal_default_cwd, terminal_delete_host,
@@ -337,18 +340,27 @@ fn export_bindings() {
dsh_unregister_shortcut, dsh_start, dsh_stop, dsh_restart,
dsh_ai_preview, dsh_ai_sync, dsh_log_tail, dsh_install_log, dsh_log_clear,
dsh_open_dir,
// notes(39)——与 `run()` 里那份保持一致,否则 bindings.ts 缺类型
notes_get_settings, notes_save_settings, notes_library_info, notes_set_library_root,
notes_scan_library, notes_read_note, notes_save_note, notes_create_note,
notes_create_folder, notes_rename_entry, notes_delete_entry,
notes_rebuild_index, notes_sync_index, notes_search_notes, notes_list_notes,
notes_tags, notes_index_stats, notes_open_file, notes_write_file,
notes_write_asset, notes_authorize_file,
notes_list_templates, notes_add_template, notes_read_template, notes_daily_note,
notes_import, notes_export_note, notes_export_zip, notes_export_snapshot_local,
notes_webdav_status, notes_set_webdav_password, notes_test_webdav,
notes_sync_now, notes_backup_now, notes_list_backups, notes_restore_backup,
notes_backlinks, notes_link_graph, notes_take_pending_file, notes_read_asset,
// editor(40)——与 `run()` 里那份保持一致,否则 bindings.ts 缺类型
editor_get_settings, editor_save_settings, editor_library_info, editor_set_library_root,
editor_scan_library, editor_read_note, editor_save_note, editor_create_note,
editor_create_folder, editor_rename_entry, editor_delete_entry,
editor_rebuild_index, editor_sync_index, editor_search_notes, editor_list_notes,
editor_tags, editor_index_stats, editor_open_file, editor_write_file,
editor_scratch_dir,
editor_redecode_file,
editor_write_asset, editor_authorize_file,
editor_list_templates, editor_add_template, editor_read_template, editor_daily_note,
editor_import, editor_export_note, editor_export_zip, editor_export_snapshot_local,
editor_webdav_status, editor_set_webdav_password, editor_test_webdav,
editor_sync_now, editor_backup_now, editor_list_backups, editor_restore_backup,
editor_backlinks, editor_link_graph, editor_take_pending_file, editor_read_asset,
// 本地目录树(P3-5)
editor_read_dir, editor_create_file, editor_create_dir, editor_rename_path,
editor_delete_path, editor_move_path,
// 在路径中查找 / 替换(统一搜索器的「当前目录 / 笔记库」范围)
editor_search_in_path, editor_replace_in_path,
// 系统集成(P4-4)
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
])
.export(Typescript::default(), "../src/lib/bindings.ts")
.expect("failed to export bindings");
@@ -384,11 +396,13 @@ pub fn run() {
let _ = window.unminimize();
let _ = window.set_focus();
}
match crate::notes::note_path_from_args(argv.clone()) {
Some(path) => crate::notes::emit_open_file(app, &path),
// argv[0] 是第二个实例自身的 exe 路径(插件传的是完整命令行),必须跳过 ——
// 否则 `open_target_from_args` 会把 exe 当成「要打开的文件」返回。
match crate::editor::open_target_from_args(argv.into_iter().skip(1)) {
Some(target) => crate::editor::emit_open_target(app, &target),
None => {
// 没有文件参数(用户又点了一次快捷方式):只把主窗口叫到前面,别开新窗口
crate::logger::log_info("notes", "第二个实例无文件参数,仅聚焦主窗口");
crate::logger::log_info("editor", "第二个实例无文件参数,仅聚焦主窗口");
}
}
}))
@@ -618,6 +632,8 @@ pub fn run() {
tray_menu_action,
tray_menu_hide,
tray_menu_ready,
tray_music_state,
tray_music_control,
snap_fix::fix_snap_background,
screenshot_capture_fullscreen,
screenshot_get_fullscreen_bmp,
@@ -812,47 +828,62 @@ pub fn run() {
dsh_install_log,
dsh_log_clear,
dsh_open_dir,
// notes(39)
notes_get_settings,
notes_save_settings,
notes_library_info,
notes_set_library_root,
notes_scan_library,
notes_read_note,
notes_save_note,
notes_create_note,
notes_create_folder,
notes_rename_entry,
notes_delete_entry,
notes_rebuild_index,
notes_sync_index,
notes_search_notes,
notes_list_notes,
notes_tags,
notes_index_stats,
notes_open_file,
notes_write_file,
notes_write_asset,
notes_authorize_file,
notes_list_templates,
notes_add_template,
notes_read_template,
notes_daily_note,
notes_import,
notes_export_note,
notes_export_zip,
notes_export_snapshot_local,
notes_webdav_status,
notes_set_webdav_password,
notes_test_webdav,
notes_sync_now,
notes_backup_now,
notes_list_backups,
notes_restore_backup,
notes_backlinks,
notes_link_graph,
notes_take_pending_file,
notes_read_asset
// editor(39)
editor_get_settings,
editor_save_settings,
editor_library_info,
editor_set_library_root,
editor_scan_library,
editor_read_note,
editor_save_note,
editor_create_note,
editor_create_folder,
editor_rename_entry,
editor_delete_entry,
editor_rebuild_index,
editor_sync_index,
editor_search_notes,
editor_list_notes,
editor_tags,
editor_index_stats,
editor_open_file,
editor_scratch_dir,
editor_write_file,
editor_redecode_file,
editor_write_asset,
editor_authorize_file,
editor_list_templates,
editor_add_template,
editor_read_template,
editor_daily_note,
editor_import,
editor_export_note,
editor_export_zip,
editor_export_snapshot_local,
editor_webdav_status,
editor_set_webdav_password,
editor_test_webdav,
editor_sync_now,
editor_backup_now,
editor_list_backups,
editor_restore_backup,
editor_backlinks,
editor_link_graph,
editor_take_pending_file,
editor_read_asset,
// 本地目录树(P3-5)
editor_read_dir,
editor_create_file,
editor_create_dir,
editor_rename_path,
editor_delete_path,
editor_move_path,
editor_search_in_path,
editor_replace_in_path,
// 系统集成(P4-4)
editor_context_menu_status,
editor_register_context_menu,
editor_unregister_context_menu
])
.setup(setup::init)
.on_window_event(|window, event| {
+1 -1
View File
@@ -43,7 +43,7 @@ pub use remote::{
pub use smtc::{
music_smtc_clear, music_smtc_update_metadata, music_smtc_update_playback_state,
music_smtc_update_position, SmtcController,
music_smtc_update_position, SmtcController, SMTC_BUTTON_EVENT,
};
pub use commands::{
-153
View File
@@ -1,153 +0,0 @@
//! 「用 Thing 打开」的参数解析与事件投递。
//!
//! # 两条入口,同一份逻辑
//!
//! 1. **冷启动**:安装器注册的文件关联让 Windows 用 `thing.exe <文件路径>` 启动本应用;
//! 2. **热启动**:应用已在运行时双击 `.md`,会起第二个进程,由
//! `tauri-plugin-single-instance` 把它的命令行参数转交给第一个实例。
//!
//! 两条路径的输入形态完全一样(都是命令行参数),因此共用 [`note_path_from_args`]。
//! 解析成功后统一发 [`crate::constants::events::NOTES_OPEN_FILE`],**窗口由前端创建** ——
//! Rust 侧不持有窗口 label 策略,也不该知道「用户是不是想让它在已有窗口里打开」。
use std::path::{Path, PathBuf};
use std::sync::Mutex;
/// 「启动时命令行指定的文件」缓存。
///
/// # 为什么需要缓存而不是启动时直接 `emit`
///
/// 冷启动的顺序是:`setup` 跑完 → 创建主窗口 → WebView 加载前端 → 前端注册监听。
/// 在 `setup` 里 `emit` 时前端还没开始监听,事件**直接丢掉**了 —— 表现是
/// 「双击 .md 打开了应用,但笔记没打开」。
///
/// 因此这里把路径存下来,由前端在注册完监听后**主动取一次**
/// (`notes_take_pending_file`)。取走即清空,避免下次打开窗口时又被翻出来。
static PENDING: std::sync::OnceLock<Mutex<Option<PathBuf>>> = std::sync::OnceLock::new();
fn pending_slot() -> &'static Mutex<Option<PathBuf>> {
PENDING.get_or_init(|| Mutex::new(None))
}
/// 记下「启动时想打开的文件」(由 `setup` 调用)。
pub fn remember_pending_file(path: PathBuf) {
if let Ok(mut slot) = pending_slot().lock() {
*slot = Some(path);
}
}
/// 取出并清空待打开文件(由 `notes_take_pending_file` 命令调用)。
pub fn take_pending_file() -> Option<PathBuf> {
pending_slot()
.lock()
.ok()
.and_then(|mut slot| slot.take())
}
/// 从一组命令行参数里挑出「看起来是笔记文件」的那个路径。
///
/// # 为什么需要挑而不是直接用 `args[1]`
///
/// 关联启动时命令行长这样:`thing.exe D:\笔记\会议.md`;
/// 但从「开始菜单 → 打开」启动时可能有别的开关参数;开发模式下还有 `cargo run --`。
/// 这里只认「**存在**的文件 + 笔记类扩展名」,其余一律忽略 ——
/// 宁可漏开一个窗口,也不要因为一个参数把主窗口的启动逻辑搞乱。
///
/// 认的扩展名比「只有 .md」宽一点:`.markdown` / `.mdx` 也常见,且编辑器都能处理
/// (打开后走「库外文件」路径,不影响库内笔记的 `.md` 约定)。
///
/// # 为什么要 `.is_file()`
///
/// 参数里出现 `foo.md` 但那个文件其实不存在(用户删了、路径编码错了)时,
/// 让前端去报「文件不存在」不如在这里就静默忽略 —— 前端那条路径会开一个空窗口。
pub fn note_path_from_args<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_file(app: &tauri::AppHandle, path: &Path) {
use tauri::Emitter;
let payload = serde_json::json!({ "path": path.to_string_lossy() });
if let Err(e) = app.emit(crate::constants::events::NOTES_OPEN_FILE, payload) {
crate::logger::log_warn("notes", &format!("发出打开文件事件失败: {e}"));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_note(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("thing-notes-args-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join(name);
std::fs::write(&path, "# x").unwrap();
path
}
#[test]
fn picks_markdown_path_and_ignores_flags() {
let note = temp_note("会议.md");
let args = vec![
"--some-flag".to_string(),
"not-a-file".to_string(),
note.to_string_lossy().to_string(),
];
assert_eq!(note_path_from_args(args), Some(note.clone()));
let _ = std::fs::remove_file(&note);
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(&note);
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(&note);
let _ = std::fs::remove_dir_all(note.parent().unwrap());
}
}
+7 -7
View File
@@ -21,7 +21,7 @@ use crate::mihomo_manager::MihomoManager;
use crate::monitor_kernel::{MonitorKernel, check_and_relaunch_if_needed};
use crate::music::MusicManager;
use crate::network_monitor::NetworkMonitor;
use crate::notes::NotesManager;
use crate::editor::EditorManager;
use crate::process_manager::{ProcessManager, start_monitoring_thread};
use crate::terminal::TerminalManager;
use crate::translate::TranslateManager;
@@ -84,19 +84,19 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
let dsh = crate::dsh::DshManager::new(app_data_dir.clone());
app.manage(dsh);
// ===== 笔记模块:NotesManager =====
// ===== 笔记模块:EditorManager =====
// 仅注册状态:库扫描与读写都在命令调用时按需触发,启动阶段只创建目录结构。
let notes = NotesManager::new(app_data_dir.clone());
let notes = EditorManager::new(app_data_dir.clone());
let _ = notes.load_settings();
// 按设置注册「新建笔记 / 打开编辑器」两个全局快捷键(失败只记日志,不阻断启动)
notes.init_on_launch(app.handle());
app.manage(notes);
// 「用 Thing 打开」的**冷启动**路径:命令行里带了 .md 就记下来。
// 不在这里 `emit` —— 此时 WebView 还没加载、前端还没注册监听,事件会丢掉。
// 前端注册完监听后会主动调 `notes_take_pending_file` 取走(见 notes/args.rs)。
if let Some(path) = crate::notes::note_path_from_args(std::env::args().skip(1)) {
crate::logger::log_info("notes", &format!("命令行指定打开: {}", path.display()));
crate::notes::remember_pending_file(path);
// 前端注册完监听后会主动调 `editor_take_pending_file` 取走(见 editor/args.rs)。
if let Some(target) = crate::editor::open_target_from_args(std::env::args().skip(1)) {
crate::logger::log_info("editor", &format!("命令行指定打开: {}", target.path().display()));
crate::editor::remember_pending_target(target);
}
// ===== 翻译模块:TranslateManager =====
+86 -6
View File
@@ -27,6 +27,7 @@ static LAST_MENU_LAYOUT: Mutex<Option<(f64, f64, f64, f64, f64)>> = Mutex::new(N
use crate::win32_util::{get_work_area, get_monitor_bounds_at_point, get_dpi_for_point};
use crate::mihomo_manager::{MihomoManager, is_pseudo_node};
use crate::monitor_kernel::MonitorKernel;
use crate::music::{AudioEngine, SmtcMetaCache, SMTC_BUTTON_EVENT};
use crate::process_manager::{ProcessManager, ProcessStatus};
/// 托盘菜单窗口标签
@@ -53,6 +54,34 @@ pub struct TrayMenuState {
pub proxy_current: Option<String>,
}
/// 托盘音乐控制条状态。
///
/// 曲目信息取自 [`SmtcMetaCache`](前端推给 SMTC 的元数据回填),
/// 播放态取自 [`AudioEngine`]:两者都在 Rust 侧,托盘菜单只需一次拉取。
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct MusicState {
pub playing: bool,
pub title: String,
pub artist: String,
}
fn get_music_state(app: &AppHandle) -> MusicState {
let playing = app
.try_state::<AudioEngine>()
.map(|e| e.state().playing)
.unwrap_or(false);
let (title, artist) = app
.try_state::<SmtcMetaCache>()
.and_then(|c| c.0.lock().ok().map(|g| (g.title.clone(), g.artist.clone())))
.unwrap_or_default();
MusicState {
playing,
title,
artist,
}
}
// ===== 状态查询 =====
fn is_proxy_running(app: &AppHandle) -> bool {
@@ -420,14 +449,18 @@ pub async fn tray_menu_action(
send_notification(&app, "Kernel 重启失败", &e);
}
}
"download_new" => {
focus_main_window(&app);
let _ = app.emit(crate::constants::events::TRAY_NEW_DOWNLOAD, ());
"terminal" => {
// 新建终端选择窗口由前端创建(label 需命中 terminal-window-* 授权)
let _ = app.emit(crate::constants::events::TRAY_OPEN_TERMINAL, ());
hide_tray_menu(&app);
}
"settings" => {
focus_main_window(&app);
let _ = app.emit(crate::constants::events::TRAY_OPEN_SETTINGS, ());
"dsh" => {
// 未启动时前端会先开进度窗口并同步拉起服务
let _ = app.emit(crate::constants::events::TRAY_OPEN_DSH, ());
hide_tray_menu(&app);
}
"editor" => {
let _ = app.emit(crate::constants::events::TRAY_OPEN_EDITOR, ());
hide_tray_menu(&app);
}
"quit" => {
@@ -463,6 +496,37 @@ pub async fn tray_menu_hide(app: AppHandle) -> Result<(), String> {
Ok(())
}
/// 读取音乐控制条状态(托盘菜单显示时 / 可见期间轮询)。
#[tauri::command]
pub fn tray_music_state(app: AppHandle) -> MusicState {
get_music_state(&app)
}
/// 托盘音乐控制条动作。
///
/// 动作统一经 [`SMTC_BUTTON_EVENT`] 转给主窗口前端(`feiniuStore`)执行——
/// 队列、洗牌、单曲循环等播放语义都在前端,托盘只负责转发,不重复实现。
/// `action`:`toggle` | `play` | `pause` | `next` | `prev`。
#[tauri::command]
pub fn tray_music_control(app: AppHandle, action: String) -> Result<(), String> {
let name = match action.as_str() {
"play" => "play",
"pause" => "pause",
// 无当前会话时按下「播放/暂停」应重新起播,故按引擎真实态决定
"toggle" => {
if get_music_state(&app).playing {
"pause"
} else {
"play"
}
}
"next" => "next",
"prev" => "prev",
other => return Err(format!("未知的音乐控制动作: {other}")),
};
app.emit(SMTC_BUTTON_EVENT, name).map_err(|e| e.to_string())
}
/// 前端测量内容高度后调用:调整窗口大小、精确定位、然后显示。
/// 这样窗口从一开始就是正确尺寸和位置,不会出现间隙。
#[tauri::command]
@@ -502,6 +566,22 @@ pub async fn tray_menu_ready(content_height: f64, app: AppHandle) -> Result<(),
let mut t = LAST_SHOW_TIME.lock().unwrap_or_else(|e| e.into_inner());
*t = Some(Instant::now());
}
// 位置与尺寸先交给一次原生 SetWindowPos 落位:窗口隐藏时,上面的 set_size/set_position
// 不保证在紧随其后的 show 之前生效,首次弹出会沿用预创建时的旧高度——表现为
// 「第一次高度不对、收起后再开正常」。原生调用同步返回,窗口已处于目标位置与尺寸。
// 显示仍走 Tauri 的 show():它才会做 tao 的可见性/激活/Z 序处理(直接 SWP_SHOWWINDOW
// 会让菜单掉到任务栏后面,且窗口拿不到焦点,失焦自动关闭随之失效)。
#[cfg(windows)]
if let Ok(hwnd) = win.hwnd() {
crate::win32_util::set_bounds(
hwnd.0 as isize,
x as i32,
y as i32,
win_w_px as i32,
win_h_px as i32,
);
}
let _ = win.show();
let _ = win.set_focus();
+42
View File
@@ -233,6 +233,45 @@ pub fn hide_window(hwnd: isize) {
}
}
/// 一次调用原子地设置窗口位置与**客户区**尺寸(物理像素),不改变可见性与 Z 序。
///
/// `w`/`h` 是客户区(内容区)尺寸,不是外框尺寸——调用方量的是内容高度,这里负责换算:
/// `SetWindowPos` 的宽高按**外框**算,而无边框 + 阴影的窗口外侧还有一段 DWM 阴影边距,
/// 直接把它当外框传会把客户区压小、内容底下被裁掉。换算方式与 tao 的 `set_inner_size`
/// 一致:用 `GetWindowRect - GetClientRect` 得到这段隐藏偏移后补上去。
///
/// 存在的理由:窗口处于隐藏态时,Tauri 的 `set_size`/`set_position` 不保证在紧随其后的
/// `show` 之前落到窗口上——托盘菜单首次弹出因此沿用预创建时的旧高度,收起后再开才正常。
/// `SetWindowPos` 是同步调用,返回时窗口已在目标位置与尺寸上;先由它落位、再走 Tauri 的
/// `show()`,首次显示即为最终尺寸且无中间帧。
///
/// 注意**不要**在这里加 `SWP_SHOWWINDOW`:那会绕开 tao 的可见性/激活处理,
/// 窗口既不置顶(掉到任务栏后面)也拿不到焦点(继而不能靠失焦自动关闭)。
#[cfg(windows)]
pub fn set_bounds(hwnd: isize, x: i32, y: i32, w: i32, h: i32) {
use windows_sys::Win32::Foundation::RECT;
use windows_sys::Win32::UI::WindowsAndMessaging::{
GetClientRect, GetWindowRect, SetWindowPos, SWP_NOACTIVATE, SWP_NOZORDER,
};
unsafe {
let (mut wr, mut cr): (RECT, RECT) = (std::mem::zeroed(), std::mem::zeroed());
if GetWindowRect(hwnd, &mut wr) == 0 || GetClientRect(hwnd, &mut cr) == 0 {
return;
}
let frame_w = (wr.right - wr.left) - (cr.right - cr.left);
let frame_h = (wr.bottom - wr.top) - (cr.bottom - cr.top);
SetWindowPos(
hwnd,
0,
x,
y,
w + frame_w,
h + frame_h,
SWP_NOACTIVATE | SWP_NOZORDER,
);
}
}
/// 系统自上次用户输入(鼠标/键盘)以来的空闲时长(毫秒)。
/// 用于闲时执行耗时后台任务(如文件索引构建),避免与应用运行/用户操作抢 IO。
/// GetLastInputInfo 的 dwTime 与 GetTickCount 同为系统启动后毫秒数,用 wrapping 减法防回绕。
@@ -288,5 +327,8 @@ pub fn show_no_activate(_hwnd: isize) {}
#[cfg(not(windows))]
pub fn hide_window(_hwnd: isize) {}
#[cfg(not(windows))]
pub fn set_bounds(_hwnd: isize, _x: i32, _y: i32, _w: i32, _h: i32) {}
#[cfg(not(windows))]
pub fn get_idle_time_ms() -> u64 { 0 }
+2 -2
View File
@@ -41,8 +41,8 @@
"fileAssociations": [
{
"ext": ["md", "markdown", "mdx"],
"name": "Markdown 笔记",
"description": "用 Thing 打开 Markdown 笔记",
"name": "Markdown 文档",
"description": "用 Thing 编辑器打开 Markdown 文档",
"role": "Editor"
}
],