199 lines
7.7 KiB
Rust
199 lines
7.7 KiB
Rust
//! 笔记 / 编辑器模块。
|
||
//!
|
||
//! 架构位置:
|
||
//!
|
||
//! ```text
|
||
//! 主模块页(设置 / 库管理) 独立窗口(CM6 编辑器)
|
||
//! ↓ Tauri IPC ↓
|
||
//! commands.rs 命令层
|
||
//! ↓
|
||
//! EditorManager(本文件):设置读写 / 库根解析
|
||
//! ↓
|
||
//! library.rs 文件系统(路径安全 / 扫描 / 读写 / 增删改移)
|
||
//! ```
|
||
//!
|
||
//! # 真相在文件
|
||
//!
|
||
//! 笔记 = 库根下的 `.md` 文件树。Rust 侧只做文件 IO 与设置持久化,
|
||
//! **不引入私有格式**;SQLite 索引(`index.rs`)只是可重建的加速层。
|
||
//!
|
||
//! # 三个入口的职责边界
|
||
//!
|
||
//! ```text
|
||
//! library.rs 库内笔记:相对路径 + 树 + front-matter(安全模型 = 根目录沙箱)
|
||
//! files.rs 库外任意文件:绝对路径 + 编码/换行(安全模型 = 授权白名单)
|
||
//! index_service.rs 索引与监听:独占 SQLite 连接的单线程 worker + notify
|
||
//! ```
|
||
//!
|
||
//! 设置持久化:`{app_data_dir}/editor/settings.json`(范式同 ai / translate)。
|
||
//! 默认库根:`{app_data_dir}/editor/library`;用户可在设置里改。
|
||
|
||
mod args;
|
||
mod backup;
|
||
mod commands;
|
||
mod dirs;
|
||
mod export;
|
||
mod files;
|
||
mod grep;
|
||
mod import;
|
||
mod index;
|
||
mod index_service;
|
||
mod library;
|
||
mod shell_menu;
|
||
mod templates;
|
||
mod types;
|
||
mod webdav;
|
||
|
||
pub use commands::{
|
||
editor_add_template, editor_authorize_file, editor_backlinks, editor_backup_now,
|
||
editor_create_folder, editor_create_note, editor_daily_note, editor_delete_entry,
|
||
editor_export_note, editor_export_snapshot_local, editor_export_zip, editor_get_settings,
|
||
editor_import, editor_index_stats, editor_library_info, editor_link_graph, editor_list_backups,
|
||
editor_list_notes, editor_list_templates, editor_open_file, editor_read_asset, editor_read_note,
|
||
editor_read_template, editor_rebuild_index, editor_redecode_file, editor_rename_entry,
|
||
editor_restore_backup,
|
||
editor_save_note, editor_save_settings, editor_scan_library, editor_scratch_dir, editor_search_notes,
|
||
editor_set_library_root, editor_set_webdav_password, editor_sync_index, editor_sync_now,
|
||
editor_tags, editor_take_pending_file, editor_test_webdav, editor_webdav_status,
|
||
editor_write_asset, editor_write_file,
|
||
};
|
||
pub use args::{emit_open_target, open_target_from_args, remember_pending_target};
|
||
pub use dirs::{
|
||
editor_create_dir, editor_create_file, editor_delete_path, editor_move_path, editor_read_dir,
|
||
editor_rename_path,
|
||
};
|
||
pub use grep::{editor_replace_in_path, editor_search_in_path};
|
||
pub use shell_menu::{
|
||
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
|
||
};
|
||
use types::EditorSettings;
|
||
|
||
use std::path::{Path, PathBuf};
|
||
use std::sync::Mutex;
|
||
use std::time::{Duration, Instant};
|
||
|
||
/// 设置内存缓存有效期(与 ai / translate / terminal 的 500ms 一致)。
|
||
const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500);
|
||
|
||
struct SettingsCache {
|
||
read_at: Instant,
|
||
settings: EditorSettings,
|
||
}
|
||
|
||
/// 笔记 / 编辑器模块管理器(Tauri State)。
|
||
pub struct EditorManager {
|
||
/// 模块自身目录:`{app_data_dir}/editor`
|
||
module_dir: PathBuf,
|
||
cache: Mutex<Option<SettingsCache>>,
|
||
}
|
||
|
||
/// 一次性迁移 `{app_data_dir}/notes/` → `{app_data_dir}/editor/`(幂等)。
|
||
///
|
||
/// 仅当旧目录存在且新目录不存在时整目录重命名;两者都在则各自独立
|
||
/// (说明已在用新目录,旧目录留着不动,避免误删用户数据)。
|
||
fn migrate_legacy_module_dir(app_data_dir: &Path, module_dir: &Path) {
|
||
let legacy = app_data_dir.join("notes");
|
||
if legacy.is_dir() && !module_dir.exists() {
|
||
match std::fs::rename(&legacy, module_dir) {
|
||
Ok(()) => crate::logger::log_info("editor", "已迁移模块目录 notes/ → editor/"),
|
||
Err(e) => crate::logger::log_warn("editor", &format!("迁移模块目录失败: {e}")),
|
||
}
|
||
}
|
||
}
|
||
|
||
impl EditorManager {
|
||
pub fn new(app_data_dir: PathBuf) -> Self {
|
||
let module_dir = app_data_dir.join("editor");
|
||
migrate_legacy_module_dir(&app_data_dir, &module_dir);
|
||
let _ = std::fs::create_dir_all(&module_dir);
|
||
Self {
|
||
module_dir,
|
||
cache: Mutex::new(None),
|
||
}
|
||
}
|
||
|
||
/// 模块自身目录(库根默认值基于它解析)。
|
||
pub fn module_dir(&self) -> &Path {
|
||
&self.module_dir
|
||
}
|
||
|
||
/// 启动时按设置注册全局快捷键。
|
||
///
|
||
/// 失败只记日志:快捷键被别的应用占了不该阻断启动(与 translate / terminal 同一姿态)。
|
||
/// 触发时**只发事件**,窗口与「新建哪一篇」由前端决定 —— Rust 侧不持有窗口 label
|
||
/// 策略,也不该知道当前打开的库是哪一篇(那是前端 store 的事)。
|
||
pub fn init_on_launch(&self, app: &tauri::AppHandle) {
|
||
use tauri::Emitter;
|
||
let settings = self.load_settings();
|
||
|
||
let new_note = settings.new_note_shortcut.clone();
|
||
if let Err(e) = crate::shortcut::register_shortcut(app, "editor-new-note", &new_note, |app| {
|
||
if let Err(e) = app.emit(crate::constants::events::EDITOR_NEW_NOTE, ()) {
|
||
crate::logger::log_warn("editor", &format!("发出新建笔记事件失败: {e}"));
|
||
}
|
||
}) {
|
||
crate::logger::log_warn("editor", &format!("注册「新建笔记」快捷键失败: {e}"));
|
||
}
|
||
|
||
let open_editor = settings.open_editor_shortcut.clone();
|
||
if let Err(e) =
|
||
crate::shortcut::register_shortcut(app, "editor-open-editor", &open_editor, |app| {
|
||
if let Err(e) = app.emit(crate::constants::events::EDITOR_OPEN_EDITOR, ()) {
|
||
crate::logger::log_warn("editor", &format!("发出打开编辑器事件失败: {e}"));
|
||
}
|
||
})
|
||
{
|
||
crate::logger::log_warn("editor", &format!("注册「打开编辑器」快捷键失败: {e}"));
|
||
}
|
||
}
|
||
|
||
fn settings_path(&self) -> PathBuf {
|
||
self.module_dir.join("settings.json")
|
||
}
|
||
|
||
/// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。
|
||
pub fn load_settings(&self) -> EditorSettings {
|
||
if let Ok(cache) = self.cache.lock() {
|
||
if let Some(entry) = cache.as_ref() {
|
||
if entry.read_at.elapsed() < SETTINGS_CACHE_TTL {
|
||
return entry.settings.clone();
|
||
}
|
||
}
|
||
}
|
||
|
||
let mut settings = std::fs::read_to_string(self.settings_path())
|
||
.ok()
|
||
.and_then(|s| serde_json::from_str::<EditorSettings>(&s).ok())
|
||
.unwrap_or_default();
|
||
let healed = settings.heal();
|
||
// 刷新「最近记录」的存在性(只读,不触发落盘)
|
||
settings.refresh_recent_exists();
|
||
if let Ok(mut cache) = self.cache.lock() {
|
||
*cache = Some(SettingsCache {
|
||
read_at: Instant::now(),
|
||
settings: settings.clone(),
|
||
});
|
||
}
|
||
if healed {
|
||
if let Err(e) = self.save_settings(&settings) {
|
||
crate::logger::log_error("editor", &format!("设置自愈落盘失败: {e}"));
|
||
}
|
||
}
|
||
settings
|
||
}
|
||
|
||
/// 保存设置并刷新缓存。
|
||
pub fn save_settings(&self, settings: &EditorSettings) -> Result<(), String> {
|
||
let json = serde_json::to_string_pretty(settings)
|
||
.map_err(|e| format!("序列化笔记设置失败: {e}"))?;
|
||
std::fs::write(self.settings_path(), json)
|
||
.map_err(|e| format!("写入笔记设置失败: {e}"))?;
|
||
if let Ok(mut cache) = self.cache.lock() {
|
||
*cache = Some(SettingsCache {
|
||
read_at: Instant::now(),
|
||
settings: settings.clone(),
|
||
});
|
||
}
|
||
Ok(())
|
||
}
|
||
} |