2 Commits
Author SHA1 Message Date
zhongluofeng 0a19b4b38a Merge branch 'main' of https://gitea.atie.fun/LFeng/Thing 2026-08-14 17:47:28 +08:00
zhongluofeng 7d49a7395f 优化调整 2026-08-14 17:47:06 +08:00
50 changed files with 2805 additions and 259 deletions
+21
View File
@@ -4753,6 +4753,7 @@ dependencies = [
"image",
"notify",
"raw-window-handle",
"regex",
"reqwest 0.12.28",
"rusqlite",
"serde",
@@ -4773,6 +4774,7 @@ dependencies = [
"tokio",
"url",
"walkdir",
"windows 0.52.0",
"windows-sys 0.52.0",
"winreg 0.52.0",
"zip",
@@ -5590,6 +5592,16 @@ dependencies = [
"windows-version",
]
[[package]]
name = "windows"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be"
dependencies = [
"windows-core 0.52.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.57.0"
@@ -5622,6 +5634,15 @@ dependencies = [
"windows-core 0.61.2",
]
[[package]]
name = "windows-core"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.57.0"
+10
View File
@@ -26,6 +26,7 @@ tauri-plugin-global-shortcut = "2"
tauri-plugin-notification = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
regex = "1"
serde_yaml = "0.9"
specta = { version = "=2.0.0-rc.25", features = ["derive", "function", "serde_json"] }
specta-typescript = "0.0.12"
@@ -65,6 +66,15 @@ windows-sys = { version = "0.52", features = [
"Win32_Storage_Xps",
"Win32_Storage_FileSystem",
] }
# Explorer 前台目录检测(IShellWindows COM):仅引入用到的 feature,控制编译体积
windows = { version = "0.52", features = [
"Win32_Foundation",
"Win32_System_Com",
"Win32_System_Ole",
"Win32_System_Variant",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-autostart = "2"
View File
Binary file not shown.
Binary file not shown.
@@ -16,7 +16,6 @@ const DEFAULT_CONFIG = {
interceptDownload: true,
minSize: 0,
excludeDomains: [],
showNotifications: true,
// 嗅探开关
sniffEnabled: true,
// 嗅探的资源类型:只保留视频/音频/图片/压缩包/种子/安装包
@@ -386,28 +385,13 @@ async function handleDownloadCreated(downloadItem) {
const filename = downloadItem.filename || ''
try {
const id = await addDownload(url, filename, downloadItem.referrer, '')
await notify('已添加到 Thing', `${filename || url}`)
await addDownload(url, filename, downloadItem.referrer, '')
} catch (e) {
await notify('Thing 添加失败', `${filename || url}\n${e.message}`)
// 添加失败:回退到浏览器自带下载,不弹通知
try { await chrome.downloads.download({ url }) } catch { /* ignore */ }
}
}
// ===== 通知 =====
async function notify(title, message) {
const config = await getConfig()
if (!config.showNotifications) return
try {
await chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon-128.png',
title,
message
})
} catch { /* ignore */ }
}
// ===== 右键菜单 =====
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
@@ -428,10 +412,7 @@ chrome.contextMenus.onClicked.addListener(async (info, tab) => {
const filename = url.split('/').pop()?.split('?')[0] || ''
try {
await addDownload(url, filename, info.pageUrl, '')
await notify('已添加到 Thing', `${filename || url}`)
} catch (e) {
await notify('Thing 添加失败', `${e.message}`)
}
} catch (e) { /* 忽略:添加失败时不打扰用户 */ }
}
})
@@ -11,9 +11,7 @@
"permissions": [
"downloads",
"storage",
"notifications",
"webRequest",
"webNavigation",
"contextMenus",
"tabs",
"scripting"
@@ -87,11 +87,6 @@
<span>启用资源嗅探</span>
</label>
<label class="checkbox">
<input type="checkbox" id="showNotifications" />
<span>显示桌面通知</span>
</label>
<label class="field">
<span>下载最小文件大小(字节,0=全部)</span>
<input type="number" id="minSize" min="0" placeholder="0" />
@@ -12,7 +12,6 @@ const DEFAULT_CONFIG = {
interceptDownload: true,
minSize: 0,
excludeDomains: [],
showNotifications: true,
sniffEnabled: true,
sniffTypes: ['video', 'audio', 'image', 'archive', 'torrent', 'installer'],
sniffMaxItems: 200,
@@ -57,7 +56,6 @@ function fillForm(config) {
$('secret').value = config.secret || ''
$('interceptDownload').checked = config.interceptDownload !== false
$('sniffEnabled').checked = config.sniffEnabled !== false
$('showNotifications').checked = config.showNotifications !== false
$('minSize').value = config.minSize || 0
$('sniffMinSize').value = config.sniffMinSize ?? DEFAULT_CONFIG.sniffMinSize
$('excludeDomains').value = (config.excludeDomains || []).join(',')
@@ -69,7 +67,6 @@ function readForm() {
secret: $('secret').value.trim(),
interceptDownload: $('interceptDownload').checked,
sniffEnabled: $('sniffEnabled').checked,
showNotifications: $('showNotifications').checked,
minSize: parseInt($('minSize').value, 10) || 0,
sniffMinSize: parseInt($('sniffMinSize').value, 10) || 0,
excludeDomains: $('excludeDomains').value
+3
View File
@@ -29,6 +29,7 @@ pub mod events {
// 快速面板
pub const QUICKPANEL_SHOW: &str = "quickpanel-show";
pub const QUICKPANEL_HIDE: &str = "quickpanel-hide";
pub const QUICKPANEL_EXTRACT_PROGRESS: &str = "quickpanel-extract-progress";
// 监控
pub const MONITOR_DATA: &str = "monitor-data";
pub const MONITOR_NETWORK: &str = "monitor-network";
@@ -51,4 +52,6 @@ pub mod events {
// 进程与下载
pub const PROCESS_STATUS_CHANGED: &str = "process-status-changed";
pub const DOWNLOAD_ADDED: &str = "download-added";
/// 浏览器扩展通过 HTTP API 新增下载(前端需置前主窗口并跳到下载画面)
pub const DOWNLOAD_EXTENSION_ADDED: &str = "download-extension-added";
}
+6 -3
View File
@@ -761,7 +761,7 @@ impl DownloadEngine {
last_time = now;
// 更新任务状态 + 发送进度事件
let total_size = {
let (total_size, live_status) = {
let mut tasks = engine.inner.tasks.lock().unwrap_or_else(|e| e.into_inner());
if let Some(task) = tasks.get_mut(&id_monitor) {
task.completed_size = completed;
@@ -771,7 +771,10 @@ impl DownloadEngine {
seg.completed = prog.load(Ordering::Relaxed);
}
}
task.total_size
// 读取任务实时状态而非硬编码 Active:
// 暂停后监控循环 break 前可能发出的最后一次事件
// 必须携带 Paused,否则前端会把任务状态覆盖回"下载中"
(task.total_size, task.status.clone())
} else {
break;
}
@@ -784,7 +787,7 @@ impl DownloadEngine {
completed_size: completed,
total_size,
speed,
status: TaskStatus::Active,
status: live_status,
},
);
}
+16 -3
View File
@@ -9,6 +9,7 @@ use axum::{
Router,
};
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, Manager};
use super::engine::DownloadEngine;
use super::task::DownloadTask;
@@ -45,14 +46,18 @@ struct ErrorResponse {
impl ExtensionServer {
/// 启动 HTTP API 服务器(绑定到 127.0.0.1:port
pub async fn start(engine: DownloadEngine, port: u16, secret: String) {
pub async fn start(engine: DownloadEngine, port: u16, secret: String, app_handle: AppHandle) {
let addr: SocketAddr = format!("127.0.0.1:{}", port).parse().expect("无效端口");
let app = Router::new()
.route("/health", get(health))
.route("/api/downloads", post(create_download).get(list_downloads))
.route("/api/downloads/:id", axum::routing::delete(remove_download))
.with_state(AppState { engine, secret });
.with_state(AppState {
engine,
secret,
app_handle,
});
let listener = match tokio::net::TcpListener::bind(&addr).await {
Ok(l) => l,
@@ -74,6 +79,7 @@ impl ExtensionServer {
struct AppState {
engine: DownloadEngine,
secret: String,
app_handle: AppHandle,
}
/// 鉴权检查:如果配置了 secret,校验 Bearer token
@@ -109,7 +115,14 @@ async fn create_download(
}
match state.engine.add_task(req.url, req.filename, req.dir, req.headers, true).await {
Ok(id) => Ok(Json(CreateDownloadResponse { id })),
Ok(id) => {
// 浏览器扩展发起下载:置前主窗口并通知前端跳到下载画面(替代原桌面通知)
crate::tray_menu::focus_main_window(&state.app_handle);
let _ = state
.app_handle
.emit(crate::constants::events::DOWNLOAD_EXTENSION_ADDED, ());
Ok(Json(CreateDownloadResponse { id }))
}
Err(e) => Err((StatusCode::BAD_REQUEST, Json(ErrorResponse { error: e }))),
}
}
+17 -7
View File
@@ -68,14 +68,15 @@ use clipboard::{
clipboard_status, clipboard_stop, clipboard_unregister_shortcut,
};
use quickpanel::{
quickpanel_build_file_index, quickpanel_clear_app_icon_cache, quickpanel_delete_file,
quickpanel_apply_rename, quickpanel_batch_extract, quickpanel_build_file_index,
quickpanel_clear_app_icon_cache, quickpanel_delete_file, quickpanel_delete_files,
quickpanel_file_index_stats, quickpanel_get_app_icon, quickpanel_get_settings,
quickpanel_get_special_locations, quickpanel_hide_popup, quickpanel_init_file_index,
quickpanel_lock_screen, quickpanel_open_file, quickpanel_open_special,
quickpanel_register_shortcut, quickpanel_reveal_in_explorer, quickpanel_run_custom_command,
quickpanel_run_system_command, quickpanel_save_settings, quickpanel_scan_apps,
quickpanel_search_files, quickpanel_show_popup, quickpanel_show_window,
quickpanel_unregister_shortcut,
quickpanel_list_archives, quickpanel_list_dir, quickpanel_lock_screen, quickpanel_open_file,
quickpanel_open_special, quickpanel_preview_rename, quickpanel_register_shortcut,
quickpanel_reveal_in_explorer, quickpanel_run_custom_command, quickpanel_run_system_command,
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 updater::{app_version, update_check, update_install, update_thinghk};
@@ -120,7 +121,9 @@ fn export_bindings() {
quickpanel_scan_apps, quickpanel_get_app_icon, quickpanel_clear_app_icon_cache,
quickpanel_reveal_in_explorer, quickpanel_open_file, quickpanel_get_special_locations,
quickpanel_open_special, quickpanel_delete_file, quickpanel_run_custom_command,
quickpanel_run_system_command,
quickpanel_run_system_command, quickpanel_list_archives, quickpanel_list_dir,
quickpanel_batch_extract, quickpanel_preview_rename, quickpanel_apply_rename,
quickpanel_delete_files, quickpanel_focus_main_window,
// clipboard20
clipboard_get_history, clipboard_get_pinned, clipboard_search, clipboard_get_item,
clipboard_set_pinned, clipboard_delete, clipboard_clear, clipboard_copy_back,
@@ -276,10 +279,17 @@ pub fn run() {
quickpanel_reveal_in_explorer,
quickpanel_open_file,
quickpanel_delete_file,
quickpanel_delete_files,
quickpanel_run_custom_command,
quickpanel_run_system_command,
quickpanel_get_special_locations,
quickpanel_open_special,
quickpanel_list_archives,
quickpanel_list_dir,
quickpanel_batch_extract,
quickpanel_preview_rename,
quickpanel_apply_rename,
quickpanel_focus_main_window,
tray_menu_action,
tray_menu_hide,
tray_menu_ready,
+344
View File
@@ -0,0 +1,344 @@
//! 快速面板:基于 7-Zipbinaries/7z.exe)的批量文件操作。
//!
//! - 批量解压:逐文件调用 7z 控制台,支持一次传入统一密码(`-p`),
//! 每完成一个文件通过事件推送进度,前端可实时展示。
//! - 批量重命名:`regex` 匹配文件名生成预览,确认后执行 `fs::rename`。
//! - 目录列表:供前端展示当前目录的压缩包 / 文件列表。
use std::path::{Path, PathBuf};
use std::process::Command;
use serde::{Deserialize, Serialize};
use specta::Type;
use tauri::{AppHandle, Emitter, Manager};
use crate::constants::events::QUICKPANEL_EXTRACT_PROGRESS;
/// 7z 可执行文件名(与 7z.dll 同目录,位于 resources/binaries)。
const _7Z_EXE: &str = "binaries/7z.exe";
/// 支持的压缩包扩展名(解压面板中列出)。
const ARCHIVE_EXTS: &[&str] = &[
".zip", ".7z", ".rar", ".tar", ".gz", ".tgz", ".bz2", ".tbz", ".xz", ".txz", ".zst",
".tzst", ".cab", ".lzma",
];
/// 定位 7z 可执行文件(resources/binaries/7z.exe)。
fn locate_7z(app: &AppHandle) -> Option<PathBuf> {
let path = app
.path()
.resolve(_7Z_EXE, tauri::path::BaseDirectory::Resource)
.ok()?;
if path.exists() {
Some(path)
} else {
None
}
}
#[derive(Serialize, Deserialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchiveInfo {
pub name: String,
pub path: String,
pub size: u64,
}
#[derive(Serialize, Deserialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct FileEntry {
pub name: String,
pub path: String,
pub is_dir: bool,
pub size: u64,
}
#[derive(Serialize, Deserialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ExtractResult {
pub name: String,
pub path: String,
pub ok: bool,
pub error: String,
}
#[derive(Serialize, Deserialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ExtractProgress {
pub done: usize,
pub total: usize,
pub current: String,
pub ok: bool,
pub error: String,
}
#[derive(Serialize, Deserialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RenamePreview {
pub path: String,
pub old_name: String,
pub new_name: String,
pub error: String,
}
#[derive(Serialize, Deserialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RenameItem {
pub path: String,
pub old_name: String,
pub new_name: String,
}
#[derive(Serialize, Deserialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RenameResult {
pub old_name: String,
pub new_name: String,
pub ok: bool,
pub error: String,
}
fn is_archive(name: &str) -> bool {
let lower = name.to_lowercase();
ARCHIVE_EXTS.iter().any(|ext| lower.ends_with(ext))
}
/// 列出目录下的压缩包文件(供批量解压面板使用)。
#[tauri::command]
#[specta::specta]
pub async fn quickpanel_list_archives(dir: String) -> Result<Vec<ArchiveInfo>, String> {
tauri::async_runtime::spawn_blocking(move || {
let d = Path::new(&dir);
if !d.is_dir() {
return Err(format!("目录不存在: {dir}"));
}
let mut out = Vec::new();
for entry in std::fs::read_dir(d).map_err(|e| format!("读取目录失败: {e}"))? {
let Ok(entry) = entry else { continue };
let path = entry.path();
if !path.is_file() {
continue;
}
let name = path
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
if is_archive(&name) {
let size = path.metadata().map(|m| m.len()).unwrap_or(0);
out.push(ArchiveInfo {
name,
path: path.to_string_lossy().to_string(),
size,
});
}
}
out.sort_by(|a, b| a.name.cmp(&b.name));
Ok(out)
})
.await
.map_err(|e| format!("读取压缩包失败: {e}"))?
}
/// 列出目录下的全部条目(供批量重命名/删除面板使用,不含子目录递归)。
#[tauri::command]
#[specta::specta]
pub async fn quickpanel_list_dir(dir: String) -> Result<Vec<FileEntry>, String> {
tauri::async_runtime::spawn_blocking(move || {
let d = Path::new(&dir);
if !d.is_dir() {
return Err(format!("目录不存在: {dir}"));
}
let mut out = Vec::new();
for entry in std::fs::read_dir(d).map_err(|e| format!("读取目录失败: {e}"))? {
let Ok(entry) = entry else { continue };
let path = entry.path();
let is_dir = path.is_dir();
let name = path
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
let size = if is_dir {
0
} else {
path.metadata().map(|m| m.len()).unwrap_or(0)
};
out.push(FileEntry {
name,
path: path.to_string_lossy().to_string(),
is_dir,
size,
});
}
out.sort_by(|a, b| {
b.is_dir
.cmp(&a.is_dir)
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
});
Ok(out)
})
.await
.map_err(|e| format!("读取目录失败: {e}"))?
}
fn extract_one(
exe: &Path,
archive: &str,
dest: &str,
password: Option<&str>,
into_subfolder: bool,
) -> Result<(), String> {
let archive_path = Path::new(archive);
let mut cmd = Command::new(exe);
cmd.arg("x").arg(archive_path);
if into_subfolder {
// 解压到「压缩包同名子文件夹」,避免文件散落在当前目录。
let sub = archive_path
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| "extracted".into());
let sub_dir = Path::new(dest).join(&sub);
std::fs::create_dir_all(&sub_dir).map_err(|e| format!("创建目录 {sub} 失败: {e}"))?;
cmd.arg(format!("-o{}", sub_dir.display()));
} else {
cmd.arg(format!("-o{}", dest));
}
cmd.arg("-y"); // 全自动覆盖确认
if let Some(p) = password.filter(|p| !p.is_empty()) {
cmd.arg(format!("-p{p}"));
}
// 静默普通输出,仅错误进 stderr,逐文件粒度足够时无需 -bsp1 进度。
cmd.arg("-bso0").arg("-bse1").arg("-bsp0");
// 以 7z.exe 所在目录为工作目录,确保同目录的 7z.dll 可被加载。
if let Some(dir) = exe.parent() {
cmd.current_dir(dir);
}
let output = cmd.output().map_err(|e| format!("启动 7-Zip 失败: {e}"))?;
if output.status.success() {
Ok(())
} else {
let msg = String::from_utf8_lossy(&output.stderr).trim().to_string();
let code = output.status.code().unwrap_or(-1);
Err(if msg.is_empty() {
format!("退出码 {code}")
} else {
msg
})
}
}
/// 批量解压。`files` 为压缩包路径列表,`dest_dir` 为目标目录,
/// `password` 为统一解压密码(可空),`into_subfolder` 是否解压到同名子文件夹。
/// 每完成一个文件通过 `quickpanel-extract-progress` 事件推送进度。
#[tauri::command]
#[specta::specta]
pub async fn quickpanel_batch_extract(
app: AppHandle,
files: Vec<String>,
dest_dir: String,
password: Option<String>,
into_subfolder: bool,
) -> Result<Vec<ExtractResult>, String> {
let exe = locate_7z(&app).ok_or("未找到 7-Zip 组件(binaries/7z.exe),请重新安装")?;
let total = files.len();
let results = tauri::async_runtime::spawn_blocking(move || {
let mut results = Vec::with_capacity(total);
for (idx, file) in files.iter().enumerate() {
let err = extract_one(&exe, file, &dest_dir, password.as_deref(), into_subfolder);
let name = Path::new(file)
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| file.clone());
let (ok, error) = match err {
Ok(()) => (true, String::new()),
Err(e) => (false, e),
};
results.push(ExtractResult {
name,
path: file.clone(),
ok,
error: error.clone(),
});
let _ = app.emit(
QUICKPANEL_EXTRACT_PROGRESS,
ExtractProgress {
done: idx + 1,
total,
current: results[idx].name.clone(),
ok,
error,
},
);
}
results
})
.await
.map_err(|e| format!("解压任务异常终止: {e}"))?;
Ok(results)
}
/// 正则批量重命名预览:对每个文件名应用 `pattern → replacement`
/// 仅返回有匹配的文件,`newName` 为替换结果。
#[tauri::command]
#[specta::specta]
pub async fn quickpanel_preview_rename(
files: Vec<String>,
pattern: String,
replacement: String,
) -> Result<Vec<RenamePreview>, String> {
let re = regex::Regex::new(&pattern).map_err(|e| format!("正则表达式无效: {e}"))?;
let mut out = Vec::new();
for file in files {
let name = Path::new(&file)
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
if !re.is_match(&name) {
continue;
}
let new_name = re.replace_all(&name, replacement.as_str()).to_string();
let error = if new_name.is_empty() || new_name == name {
"名称未变化".to_string()
} else {
String::new()
};
out.push(RenamePreview {
path: file,
old_name: name,
new_name,
error,
});
}
Ok(out)
}
/// 执行重命名。同一目录下若目标已存在则跳过该项。
#[tauri::command]
#[specta::specta]
pub async fn quickpanel_apply_rename(items: Vec<RenameItem>) -> Result<Vec<RenameResult>, String> {
let mut out = Vec::new();
for item in items {
let result = (|| -> Result<(), String> {
if item.new_name.is_empty() {
return Err("新文件名为空".into());
}
if item.new_name.contains(['/', '\\', ':', '*', '?', '"', '<', '>', '|']) {
return Err("文件名包含非法字符".into());
}
let old = Path::new(&item.path);
let parent = old.parent().unwrap_or(Path::new("."));
let new_path = parent.join(&item.new_name);
if new_path.exists() {
return Err("目标已存在".into());
}
std::fs::rename(old, &new_path).map_err(|e| format!("重命名失败: {e}"))?;
Ok(())
})();
out.push(RenameResult {
old_name: item.old_name,
new_name: item.new_name,
ok: result.is_ok(),
error: result.err().unwrap_or_default(),
});
}
Ok(out)
}
+106 -5
View File
@@ -1,10 +1,20 @@
//! Tauri 命令:快速面板模块
use tauri::AppHandle;
use tauri::{AppHandle, Manager};
use super::popup::{self, QuickPanelSettings};
use super::{file_index, app_scanner, icon_extractor};
/// 批量删除单个条目的结果。
#[derive(serde::Serialize, serde::Deserialize, specta::Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DeleteResult {
pub name: String,
pub path: String,
pub ok: bool,
pub error: String,
}
/// 读取快速面板设置(快捷键等)
#[tauri::command]
#[specta::specta]
@@ -76,6 +86,26 @@ pub async fn quickpanel_show_window(app: AppHandle) -> Result<(), String> {
Ok(())
}
/// 显示主窗口并强制置为前台。
/// Tauri 的 set_focus 在 Windows 上受前台锁定限制,主窗口被其他应用遮挡时无法到前台;
/// 改用原生 SetForegroundWindow + BringWindowToTop(模拟 Alt 键重置前台锁定)。
#[tauri::command]
#[specta::specta]
pub async fn quickpanel_focus_main_window(app: AppHandle) -> Result<(), String> {
use crate::constants::windows::MAIN;
if let Some(window) = app.get_webview_window(MAIN) {
window.show().map_err(|e| e.to_string())?;
window.unminimize().map_err(|e| e.to_string())?;
match window.hwnd() {
Ok(hwnd) => crate::win32_util::force_foreground(hwnd.0 as isize),
Err(_) => {
window.set_focus().ok();
}
}
}
Ok(())
}
/// 锁定屏幕(Windows: rundll32 user32.dll,LockWorkStationCREATE_NO_WINDOW 避免黑窗)
#[tauri::command]
#[specta::specta]
@@ -95,13 +125,21 @@ pub fn quickpanel_lock_screen() -> Result<(), String> {
Ok(())
}
/// 初始化文件索引数据库(应用启动时调用)
/// 初始化文件索引数据库(应用启动时调用)
/// 若存在上次构建的索引(last_built_dirs 非空),自动恢复 notify 增量监听,
/// 无需重建即可继续自动同步文件变更。
#[tauri::command]
#[specta::specta]
pub async fn quickpanel_init_file_index(app: AppHandle) -> Result<(), String> {
tauri::async_runtime::spawn_blocking(move || file_index::init(&app))
.await
.map_err(|e| format!("索引初始化任务失败: {}", e))
tauri::async_runtime::spawn_blocking(move || {
file_index::init(&app);
let stats = file_index::stats();
if stats.last_built_at > 0 && !stats.last_built_dirs.is_empty() {
file_index::start_watcher(&stats.last_built_dirs);
}
})
.await
.map_err(|e| format!("索引初始化任务失败: {}", e))
}
/// 构建文件索引(全量重建,阻塞操作建议在 spawn_blocking 调用)
@@ -305,6 +343,69 @@ fn delete_file_impl(path: &str) -> Result<(), String> {
Ok(())
}
/// 批量删除文件/目录。`force=false` 时移动至回收站;`force=true` 时先递归清除
/// 只读属性再永久删除(可绕过只读/部分占用导致的删除失败,但被其他进程真正
/// 锁定的文件仍会失败并返回原因)。
#[tauri::command]
#[specta::specta]
pub async fn quickpanel_delete_files(
paths: Vec<String>,
force: bool,
) -> Result<Vec<DeleteResult>, String> {
tauri::async_runtime::spawn_blocking(move || {
let mut out = Vec::new();
for path in paths {
let name = std::path::Path::new(&path)
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_else(|| path.clone());
let result = if force {
delete_force_impl(&path)
} else {
delete_file_impl(&path)
};
out.push(DeleteResult {
name,
path: path.clone(),
ok: result.is_ok(),
error: result.err().unwrap_or_default(),
});
}
Ok(out)
})
.await
.map_err(|e| format!("删除任务失败: {e}"))?
}
/// 强行删除:递归清除只读属性后永久删除(不经过回收站)。
fn delete_force_impl(path: &str) -> Result<(), String> {
let p = std::path::Path::new(path);
clear_readonly(p);
if p.is_dir() {
std::fs::remove_dir_all(p).map_err(|e| format!("删除失败: {e}"))
} else {
std::fs::remove_file(p).map_err(|e| format!("删除失败: {e}"))
}
}
/// 递归清除只读属性(只读文件/目录无法直接删除)。
fn clear_readonly(path: &std::path::Path) {
if let Ok(meta) = std::fs::metadata(path) {
if meta.permissions().readonly() {
let mut perms = meta.permissions();
perms.set_readonly(false);
let _ = std::fs::set_permissions(path, perms);
}
if meta.is_dir() {
if let Ok(rd) = std::fs::read_dir(path) {
for entry in rd.flatten() {
clear_readonly(&entry.path());
}
}
}
}
}
/// 运行自定义命令(执行可执行文件 + 参数)
/// .lnk 快捷方式不能直接 spawnos error 193),需通过 cmd /C 启动
#[tauri::command]
+139
View File
@@ -0,0 +1,139 @@
//! 快速面板:检测前台 Explorer 窗口的当前目录。
//!
//! 必须在快捷键回调(`show_popup`)内调用:此时前台窗口仍是资源管理器,
//! 面板尚未取得焦点,`GetForegroundWindow` 拿到的才是 Explorer 主窗口;
//! 若等面板显示后再调用,前台就变成面板自身了。
//!
//! 思路(Listary / PowerToys Run 同款):前台窗口 HWND 匹配 `IShellWindows`
//! 中某个 Shell 窗口 → 取其 `LocationURL`file:///...)→ 转成本地路径。
//!
//! Win11 多选项卡:同一顶层窗口下每个选项卡都是独立的 `IShellWindows` 条目,
//! 共享顶层 HWND。活动选项卡的内容窗口(`ShellTabWindowClass`)在子窗口
//! z-order 顶层,用 `IID_IShellBrowser` 作为 `QueryService` 的 service ID 获取
//! 每个选项卡自己的 `IShellBrowser`(而非 `SID_STopLevelBrowser` 返回的顶层
//! browser),再通过 `GetWindow()` 拿到该选项卡的内容窗口句柄,与活动选项卡
//! 的内容窗口比对,从而定位当前正在浏览的选项卡(`IsWindowVisible` 对所有
//! 选项卡都成立,不可用)。
use std::path::Path;
#[cfg(windows)]
use windows::core::ComInterface;
#[cfg(windows)]
use windows::Win32::Foundation::HWND;
#[cfg(windows)]
use windows::Win32::System::Com::{
CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_APARTMENTTHREADED,
IServiceProvider,
};
#[cfg(windows)]
use windows::Win32::System::Variant::{VARIANT, VT_I4};
#[cfg(windows)]
use windows::Win32::UI::Shell::{
IWebBrowserApp, IShellBrowser, IShellWindows, ShellWindows,
};
#[cfg(windows)]
use windows::Win32::UI::WindowsAndMessaging::{
GetClassNameW, GetForegroundWindow, GetWindow, GW_CHILD, GW_HWNDNEXT,
};
/// 检测前台 Explorer 窗口的当前目录。
/// 返回 `None`:前台不是 Explorer / COM 初始化失败 / URL 无法转路径。
#[cfg(windows)]
pub fn detect_explorer_folder() -> Option<String> {
// 首次 COM 初始化失败(例如已在 MTA 线程)时,后续 COM 调用一般仍可用,忽略错误继续。
let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
let fg = unsafe { GetForegroundWindow() };
let result = if fg.0 == 0 {
None
} else {
unsafe { find_folder_for_hwnd(fg) }
};
unsafe { CoUninitialize() };
result
}
#[cfg(windows)]
unsafe fn find_folder_for_hwnd(fg: HWND) -> Option<String> {
let shell: IShellWindows = CoCreateInstance(&ShellWindows, None, CLSCTX_ALL).ok()?;
let count = shell.Count().ok()?;
// Win11 多选项卡:活动选项卡的内容窗口(ShellTabWindowClass)在子窗口 z-order
// 顶层。在 IShellWindows 条目中,用 IShellBrowser::GetWindow() 取到的内容窗口
// HWND 与它比对,即可定位当前正在浏览的选项卡(IsWindowVisible 对所有选项卡
// 都成立,不可用)。
let active_tab = find_active_shell_tab(fg);
for i in 0..count {
// 索引过期的窗口会返回失败,跳过继续即可,不能 `?` 提前结束整个循环。
// 0.52 的 Win32 VARIANT 无 From<i32>,手动构造 VT_I4 变体。
let mut index = VARIANT::default();
{
let value = &mut *index.Anonymous.Anonymous;
value.vt = VT_I4;
value.Anonymous.lVal = i;
}
let Ok(dispatch) = shell.Item(index) else { continue };
let Ok(app) = dispatch.cast::<IWebBrowserApp>() else { continue };
// 只考虑前台顶层窗口对应的条目;同一窗口的多个选项卡条目共享顶层句柄。
let Ok(hwnd) = app.HWND() else { continue };
if HWND(hwnd.0) != fg {
continue;
}
// 有选项卡时,必须匹配活动选项卡的内容窗口;否则退化为任意条目(旧版无选项卡)。
if let Some(active) = active_tab {
let Ok(svc) = app.cast::<IServiceProvider>() else { continue };
let Ok(browser) = svc.QueryService::<IShellBrowser>(&IShellBrowser::IID) else {
continue;
};
let Ok(this_tab) = browser.GetWindow() else { continue };
if this_tab != active {
continue;
}
}
if let Ok(url) = app.LocationURL() {
return url_to_path(&url.to_string());
}
}
None
}
/// 枚举前台窗口的子窗口(z-order 自上而下),返回第一个类名为 `ShellTabWindowClass`
/// 的窗口句柄,即 Win11 资源管理器活动选项卡的内容窗口;无选项卡时返回 `None`。
#[cfg(windows)]
unsafe fn find_active_shell_tab(fg: HWND) -> Option<HWND> {
const CLASS: &str = "ShellTabWindowClass";
let mut hwnd = GetWindow(fg, GW_CHILD);
while hwnd.0 != 0 {
let mut buf = [0u16; 64];
let len = GetClassNameW(hwnd, &mut buf);
if len > 0 {
let name = String::from_utf16_lossy(&buf[..len as usize]);
if name == CLASS {
return Some(hwnd);
}
}
hwnd = GetWindow(hwnd, GW_HWNDNEXT);
}
None
}
/// 把 `file:///C:/xxx`(可能带百分号编码)转成本地路径,仅接受目录。
#[cfg(windows)]
fn url_to_path(url: &str) -> Option<String> {
if !url.starts_with("file:") {
return None;
}
let parsed = url::Url::parse(url).ok()?;
let path = parsed.to_file_path().ok()?;
let path = Path::new(&path);
if path.is_dir() {
Some(path.to_string_lossy().to_string())
} else {
None
}
}
/// 非 Windows 平台占位:保持模块可编译。
#[cfg(not(windows))]
pub fn detect_explorer_folder() -> Option<String> {
None
}
+37 -2
View File
@@ -344,16 +344,51 @@ pub fn start_watcher(dirs: &[String]) {
crate::logger::log_info("quickpanel", &format!("notify 监听已启动,监听 {} 个目录", dirs.len()));
}
/// 处理文件系统事件:创建/修改 → upsert,删除 → remove,重命名 → remove + upsert
/// 处理文件系统事件:
/// - 创建/数据或元数据修改 → upsert
/// - 重命名:旧路径(From) → remove,新路径(To) → upsert
/// - 删除 → remove
fn handle_fs_event(event: &notify::Event) {
use notify::event::{ModifyKind, RenameMode};
match event.kind {
EventKind::Create(_) | EventKind::Modify(_) => {
// 创建、数据/元数据修改、类型未知 → upsert
EventKind::Create(_)
| EventKind::Modify(ModifyKind::Data(_))
| EventKind::Modify(ModifyKind::Metadata(_))
| EventKind::Modify(ModifyKind::Other)
| EventKind::Modify(ModifyKind::Any) => {
for path in &event.paths {
if path.exists() {
upsert_path(path);
}
}
}
// 重命名旧路径 → 删除旧记录(含目录子项,避免索引残留失效路径)
EventKind::Modify(ModifyKind::Name(RenameMode::From)) => {
for path in &event.paths {
remove_path(path);
}
}
// 重命名新路径 → 写入新记录
EventKind::Modify(ModifyKind::Name(RenameMode::To)) => {
for path in &event.paths {
if path.exists() {
upsert_path(path);
}
}
}
// 重命名模式未知:存在则写入,不存在则删除(幂等兜底)
EventKind::Modify(ModifyKind::Name(RenameMode::Any | RenameMode::Both)) => {
for path in &event.paths {
if path.exists() {
upsert_path(path);
} else {
remove_path(path);
}
}
}
// 删除 → remove(含子项)
EventKind::Remove(_) => {
for path in &event.paths {
remove_path(path);
+13 -7
View File
@@ -4,21 +4,27 @@
//! Phase 2fuzzy + 拼音引擎,command/calc/web/system Provider
//! Phase 3:文件索引(walkdir + rusqlite)、应用扫描、剪贴板历史复用
pub mod actions;
pub mod app_scanner;
pub mod commands;
pub mod explorer;
pub mod file_index;
pub mod icon_extractor;
pub mod popup;
pub mod special_locations;
pub use actions::{
quickpanel_apply_rename, quickpanel_batch_extract, quickpanel_list_archives,
quickpanel_list_dir, quickpanel_preview_rename,
};
pub use commands::{
quickpanel_build_file_index, quickpanel_clear_app_icon_cache, quickpanel_delete_file,
quickpanel_file_index_stats, quickpanel_get_app_icon, quickpanel_get_settings,
quickpanel_get_special_locations, quickpanel_hide_popup, quickpanel_init_file_index,
quickpanel_lock_screen, quickpanel_open_file, quickpanel_open_special,
quickpanel_register_shortcut, quickpanel_reveal_in_explorer, quickpanel_run_custom_command,
quickpanel_run_system_command, quickpanel_save_settings, quickpanel_scan_apps,
quickpanel_search_files, quickpanel_show_popup, quickpanel_show_window,
quickpanel_unregister_shortcut,
quickpanel_delete_files, quickpanel_file_index_stats, quickpanel_focus_main_window,
quickpanel_get_app_icon, quickpanel_get_settings, quickpanel_get_special_locations,
quickpanel_hide_popup, quickpanel_init_file_index, quickpanel_lock_screen,
quickpanel_open_file, quickpanel_open_special, quickpanel_register_shortcut,
quickpanel_reveal_in_explorer, quickpanel_run_custom_command, quickpanel_run_system_command,
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
quickpanel_show_window, quickpanel_unregister_shortcut,
};
pub use popup::{ensure_window, load_settings};
+25 -4
View File
@@ -20,6 +20,8 @@ use tauri::window::{Effect, EffectsBuilder};
use crate::win32_util::{get_cursor_pos, get_work_area_at_point, get_dpi_for_point};
use super::explorer;
use specta::Type;
/// 弹窗窗口标签
@@ -29,6 +31,24 @@ pub const POPUP_LABEL: &str = "quick-panel";
const WIN_W: f64 = 600.0;
const WIN_H: f64 = 420.0;
/// `quickpanel-show` 事件负载:携带快捷键按下时检测到的 Explorer 当前目录,
/// 前端据此渲染"当前目录"文件操作分组。
#[derive(Clone, Serialize)]
pub struct QuickPanelShowPayload {
pub dir: Option<String>,
}
/// 检测前台 Explorer 目录并连同 show 事件一起下发。
/// 必须在快捷键回调内调用:此时前台窗口仍是 Explorer,面板尚未抢焦点。
fn emit_show(app: &AppHandle) {
let dir = explorer::detect_explorer_folder();
crate::logger::log_info("quickpanel", &format!("show_popup: explorer_dir={:?}", dir));
let _ = app.emit(
crate::constants::events::QUICKPANEL_SHOW,
QuickPanelShowPayload { dir },
);
}
/// 标志:show_popup 兜底创建路径设为 true,前端 onMounted 回调 show_window 时据此判断是否显示。
/// 预创建路径不设置,避免应用启动时弹窗自动弹出。
static POPUP_PENDING_SHOW: AtomicBool = AtomicBool::new(false);
@@ -226,14 +246,15 @@ pub fn show_popup(app: &AppHandle) {
// 窗口已存在:移动 + 显示 + 请求焦点
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
// 必须先于窗口显示/聚焦检测 Explorer 目录:show/set_focus 会立即抢走前台焦点,
// 之后调用 GetForegroundWindow 拿到的就是面板自身了。
emit_show(app);
let _ = win.set_position(tauri::Position::Physical(tauri::PhysicalPosition {
x: x as i32,
y: y as i32,
}));
let _ = win.show();
let _ = win.set_focus();
// 通知前端刷新数据
let _ = app.emit(crate::constants::events::QUICKPANEL_SHOW, ());
return;
}
@@ -261,10 +282,10 @@ pub fn show_window(app: &AppHandle) {
y: y as i32,
}));
}
// 同样先检测 Explorer 目录再显示,避免面板抢焦点导致检测失败。
emit_show(app);
let _ = win.show();
let _ = win.set_focus();
// 通知前端刷新数据
let _ = app.emit(crate::constants::events::QUICKPANEL_SHOW, ());
}
}
+2 -1
View File
@@ -66,8 +66,9 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
let server_engine = engine.clone();
let server_port = settings.extension_port;
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).await;
ExtensionServer::start(server_engine, server_port, server_secret, server_app).await;
});
// ===== 剪贴板模块:监听 + 快捷键 + 预创建弹窗 =====
+76 -45
View File
@@ -21,10 +21,10 @@ use tauri::{
static LAST_SHOW_TIME: Mutex<Option<Instant>> = Mutex::new(None);
/// 保存最近一次右键时计算出的定位参数(物理坐标),供 `tray_menu_ready` 使用
/// (x, tray_top, wa_top, wa_bottom, scale)
/// (x, cursor_y, screen_top, screen_bottom, scale)
static LAST_MENU_LAYOUT: Mutex<Option<(f64, f64, f64, f64, f64)>> = Mutex::new(None);
use crate::win32_util::{get_work_area, get_work_area_at_point, get_dpi_for_point};
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::process_manager::{ProcessManager, ProcessStatus};
@@ -148,7 +148,25 @@ async fn fetch_proxy_nodes(app: &AppHandle) -> Option<(String, Vec<(String, Opti
// ===== 获取菜单状态 =====
pub async fn get_tray_menu_state(app: &AppHandle) -> TrayMenuState {
/// 基础状态(不含代理节点)。托盘菜单显示不应受 mihomo API 慢/卡死影响,
/// 因此先秒发基础状态让菜单立即出现,代理节点随后异步补充。
fn get_base_tray_state(app: &AppHandle) -> TrayMenuState {
let proxy_running = is_proxy_running(app);
let monitor_running = is_monitor_running(app);
// 读取 Windows 注册表中的真实系统代理状态(不依赖 settings.json 缓存)
let system_proxy = crate::mihomo_manager::get_system_proxy_windows();
TrayMenuState {
proxy_running,
system_proxy,
monitor_running,
proxy_group: None,
proxy_nodes: vec![],
proxy_current: None,
}
}
/// 完整状态(含代理节点)。可能因调用 mihomo /proxies 而耗时(最长 10s)。
async fn get_full_tray_state(app: &AppHandle) -> TrayMenuState {
let proxy_running = is_proxy_running(app);
let monitor_running = is_monitor_running(app);
// 读取 Windows 注册表中的真实系统代理状态(不依赖 settings.json 缓存)
@@ -183,6 +201,10 @@ pub async fn get_tray_menu_state(app: &AppHandle) -> TrayMenuState {
}
}
pub async fn get_tray_menu_state(app: &AppHandle) -> TrayMenuState {
get_full_tray_state(app).await
}
// ===== 显示/隐藏托盘菜单窗口 =====
/// 托盘菜单窗口尺寸(逻辑像素)
@@ -249,29 +271,30 @@ pub fn precreate_tray_menu_window(app: &AppHandle) {
}
/// 右键托盘时调用:计算定位参数、发送状态给前端,但不立即显示窗口。
/// 窗口等待前端测量内容高度后调用 `tray_menu_ready` 才显示,确保底部精确对齐托盘图标
/// 窗口等待前端测量内容高度后调用 `tray_menu_ready` 才显示,确保底部对齐鼠标点击位置
///
/// `cursor_pos`: 事件报告的鼠标物理坐标`tray_rect`: 托盘图标区域(物理像素)
pub fn show_tray_menu(app: &AppHandle, cursor_pos: (f64, f64), tray_rect: (f64, f64, f64, f64)) {
/// `cursor_pos`: 事件报告的鼠标物理坐标。
pub fn show_tray_menu(app: &AppHandle, cursor_pos: (f64, f64)) {
let (mx, my) = (cursor_pos.0, cursor_pos.1);
let tray_top = tray_rect.1;
// 获取光标所在显示器的工作区(物理像素)
let (wa_left, wa_top, wa_right, wa_bottom) = get_work_area_at_point(mx as i32, my as i32)
.unwrap_or((0, 0, 1920, 1040));
// 获取光标所在显示器的完整边界(含任务栏,物理像素)
// 托盘图标位于任务栏上,菜单需在鼠标位置弹出,因此用屏幕边界而非工作区做 clamp,
// 否则会被工作区底部(任务栏顶部)截断,导致菜单整体被推到任务栏上方。
let (scr_left, scr_top, scr_right, scr_bottom) = get_monitor_bounds_at_point(mx as i32, my as i32)
.unwrap_or((0, 0, 1920, 1080));
// 光标所在显示器的 DPI:菜单宽度按物理像素换算
let dpi = get_dpi_for_point(mx as i32, my as i32).unwrap_or(96);
let scale = dpi as f64 / 96.0;
let menu_w_px = MENU_W * scale;
// 水平:菜单左边缘对齐鼠标 X(向右延伸),超出右边界则左移(物理坐标)
let x = mx.max(wa_left as f64).min(wa_right as f64 - menu_w_px);
// 水平:菜单左边缘对齐鼠标 X(向右延伸),超出屏幕右边界则左移(物理坐标)
let x = mx.max(scr_left as f64).min(scr_right as f64 - menu_w_px);
// 保存布局参数(全部物理坐标 + scale,供 tray_menu_ready 换算前端上报的逻辑高度)
{
let mut layout = LAST_MENU_LAYOUT.lock().unwrap_or_else(|e| e.into_inner());
*layout = Some((x, tray_top, wa_top as f64, wa_bottom as f64, scale));
*layout = Some((x, my, scr_top as f64, scr_bottom as f64, scale));
}
// 记录显示时间,用于失焦防抖
@@ -285,10 +308,20 @@ pub fn show_tray_menu(app: &AppHandle, cursor_pos: (f64, f64), tray_rect: (f64,
precreate_tray_menu_window(app);
}
// 发送状态给前端(前端测量内容高度后调用 tray_menu_ready 显示窗口)
// 发送状态给前端(前端测量内容高度后调用 tray_menu_ready 显示窗口)
// 代理节点拉取默认最长 10s;这里用 1.5s 短超时兜底,避免 mihomo API 卡死时
// 菜单迟迟不出现(超时则退回基础状态,节点区留空,后续 refresh 可补)。
let app_clone = app.clone();
tauri::async_runtime::spawn(async move {
let state = get_tray_menu_state(&app_clone).await;
let state = match tokio::time::timeout(
Duration::from_millis(1500),
get_full_tray_state(&app_clone),
)
.await
{
Ok(s) => s,
Err(_) => get_base_tray_state(&app_clone),
};
let _ = app_clone.emit(crate::constants::events::TRAY_MENU_SHOW, state);
});
}
@@ -306,6 +339,22 @@ async fn refresh_and_emit_state(app: &AppHandle) {
let _ = app.emit(crate::constants::events::TRAY_MENU_STATE_UPDATED, state);
}
/// 显示主窗口并强制置为前台。
/// Tauri 的 set_focus 在 Windows 上受前台锁定限制,主窗口被其他应用遮挡时无法到前台;
/// 改用原生 SetForegroundWindow + BringWindowToTop(模拟 Alt 键重置前台锁定)。
pub fn focus_main_window(app: &AppHandle) {
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
let _ = window.show();
let _ = window.unminimize();
match window.hwnd() {
Ok(hwnd) => crate::win32_util::force_foreground(hwnd.0 as isize),
Err(_) => {
window.set_focus().ok();
}
}
}
}
// ===== Tauri 命令 =====
/// 执行菜单项动作(统一入口)
@@ -367,18 +416,12 @@ pub async fn tray_menu_action(
}
}
"download_new" => {
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
window.show().ok();
window.set_focus().ok();
}
focus_main_window(&app);
let _ = app.emit(crate::constants::events::TRAY_NEW_DOWNLOAD, ());
hide_tray_menu(&app);
}
"settings" => {
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
window.show().ok();
window.set_focus().ok();
}
focus_main_window(&app);
let _ = app.emit(crate::constants::events::TRAY_OPEN_SETTINGS, ());
hide_tray_menu(&app);
}
@@ -411,9 +454,9 @@ pub async fn tray_menu_ready(content_height: f64, app: AppHandle) -> Result<(),
let win = app.get_webview_window(TRAY_MENU_LABEL)
.ok_or("tray-menu window not found")?;
let (x, tray_top, wa_top, wa_bottom, scale) = {
let (x, cursor_y, scr_top, scr_bottom, scale) = {
let layout = LAST_MENU_LAYOUT.lock().unwrap_or_else(|e| e.into_inner());
layout.unwrap_or((0.0, 1040.0, 0.0, 1040.0, 1.0))
layout.unwrap_or((0.0, 1040.0, 0.0, 1080.0, 1.0))
};
// 将内容高度限制在合理范围内(前端上报为逻辑像素)
@@ -427,8 +470,10 @@ pub async fn tray_menu_ready(content_height: f64, app: AppHandle) -> Result<(),
height: win_h_px as u32,
}));
// 垂直:菜单下边缘紧贴托盘图标顶部(向上弹出,物理坐标)
let y = (tray_top - win_h_px).max(wa_top).min(wa_bottom - win_h_px);
// 垂直:菜单底部对齐鼠标点击位置(向上弹出,物理坐标)
// 用屏幕边界而非工作区 clamp,使菜单贴近/覆盖任务栏上的鼠标位置,
// 而不是被工作区底部(任务栏顶部)截断后整体出现在任务栏上方。
let y = (cursor_y - win_h_px).max(scr_top).min(scr_bottom - win_h_px);
let pos = tauri::Position::Physical(tauri::PhysicalPosition {
x: x as i32,
@@ -666,31 +711,17 @@ pub fn create_tray_menu(app: &AppHandle) -> Result<(), tauri::Error> {
button: MouseButton::Left,
..
} => {
// 左键:显示主窗口
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
window.show().ok();
window.set_focus().ok();
}
// 左键:显示主窗口(强制置前,绕过前台锁定)
focus_main_window(&app);
}
TrayIconEvent::Click {
button: MouseButton::Right,
position,
rect,
..
} => {
// 右键:显示自定义菜单窗口(使用事件中的精确坐标)
// 右键:显示自定义菜单窗口(使用事件中的鼠标坐标)
let cursor = (position.x, position.y);
// 从 Rect 的 Position/Size 枚举中提取物理像素值
let (rx, ry) = match rect.position {
tauri::Position::Physical(p) => (p.x as f64, p.y as f64),
tauri::Position::Logical(p) => (p.x, p.y),
};
let (_rw, rh) = match rect.size {
tauri::Size::Physical(s) => (s.width as f64, s.height as f64),
tauri::Size::Logical(s) => (s.width, s.height),
};
let tray_r = (rx, ry, _rw, rh);
show_tray_menu(&app, cursor, tray_r);
show_tray_menu(&app, cursor);
}
_ => {}
}
+48
View File
@@ -60,6 +60,30 @@ pub fn get_work_area_at_point(x: i32, y: i32) -> Option<(i32, i32, i32, i32)> {
}
}
/// 获取指定点所在显示器的完整边界(含任务栏),返回 (left, top, right, bottom) 物理像素。
/// 与 get_work_area_at_point 不同,这里用 rcMonitor 而非 rcWork
/// 用于需要在鼠标位置弹出、允许贴近/覆盖任务栏的场景(如托盘菜单)。
#[cfg(windows)]
pub fn get_monitor_bounds_at_point(x: i32, y: i32) -> Option<(i32, i32, i32, i32)> {
use windows_sys::Win32::Foundation::POINT;
use windows_sys::Win32::Graphics::Gdi::{
GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTONEAREST,
};
let pt = POINT { x, y };
let hmon = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) };
let mut mi: MONITORINFO = unsafe { std::mem::zeroed() };
mi.cbSize = std::mem::size_of::<MONITORINFO>() as u32;
unsafe {
if GetMonitorInfoW(hmon, &mut mi) != 0 {
let rc = mi.rcMonitor;
Some((rc.left, rc.top, rc.right, rc.bottom))
} else {
None
}
}
}
/// 获取指定点所在显示器的有效 DPI。
/// scale factor = dpi / 96。
#[cfg(windows)]
@@ -81,6 +105,24 @@ pub fn get_dpi_for_point(x: i32, y: i32) -> Option<u32> {
}
}
/// 强制将窗口置为前台(绕过 Windows 前台锁定限制)。
/// Tauri 的 set_focus 内部调用 SetForegroundWindow,受前台锁定(foreground lock)限制:
/// 本进程不拥有前台时调用会被系统忽略,导致已打开但被遮挡的窗口无法到前台。
/// 先模拟 Alt 键释放以重置前台锁定,再 SetForegroundWindow + BringWindowToTop。
#[cfg(windows)]
pub fn force_foreground(hwnd: isize) {
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
keybd_event, KEYEVENTF_KEYUP, VK_MENU,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{BringWindowToTop, SetForegroundWindow};
unsafe {
keybd_event(VK_MENU as u8, 0, KEYEVENTF_KEYUP, 0);
let _ = SetForegroundWindow(hwnd);
let _ = BringWindowToTop(hwnd);
}
}
// ===== 非 Windows 平台空实现 =====
#[cfg(not(windows))]
@@ -94,3 +136,9 @@ pub fn get_work_area_at_point(_x: i32, _y: i32) -> Option<(i32, i32, i32, i32)>
#[cfg(not(windows))]
pub fn get_dpi_for_point(_x: i32, _y: i32) -> Option<u32> { None }
#[cfg(not(windows))]
pub fn get_monitor_bounds_at_point(_x: i32, _y: i32) -> Option<(i32, i32, i32, i32)> { None }
#[cfg(not(windows))]
pub fn force_foreground(_hwnd: isize) {}
+34 -7
View File
@@ -14,8 +14,9 @@ import { useProcessStore } from '@/stores/processStore'
import { TooltipProvider } from '@/components/ui/tooltip'
import { moduleRegistry } from '@/modules/registry'
import type { ModuleMeta } from '@/types/module'
import { pendingNewDownload } from '@/lib/trayEvents'
import { pendingNewDownload, pendingShowDownloadTasks } from '@/lib/trayEvents'
import { EVENTS, STORAGE_KEYS } from '@/lib/constants'
import { commands } from '@/lib/bindings'
const appStore = useAppStore()
const screenshotStore = useScreenshotStore()
@@ -43,6 +44,9 @@ const activeModule = ref('')
const activeComponent = shallowRef<Component | null>(null)
/** 模块组件加载中(异步 import 未完成)标志,避免切换期间仍显示上一个模块内容 */
const moduleLoading = ref(false)
/** 当前可显示的模块(内置模块 + 已启用的用户模块),按用户排序显示 */
const availableModules = computed<NavModule[]>(() => {
const enabledIds = appStore.enabledModules.map(m => m.id)
@@ -67,10 +71,15 @@ const availableModules = computed<NavModule[]>(() => {
let moduleLoadSeq = 0
const loadModule = async (moduleId: string) => {
const seq = ++moduleLoadSeq
// 立即清空旧组件并进入加载态,避免异步 import 期间仍渲染上一个模块内容
// (否则 ModuleContainer 以 :key="activeModule" 重挂载旧组件,用户误以为切换失败)
activeComponent.value = null
moduleLoading.value = true
const component = await moduleRegistry.loadComponent(moduleId)
// 过期请求(期间用户又切换了模块)直接丢弃,不覆盖 activeComponent 也不触发钩子
if (seq !== moduleLoadSeq) return
activeComponent.value = component
moduleLoading.value = false
// 调用模块的 onActivate 生命周期钩子
const config = moduleRegistry.getConfig(moduleId)
@@ -151,16 +160,24 @@ onMounted(async () => {
// 快速面板:同步命令缓存与设置到 localStorage,供独立窗口读取
quickpanelStore.syncCommands()
quickpanelStore.syncSettings()
// 初始化文件索引 DB 并恢复增量监听(上次构建过索引时自动恢复,不重建)
commands.quickpanelInitFileIndex().catch(e => console.error('文件索引初始化失败:', e))
// 监听快速面板执行命令事件:显示主窗口 + 切换模块
trayUnlisteners.push(
await listen<{ moduleId: string }>('quickpanel-execute-command', async (e) => {
const win = getCurrentWindow()
// Rust 端强制置前(绕过 Windows 前台锁定,主窗口被遮挡时也能到前台)
try {
await win.show()
await win.unminimize()
await win.setFocus()
await commands.quickpanelFocusMainWindow()
} catch {
/* 忽略窗口操作失败 */
// 回退:前端 show + setFocus
const win = getCurrentWindow()
try {
await win.show()
await win.unminimize()
await win.setFocus()
} catch {
/* 忽略窗口操作失败 */
}
}
handleSearch(e.payload.moduleId)
})
@@ -179,6 +196,16 @@ onMounted(async () => {
}
})
)
// 浏览器扩展新增下载:直接切到下载模块的任务列表页(主窗口已由 Rust 端置前)
trayUnlisteners.push(
await listen(EVENTS.downloadExtensionAdded, () => {
const enabledIds = appStore.enabledModules.map(m => m.id)
if (enabledIds.includes('downloader') || moduleRegistry.getConfig('downloader')?.builtin) {
pendingShowDownloadTasks.value = true
handleModuleChange('downloader')
}
})
)
trayUnlisteners.push(
await listen(EVENTS.trayOpenSettings, () => {
handleModuleChange('settings')
@@ -210,7 +237,7 @@ onUnmounted(() => {
:active-module="activeModule"
@change="handleModuleChange"
/>
<ModuleContainer :active-component="activeComponent" :active-module="activeModule" />
<ModuleContainer :active-component="activeComponent" :active-module="activeModule" :loading="moduleLoading" />
</div>
</div>
<Toaster position="bottom-right" rich-colors close-button :style="{ zIndex: 99999 }" />
+42 -1
View File
@@ -1,15 +1,32 @@
<script setup lang="ts">
import type { Component } from 'vue'
import { ref, watch } from 'vue'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Skeleton } from '@/components/ui/skeleton'
defineProps<{
const props = defineProps<{
activeComponent: Component | null
activeModule: string
loading: boolean
}>()
const containerRef = ref<HTMLElement | null>(null)
// 切换模块时重置主滚动区位置,避免新模块沿用上一个模块的滚动距离
watch(
() => props.activeModule,
() => {
const viewport = containerRef.value?.querySelector<HTMLElement>(
'[data-slot="scroll-area-viewport"]'
)
if (viewport) viewport.scrollTop = 0
}
)
</script>
<template>
<main
ref="containerRef"
class="flex-1"
:style="{ backgroundColor: 'var(--effect-bg)', backdropFilter: 'var(--effect-blur)' }"
>
@@ -22,6 +39,30 @@ defineProps<{
>
<component :is="activeComponent" />
</div>
<div
v-else-if="loading"
key="loading"
class="h-full w-full p-6"
>
<!-- 模块加载骨架撑起画面避免空白闪屏 -->
<div class="h-full max-w-5xl mx-auto space-y-5">
<div class="flex items-center gap-3">
<Skeleton class="h-8 w-40" />
<Skeleton class="h-6 w-24 ml-auto" />
</div>
<div class="grid gap-4 md:grid-cols-2">
<div v-for="n in 4" :key="n" class="rounded-lg border p-5 space-y-4">
<div class="flex items-center justify-between">
<Skeleton class="h-5 w-32" />
<Skeleton class="h-5 w-16" />
</div>
<Skeleton class="h-4 w-full" />
<Skeleton class="h-4 w-5/6" />
<Skeleton class="h-4 w-2/3" />
</div>
</div>
</div>
</div>
<div
v-else
key="empty"
+2 -2
View File
@@ -36,7 +36,7 @@ const displayModules = computed(() => {
'bg-primary text-primary-foreground shadow-md': activeModule === module.id,
'hover:bg-secondary/50': activeModule !== module.id
}"
@click="emit('change', module.id)"
@click="activeModule !== module.id && emit('change', module.id)"
>
<component :is="getModuleIcon(module.icon)" class="size-4" />
</Button>
@@ -60,7 +60,7 @@ const displayModules = computed(() => {
'bg-primary text-primary-foreground shadow-md': activeModule === 'settings',
'hover:bg-secondary/50': activeModule !== 'settings'
}"
@click="emit('change', 'settings')"
@click="activeModule !== 'settings' && emit('change', 'settings')"
>
<Settings class="size-4" />
</Button>
+20
View File
@@ -0,0 +1,20 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div
data-slot="empty"
:class="cn(
'flex min-w-0 flex-1 flex-col items-center justify-center gap-6 text-balance rounded-lg border-dashed p-6 text-center md:p-12',
props.class,
)"
>
<slot />
</div>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div
data-slot="empty-content"
:class="cn(
'flex w-full min-w-0 max-w-sm flex-col items-center gap-4 text-balance text-sm',
props.class,
)"
>
<slot />
</div>
</template>
@@ -0,0 +1,20 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<p
data-slot="empty-description"
:class="cn(
'text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4',
$attrs.class ?? '',
)"
>
<slot />
</p>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div
data-slot="empty-header"
:class="cn(
'flex max-w-sm flex-col items-center gap-2 text-center',
props.class,
)"
>
<slot />
</div>
</template>
+21
View File
@@ -0,0 +1,21 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import type { EmptyMediaVariants } from "."
import { cn } from "@/lib/utils"
import { emptyMediaVariants } from "."
const props = defineProps<{
class?: HTMLAttributes["class"]
variant?: EmptyMediaVariants["variant"]
}>()
</script>
<template>
<div
data-slot="empty-icon"
:data-variant="variant"
:class="cn(emptyMediaVariants({ variant }), props.class)"
>
<slot />
</div>
</template>
+17
View File
@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div
data-slot="empty-title"
:class="cn('text-lg font-medium tracking-tight', props.class)"
>
<slot />
</div>
</template>
+26
View File
@@ -0,0 +1,26 @@
import type { VariantProps } from "class-variance-authority"
import { cva } from "class-variance-authority"
export { default as Empty } from "./Empty.vue"
export { default as EmptyContent } from "./EmptyContent.vue"
export { default as EmptyDescription } from "./EmptyDescription.vue"
export { default as EmptyHeader } from "./EmptyHeader.vue"
export { default as EmptyMedia } from "./EmptyMedia.vue"
export { default as EmptyTitle } from "./EmptyTitle.vue"
export const emptyMediaVariants = cva(
"mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-transparent",
icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
},
},
defaultVariants: {
variant: "default",
},
},
)
export type EmptyMediaVariants = VariantProps<typeof emptyMediaVariants>
+15
View File
@@ -0,0 +1,15 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
const props = defineProps<{
class?: HTMLAttributes["class"]
}>()
</script>
<template>
<div
data-slot="skeleton"
:class="cn('animate-pulse rounded-md bg-muted', props.class)"
/>
</template>
+1
View File
@@ -0,0 +1 @@
export { default as Skeleton } from "./Skeleton.vue"
+82 -1
View File
@@ -54,7 +54,11 @@ export const commands = {
quickpanelShowWindow: () => __TAURI_INVOKE<null>("quickpanel_show_window"),
/** 锁定屏幕(Windows: rundll32 user32.dll,LockWorkStationCREATE_NO_WINDOW 避免黑窗) */
quickpanelLockScreen: () => __TAURI_INVOKE<null>("quickpanel_lock_screen"),
/** 初始化文件索引数据库(应用启动时调用) */
/**
* 初始化文件索引数据库(应用启动时调用)。
* 若存在上次构建的索引(last_built_dirs 非空),自动恢复 notify 增量监听,
* 无需重建即可继续自动同步文件变更。
*/
quickpanelInitFileIndex: () => __TAURI_INVOKE<null>("quickpanel_init_file_index"),
/** 构建文件索引(全量重建,阻塞操作建议在 spawn_blocking 调用) */
quickpanelBuildFileIndex: () => __TAURI_INVOKE<number>("quickpanel_build_file_index"),
@@ -96,6 +100,35 @@ export const commands = {
* 适用于内置系统工具:regedit、shutdown、cmd、powershell、taskmgr 等。
*/
quickpanelRunSystemCommand: (command: string, args: string[]) => __TAURI_INVOKE<null>("quickpanel_run_system_command", { command, args }),
/** 列出目录下的压缩包文件(供批量解压面板使用)。 */
quickpanelListArchives: (dir: string) => __TAURI_INVOKE<ArchiveInfo[]>("quickpanel_list_archives", { dir }),
/** 列出目录下的全部条目(供批量重命名/删除面板使用,不含子目录递归)。 */
quickpanelListDir: (dir: string) => __TAURI_INVOKE<FileEntry[]>("quickpanel_list_dir", { dir }),
/**
* 批量解压。`files` 为压缩包路径列表,`dest_dir` 为目标目录,
* `password` 为统一解压密码(可空),`into_subfolder` 是否解压到同名子文件夹。
* 每完成一个文件通过 `quickpanel-extract-progress` 事件推送进度。
*/
quickpanelBatchExtract: (files: string[], destDir: string, password: string | null, intoSubfolder: boolean) => __TAURI_INVOKE<ExtractResult[]>("quickpanel_batch_extract", { files, destDir, password, intoSubfolder }),
/**
* 正则批量重命名预览:对每个文件名应用 `pattern → replacement`
* 仅返回有匹配的文件,`newName` 为替换结果。
*/
quickpanelPreviewRename: (files: string[], pattern: string, replacement: string) => __TAURI_INVOKE<RenamePreview[]>("quickpanel_preview_rename", { files, pattern, replacement }),
/** 执行重命名。同一目录下若目标已存在则跳过该项。 */
quickpanelApplyRename: (items: RenameItem[]) => __TAURI_INVOKE<RenameResult[]>("quickpanel_apply_rename", { items }),
/**
* 批量删除文件/目录。`force=false` 时移动至回收站;`force=true` 时先递归清除
* 只读属性再永久删除(可绕过只读/部分占用导致的删除失败,但被其他进程真正
* 锁定的文件仍会失败并返回原因)。
*/
quickpanelDeleteFiles: (paths: string[], force: boolean) => __TAURI_INVOKE<DeleteResult[]>("quickpanel_delete_files", { paths, force }),
/**
* 显示主窗口并强制置为前台。
* Tauri 的 set_focus 在 Windows 上受前台锁定限制,主窗口被其他应用遮挡时无法到前台;
* 改用原生 SetForegroundWindow + BringWindowToTop(模拟 Alt 键重置前台锁定)。
*/
quickpanelFocusMainWindow: () => __TAURI_INVOKE<null>("quickpanel_focus_main_window"),
clipboardGetHistory: (limit: number | null, offset: number | null, kind: string | null) => __TAURI_INVOKE<HistoryPage>("clipboard_get_history", { limit, offset, kind }),
clipboardGetPinned: () => __TAURI_INVOKE<ClipboardItem[]>("clipboard_get_pinned"),
clipboardSearch: (query: string, limit: number | null, offset: number | null) => __TAURI_INVOKE<HistoryPage>("clipboard_search", { query, limit, offset }),
@@ -206,6 +239,12 @@ export type AppRecord = {
path: string,
};
export type ArchiveInfo = {
name: string,
path: string,
size: number,
};
/** 前端可见的捕获数据 */
export type CaptureData = {
pngBase64: string,
@@ -280,6 +319,14 @@ export type CustomCommand = {
args?: string[],
};
/** 批量删除单个条目的结果。 */
export type DeleteResult = {
name: string,
path: string,
ok: boolean,
error: string,
};
/** 下载任务 */
export type DownloadTask = {
/** 任务 ID(自增 hex 字符串) */
@@ -350,6 +397,20 @@ export type ExistingTaskInfo = {
status: TaskStatus,
};
export type ExtractResult = {
name: string,
path: string,
ok: boolean,
error: string,
};
export type FileEntry = {
name: string,
path: string,
isDir: boolean,
size: number,
};
/** 单个文件记录(返回给前端) */
export type FileRecord = {
path: string,
@@ -449,6 +510,26 @@ export type QuickPanelSettings = {
customCommands?: CustomCommand[],
};
export type RenameItem = {
path: string,
oldName: string,
newName: string,
};
export type RenamePreview = {
path: string,
oldName: string,
newName: string,
error: string,
};
export type RenameResult = {
oldName: string,
newName: string,
ok: boolean,
error: string,
};
export type ScreenRect = {
x: number,
y: number,
+11
View File
@@ -28,6 +28,7 @@ export const EVENTS = {
quickpanelShow: 'quickpanel-show',
quickpanelHide: 'quickpanel-hide',
quickpanelExecuteCommand: 'quickpanel-execute-command',
quickpanelExtractProgress: 'quickpanel-extract-progress',
// 截图
screenshotBegin: 'screenshot-begin',
screenshotOverlayReady: 'screenshot-overlay-ready',
@@ -56,6 +57,8 @@ export const EVENTS = {
// 其他
processStatusChanged: 'process-status-changed',
downloadAdded: 'download-added',
/** 浏览器扩展通过 HTTP API 新增下载(置前主窗口并跳到下载画面) */
downloadExtensionAdded: 'download-extension-added',
} as const
/** localStorage 存储键 */
@@ -66,6 +69,14 @@ export const STORAGE_KEYS = {
quickpanelSettings: 'thing_quickpanel_settings',
quickpanelHistory: 'thing_quickpanel_history',
quickpanelHistoryItems: 'thing_quickpanel_history_items',
quickpanelPwdHistory: 'thing_quickpanel_pwd_history',
quickpanelPwdFavs: 'thing_quickpanel_pwd_favs',
quickpanelRenameMatchHistory: 'thing_quickpanel_rename_match_history',
quickpanelRenameMatchFavs: 'thing_quickpanel_rename_match_favs',
quickpanelRenameReplaceHistory: 'thing_quickpanel_rename_replace_history',
quickpanelRenameReplaceFavs: 'thing_quickpanel_rename_replace_favs',
quickpanelDeleteFilterHistory: 'thing_quickpanel_delete_filter_history',
quickpanelDeleteFilterFavs: 'thing_quickpanel_delete_filter_favs',
currencyRates: 'thing_quickpanel_currency_rates',
monitorOsdConfig: 'thing_monitor_osd_config',
screenshotHistory: 'thing_screenshot_history',
+3
View File
@@ -10,3 +10,6 @@ import { ref } from 'vue'
/** 待打开新建下载对话框(由托盘"新建下载"触发) */
export const pendingNewDownload = ref(false)
/** 待切换到下载任务列表页(由浏览器扩展新增下载触发,不弹对话框直接看任务) */
export const pendingShowDownloadTasks = ref(false)
+76 -66
View File
@@ -16,7 +16,6 @@ import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { Badge } from '@/components/ui/badge'
import { Label } from '@/components/ui/label'
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription,
} from '@/components/ui/dialog'
@@ -27,6 +26,10 @@ import {
import {
Pagination, PaginationContent, PaginationItem, PaginationEllipsis,
} from '@/components/ui/pagination'
import { Skeleton } from '@/components/ui/skeleton'
import {
Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle,
} from '@/components/ui/empty'
const store = useClipboardStore()
@@ -74,6 +77,12 @@ const detailOpen = ref(false)
const detailLoading = ref(false)
const detail = ref<ClipboardItemDetail | null>(null)
const openDetail = async (item: ClipboardItem) => {
// reka-ui Dialog 打开时会把当前活动元素记为 triggerElement,关闭时对其无 preventScroll 地 focus
// 导致历史列表的 ScrollAreaViewport(tabindex=0) 被聚焦并滚回顶部。打开前 blur,避免记录滚动容器。
const active = document.activeElement
if (active instanceof HTMLElement) {
active.blur()
}
detailOpen.value = true
detailLoading.value = true
detail.value = null
@@ -283,9 +292,17 @@ const historyList = computed(() => store.history)
const pinnedList = computed(() => store.pinned)
onMounted(async () => {
await store.init()
await Promise.all([loadPage(), store.refreshPinned()])
form.value = { ...store.settings }
// 首次进入:异步加载并显示骨架屏。再次进入时 store 已缓存历史/固定/设置,
// 直接即时渲染缓存数据,后台并行静默刷新,避免每次切换都出现骨架屏/空态闪烁。
const isFirst = !store.initialized
if (isFirst) store.loading = true
try {
await Promise.all([store.init(), loadPage(), store.refreshPinned()])
store.initialized = true
form.value = { ...store.settings }
} finally {
store.loading = false
}
})
onUnmounted(() => {
@@ -369,13 +386,33 @@ onUnmounted(() => {
<ScrollArea class="flex-1 min-h-0">
<div class="space-y-1.5 pr-2">
<div
v-if="!historyList.length"
class="flex flex-col items-center justify-center text-muted-foreground py-12"
>
<ClipboardList class="size-12 mb-3 opacity-40" />
<p class="text-sm">暂无历史记录复制内容后将自动收录</p>
<!-- 加载骨架数据异步返回前撑起画面避免误显示"暂无历史" -->
<div v-if="store.loading" class="space-y-1.5">
<div
v-for="n in 8" :key="n"
class="flex items-center gap-3 rounded-lg border p-3"
>
<Skeleton class="size-4 shrink-0" />
<div class="flex-1 space-y-2">
<Skeleton class="h-3.5 w-3/4" />
<Skeleton class="h-2.5 w-1/4" />
</div>
</div>
</div>
<Empty
v-else-if="!historyList.length"
class="py-12"
>
<EmptyHeader>
<EmptyMedia variant="icon">
<ClipboardList class="size-6" />
</EmptyMedia>
<EmptyTitle>暂无历史记录</EmptyTitle>
</EmptyHeader>
<EmptyContent>
<EmptyDescription>复制内容后将自动收录图片与文件也会被记录</EmptyDescription>
</EmptyContent>
</Empty>
<Card
v-for="item in historyList"
:key="item.id"
@@ -392,30 +429,15 @@ onUnmounted(() => {
</div>
</div>
<div class="flex items-center gap-0.5 shrink-0 opacity-0 group-hover:opacity-100 transition">
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="size-7" @click.stop="handleCopy(item)">
<Copy class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>复制</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="size-7" @click.stop="handlePin(item)">
<component :is="item.pinned ? PinOff : Pin" class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{{ item.pinned ? '取消固定' : '固定' }}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="size-7 hover:text-destructive" @click.stop="handleDelete(item)">
<Trash2 class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>删除</TooltipContent>
</Tooltip>
<Button variant="ghost" size="icon" class="size-7" title="复制" @click.stop="handleCopy(item)">
<Copy class="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" class="size-7" :title="item.pinned ? '取消固定' : '固定'" @click.stop="handlePin(item)">
<component :is="item.pinned ? PinOff : Pin" class="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" class="size-7 hover:text-destructive" title="删除" @click.stop="handleDelete(item)">
<Trash2 class="h-3.5 w-3.5" />
</Button>
</div>
</CardContent>
</Card>
@@ -426,14 +448,17 @@ onUnmounted(() => {
<!-- 固定 -->
<TabsContent value="pinned" class="flex-1 min-h-0 flex flex-col mt-4 tab-animate">
<div class="flex-1 min-h-0 overflow-y-auto space-y-1.5 pr-1">
<div
v-if="!pinnedList.length"
class="flex flex-col items-center justify-center h-full text-muted-foreground"
>
<Pin class="size-12 mb-3 opacity-40" />
<p class="text-sm">暂无固定条目</p>
<p class="text-xs mt-1">鼠标悬停历史条目点击图钉按钮即可固定</p>
</div>
<Empty v-if="!pinnedList.length" class="h-full py-8">
<EmptyHeader>
<EmptyMedia variant="icon">
<Pin class="size-6" />
</EmptyMedia>
<EmptyTitle>暂无固定条目</EmptyTitle>
</EmptyHeader>
<EmptyContent>
<EmptyDescription>鼠标悬停历史条目点击图钉按钮即可固定</EmptyDescription>
</EmptyContent>
</Empty>
<Card v-for="item in pinnedList" :key="item.id" class="group hover:shadow-md transition-shadow py-0">
<CardContent class="flex items-center gap-3 px-3 py-2">
<component :is="kindIcon(item.kind)" class="size-4 text-primary shrink-0" />
@@ -446,30 +471,15 @@ onUnmounted(() => {
</div>
</div>
<div class="flex items-center gap-0.5 shrink-0 opacity-0 group-hover:opacity-100 transition">
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="size-7" @click.stop="handleCopy(item)">
<Copy class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>复制</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="size-7" @click.stop="handlePin(item)">
<PinOff class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>取消固定</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon" class="size-7 hover:text-destructive" @click.stop="handleDelete(item)">
<Trash2 class="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>删除</TooltipContent>
</Tooltip>
<Button variant="ghost" size="icon" class="size-7" title="复制" @click.stop="handleCopy(item)">
<Copy class="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" class="size-7" title="取消固定" @click.stop="handlePin(item)">
<PinOff class="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" class="size-7 hover:text-destructive" title="删除" @click.stop="handleDelete(item)">
<Trash2 class="h-3.5 w-3.5" />
</Button>
</div>
</CardContent>
</Card>
+20 -22
View File
@@ -8,14 +8,14 @@ import { Effect, EffectState } from '@tauri-apps/api/window'
import { commands } from '@/lib/bindings'
import {
ClipboardList, Pin, PinOff, Trash2, Search, Image as ImageIcon,
FileText, Files, Loader2,
FileText, Files,
} from '@lucide/vue'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Input } from '@/components/ui/input'
import {
Pagination, PaginationContent, PaginationItem, PaginationEllipsis,
} from '@/components/ui/pagination'
import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from '@/components/ui/tooltip'
import { Skeleton } from '@/components/ui/skeleton'
// ===== 与 Rust 端对应的数据结构(bindings 提供,camelCase =====
// kind 为 bindings 生成的 string,前端按字符串比较即可
@@ -364,7 +364,6 @@ onUnmounted(() => {
<template>
<div class="popup-root flex flex-col h-screen w-screen" @keydown="onKeydown">
<TooltipProvider>
<!-- 搜索栏与剪切板主页统一样式 -->
<div class="flex items-center gap-2 px-3 py-2 border-b border-border shrink-0">
<div class="relative flex-1 max-w-sm">
@@ -390,8 +389,18 @@ onUnmounted(() => {
<!-- 列表 -->
<ScrollArea class="popup-list flex-1 min-h-0">
<div class="space-y-1.5 p-2">
<div v-if="loading && !hasItems" class="flex flex-col items-center justify-center py-12 text-muted-foreground">
<Loader2 class="size-6 animate-spin" />
<div v-if="loading && !hasItems" class="space-y-1.5">
<div
v-for="n in 8"
:key="n"
class="flex items-start gap-3 rounded-lg border px-3 py-2"
>
<Skeleton class="size-4 shrink-0 mt-0.5" />
<div class="flex-1 space-y-1.5">
<Skeleton class="h-3.5 w-3/4" />
<Skeleton class="h-2.5 w-1/4" />
</div>
</div>
</div>
<div v-else-if="!hasItems" class="flex flex-col items-center justify-center py-12 text-muted-foreground">
<ClipboardList class="size-10 mb-2 opacity-40" />
@@ -417,22 +426,12 @@ onUnmounted(() => {
</div>
</div>
<div class="popup-item-actions shrink-0">
<Tooltip>
<TooltipTrigger as-child>
<button class="popup-action-btn size-7" @click="togglePin(item, $event)">
<component :is="item.pinned ? PinOff : Pin" class="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent>固定</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<button class="popup-action-btn size-7 hover:text-destructive" @click="deleteItem(item, $event)">
<Trash2 class="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent>删除</TooltipContent>
</Tooltip>
<button class="popup-action-btn size-7" :title="item.pinned ? '取消固定' : '固定'" @click="togglePin(item, $event)">
<component :is="item.pinned ? PinOff : Pin" class="h-3.5 w-3.5" />
</button>
<button class="popup-action-btn size-7 hover:text-destructive" title="删除" @click="deleteItem(item, $event)">
<Trash2 class="h-3.5 w-3.5" />
</button>
</div>
</div>
</div>
@@ -472,7 +471,6 @@ onUnmounted(() => {
<span><kbd>Enter</kbd> 粘贴</span>
<span><kbd>Esc</kbd> 关闭</span>
</div>
</TooltipProvider>
</div>
</template>
+6 -1
View File
@@ -16,7 +16,7 @@ import { useDownloaderStore, type DownloadTask, type TaskStatus, type CheckUrlRe
import { useModuleTabs } from '@/lib/use-module-tabs'
import { useModuleTabsStore } from '@/stores/moduleTabsStore'
import { createLogger } from '@/lib/logger'
import { pendingNewDownload } from '@/lib/trayEvents'
import { pendingNewDownload, pendingShowDownloadTasks } from '@/lib/trayEvents'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
@@ -536,6 +536,11 @@ onMounted(async () => {
pendingNewDownload.value = false
addDialogOpen.value = true
}
// 消费浏览器扩展新增下载标志位:直接显示任务列表页
if (pendingShowDownloadTasks.value) {
pendingShowDownloadTasks.value = false
activeTab.value = 'tasks'
}
})
onUnmounted(() => {
+3 -2
View File
@@ -1102,8 +1102,9 @@ onUnmounted(() => {
// 不 dispose storeSSE 订阅保持,确保切走监控模块后 OSD 仍有数据
// store.subscribe() 内部有守卫(if unlistenFns.length return),重复 init 不会重复订阅
// 不关闭 OSD 窗口:切走监控模块时保持 OSD 显示,由模块禁用或应用退出时统一清理
// 释放 OSD 事件监听(App 启动或模块重新挂载时会重新注册)
store.disposeOsd()
// 不调用 store.disposeOsd()tray:toggle-osd 监听与 OSD 配置 watcher 由 App.vue 的
// initOsd() 注册,属应用级常驻(与模块生命周期解耦);若在此释放,切走监控模块后
// 托盘菜单的 OSD 开关会失效。OSD 事件监听仅在 App 卸载(应用退出)时统一释放。
})
// 当 Kernel 从未就绪变成就绪时,主动拉一次快照填充 UI
+15 -10
View File
@@ -328,9 +328,9 @@ const init = async () => {
await store.waitForApi()
store.refreshVersion()
loadProxiesWithError()
//
//
if (autoSwitchEnabled.value) {
startAutoSwitch()
startAutoSwitch(false, false)
}
}
} finally {
@@ -370,10 +370,10 @@ watch(running, async (val, old) => {
await store.waitForApi()
await store.refreshVersion()
await loadProxiesWithError()
// mihomo /
// mihomo /
// handleStop
if (autoSwitchEnabled.value) {
startAutoSwitch()
startAutoSwitch(false)
}
}
})
@@ -495,16 +495,21 @@ const quickSwitchNode = async (name: string) => {
}
// ===== =====
const startAutoSwitch = () => {
const startAutoSwitch = (notify = true, immediate = true) => {
stopAutoSwitch()
if (!autoSwitchEnabled.value) return
const ms = autoSwitchInterval.value * 60 * 1000
autoSwitchTimer = setInterval(runAutoSwitch, ms)
toast.success('自动切换已开启', {
description: `${autoSwitchInterval.value} 分钟测试并切换至最优节点`
})
//
runAutoSwitch()
// /
if (notify) {
toast.success('自动切换已开启', {
description: `${autoSwitchInterval.value} 分钟测试并切换至最优节点`
})
}
// /
if (immediate) {
runAutoSwitch()
}
}
const stopAutoSwitch = () => {
+159
View File
@@ -0,0 +1,159 @@
<script setup lang="ts">
import { Pin } from '@lucide/vue'
defineProps<{
items: string[]
favs?: string[]
open?: boolean
}>()
const emit = defineEmits<{
pick: [value: string]
fav: [value: string]
}>()
function pick(value: string) {
emit('pick', value)
}
</script>
<template>
<!-- mousedown.prevent 阻止点击下拉项时输入框失焦使 focus 触发的历史面板保持展开 -->
<div
v-if="open && ((favs && favs.length) || items.length)"
class="qp-fa-dropdown"
@mousedown.prevent
>
<!-- 钉住/常用独立保存显示在历史之上 -->
<template v-if="favs && favs.length">
<p class="qp-fa-dropdown-label">常用</p>
<div
v-for="f in favs"
:key="'fav-' + f"
class="qp-fa-dropdown-item"
>
<button
type="button"
class="flex-1 min-w-0 text-left text-xs truncate"
:title="f"
@click="pick(f)"
>
{{ f || '(空)' }}
</button>
<button
type="button"
class="qp-fa-pin pinned"
title="取消钉住"
@click="emit('fav', f)"
>
<Pin class="size-3.5" />
</button>
</div>
</template>
<!-- 历史最多 10 排除已钉住的 -->
<p
v-if="items.filter(x => !(favs ?? []).includes(x)).length"
class="qp-fa-dropdown-label"
>
历史
</p>
<div
v-for="it in items.filter(x => !(favs ?? []).includes(x))"
:key="'his-' + it"
class="qp-fa-dropdown-item"
>
<button
type="button"
class="flex-1 min-w-0 text-left text-xs truncate"
:title="it"
@click="pick(it)"
>
{{ it || '(空)' }}
</button>
<button
v-if="favs"
type="button"
class="qp-fa-pin"
title="钉住为常用"
@click="emit('fav', it)"
>
<Pin class="size-3.5" />
</button>
</div>
</div>
</template>
<style scoped>
.qp-fa-dropdown {
position: absolute;
top: calc(100% + 2px);
left: 0;
right: 0;
z-index: 50;
max-height: 220px;
overflow-y: auto;
background: var(--popover, var(--card));
border: 1px solid var(--border);
border-radius: 6px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
padding: 4px;
}
.qp-fa-dropdown-label {
padding: 3px 8px 1px;
font-size: 10px;
color: var(--muted-foreground);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.qp-fa-dropdown-item {
display: flex;
align-items: center;
gap: 4px;
padding: 3px 6px;
border-radius: 5px;
}
.qp-fa-dropdown-item:hover {
background: var(--accent);
}
.qp-fa-pin {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
border: none;
background: none;
padding: 2px;
color: var(--muted-foreground);
cursor: pointer;
opacity: 0.5;
transition: opacity 0.1s, color 0.1s;
}
.qp-fa-pin:hover {
opacity: 1;
color: var(--foreground);
}
.qp-fa-pin.pinned {
color: var(--primary);
opacity: 1;
}
.qp-fa-dropdown::-webkit-scrollbar {
width: 6px;
}
.qp-fa-dropdown::-webkit-scrollbar-thumb {
background: var(--muted-foreground);
opacity: 0.3;
border-radius: 3px;
}
.qp-fa-dropdown::-webkit-scrollbar-track {
background: transparent;
}
</style>
File diff suppressed because it is too large Load Diff
+10 -2
View File
@@ -528,7 +528,15 @@ async function changeEngine(v: string) {
</div>
<div class="flex items-center gap-2 text-sm">
<Badge variant="secondary">文件</Badge>
<span class="text-muted-foreground">索引指定目录快速定位文件</span>
<span class="text-muted-foreground">索引指定目录快速定位文件支持打开/显示/复制路径/删除.lnk 按应用处理</span>
</div>
<div class="flex items-center gap-2 text-sm">
<Badge variant="secondary">目录操作</Badge>
<span class="text-muted-foreground">文件资源管理器批量处理批量解压正则批量重命名实时预览筛选批量删除</span>
</div>
<div class="flex items-center gap-2 text-sm">
<Badge variant="secondary">历史</Badge>
<span class="text-muted-foreground">记录最近交互空查询优先展示</span>
</div>
<div class="flex items-center gap-2 text-sm">
<Badge variant="secondary">剪贴板</Badge>
@@ -548,7 +556,7 @@ async function changeEngine(v: string) {
</div>
<div class="flex items-center gap-2 text-sm">
<Badge variant="secondary">系统</Badge>
<span class="text-muted-foreground">锁屏退出应用</span>
<span class="text-muted-foreground">系统命令注册表CMD/PowerShell任务管理器控制面板关机/重启/休眠锁屏退出应用</span>
</div>
<div class="flex items-center gap-2 text-sm">
<Badge variant="secondary">网页</Badge>
+20
View File
@@ -38,8 +38,17 @@ const state = reactive<TrayMenuState>({
const loadingAction = ref<string | null>(null)
const refreshing = ref(false)
const osdVisible = ref(false)
const nodeSelectOpen = ref(false)
let unlistenFns: UnlistenFn[] = []
/** 菜单关闭/失焦前重置状态:关闭节点下拉框并取消所有焦点,避免下次打开时残留 */
function resetMenuState() {
nodeSelectOpen.value = false
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur()
}
}
function readOsdVisible(): boolean {
try {
const raw = localStorage.getItem(STORAGE_KEYS.monitorOsdConfig)
@@ -260,6 +269,8 @@ const sortedNodes = computed(() => {
})
async function handleAction(action: string, payload?: Record<string, unknown>) {
//
resetMenuState()
try { await invoke('tray_menu_hide') } catch { /* 忽略 */ }
if (action === 'proxy_refresh') refreshing.value = true
@@ -305,6 +316,7 @@ function delayClass(delay: number | null): string {
function onKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') {
e.preventDefault()
resetMenuState()
invoke('tray_menu_hide').catch(() => {})
}
}
@@ -410,9 +422,16 @@ onMounted(async () => {
await applyTheme()
Object.assign(state, event.payload)
osdVisible.value = readOsdVisible()
// /
resetMenuState()
await measureAndShow()
}))
//
unlistenFns.push(await getCurrentWindow().onFocusChanged(({ payload: focused }) => {
if (!focused) resetMenuState()
}))
//
// measureAndShow win.show
// tray-menu-show
@@ -465,6 +484,7 @@ onUnmounted(() => {
<label class="tray-node-label">节点</label>
<Select
:model-value="state.proxyCurrent ?? ''"
v-model:open="nodeSelectOpen"
:disabled="proxyLoading"
@update:model-value="handleSelectNode"
>
+3
View File
@@ -43,6 +43,8 @@ export const useClipboardStore = defineStore('clipboard', () => {
const settings = ref<ClipboardSettings>({ ...DEFAULT_SETTINGS })
const status = ref<ClipboardStatus>({ running: false, count: 0 })
const loading = ref(false)
/** 是否已完成首次加载:再次进入模块时 store 已有缓存,可即时渲染而非再弹骨架屏 */
const initialized = ref(false)
// 事件监听(应用级单例,只注册一次)
let changedUnlisten: UnlistenFn | null = null
@@ -238,6 +240,7 @@ export const useClipboardStore = defineStore('clipboard', () => {
settings,
status,
loading,
initialized,
init,
dispose,
fetchHistoryPage,
+17 -3
View File
@@ -74,11 +74,21 @@ export const useDownloaderStore = defineStore('downloader', () => {
try {
// Rust 端序列化保证字段完整,断言为 Required 收窄后的类型
const fresh = (await commands.downloaderGetTasks()) as DownloadTask[]
// merge 化:保留本地仍在更新的任务对象(进度事件可能刚修改过它),
// 避免整体替换导致进行中任务的实时进度/速度被快照回退
// merge 化:进行中任务保留本地实时进度,避免快照回退;
// 暂停/终态(paused/complete/error)时 Rust 端已同步完整进度(完成时
// completed_size 已对齐 total_size),整体替换为服务端快照,
// 避免本地旧进度覆盖导致"已完成但停在 99%"的状态不一致
const merged = fresh.map(freshTask => {
if (
freshTask.status === 'paused' ||
freshTask.status === 'complete' ||
freshTask.status === 'error'
) {
return freshTask
}
const local = tasks.value.find(t => t.id === freshTask.id)
return local ?? freshTask
if (!local) return freshTask
return { ...local, status: freshTask.status, error: freshTask.error }
})
tasks.value = merged
} catch (e) {
@@ -91,6 +101,10 @@ export const useDownloaderStore = defineStore('downloader', () => {
const updateTaskProgress = (payload: ProgressPayload) => {
const task = tasks.value.find((t) => t.id === payload.id)
if (task) {
// 终态任务忽略迟到的进度事件(下载完成后 in-flight 事件可能把状态/进度回退)
if (task.status === 'complete' || task.status === 'error') return
// 已暂停任务忽略仍携带 active 的迟到事件(暂停瞬间发出的旧事件)
if (task.status === 'paused' && payload.status === 'active') return
task.completedSize = payload.completedSize
task.totalSize = payload.totalSize
task.speed = payload.speed
+5 -9
View File
@@ -980,18 +980,14 @@ export const useMonitorStore = defineStore('monitor', () => {
// 注册 OSD 窗口事件监听
setupOsdEventListeners().catch(e => logger.error('[OSD] 事件监听注册失败: ' + e))
// 监听托盘菜单"切换 OSD"事件(应用级常驻,不随模块挂载/卸载变化)
// 监听托盘菜单"切换 OSD"事件(应用级常驻,不随模块挂载/卸载变化)
// 只修改 overlayEnabled,窗口显示/隐藏统一由下方 store watch 处理,
// 与主界面 OSD 开关(updateOsdConfig)走完全相同的路径,避免双 hide 竞态。
listen(EVENTS.trayToggleOsd, () => {
osdConfig.value.overlayEnabled = !osdConfig.value.overlayEnabled
saveOsdConfig(osdConfig.value)
if (osdConfig.value.overlayEnabled) {
if (osdConfig.value.overlayItems.length === 0) {
toast.warning('OSD 显示项为空,已开启但未创建窗口')
} else {
ensureOverlayWindow().catch(e => logger.error('[OSD] 托盘开启悬浮窗失败: ' + e))
}
} else {
hideOverlayWindow().catch(e => logger.error('[OSD] 托盘关闭悬浮窗失败: ' + e))
if (osdConfig.value.overlayEnabled && osdConfig.value.overlayItems.length === 0) {
toast.warning('OSD 显示项为空,已开启但未创建窗口')
}
}).then(unlisten => { osdEventUnlisteners.push(unlisten) })
.catch(e => logger.error('[OSD] 注册 tray:toggle-osd 监听失败: ' + e))