1 Commits
Author SHA1 Message Date
zhongluofeng 6f875bd7b4 模块调整 2026-10-28 15:57:31 +08:00
23 changed files with 538 additions and 116 deletions

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "thing", "name": "thing",
"private": true, "private": true,
"version": "26.10.1", "version": "26.10.2",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
+1 -1
View File
@@ -7658,7 +7658,7 @@ dependencies = [
[[package]] [[package]]
name = "thing" name = "thing"
version = "26.10.1" version = "26.10.2"
dependencies = [ dependencies = [
"aes 0.8.4", "aes 0.8.4",
"async-trait", "async-trait",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "thing" name = "thing"
version = "26.10.1" version = "26.10.2"
description = "A Tauri App" description = "A Tauri App"
authors = ["you"] authors = ["you"]
edition = "2021" edition = "2021"
+5
View File
@@ -9,6 +9,7 @@ mod drag_drop;
mod dsh; mod dsh;
mod logger; mod logger;
mod mihomo_manager; mod mihomo_manager;
mod module_state;
mod monitor_kernel; mod monitor_kernel;
pub mod music; pub mod music;
mod network_monitor; mod network_monitor;
@@ -42,6 +43,7 @@ use download_engine::{
use logger::{ use logger::{
log_clear, log_info_state, log_list, log_message, log_clear, log_info_state, log_list, log_message,
}; };
use module_state::module_sync_states;
use editor::{ use editor::{
editor_add_template, editor_authorize_file, editor_backlinks, editor_backup_now, editor_add_template, editor_authorize_file, editor_backlinks, editor_backup_now,
editor_create_folder, editor_create_note, editor_daily_note, editor_delete_entry, editor_create_folder, editor_create_note, editor_daily_note, editor_delete_entry,
@@ -253,6 +255,8 @@ fn export_bindings() {
// 应用更新(6) // 应用更新(6)
app_version, update_check, update_install, update_thinghk_apply, app_version, update_check, update_install, update_thinghk_apply,
update_thinghk_confirm, update_thinghk_cancel, update_thinghk_confirm, update_thinghk_cancel,
// 模块启停(1)
module_sync_states,
// proxy(20) // proxy(20)
proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy, proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy,
proxy_close_connection, proxy_confirm_install, proxy_delete_profile, proxy_get_settings, proxy_close_connection, proxy_confirm_install, proxy_delete_profile, proxy_get_settings,
@@ -495,6 +499,7 @@ pub fn run() {
update_thinghk_apply, update_thinghk_apply,
update_thinghk_confirm, update_thinghk_confirm,
update_thinghk_cancel, update_thinghk_cancel,
module_sync_states,
process_start, process_start,
process_stop, process_stop,
process_status, process_status,
+231
View File
@@ -0,0 +1,231 @@
//! 模块启停状态的 Rust 侧镜像与统一同步入口。
//!
//! 前端把「已禁用模块列表」持久化在 WebView 的 localStorage 里,Rust 启动阶段
//! (WebView 就绪之前)读不到它。于是会出现:用户在设置里禁用了截图 / 编辑器 /
//! 翻译等模块,重启后 Rust 仍按「全部启用」注册全局快捷键、自动拉起后台服务、
//! 预创建常驻窗口。
//!
//! 这里的做法:
//! - 前端在启动完成和每次切换模块后调用 [`module_sync_states`],把完整禁用列表
//! 落到 `{app_data_dir}/module_states.json`,并立即同步 Rust 侧副作用;
//! - `setup` 启动阶段先读该文件,再决定是否注册快捷键 / 自动启动 / 预创建窗口。
//!
//! 只覆盖 Rust 侧拥有的资源;前端拥有的资源(终端会话、播放器、OSD store 等)
//! 由各模块自己的 `onEnable` / `onDisable` 生命周期处理。
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Manager};
use crate::clipboard::ClipboardManager;
use crate::diff::DiffManager;
use crate::editor::EditorManager;
const FILE_NAME: &str = "module_states.json";
/// 文件尚未生成(首次启动)时的兜底:与各模块 `defaultEnabled` 保持一致。
const DEFAULT_DISABLED: &[&str] = &["smarthome"];
/// `setup` 是否已返回。启动期间主线程正在逐个创建隐藏窗口(剪贴板 / 快速面板 /
/// 托盘菜单…)并阻塞在 WebView2 初始化上;此时若 IPC 线程在本命令里同步发起
/// 窗口创建或快捷键注册,主线程与 IPC 线程会互等 —— 浏览器进程随之冻结,
/// 表现为「进程在、主窗口不显示、所有 IPC 无响应」。因此启动阶段只落盘,
/// 副作用延后到 [`finish_setup`]。
static SETUP_DONE: AtomicBool = AtomicBool::new(false);
/// 启动阶段收到的禁用列表(最后一次),由 [`finish_setup`] 补应用。
static PENDING_DISABLED: Mutex<Option<Vec<String>>> = Mutex::new(None);
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ModuleStatesFile {
/// 已禁用模块 id(完整列表;未列出的按启用处理)
#[serde(default)]
disabled: Vec<String>,
}
fn file_path(app_data_dir: &Path) -> PathBuf {
app_data_dir.join(FILE_NAME)
}
/// 读取已禁用模块集合(setup 启动阶段调用)。
pub fn load_disabled(app_data_dir: &Path) -> HashSet<String> {
let fallback = || DEFAULT_DISABLED.iter().map(|s| s.to_string()).collect();
match std::fs::read_to_string(file_path(app_data_dir)) {
Ok(raw) => match serde_json::from_str::<ModuleStatesFile>(&raw) {
Ok(file) => file.disabled.into_iter().collect(),
Err(e) => {
crate::logger::log_warn(
"module",
&format!("模块状态文件解析失败,按默认值处理: {e}"),
);
fallback()
}
},
Err(_) => fallback(),
}
}
pub fn is_enabled(disabled: &HashSet<String>, id: &str) -> bool {
!disabled.contains(id)
}
fn save_disabled(app: &AppHandle, disabled: &HashSet<String>) -> Result<(), String> {
let dir = app
.path()
.app_data_dir()
.map_err(|e| format!("获取数据目录失败: {e}"))?;
let payload = ModuleStatesFile {
disabled: disabled.iter().cloned().collect(),
};
let text = serde_json::to_string_pretty(&payload)
.map_err(|e| format!("序列化模块状态失败: {e}"))?;
std::fs::write(file_path(&dir), text).map_err(|e| format!("写入模块状态失败: {e}"))
}
/// 前端启动完成 / 切换模块后调用:持久化禁用列表并同步 Rust 侧副作用。
///
/// 幂等:重复调用等价于「按当前状态重新应用一次」,不会留下重复注册。
///
/// `setup` 尚未返回时(应用启动阶段)只落盘并暂存,副作用延后到
/// [`finish_setup`]:启动期间主线程忙于创建隐藏窗口,此处若同步创建窗口
/// 会与主线程互等,导致整个界面卡在「进程在但窗口不显示」。
#[tauri::command]
#[specta::specta]
pub fn module_sync_states(app: AppHandle, disabled: Vec<String>) -> Result<(), String> {
let disabled: HashSet<String> = disabled.into_iter().collect();
save_disabled(&app, &disabled)?;
if !SETUP_DONE.load(Ordering::SeqCst) {
let mut pending = PENDING_DISABLED.lock().unwrap_or_else(|e| e.into_inner());
*pending = Some(disabled.into_iter().collect());
return Ok(());
}
apply_all(&app, &disabled);
Ok(())
}
/// `setup` 末尾调用:标记启动完成,并补应用启动期间收到的模块状态。
pub fn finish_setup(app: &AppHandle) {
SETUP_DONE.store(true, Ordering::SeqCst);
let pending = PENDING_DISABLED
.lock()
.unwrap_or_else(|e| e.into_inner())
.take();
if let Some(pending) = pending {
let disabled: HashSet<String> = pending.into_iter().collect();
apply_all(app, &disabled);
}
}
/// 按禁用列表同步全部 Rust 侧副作用(快捷键 / 后台服务 / 预创建窗口)。
fn apply_all(app: &AppHandle, disabled: &HashSet<String>) {
apply_clipboard(app, is_enabled(disabled, "clipboard"));
apply_quickpanel(app, is_enabled(disabled, "quickpanel"));
apply_translate(app, is_enabled(disabled, "translate"));
apply_editor(app, is_enabled(disabled, "editor"));
apply_diff(app, is_enabled(disabled, "diff"));
crate::logger::log_info(
"module",
&format!(
"模块状态已同步,禁用: [{}]",
disabled.iter().cloned().collect::<Vec<_>>().join(", ")
),
);
}
fn log_err(module: &str, result: Result<(), String>) {
if let Err(e) = result {
crate::logger::log_warn(module, &format!("模块启停同步失败: {e}"));
}
}
/// 剪贴板:监听线程 + 快捷弹窗快捷键 + 预创建弹窗。
pub fn apply_clipboard(app: &AppHandle, enabled: bool) {
let Some(manager) = app.try_state::<ClipboardManager>() else {
return;
};
if enabled {
if manager.get_settings().enabled {
manager.start(app);
}
let shortcut = manager.get_settings().shortcut;
if !shortcut.trim().is_empty() {
log_err(
"clipboard",
crate::shortcut::register_shortcut(app, "剪贴板", &shortcut, |a| {
crate::clipboard::popup::show_popup(a)
}),
);
// 预创建弹窗窗口(隐藏),首次按快捷键时直接 show,避免首次创建时序问题
crate::clipboard::popup::ensure_popup_window(app);
crate::clipboard::popup::ensure_preview_window(app);
}
} else {
manager.stop();
crate::shortcut::unregister_shortcut(app, "剪贴板");
crate::clipboard::popup::hide_popup(app);
crate::clipboard::popup::hide_preview(app);
}
}
/// 快速面板:全局快捷键 + 预创建弹窗窗口。
pub fn apply_quickpanel(app: &AppHandle, enabled: bool) {
if enabled {
let settings = crate::quickpanel::load_settings(app);
if !settings.shortcut.trim().is_empty() {
log_err(
"quickpanel",
crate::shortcut::register_shortcut(app, "快速面板", &settings.shortcut, |a| {
crate::quickpanel::popup::show_popup(a)
}),
);
// 预创建弹窗窗口(隐藏),首次按快捷键时直接 show,避免首次创建时序问题
crate::quickpanel::ensure_window(app);
}
} else {
crate::shortcut::unregister_shortcut(app, "快速面板");
crate::quickpanel::popup::hide_popup(app);
}
}
/// 翻译:面板全局快捷键 + 预创建悬浮窗。
pub fn apply_translate(app: &AppHandle, enabled: bool) {
if enabled {
crate::translate::init_on_launch(app);
} else {
crate::translate::disable_on_module_off(app);
}
}
/// 编辑器:新建笔记 / 打开编辑器两个全局快捷键。
pub fn apply_editor(app: &AppHandle, enabled: bool) {
let Some(manager) = app.try_state::<EditorManager>() else {
return;
};
if enabled {
manager.init_on_launch(app);
} else {
crate::shortcut::unregister_shortcut(app, "editor-new-note");
crate::shortcut::unregister_shortcut(app, "editor-open-editor");
}
}
/// 对比工具:打开对比窗口全局快捷键。
pub fn apply_diff(app: &AppHandle, enabled: bool) {
let Some(manager) = app.try_state::<DiffManager>() else {
return;
};
if enabled {
manager.init_on_launch(app);
} else {
crate::shortcut::unregister_shortcut(app, "diff-open-window");
}
}
+51 -57
View File
@@ -47,6 +47,12 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
.app_data_dir() .app_data_dir()
.unwrap_or_else(|_| std::path::PathBuf::from(".")); .unwrap_or_else(|_| std::path::PathBuf::from("."));
// ===== 模块启停状态:Rust 侧镜像 =====
// 前端每次切换模块都会写回这份文件;启动阶段先读它,避免为已禁用模块
// 注册全局快捷键、自动拉起后台服务或预创建常驻窗口。
let disabled_modules = crate::module_state::load_disabled(&app_data_dir);
let module_enabled = |id: &str| crate::module_state::is_enabled(&disabled_modules, id);
// ===== 代理模块:MihomoManager ===== // ===== 代理模块:MihomoManager =====
let mihomo = MihomoManager::new(app_data_dir.clone()); let mihomo = MihomoManager::new(app_data_dir.clone());
app.manage(mihomo); app.manage(mihomo);
@@ -63,7 +69,10 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
app.manage(music); app.manage(music);
// ===== 手机互联:按设置自启(RemoteManager 本体在 lib.rs 平级 manage)===== // ===== 手机互联:按设置自启(RemoteManager 本体在 lib.rs 平级 manage)=====
crate::music::init_on_launch(app.handle()); // 音乐模块禁用时不恢复手机遥控连接。
if module_enabled("music") {
crate::music::init_on_launch(app.handle());
}
// ===== AI 模块:AiManager(全局供应商配置,主设置 → AI 服务)===== // ===== AI 模块:AiManager(全局供应商配置,主设置 → AI 服务)=====
// 迁移必须在建 State 之前跑:把旧版存在翻译设置里的 AI 引擎(含密钥)搬过来, // 迁移必须在建 State 之前跑:把旧版存在翻译设置里的 AI 引擎(含密钥)搬过来,
@@ -84,9 +93,9 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
// 仅注册状态:库扫描与读写都在命令调用时按需触发,启动阶段只创建目录结构。 // 仅注册状态:库扫描与读写都在命令调用时按需触发,启动阶段只创建目录结构。
let notes = EditorManager::new(app_data_dir.clone()); let notes = EditorManager::new(app_data_dir.clone());
let _ = notes.load_settings(); let _ = notes.load_settings();
// 按设置注册「新建笔记 / 打开编辑器」两个全局快捷键(失败只记日志,不阻断启动)
notes.init_on_launch(app.handle());
app.manage(notes); app.manage(notes);
// 按模块启停状态注册「新建笔记 / 打开编辑器」两个全局快捷键(失败只记日志,不阻断启动)
crate::module_state::apply_editor(app.handle(), module_enabled("editor"));
// 「用 Thing 打开」的**冷启动**路径:命令行里带了 .md 就记下来。 // 「用 Thing 打开」的**冷启动**路径:命令行里带了 .md 就记下来。
// 不在这里 `emit` —— 此时 WebView 还没加载、前端还没注册监听,事件会丢掉。 // 不在这里 `emit` —— 此时 WebView 还没加载、前端还没注册监听,事件会丢掉。
// 前端注册完监听后会主动调 `editor_take_pending_file` 取走(见 editor/args.rs)。 // 前端注册完监听后会主动调 `editor_take_pending_file` 取走(见 editor/args.rs)。
@@ -99,8 +108,8 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
// 只承担设置的读写与「打开对比窗口」全局快捷键(默认 Alt+C)的注册; // 只承担设置的读写与「打开对比窗口」全局快捷键(默认 Alt+C)的注册;
// 左右目标(比哪两个文件 / 目录)是前端会话状态,Rust 侧不需要知道。 // 左右目标(比哪两个文件 / 目录)是前端会话状态,Rust 侧不需要知道。
let diff = DiffManager::new(app_data_dir.clone()); let diff = DiffManager::new(app_data_dir.clone());
diff.init_on_launch(app.handle());
app.manage(diff); app.manage(diff);
crate::module_state::apply_diff(app.handle(), module_enabled("diff"));
// ===== 智能家居模块:HaManager(Home Assistant 对接) ===== // ===== 智能家居模块:HaManager(Home Assistant 对接) =====
// 仅注册状态:连接与令牌都在命令调用时按需读取,**启动阶段不发任何网络请求**。 // 仅注册状态:连接与令牌都在命令调用时按需读取,**启动阶段不发任何网络请求**。
@@ -109,7 +118,8 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
app.manage(smarthome); app.manage(smarthome);
// P4:用户上次开着「实时推送」或「本地规则总开关」时,启动后恢复 WS 连接。 // P4:用户上次开着「实时推送」或「本地规则总开关」时,启动后恢复 WS 连接。
// 放在后台任务里(不阻塞启动),且**只有用户显式开过才会连** —— 与"启动不发请求"一致。 // 放在后台任务里(不阻塞启动),且**只有用户显式开过才会连** —— 与"启动不发请求"一致。
{ // 模块被禁用时跳过;重新启用时由该模块 onEnable 调 smarthome_ws_start 恢复。
if module_enabled("smarthome") {
let handle = app.handle().clone(); let handle = app.handle().clone();
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
let manager = handle.state::<HaManager>(); let manager = handle.state::<HaManager>();
@@ -122,9 +132,9 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
// (模型可用性校验因此改为懒校验:首次翻译失败时解释原因 + 设置页手动拉取模型列表)。 // (模型可用性校验因此改为懒校验:首次翻译失败时解释原因 + 设置页手动拉取模型列表)。
let translate = TranslateManager::new(app_data_dir.clone()); let translate = TranslateManager::new(app_data_dir.clone());
app.manage(translate); app.manage(translate);
// 按设置注册「翻译取词 / 翻译剪贴板」两个全局快捷键并预创建悬浮窗。 // 按设置注册翻译面板全局快捷键并预创建悬浮窗;模块禁用时注销并隐藏。
// 失败只记日志(快捷键被占用不该阻断启动)。 // 失败只记日志(快捷键被占用不该阻断启动)。
crate::translate::init_on_launch(app.handle()); crate::module_state::apply_translate(app.handle(), module_enabled("translate"));
// ===== 终端模块:TerminalManager ===== // ===== 终端模块:TerminalManager =====
// 仅注册状态 + 做一次 Shell 探测,**不建立任何 SSH 连接** // 仅注册状态 + 做一次 Shell 探测,**不建立任何 SSH 连接**
@@ -150,54 +160,28 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
let settings = engine.get_settings(); let settings = engine.get_settings();
app.manage(engine.clone()); app.manage(engine.clone());
let server_engine = engine.clone(); // 扩展 HTTP 服务只在下载模块启用时监听:模块禁用后不应继续接受浏览器扩展请求。
let server_port = settings.extension_port; // 注:运行期重新启用下载模块不会补起该服务(需要重启应用),这是当前服务的生命周期限制。
let server_secret = settings.extension_secret.clone(); if module_enabled("downloader") {
let server_app = app.handle().clone(); let server_engine = engine.clone();
tauri::async_runtime::spawn(async move { let server_port = settings.extension_port;
ExtensionServer::start(server_engine, server_port, server_secret, server_app).await; let server_secret = settings.extension_secret.clone();
}); let server_app = app.handle().clone();
tauri::async_runtime::spawn(async move {
ExtensionServer::start(server_engine, server_port, server_secret, server_app).await;
});
}
// ===== 剪贴板模块:监听 + 快捷键 + 预创建弹窗 ===== // ===== 剪贴板模块:监听 + 快捷键 + 预创建弹窗 =====
let clipboard = crate::clipboard::ClipboardManager::new(app_data_dir.clone()); let clipboard = crate::clipboard::ClipboardManager::new(app_data_dir.clone());
// 应用启动时若已启用则自动开始监听
if clipboard.get_settings().enabled {
clipboard.start(&app.handle());
}
// 应用启动时注册快捷弹窗全局快捷键(共享工具模块)
let shortcut = clipboard.get_settings().shortcut.clone();
if !shortcut.trim().is_empty() {
let app_handle = app.handle().clone();
if let Err(e) = crate::shortcut::register_shortcut(&app_handle, "剪贴板", &shortcut, |a| {
crate::clipboard::popup::show_popup(a)
}) {
crate::logger::log_error("clipboard", &format!("快捷键注册失败: {}", e));
}
// 预创建弹窗窗口(隐藏),首次按快捷键时直接 show,避免首次创建时序问题
crate::clipboard::popup::ensure_popup_window(&app_handle);
// 同时预创建独立预览窗口(隐藏),弹窗悬停条目时直接显示
crate::clipboard::popup::ensure_preview_window(&app_handle);
}
app.manage(clipboard); app.manage(clipboard);
// 监听线程 + 快捷键 + 预创建弹窗统一由模块状态决定(禁用时不占快捷键、不建窗口)
crate::module_state::apply_clipboard(app.handle(), module_enabled("clipboard"));
// ===== 快速面板:快捷键 + 预创建弹窗 ===== // ===== 快速面板:快捷键 + 预创建弹窗 =====
// defaultEnabled:true 假设启用;用户在设置页禁用模块时由前端 onDisable 钩子注销快捷键。
// 文件索引 DB 连接改为懒加载(首次搜索/构建时由 commands 中的 ensure_initialized 触发), // 文件索引 DB 连接改为懒加载(首次搜索/构建时由 commands 中的 ensure_initialized 触发),
// 避免应用启动时即打开 SQLite 连接,降低启动 IO 开销。 // 避免应用启动时即打开 SQLite 连接,降低启动 IO 开销。
let qp_settings = crate::quickpanel::load_settings(&app.handle()); crate::module_state::apply_quickpanel(app.handle(), module_enabled("quickpanel"));
if !qp_settings.shortcut.trim().is_empty() {
let app_handle = app.handle().clone();
if let Err(e) = crate::shortcut::register_shortcut(
&app_handle,
"快速面板",
&qp_settings.shortcut,
|a| crate::quickpanel::popup::show_popup(a),
) {
crate::logger::log_error("quickpanel", &format!("快捷键注册失败: {}", e));
}
// 预创建弹窗窗口(隐藏),首次按快捷键时直接 show,避免首次创建时序问题
crate::quickpanel::ensure_window(&app_handle);
}
// ===== 托盘菜单 ===== // ===== 托盘菜单 =====
crate::tray_menu::create_tray_menu(app.handle())?; crate::tray_menu::create_tray_menu(app.handle())?;
@@ -208,25 +192,35 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
// ===== 代理:自动切换节点后台调度(独立于模块激活状态) ===== // ===== 代理:自动切换节点后台调度(独立于模块激活状态) =====
crate::mihomo_manager::start_auto_switch_loop(app.handle().clone()); crate::mihomo_manager::start_auto_switch_loop(app.handle().clone());
// ===== 自动启动(随应用启动,不依赖模块启用) ===== // ===== 自动启动(仅对已启用模块生效) =====
// mihomo:用户在设置中开启"自动启动"时随应用启动 // mihomo:模块启用且用户在设置中开启"自动启动"时随应用启动
if let Some(mihomo) = app.try_state::<MihomoManager>() { if module_enabled("proxy") {
if let Some(pm) = app.try_state::<ProcessManager>() { if let Some(mihomo) = app.try_state::<MihomoManager>() {
mihomo.auto_start_on_launch(app.handle(), &pm); if let Some(pm) = app.try_state::<ProcessManager>() {
mihomo.auto_start_on_launch(app.handle(), &pm);
}
} }
} }
// monitor Kernel:用户在设置中开启"自动启动"时随应用启动 // monitor Kernel:模块启用且用户开启"自动启动"时随应用启动
if let Some(monitor) = app.try_state::<MonitorKernel>() { if module_enabled("monitor") {
monitor.auto_start_on_launch(app.handle()); if let Some(monitor) = app.try_state::<MonitorKernel>() {
monitor.auto_start_on_launch(app.handle());
}
} }
// dsh:开启"自动启动"且已安装时拉起 Web 服务(后台线程执行就绪探测,不阻塞启动)。 // dsh:模块启用、开启"自动启动"且已安装时拉起 Web 服务(后台线程执行就绪探测,不阻塞启动)。
// 「打开独立窗口」快捷键由前端 dshStore 启动时注册(同截图模块约定)。 // 「打开独立窗口」快捷键由前端 dshStore 启动时注册(同截图模块约定)。
crate::dsh::autostart_if_enabled(app.handle()); if module_enabled("dsh") {
crate::dsh::autostart_if_enabled(app.handle());
}
// 截图快捷键由前端 screenshotStore 启动时调用 screenshot_register_shortcut 注册 // 截图快捷键由前端 screenshotStore 启动时调用 screenshot_register_shortcut 注册
// (支持自定义,默认 F3),此处不再硬编码注册 // (支持自定义,默认 F3),此处不再硬编码注册
// 启动阶段的窗口创建已全部完成:解除 module_sync_states 的延后标记,
// 并补应用前端在启动过程中同步过来的模块状态(此前只落盘、不产生副作用)。
crate::module_state::finish_setup(app.handle());
Ok(()) Ok(())
} }
+6
View File
@@ -85,6 +85,12 @@ pub fn init_on_launch(app: &tauri::AppHandle) {
} }
} }
/// 模块被禁用时注销面板快捷键并隐藏悬浮窗(与 [`init_on_launch`] 对称)。
pub fn disable_on_module_off(app: &tauri::AppHandle) {
crate::shortcut::unregister_shortcut(app, "翻译面板");
popup::hide(app);
}
/// 读取某引擎实例的 API Key(未配置或读取失败 → 空串)。 /// 读取某引擎实例的 API Key(未配置或读取失败 → 空串)。
/// ///
/// AI 引擎(kind = "ai")的密钥在 `ai-provider-*`,走 [`crate::ai::provider_api_key`]; /// AI 引擎(kind = "ai")的密钥在 `ai-provider-*`,走 [`crate::ai::provider_api_key`];
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "thing", "productName": "thing",
"version": "26.10.1", "version": "26.10.2",
"identifier": "thing.lfeng.me", "identifier": "thing.lfeng.me",
"build": { "build": {
"beforeDevCommand": "bun run dev", "beforeDevCommand": "bun run dev",
+47 -17
View File
@@ -34,6 +34,19 @@ const processStore = useProcessStore()
const dshStore = useDshStore() const dshStore = useDshStore()
const editorStore = useEditorStore() const editorStore = useEditorStore()
/** 模块是否启用(应用级入口/常驻资源统一用这一个判定) */
const moduleOn = (id: string) => appStore.getModule(id)?.enabled !== false
/** 是否允许打开某个模块页(内置模块始终允许) */
const canOpenModule = (id: string) => {
const config = moduleRegistry.getConfig(id)
if (!config) return false
return config.builtin || moduleOn(id)
}
/** 音乐模块是否启用:禁用时不初始化播放器、不挂载播放控制弹窗 */
const musicEnabled = computed(() => moduleOn('music'))
/** 侧边栏 / 标题栏需要的模块信息(id + name + icon) */ /** 侧边栏 / 标题栏需要的模块信息(id + name + icon) */
interface NavModule { interface NavModule {
id: string id: string
@@ -97,6 +110,10 @@ const loadModule = async (moduleId: string) => {
} }
const handleModuleChange = (moduleId: string) => { const handleModuleChange = (moduleId: string) => {
// 已禁用的模块不允许被搜索 / 托盘 / 全局快捷键等入口切出来
// (禁用只应隐藏入口,若这里放行就会出现「侧边栏没有、页面却被打开了」)
if (!canOpenModule(moduleId)) return
// 同模块不重新加载(保留组件状态);搜索/托盘跳转到当前模块时仅触发 tab 导航 // 同模块不重新加载(保留组件状态);搜索/托盘跳转到当前模块时仅触发 tab 导航
if (activeModule.value === moduleId) return if (activeModule.value === moduleId) return
@@ -207,16 +224,18 @@ const resolveDefaultModule = (): string => {
onMounted(async () => { onMounted(async () => {
await appStore.init().catch(e => console.error('App init error:', e)) await appStore.init().catch(e => console.error('App init error:', e))
// 全局播放器:恢复队列/音量/播放模式等本地状态(幂等,音乐模块内会再次调用但不会重复执行) // 全局播放器:恢复队列/音量/播放模式等本地状态(幂等,音乐模块内会再次调用但不会重复执行)。
feiniuStore.init().catch(e => console.error('播放器初始化失败:', e)) // 音乐模块被禁用时跳过:避免禁用状态下仍建立播放器监听/回填队列。
if (musicEnabled.value) {
feiniuStore.init().catch(e => console.error('播放器初始化失败:', e))
}
// 初始化监控 store:订阅后端 monitor-data / monitor-network 等事件, // 监控 store:仅在模块启用时订阅后端事件 / 初始化 OSD。
// 使 OSD 窗口在应用启动后即可接收数据流,不依赖用户手动打开监控模块。 // 禁用状态下不应建立 SSE 订阅、心跳,也不应创建 OSD 悬浮窗。
// init() 幂等:MonitorModule 挂载时再次调用不会重复订阅。 if (moduleOn('monitor')) {
monitorStore.init() monitorStore.init()
// 显式初始化 OSD monitorStore.initOsd()
// 使 OSD 窗口在应用启动时创建(若配置已开启),且不依赖监控模块挂载/卸载 }
monitorStore.initOsd()
const defaultModule = resolveDefaultModule() const defaultModule = resolveDefaultModule()
activeModule.value = defaultModule activeModule.value = defaultModule
@@ -225,8 +244,11 @@ onMounted(async () => {
// 快速面板:同步命令缓存与设置到 localStorage,供独立窗口读取 // 快速面板:同步命令缓存与设置到 localStorage,供独立窗口读取
quickpanelStore.syncCommands() quickpanelStore.syncCommands()
quickpanelStore.syncSettings() quickpanelStore.syncSettings()
// 初始化文件索引 DB 并恢复增量监听(上次构建过索引时自动恢复,不重建) // 初始化文件索引 DB 并恢复增量监听(上次构建过索引时自动恢复,不重建)。
commands.quickpanelInitFileIndex().catch(e => console.error('文件索引初始化失败:', e)) // 快速面板禁用时不做这件事:索引初始化会打开 SQLite + 恢复目录监听。
if (moduleOn('quickpanel')) {
commands.quickpanelInitFileIndex().catch(e => console.error('文件索引初始化失败:', e))
}
// 监听快速面板执行命令事件:显示主窗口 + 切换模块 // 监听快速面板执行命令事件:显示主窗口 + 切换模块
trayUnlisteners.push( trayUnlisteners.push(
await listen<{ moduleId: string }>('quickpanel-execute-command', async (e) => { await listen<{ moduleId: string }>('quickpanel-execute-command', async (e) => {
@@ -253,6 +275,7 @@ onMounted(async () => {
// 托盘「终端」:开「新建终端选择窗口」(与快捷键同一条路径,全程不打扰主窗口) // 托盘「终端」:开「新建终端选择窗口」(与快捷键同一条路径,全程不打扰主窗口)
trayUnlisteners.push( trayUnlisteners.push(
await listen(EVENTS.trayOpenTerminal, () => { await listen(EVENTS.trayOpenTerminal, () => {
if (!moduleOn('terminal')) return
void openTerminalPickerWindow().catch(e => void openTerminalPickerWindow().catch(e =>
console.error('[tray] 打开终端窗口失败:', e) console.error('[tray] 打开终端窗口失败:', e)
) )
@@ -261,6 +284,7 @@ onMounted(async () => {
// 托盘「编辑器」:开编辑器独立窗口 // 托盘「编辑器」:开编辑器独立窗口
trayUnlisteners.push( trayUnlisteners.push(
await listen(EVENTS.trayOpenEditor, () => { await listen(EVENTS.trayOpenEditor, () => {
if (!moduleOn('editor')) return
void openEditorWindow().catch(e => console.error('[tray] 打开编辑器窗口失败:', e)) void openEditorWindow().catch(e => console.error('[tray] 打开编辑器窗口失败:', e))
}) })
) )
@@ -271,6 +295,7 @@ onMounted(async () => {
// (同 main.ts 里 dsh 快捷键的取舍:模块卸载不能把快捷键带走)。 // (同 main.ts 里 dsh 快捷键的取舍:模块卸载不能把快捷键带走)。
trayUnlisteners.push( trayUnlisteners.push(
await listen(EVENTS.editorOpenEditor, () => { await listen(EVENTS.editorOpenEditor, () => {
if (!moduleOn('editor')) return
void openEditorWindow().catch(e => console.error('[shortcut] 打开编辑器窗口失败:', e)) void openEditorWindow().catch(e => console.error('[shortcut] 打开编辑器窗口失败:', e))
}) })
) )
@@ -279,6 +304,7 @@ onMounted(async () => {
// 「刚启动、还没进过对比页」时按了没反应(同上面 Alt+E 的取舍)。 // 「刚启动、还没进过对比页」时按了没反应(同上面 Alt+E 的取舍)。
trayUnlisteners.push( trayUnlisteners.push(
await listen(EVENTS.diffOpenWindow, () => { await listen(EVENTS.diffOpenWindow, () => {
if (!moduleOn('diff')) return
void openDiffWindow().catch(e => console.error('[shortcut] 打开对比窗口失败:', e)) void openDiffWindow().catch(e => console.error('[shortcut] 打开对比窗口失败:', e))
}) })
) )
@@ -287,6 +313,7 @@ onMounted(async () => {
// 同理不能放进模块页里监听,否则没进过编辑器页时按了没反应。 // 同理不能放进模块页里监听,否则没进过编辑器页时按了没反应。
trayUnlisteners.push( trayUnlisteners.push(
await listen(EVENTS.editorNewNote, () => { await listen(EVENTS.editorNewNote, () => {
if (!moduleOn('editor')) return
editorStore.requestNewNote() editorStore.requestNewNote()
handleModuleChange('editor') handleModuleChange('editor')
}) })
@@ -294,6 +321,7 @@ onMounted(async () => {
// 托盘「dsh」:就绪则直接开界面,否则先开启动进度窗口并同步拉起服务 // 托盘「dsh」:就绪则直接开界面,否则先开启动进度窗口并同步拉起服务
trayUnlisteners.push( trayUnlisteners.push(
await listen(EVENTS.trayOpenDsh, () => { await listen(EVENTS.trayOpenDsh, () => {
if (!moduleOn('dsh')) return
void dshStore.openFromTray().catch(e => console.error('[tray] 打开 dsh 失败:', e)) void dshStore.openFromTray().catch(e => console.error('[tray] 打开 dsh 失败:', e))
}) })
) )
@@ -301,14 +329,16 @@ onMounted(async () => {
// 主窗口本身无需置前,下载进度/完成事件由独立窗口自行监听。 // 主窗口本身无需置前,下载进度/完成事件由独立窗口自行监听。
trayUnlisteners.push( trayUnlisteners.push(
await listen<{ id: string }>(EVENTS.downloadExtensionAdded, (e) => { await listen<{ id: string }>(EVENTS.downloadExtensionAdded, (e) => {
if (!e.payload?.id) return if (!e.payload?.id || !moduleOn('downloader')) return
void openDownloadWindow(e.payload.id) void openDownloadWindow(e.payload.id)
}) })
) )
// 截图导出监听(应用级常驻,确保任何来源的截图都记录到历史) // 截图导出 / 滚动截图事件:仅截图模块启用时注册,模块启停时由该模块的
screenshotStore.initExportListener().catch(e => console.error('[screenshot] 导出监听初始化失败:', e)) // onEnable / onDisable 负责补挂与卸载(见 modules/screenshot/index.ts)。
// 滚动截图完成 → 进编辑器(应用级常驻) if (moduleOn('screenshot')) {
screenshotStore.initScrollEditorListener().catch(e => console.error('[screenshot] 滚动进编辑器监听初始化失败:', e)) screenshotStore.initExportListener().catch(e => console.error('[screenshot] 导出监听初始化失败:', e))
screenshotStore.initScrollEditorListener().catch(e => console.error('[screenshot] 滚动进编辑器监听初始化失败:', e))
}
}) })
const trayUnlisteners: UnlistenFn[] = [] const trayUnlisteners: UnlistenFn[] = []
@@ -336,7 +366,7 @@ onUnmounted(() => {
<ModuleContainer :active-component="activeComponent" :active-module="activeModule" :loading="moduleLoading" /> <ModuleContainer :active-component="activeComponent" :active-module="activeModule" :loading="moduleLoading" />
</div> </div>
</div> </div>
<NowPlayingDialog /> <NowPlayingDialog v-if="musicEnabled" />
<TerminalQuickLaunch /> <TerminalQuickLaunch />
<Toaster position="bottom-right" rich-colors close-button :style="{ zIndex: 99999 }" /> <Toaster position="bottom-right" rich-colors close-button :style="{ zIndex: 99999 }" />
</TooltipProvider> </TooltipProvider>
+8 -2
View File
@@ -7,10 +7,15 @@ import { invoke } from '@tauri-apps/api/core'
import { getCurrentWindow } from '@tauri-apps/api/window' import { getCurrentWindow } from '@tauri-apps/api/window'
import { useSearchStore, type SearchItem } from '@/stores/searchStore' import { useSearchStore, type SearchItem } from '@/stores/searchStore'
import { useModuleTabsStore } from '@/stores/moduleTabsStore' import { useModuleTabsStore } from '@/stores/moduleTabsStore'
import { useAppStore } from '@/stores/appStore'
// 复用快速面板匹配引擎(支持拼音/子序列模糊匹配) // 复用快速面板匹配引擎(支持拼音/子序列模糊匹配)
import { getTextForms, bestScore } from '@/modules/quickpanel/engine' import { getTextForms, bestScore } from '@/modules/quickpanel/engine'
const tabsStore = useModuleTabsStore() const tabsStore = useModuleTabsStore()
const appStore = useAppStore()
/** 音乐模块是否启用(标题栏音乐条属于音乐模块的常驻 UI,禁用模块时一并隐藏) */
const musicEnabled = computed(() => appStore.getModule('music')?.enabled !== false)
const props = defineProps<{ const props = defineProps<{
modules: Array<{ id: string; name: string; icon: string }> modules: Array<{ id: string; name: string; icon: string }>
@@ -364,8 +369,9 @@ const handleBlur = () => {
保存设置 保存设置
</button> </button>
</Transition> </Transition>
<!-- 音乐栏:唱片图标 + 歌名(点击弹出方形播放控制窗),位于搜索框左侧 --> <!-- 音乐栏:唱片图标 + 歌名(点击弹出方形播放控制窗),位于搜索框左侧;
<div class="pointer-events-auto"> 跟随音乐模块启停状态,模块禁用时整条隐藏 -->
<div v-if="musicEnabled" class="pointer-events-auto">
<TitleBarMusic /> <TitleBarMusic />
</div> </div>
+6
View File
@@ -26,6 +26,12 @@ export const commands = {
updateThinghkConfirm: () => __TAURI_INVOKE<null>("update_thinghk_confirm"), updateThinghkConfirm: () => __TAURI_INVOKE<null>("update_thinghk_confirm"),
/** 取消 ThingHK 内核更新(need_stop 等待阶段有效:唤醒 apply 以「已取消」返回,zip 保留便于重试) */ /** 取消 ThingHK 内核更新(need_stop 等待阶段有效:唤醒 apply 以「已取消」返回,zip 保留便于重试) */
updateThinghkCancel: () => __TAURI_INVOKE<null>("update_thinghk_cancel"), updateThinghkCancel: () => __TAURI_INVOKE<null>("update_thinghk_cancel"),
/**
* 前端启动完成 / 切换模块后调用:持久化禁用列表并同步 Rust 侧副作用。
*
* 幂等:重复调用等价于「按当前状态重新应用一次」,不会留下重复注册。
*/
moduleSyncStates: (disabled: string[]) => __TAURI_INVOKE<null>("module_sync_states", { disabled }),
proxyActivateProfile: (id: string) => __TAURI_INVOKE<null>("proxy_activate_profile", { id }), proxyActivateProfile: (id: string) => __TAURI_INVOKE<null>("proxy_activate_profile", { id }),
/** 应用内核更新:下载阶段已由下载模块完成,本方法仅做 need_stop → 解压 → 替换。 */ /** 应用内核更新:下载阶段已由下载模块完成,本方法仅做 need_stop → 解压 → 替换。 */
proxyApplyKernelUpdate: (zipPath: string) => __TAURI_INVOKE<KernelInfo>("proxy_apply_kernel_update", { zipPath }), proxyApplyKernelUpdate: (zipPath: string) => __TAURI_INVOKE<KernelInfo>("proxy_apply_kernel_update", { zipPath }),
+35
View File
@@ -0,0 +1,35 @@
import { STORAGE_KEYS } from '@/lib/constants'
/**
* 模块启停状态的统一读取入口。
*
* 真相仍是 appStore 持久化的 `appSettings.modules`,但独立窗口(托盘菜单、快速面板等)
* 以及主窗口挂载前的启动阶段拿不到 Pinia store,只能直接读 localStorage。
* 把解析逻辑收敛到这里,避免每个入口各写一份(字段/默认值不一致时就会出现
* “侧边栏隐藏了但标题栏还在”这类偏差)。
*/
/** 默认禁用模块(与各模块 `defaultEnabled` 保持一致;文件缺失时作为兜底) */
const DEFAULT_DISABLED = ['smarthome']
/** 读取已禁用模块集合 */
export function readDisabledModules(): Set<string> {
try {
const raw = localStorage.getItem(STORAGE_KEYS.appSettings)
if (!raw) return new Set(DEFAULT_DISABLED)
const parsed = JSON.parse(raw)
if (!Array.isArray(parsed.modules)) return new Set(DEFAULT_DISABLED)
const disabled = new Set<string>()
for (const m of parsed.modules) {
if (m && typeof m.id === 'string' && m.enabled === false) disabled.add(m.id)
}
return disabled
} catch {
return new Set(DEFAULT_DISABLED)
}
}
/** 模块是否启用(主窗口已初始化后应优先使用 appStore,此处用于启动早期 / 独立窗口) */
export function isModuleEnabled(id: string): boolean {
return !readDisabledModules().has(id)
}
+23 -16
View File
@@ -4,6 +4,7 @@ import './style.css'
import 'vue-sonner/style.css' import 'vue-sonner/style.css'
import { createLogger } from './lib/logger' import { createLogger } from './lib/logger'
import { isModuleEnabled } from './lib/moduleState'
const logger = createLogger('main') const logger = createLogger('main')
// 禁用 WebView 默认右键菜单(桌面应用体验,主窗口与独立窗口共用) // 禁用 WebView 默认右键菜单(桌面应用体验,主窗口与独立窗口共用)
@@ -114,24 +115,30 @@ if (matched) {
useProcessStore().initListener().catch(e => console.error('Process listener init error:', e)) useProcessStore().initListener().catch(e => console.error('Process listener init error:', e))
}) })
// 截图模块:加载设置 + 恢复持久化历史 + 预创建常驻覆盖层窗口 + 监听导出事件(历史/自动保存)+ 注册并监听全局快捷键(截图/贴图) // 截图模块:仅在启用时加载设置、恢复历史、预创建覆盖层并注册全局快捷键。
void import('./stores/screenshotStore').then(({ useScreenshotStore }) => { // 禁用状态不预创建常驻窗口、不占用 F3/F4 等系统热键;模块启用时由其
const screenshotStore = useScreenshotStore() // onEnable 生命周期补齐(见 modules/screenshot/index.ts)。
screenshotStore.loadSettings() if (isModuleEnabled('screenshot')) {
screenshotStore.loadHistory() void import('./stores/screenshotStore').then(({ useScreenshotStore }) => {
screenshotStore.initOverlay().catch(e => console.error('Screenshot overlay init error:', e)) const screenshotStore = useScreenshotStore()
screenshotStore.initExportListener().catch(e => console.error('Screenshot export listener init error:', e)) screenshotStore.loadSettings()
screenshotStore.initShortcutListener().catch(e => console.error('Screenshot shortcut listener init error:', e)) screenshotStore.loadHistory()
screenshotStore.initShortcutRegistration().catch(e => console.error('Screenshot shortcut registration init error:', e)) screenshotStore.initOverlay().catch(e => console.error('Screenshot overlay init error:', e))
screenshotStore.initPinShortcutListener().catch(e => console.error('Screenshot pin shortcut listener init error:', e)) screenshotStore.initExportListener().catch(e => console.error('Screenshot export listener init error:', e))
screenshotStore.initPinShortcutRegistration().catch(e => console.error('Screenshot pin shortcut registration init error:', e)) screenshotStore.initShortcutListener().catch(e => console.error('Screenshot shortcut listener init error:', e))
}) screenshotStore.initShortcutRegistration().catch(e => console.error('Screenshot shortcut registration init error:', e))
screenshotStore.initPinShortcutListener().catch(e => console.error('Screenshot pin shortcut listener init error:', e))
screenshotStore.initPinShortcutRegistration().catch(e => console.error('Screenshot pin shortcut registration init error:', e))
})
}
// dsh 模块:应用级初始化全局快捷键(注册 + 监听「打开独立窗口」事件)。 // dsh 模块:启用时才注册应用级全局快捷键(注册 + 监听「打开独立窗口」事件)。
// 放这里而不是模块挂载时:快捷键要在任意模块下都能用,模块卸载不能把它带走。 // 放这里而不是模块挂载时:快捷键要在任意模块下都能用,模块卸载不能把它带走。
void import('./stores/dshStore').then(({ useDshStore }) => { if (isModuleEnabled('dsh')) {
useDshStore().initGlobalShortcut().catch(e => console.error('dsh shortcut init error:', e)) void import('./stores/dshStore').then(({ useDshStore }) => {
}) useDshStore().initGlobalShortcut().catch(e => console.error('dsh shortcut init error:', e))
})
}
}) })
} }
+7 -3
View File
@@ -44,13 +44,17 @@ export const moduleConfig: ModuleConfig = {
loader: () => import('./DshModule.vue'), loader: () => import('./DshModule.vue'),
searchItems, searchItems,
lifecycle: { lifecycle: {
// 模块启用:恢复全局快捷键(应用启动时由 main.ts 注册;这里覆盖「先禁用再启用」) // 模块启用:先刷新设置再恢复全局快捷键(启动时模块若被禁用,设置从未加载过),
// 并按 autoStart 决定是否拉起服务。
onEnable: async () => { onEnable: async () => {
try { try {
const { useDshStore } = await import('@/stores/dshStore') const { useDshStore } = await import('@/stores/dshStore')
await useDshStore().registerShortcut() const store = useDshStore()
await store.refresh()
await store.registerShortcut()
if (store.settings?.autoStart && !store.running) await store.start()
} catch (e) { } catch (e) {
console.error('[dsh] onEnable 注册快捷键失败:', e) console.error('[dsh] onEnable 恢复失败:', e)
} }
}, },
// 模块禁用:停服务 + 注销快捷键(服务停了快捷键也没意义,且组合键不该被占着) // 模块禁用:停服务 + 注销快捷键(服务停了快捷键也没意义,且组合键不该被占着)
+18
View File
@@ -94,8 +94,26 @@ export const moduleConfig: ModuleConfig = {
} catch { } catch {
/* 忽略:可能 Kernel 未安装 */ /* 忽略:可能 Kernel 未安装 */
} }
// 恢复事件订阅 / 心跳 / OSD 窗口(启动时因模块禁用被跳过)
try {
const { useMonitorStore } = await import('@/stores/monitorStore')
const store = useMonitorStore()
await store.init()
store.initOsd()
} catch (e) {
console.error('[monitor] onEnable 初始化 store 失败:', e)
}
}, },
onDisable: async () => { onDisable: async () => {
// 先释放 SSE 订阅 / 心跳 / OSD 监听,再停止 Kernel
try {
const { useMonitorStore } = await import('@/stores/monitorStore')
const store = useMonitorStore()
store.dispose()
store.disposeOsd()
} catch (e) {
console.error('[monitor] onDisable 释放 store 失败:', e)
}
// 禁用模块时停止 SSE 订阅并终止 Kernel 进程 // 禁用模块时停止 SSE 订阅并终止 Kernel 进程
try { try {
await invoke('monitor_stop') await invoke('monitor_stop')
+5 -2
View File
@@ -42,8 +42,11 @@ export const moduleConfig: ModuleConfig = {
// 桥接进程按需拉起(首次搜索/环境检测时自动启动),此处无需预启动 // 桥接进程按需拉起(首次搜索/环境检测时自动启动),此处无需预启动
}, },
onDisable: () => { onDisable: () => {
// 禁用模块时停止桥接进程,释放 Python 进程 // 禁用模块时停止播放并释放桥接进程(Python)。
// 直接 invoke 避免模块 index.ts 导入 store 造成循环依赖 // 动态导入避免模块 index.ts 直接依赖 store 造成循环依赖(同 monitor / terminal 的处理)。
import('@/stores/feiniuStore')
.then(({ useFeiniuStore }) => useFeiniuStore().stopEngine())
.catch(() => {})
import('@tauri-apps/api/core') import('@tauri-apps/api/core')
.then(({ invoke }) => invoke('music_stop_bridge')) .then(({ invoke }) => invoke('music_stop_bridge'))
.catch(() => {}) .catch(() => {})
+6
View File
@@ -56,6 +56,12 @@ export const moduleConfig: ModuleConfig = {
} catch (e) { } catch (e) {
console.error('[quickpanel] onEnable 注册快捷键失败:', e) console.error('[quickpanel] onEnable 注册快捷键失败:', e)
} }
// 启动时若模块被禁用,文件索引从未初始化;启用时补一次(懒加载,失败只记日志)
try {
await commands.quickpanelInitFileIndex()
} catch (e) {
console.error('[quickpanel] onEnable 初始化文件索引失败:', e)
}
}, },
// 模块禁用:注销全局快捷键 // 模块禁用:注销全局快捷键
onDisable: async () => { onDisable: async () => {
+33
View File
@@ -1,5 +1,6 @@
import type { ModuleConfig } from '@/types/module' import type { ModuleConfig } from '@/types/module'
import type { SearchIndexItem } from '@/stores/searchIndex' import type { SearchIndexItem } from '@/stores/searchIndex'
import { commands } from '@/lib/bindings'
const searchItems: SearchIndexItem[] = [ const searchItems: SearchIndexItem[] = [
{ {
@@ -55,5 +56,37 @@ export const moduleConfig: ModuleConfig = {
defaultEnabled: true, defaultEnabled: true,
loader: () => import('./ScreenshotModule.vue'), loader: () => import('./ScreenshotModule.vue'),
searchItems, searchItems,
lifecycle: {
// 模块启用:补齐启动时被跳过的设置加载、覆盖层预创建、事件监听与全局快捷键
onEnable: async () => {
try {
const { useScreenshotStore } = await import('@/stores/screenshotStore')
const store = useScreenshotStore()
store.loadSettings()
store.loadHistory()
await store.initOverlay()
await store.initExportListener()
await store.initScrollEditorListener()
await store.initShortcutListener()
await store.initPinShortcutListener()
await store.initShortcutRegistration()
await store.initPinShortcutRegistration()
} catch (e) {
console.error('[screenshot] onEnable 初始化失败:', e)
}
},
// 模块禁用:注销截图/贴图全局快捷键并停止快捷键事件监听,
// 避免入口已隐藏但 F3/F4 仍能唤起截图。
onDisable: async () => {
try {
const { useScreenshotStore } = await import('@/stores/screenshotStore')
useScreenshotStore().destroyShortcutListener()
await commands.screenshotUnregisterShortcut()
await commands.screenshotUnregisterPinShortcut()
} catch (e) {
console.error('[screenshot] onDisable 清理失败:', e)
}
}
},
order: 70 order: 70
} }
+2 -1
View File
@@ -848,7 +848,8 @@ const onDragEnd = () => {
</div> </div>
</VueDraggable> </VueDraggable>
<p class="mt-4 text-xs text-muted-foreground"> <p class="mt-4 text-xs text-muted-foreground">
拖拽手柄可调整模块顺序,禁用模块将从侧边栏隐藏并停止后台进程以减少内存占用。更改后立即生效。 拖拽手柄可调整模块顺序。禁用模块会同时隐藏侧边栏、标题栏、托盘与搜索入口,
并注销其全局快捷键、停止后台进程、断开常驻连接;下次启动也不会再被自动拉起。更改后立即生效。
</p> </p>
</CardContent> </CardContent>
</Card> </Card>
+20
View File
@@ -46,5 +46,25 @@ export const moduleConfig: ModuleConfig = {
defaultEnabled: false, defaultEnabled: false,
loader: () => import('./SmartHomeModule.vue'), loader: () => import('./SmartHomeModule.vue'),
searchItems, searchItems,
lifecycle: {
// 启用:如果用户开着实时推送,立即恢复 WebSocket(与启动阶段 Rust 侧逻辑一致)
onEnable: async () => {
try {
const { useSmartHomeStore } = await import('@/stores/smartHomeStore')
await useSmartHomeStore().ensureRealtime()
} catch (e) {
console.error('[smarthome] onEnable 恢复实时连接失败:', e)
}
},
// 禁用:断开实时连接,避免入口隐藏后仍持续接收 HA 事件与执行本地规则
onDisable: async () => {
try {
const { useSmartHomeStore } = await import('@/stores/smartHomeStore')
await useSmartHomeStore().stopRealtime()
} catch (e) {
console.error('[smarthome] onDisable 断开实时连接失败:', e)
}
}
},
order: 85 order: 85
} }
+3 -14
View File
@@ -4,6 +4,7 @@ import { invoke } from '@tauri-apps/api/core'
import { listen, type UnlistenFn } from '@tauri-apps/api/event' import { listen, type UnlistenFn } from '@tauri-apps/api/event'
import { getCurrentWindow } from '@tauri-apps/api/window' import { getCurrentWindow } from '@tauri-apps/api/window'
import { STORAGE_KEYS } from '@/lib/constants' import { STORAGE_KEYS } from '@/lib/constants'
import { readDisabledModules } from '@/lib/moduleState'
import { applyAccent, readStoredAccent } from '@/lib/theme' import { applyAccent, readStoredAccent } from '@/lib/theme'
import { Effect, EffectState } from '@tauri-apps/api/window' import { Effect, EffectState } from '@tauri-apps/api/window'
import { import {
@@ -75,21 +76,9 @@ function resetMenuState() {
/** 被禁用的模块 ID 集合(模块启停状态的真相在 appSettings.modules) */ /** 被禁用的模块 ID 集合(模块启停状态的真相在 appSettings.modules) */
const disabledModules = ref<Set<string>>(new Set()) const disabledModules = ref<Set<string>>(new Set())
/** 读取模块启停状态:未记录的模块按默认启用处理 */ /** 读取模块启停状态(与主窗口共用同一份解析逻辑,未记录的模块按默认启用处理) */
function readModuleStates() { function readModuleStates() {
const disabled = new Set<string>() disabledModules.value = readDisabledModules()
try {
const raw = localStorage.getItem(STORAGE_KEYS.appSettings)
if (raw) {
const parsed = JSON.parse(raw)
if (Array.isArray(parsed.modules)) {
for (const m of parsed.modules) {
if (m && typeof m.id === 'string' && m.enabled === false) disabled.add(m.id)
}
}
}
} catch { /* 忽略 */ }
disabledModules.value = disabled
} }
function moduleEnabled(id: string): boolean { function moduleEnabled(id: string): boolean {
+27
View File
@@ -5,6 +5,7 @@ import { enable, isEnabled, disable } from '@tauri-apps/plugin-autostart'
import { moduleRegistry } from '@/modules/registry' import { moduleRegistry } from '@/modules/registry'
import { useSearchStore } from '@/stores/searchStore' import { useSearchStore } from '@/stores/searchStore'
import { useProcessStore } from '@/stores/processStore' import { useProcessStore } from '@/stores/processStore'
import { commands } from '@/lib/bindings'
import { toast } from 'vue-sonner' import { toast } from 'vue-sonner'
import { createLogger } from '@/lib/logger' import { createLogger } from '@/lib/logger'
import { STORAGE_KEYS } from '@/lib/constants' import { STORAGE_KEYS } from '@/lib/constants'
@@ -183,10 +184,31 @@ export const useAppStore = defineStore('app', () => {
} }
} }
// 首屏渲染前先套用已保存的模块启停与排序(loadSettings 内部无 await,调用即同步生效)。
// 否则禁用模块的标题栏/侧边栏入口会先按“全部启用”渲染一帧再消失。
// init() 里会再次调用,二者幂等。
void loadSettings()
const enabledModules = computed(() => modules.value.filter(m => m.enabled)) const enabledModules = computed(() => modules.value.filter(m => m.enabled))
const getModule = (id: string) => modules.value.find(m => m.id === id) const getModule = (id: string) => modules.value.find(m => m.id === id)
/**
* 把模块启停状态同步给 Rust 侧。
*
* Rust 在启动阶段(WebView 就绪之前)就要决定:是否注册全局快捷键、
* 是否自动拉起 mihomo / 监控 Kernel / dsh、是否预创建常驻窗口。
* 这些都无法直接读 localStorage,因此由前端在启动完成和每次切换模块后
* 把完整禁用列表写过去(落盘 + 立即生效)。
*/
const syncModuleStatesToRust = () => {
const disabled = modules.value.filter(m => !m.enabled).map(m => m.id)
commands.moduleSyncStates(disabled).catch(e => {
console.error('[appStore] 同步模块启停状态到 Rust 失败:', e)
logger.error(`同步模块启停状态失败: ${e}`)
})
}
/** 重新排序模块 */ /** 重新排序模块 */
const reorderModules = (newOrder: string[]) => { const reorderModules = (newOrder: string[]) => {
moduleOrder.value = newOrder moduleOrder.value = newOrder
@@ -229,6 +251,7 @@ export const useAppStore = defineStore('app', () => {
// 1. 先更新状态(让开关立即响应) // 1. 先更新状态(让开关立即响应)
modules.value[moduleIndex] = { ...moduleInfo, enabled: false } modules.value[moduleIndex] = { ...moduleInfo, enabled: false }
saveSettings() saveSettings()
syncModuleStatesToRust()
// 2. 清理搜索项 // 2. 清理搜索项
try { try {
@@ -274,6 +297,7 @@ export const useAppStore = defineStore('app', () => {
// 1. 先更新状态(让开关立即响应) // 1. 先更新状态(让开关立即响应)
modules.value[moduleIndex] = { ...moduleInfo, enabled: true } modules.value[moduleIndex] = { ...moduleInfo, enabled: true }
saveSettings() saveSettings()
syncModuleStatesToRust()
// 2. 调用生命周期钩子 // 2. 调用生命周期钩子
try { try {
@@ -519,6 +543,9 @@ export const useAppStore = defineStore('app', () => {
const init = async () => { const init = async () => {
try { try {
await loadSettings() await loadSettings()
// 首次启动没有状态文件时,Rust 按默认值注册了快捷键/自启;这里补齐一次,
// 把真实状态落盘并纠正副作用(已启用模块重新注册,已禁用模块注销)
syncModuleStatesToRust()
try { try {
const saved = localStorage.getItem(STORAGE_KEY) const saved = localStorage.getItem(STORAGE_KEY)
+1
View File
@@ -1946,6 +1946,7 @@ export const useFeiniuStore = defineStore('feiniu', () => {
toggleMute, toggleMute,
togglePlayMode, togglePlayMode,
setPlayMode, setPlayMode,
stopEngine,
clearPlayback, clearPlayback,
persistQueue, persistQueue,
persistProgress, persistProgress,