编辑器模块(笔记)初版

This commit is contained in:
zhongluofeng committed 2026-09-30 18:12:53 +08:00
1 parent 7e65825d3e
commit ad987111a3
66 files changed
+17470 -283

No files matched your search

+170
View File
@@ -0,0 +1,170 @@
//! 笔记 / 编辑器模块。
//!
//! 架构位置:
//!
//! ```text
//! 主模块页(设置 / 库管理) 独立窗口(CM6 编辑器)
//! ↓ Tauri IPC ↓
//! commands.rs 命令层
//! ↓
//! NotesManager(本文件):设置读写 / 库根解析
//! ↓
//! library.rs 文件系统(路径安全 / 扫描 / 读写 / 增删改移)
//! ```
//!
//! # 真相在文件
//!
//! 笔记 = 库根下的 `.md` 文件树。Rust 侧只做文件 IO 与设置持久化,
//! **不引入私有格式**;SQLite 索引(`index.rs`)只是可重建的加速层。
//!
//! # 三个入口的职责边界
//!
//! ```text
//! library.rs 库内笔记:相对路径 + 树 + front-matter(安全模型 = 根目录沙箱)
//! files.rs 库外任意文件:绝对路径 + 编码/换行(安全模型 = 授权白名单)
//! index_service.rs 索引与监听:独占 SQLite 连接的单线程 worker + notify
//! ```
//!
//! 设置持久化:`{app_data_dir}/notes/settings.json`(范式同 ai / translate)。
//! 默认库根:`{app_data_dir}/notes/library`;用户可在设置里改。
mod args;
mod backup;
mod commands;
mod export;
mod files;
mod import;
mod index;
mod index_service;
mod library;
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,
};
pub use args::{emit_open_file, note_path_from_args, remember_pending_file};
use types::NoteSettings;
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: NoteSettings,
}
/// 笔记模块管理器(Tauri State)。
pub struct NotesManager {
/// 模块自身目录:`{app_data_dir}/notes`
module_dir: PathBuf,
cache: Mutex<Option<SettingsCache>>,
}
impl NotesManager {
pub fn new(app_data_dir: PathBuf) -> Self {
let module_dir = app_data_dir.join("notes");
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, "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}"));
}
}) {
crate::logger::log_warn("notes", &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::logger::log_warn("notes", &format!("注册「打开编辑器」快捷键失败: {e}"));
}
}
fn settings_path(&self) -> PathBuf {
self.module_dir.join("settings.json")
}
/// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。
pub fn load_settings(&self) -> NoteSettings {
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::<NoteSettings>(&s).ok())
.unwrap_or_default();
let healed = settings.heal();
if let Ok(mut cache) = self.cache.lock() {
*cache = Some(SettingsCache {
read_at: Instant::now(),
settings: settings.clone(),
});
}
if healed {
if let Err(e) = self.save_settings(&settings) {
crate::logger::log_error("notes", &format!("设置自愈落盘失败: {e}"));
}
}
settings
}
/// 保存设置并刷新缓存。
pub fn save_settings(&self, settings: &NoteSettings) -> 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(())
}
}