优化调整
This commit is contained in:
@@ -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, ());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user