优化调整
This commit is contained in:
Generated
+21
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
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
|
||||
|
||||
Binary file not shown.
@@ -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";
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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
@@ -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,
|
||||
// clipboard(20)
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! 快速面板:基于 7-Zip(binaries/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)
|
||||
}
|
||||
@@ -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,LockWorkStation,CREATE_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 快捷方式不能直接 spawn(os error 193),需通过 cmd /C 启动
|
||||
#[tauri::command]
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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: ¬ify::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);
|
||||
|
||||
@@ -4,21 +4,27 @@
|
||||
//! Phase 2:fuzzy + 拼音引擎,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};
|
||||
|
||||
@@ -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, ());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -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) {}
|
||||
|
||||
Reference in New Issue
Block a user