快速面板模块
This commit is contained in:
@@ -10,6 +10,7 @@ mod monitor_kernel;
|
||||
mod network_monitor;
|
||||
mod osd_window;
|
||||
mod process_manager;
|
||||
mod quickpanel;
|
||||
mod screenshot;
|
||||
mod snap_fix;
|
||||
mod tray_menu;
|
||||
@@ -61,6 +62,15 @@ use clipboard::{
|
||||
clipboard_set_pinned, clipboard_show_popup, clipboard_show_window, clipboard_start,
|
||||
clipboard_status, clipboard_stop, clipboard_unregister_shortcut,
|
||||
};
|
||||
use quickpanel::{
|
||||
quickpanel_build_file_index, quickpanel_clear_app_icon_cache, quickpanel_delete_file,
|
||||
quickpanel_file_index_stats, quickpanel_get_app_icon, quickpanel_get_settings,
|
||||
quickpanel_hide_popup, quickpanel_init_file_index, quickpanel_lock_screen,
|
||||
quickpanel_open_file, 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,
|
||||
};
|
||||
use tray_menu::{tray_menu_action, tray_menu_hide, tray_menu_ready};
|
||||
|
||||
#[tauri::command]
|
||||
@@ -195,6 +205,26 @@ pub fn run() {
|
||||
clipboard_show_window,
|
||||
clipboard_hide_popup,
|
||||
clipboard_paste_to_target,
|
||||
quickpanel_get_settings,
|
||||
quickpanel_save_settings,
|
||||
quickpanel_register_shortcut,
|
||||
quickpanel_unregister_shortcut,
|
||||
quickpanel_show_popup,
|
||||
quickpanel_show_window,
|
||||
quickpanel_hide_popup,
|
||||
quickpanel_lock_screen,
|
||||
quickpanel_init_file_index,
|
||||
quickpanel_build_file_index,
|
||||
quickpanel_search_files,
|
||||
quickpanel_file_index_stats,
|
||||
quickpanel_scan_apps,
|
||||
quickpanel_get_app_icon,
|
||||
quickpanel_clear_app_icon_cache,
|
||||
quickpanel_reveal_in_explorer,
|
||||
quickpanel_open_file,
|
||||
quickpanel_delete_file,
|
||||
quickpanel_run_custom_command,
|
||||
quickpanel_run_system_command,
|
||||
tray_menu_action,
|
||||
tray_menu_hide,
|
||||
tray_menu_ready,
|
||||
@@ -286,6 +316,20 @@ pub fn run() {
|
||||
}
|
||||
app.manage(clipboard);
|
||||
|
||||
// 快速面板:应用启动时注册全局快捷键 + 预创建隐藏窗口。
|
||||
// defaultEnabled:true 假设启用;用户在设置页禁用模块时由前端 onDisable 钩子注销快捷键。
|
||||
let qp_settings = quickpanel::load_settings(&app.handle());
|
||||
if !qp_settings.shortcut.trim().is_empty() {
|
||||
let app_handle = app.handle().clone();
|
||||
if let Err(e) = quickpanel::register_shortcut(&app_handle, &qp_settings.shortcut) {
|
||||
eprintln!("[quickpanel] 快捷键注册失败: {}", e);
|
||||
}
|
||||
// 预创建弹窗窗口(隐藏),首次按快捷键时直接 show,避免首次创建时序问题
|
||||
quickpanel::ensure_window(&app_handle);
|
||||
}
|
||||
// 初始化文件索引数据库(不立即构建,由前端设置页或首次唤起时触发)
|
||||
quickpanel::file_index::init(&app.handle());
|
||||
|
||||
// 自定义托盘菜单(代理/OSD/Kernel/下载/设置/退出)
|
||||
tray_menu::create_tray_menu(app.handle())?;
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! 应用扫描:Windows 开始菜单 .lnk + PATH 中的可执行文件。
|
||||
//!
|
||||
//! 简化实现:扫描开始菜单目录(系统 + 用户)下的 .lnk 快捷方式,
|
||||
//! 名称取文件名(去 .lnk 后缀)。PATH 可执行文件扫描可选(避免噪音过多)。
|
||||
//! 结果不持久化,每次唤起时按需刷新(数据量小,几十毫秒内完成)。
|
||||
|
||||
use std::path::PathBuf;
|
||||
use serde::Serialize;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AppRecord {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// 扫描开始菜单(系统 + 用户)。返回去重后的应用列表。
|
||||
pub fn scan_apps() -> Vec<AppRecord> {
|
||||
let mut apps = Vec::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
|
||||
// 开始菜单目录
|
||||
let mut dirs = Vec::new();
|
||||
|
||||
// 系统开始菜单:C:\ProgramData\Microsoft\Windows\Start Menu\Programs
|
||||
if let Ok(prog_data) = std::env::var("ProgramData") {
|
||||
dirs.push(
|
||||
PathBuf::from(prog_data)
|
||||
.join("Microsoft")
|
||||
.join("Windows")
|
||||
.join("Start Menu")
|
||||
.join("Programs"),
|
||||
);
|
||||
}
|
||||
// 用户开始菜单:%APPDATA%\Microsoft\Windows\Start Menu\Programs
|
||||
if let Ok(appdata) = std::env::var("APPDATA") {
|
||||
dirs.push(
|
||||
PathBuf::from(appdata)
|
||||
.join("Microsoft")
|
||||
.join("Windows")
|
||||
.join("Start Menu")
|
||||
.join("Programs"),
|
||||
);
|
||||
}
|
||||
|
||||
for dir in dirs {
|
||||
if !dir.exists() {
|
||||
continue;
|
||||
}
|
||||
for entry in WalkDir::new(&dir)
|
||||
.max_depth(5)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_map(|e| e.ok())
|
||||
{
|
||||
let p = entry.path();
|
||||
if !p.is_file() {
|
||||
continue;
|
||||
}
|
||||
let ext = p.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
if ext != "lnk" {
|
||||
continue;
|
||||
}
|
||||
let Some(name_os) = p.file_stem() else { continue };
|
||||
let name = name_os.to_string_lossy().to_string();
|
||||
let path_str = p.to_string_lossy().to_string();
|
||||
// 去重:同名应用保留第一个
|
||||
if seen.insert(name.to_lowercase()) {
|
||||
apps.push(AppRecord { name, path: path_str });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 按名称排序
|
||||
apps.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||
apps
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
//! Tauri 命令:快速面板模块
|
||||
|
||||
use tauri::AppHandle;
|
||||
|
||||
use super::popup::{self, QuickPanelSettings};
|
||||
use super::{file_index, app_scanner, icon_extractor};
|
||||
|
||||
/// 读取快速面板设置(快捷键等)
|
||||
#[tauri::command]
|
||||
pub async fn quickpanel_get_settings(app: AppHandle) -> Result<QuickPanelSettings, String> {
|
||||
Ok(popup::load_settings(&app))
|
||||
}
|
||||
|
||||
/// 保存快速面板设置;快捷键变化时自动重新注册 + 预创建窗口
|
||||
#[tauri::command]
|
||||
pub async fn quickpanel_save_settings(
|
||||
settings: QuickPanelSettings,
|
||||
app: AppHandle,
|
||||
) -> Result<(), String> {
|
||||
let prev_shortcut = popup::load_settings(&app).shortcut;
|
||||
popup::save_settings(&app, &settings)?;
|
||||
// 快捷键变化时重新注册
|
||||
if settings.shortcut != prev_shortcut {
|
||||
popup::register_shortcut(&app, &settings.shortcut)?;
|
||||
// 新快捷键非空时确保弹窗窗口已预创建
|
||||
if !settings.shortcut.trim().is_empty() {
|
||||
popup::ensure_window(&app);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 注册(或切换)快速面板全局快捷键
|
||||
#[tauri::command]
|
||||
pub async fn quickpanel_register_shortcut(
|
||||
shortcut: String,
|
||||
app: AppHandle,
|
||||
) -> Result<(), String> {
|
||||
popup::register_shortcut(&app, &shortcut)
|
||||
}
|
||||
|
||||
/// 注销快速面板全局快捷键
|
||||
#[tauri::command]
|
||||
pub async fn quickpanel_unregister_shortcut(app: AppHandle) -> Result<(), String> {
|
||||
popup::unregister_shortcut(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 手动触发显示快速面板(供 UI 按钮调用)
|
||||
#[tauri::command]
|
||||
pub async fn quickpanel_show_popup(app: AppHandle) -> Result<(), String> {
|
||||
popup::show_popup(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 隐藏快速面板
|
||||
#[tauri::command]
|
||||
pub async fn quickpanel_hide_popup(app: AppHandle) -> Result<(), String> {
|
||||
popup::hide_popup(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 显示已创建的弹窗窗口(前端 onMounted 后调用)
|
||||
#[tauri::command]
|
||||
pub async fn quickpanel_show_window(app: AppHandle) -> Result<(), String> {
|
||||
popup::show_window(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 锁定屏幕(Windows: rundll32 user32.dll,LockWorkStation,CREATE_NO_WINDOW 避免黑窗)
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_lock_screen() -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use crate::process_manager::setup_creation_flags;
|
||||
let mut cmd = std::process::Command::new("rundll32.exe");
|
||||
cmd.arg("user32.dll,LockWorkStation");
|
||||
setup_creation_flags(&mut cmd);
|
||||
cmd.spawn().map_err(|e| format!("锁屏失败: {}", e))?;
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
return Err("当前平台不支持锁屏".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 初始化文件索引数据库(应用启动时调用)
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_init_file_index(app: AppHandle) -> Result<(), String> {
|
||||
file_index::init(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 构建文件索引(全量重建,阻塞操作建议在 spawn_blocking 调用)
|
||||
#[tauri::command]
|
||||
pub async fn quickpanel_build_file_index(app: AppHandle) -> Result<i64, String> {
|
||||
let settings = popup::load_settings(&app);
|
||||
let dirs = if settings.index_dirs.is_empty() {
|
||||
popup::QuickPanelSettings::default().index_dirs
|
||||
} else {
|
||||
settings.index_dirs
|
||||
};
|
||||
// 阻塞操作放到 spawn_blocking
|
||||
tauri::async_runtime::spawn_blocking(move || file_index::build_index(&dirs))
|
||||
.await
|
||||
.map_err(|e| format!("索引任务失败: {}", e))?
|
||||
}
|
||||
|
||||
/// 搜索文件索引
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_search_files(query: String, limit: Option<i64>) -> Vec<file_index::FileRecord> {
|
||||
file_index::search(&query, limit.unwrap_or(50))
|
||||
}
|
||||
|
||||
/// 获取索引状态
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_file_index_stats() -> file_index::IndexStats {
|
||||
file_index::stats()
|
||||
}
|
||||
|
||||
/// 扫描已安装应用
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_scan_apps() -> Vec<app_scanner::AppRecord> {
|
||||
app_scanner::scan_apps()
|
||||
}
|
||||
|
||||
/// 获取应用图标(data URL)。命中内存/磁盘缓存时零 Windows API 调用。
|
||||
/// 前端按需为可见项调用,避免一次性加载全部图标。
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_get_app_icon(app: AppHandle, path: String) -> Option<String> {
|
||||
icon_extractor::get_icon_data_url(&app, &path)
|
||||
}
|
||||
|
||||
/// 清理图标缓存(磁盘 + 内存)
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_clear_app_icon_cache(app: AppHandle) -> Result<(), String> {
|
||||
icon_extractor::clear_cache(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 在资源管理器中显示文件(选中)
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_reveal_in_explorer(path: String) -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::ffi::OsStr;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Foundation::HWND;
|
||||
use windows_sys::Win32::UI::Shell::ShellExecuteW;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
|
||||
|
||||
// 规范化路径分隔符
|
||||
let normalized = path.replace('/', "\\");
|
||||
// explorer.exe /select,"path" — 用 ShellExecuteW 直接传参,
|
||||
// 避免 std::process::Command 的 arg 转义破坏 /select 语法。
|
||||
// 对 .lnk 文件也能正确选中(explorer 直接选中 .lnk 文件本身)。
|
||||
let params = format!("/select,\"{}\"", normalized);
|
||||
let wide_exe: Vec<u16> = OsStr::new("explorer.exe")
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
let wide_params: Vec<u16> = OsStr::new(¶ms)
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
|
||||
unsafe {
|
||||
let hinst = ShellExecuteW(
|
||||
0 as HWND,
|
||||
std::ptr::null(),
|
||||
wide_exe.as_ptr(),
|
||||
wide_params.as_ptr(),
|
||||
std::ptr::null(),
|
||||
SW_SHOWNORMAL,
|
||||
);
|
||||
// ShellExecuteW 返回值 <= 32 表示错误
|
||||
if hinst <= 32 {
|
||||
return Err(format!("打开资源管理器失败 (code: {})", hinst as i32));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = path;
|
||||
return Err("当前平台不支持".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 用系统默认程序打开文件(ShellExecuteW)。
|
||||
/// 无关联应用时,自动 fallback 到「打开方式」对话框(verb: openas)。
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_open_file(path: String) -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::ffi::OsStr;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Foundation::HWND;
|
||||
use windows_sys::Win32::UI::Shell::ShellExecuteW;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
|
||||
|
||||
let normalized = path.replace('/', "\\");
|
||||
let wide_path: Vec<u16> = OsStr::new(&normalized)
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
let wide_open: Vec<u16> = OsStr::new("open")
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
let wide_openas: Vec<u16> = OsStr::new("openas")
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
|
||||
unsafe {
|
||||
let mut hinst = ShellExecuteW(
|
||||
0 as HWND,
|
||||
wide_open.as_ptr(),
|
||||
wide_path.as_ptr(),
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
SW_SHOWNORMAL,
|
||||
);
|
||||
if hinst <= 32 {
|
||||
hinst = ShellExecuteW(
|
||||
0 as HWND,
|
||||
wide_openas.as_ptr(),
|
||||
wide_path.as_ptr(),
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
SW_SHOWNORMAL,
|
||||
);
|
||||
if hinst <= 32 {
|
||||
return Err(format!("打开文件失败 (code: {})", hinst as i32));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = path;
|
||||
return Err(String::from("当前平台不支持"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 删除文件(移到回收站)
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_delete_file(path: String) -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use crate::process_manager::setup_creation_flags;
|
||||
let p = std::path::Path::new(&path);
|
||||
let is_dir = p.is_dir();
|
||||
// 用 PowerShell + Microsoft.VisualBasic 移到回收站
|
||||
let script = if is_dir {
|
||||
format!(
|
||||
"Add-Type -AssemblyName Microsoft.VisualBasic; [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory('{}','OnlyErrorDialogs','SendToRecycleBin')",
|
||||
path.replace('\'', "''")
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"Add-Type -AssemblyName Microsoft.VisualBasic; [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile('{}','OnlyErrorDialogs','SendToRecycleBin')",
|
||||
path.replace('\'', "''")
|
||||
)
|
||||
};
|
||||
let mut cmd = std::process::Command::new("powershell.exe");
|
||||
cmd.args(["-NoProfile", "-NonInteractive", "-Command", &script]);
|
||||
setup_creation_flags(&mut cmd);
|
||||
let output = cmd.output().map_err(|e| format!("删除失败: {}", e))?;
|
||||
if !output.status.success() {
|
||||
return Err(format!(
|
||||
"删除失败: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
));
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = path;
|
||||
return Err("当前平台不支持".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 运行自定义命令(执行可执行文件 + 参数)
|
||||
/// .lnk 快捷方式不能直接 spawn(os error 193),需通过 cmd /C 启动
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_run_custom_command(command: String, args: Vec<String>) -> Result<(), String> {
|
||||
use crate::process_manager::setup_creation_flags;
|
||||
let is_lnk = command
|
||||
.to_lowercase()
|
||||
.ends_with(".lnk");
|
||||
let mut cmd = if is_lnk {
|
||||
// cmd /C start "" "path.lnk" arg1 arg2
|
||||
let mut c = std::process::Command::new("cmd");
|
||||
c.args(["/C", "start", "", &command]);
|
||||
c.args(&args);
|
||||
c
|
||||
} else {
|
||||
let mut c = std::process::Command::new(&command);
|
||||
c.args(&args);
|
||||
c
|
||||
};
|
||||
setup_creation_flags(&mut cmd);
|
||||
cmd.spawn().map_err(|e| format!("运行命令失败: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 运行系统命令(不设置 CREATE_NO_WINDOW,使 cmd/powershell/regedit 等显示自身窗口)
|
||||
/// 适用于内置系统工具:regedit、shutdown、cmd、powershell、taskmgr 等。
|
||||
#[tauri::command]
|
||||
pub fn quickpanel_run_system_command(command: String, args: Vec<String>) -> Result<(), String> {
|
||||
let mut cmd = std::process::Command::new(&command);
|
||||
cmd.args(&args);
|
||||
cmd.spawn().map_err(|e| format!("运行系统命令失败: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
//! 文件索引:walkdir 遍历 + rusqlite 存储/搜索。
|
||||
//!
|
||||
//! schema:
|
||||
//! files(path TEXT PK, name TEXT, ext TEXT, size INT, mtime INT, is_dir INT)
|
||||
//! 索引:name LIKE 搜索(name_lower 已预存为小写,避免 lower() 全表扫描)。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::Serialize;
|
||||
use tauri::{AppHandle, Manager};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
/// 单个文件记录(返回给前端)
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileRecord {
|
||||
pub path: String,
|
||||
pub name: String,
|
||||
pub ext: String,
|
||||
pub size: i64,
|
||||
pub is_dir: bool,
|
||||
}
|
||||
|
||||
/// 索引状态(返回给前端)
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IndexStats {
|
||||
pub total: i64,
|
||||
pub last_built_at: i64,
|
||||
pub last_built_dirs: Vec<String>,
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
conn: Mutex<Connection>,
|
||||
}
|
||||
|
||||
static INDEX: std::sync::OnceLock<Mutex<Option<Inner>>> = std::sync::OnceLock::new();
|
||||
|
||||
fn index_slot() -> &'static Mutex<Option<Inner>> {
|
||||
INDEX.get_or_init(|| Mutex::new(None))
|
||||
}
|
||||
|
||||
/// 数据库路径:{app_data_dir}/quickpanel/files.db
|
||||
fn db_path(app: &AppHandle) -> PathBuf {
|
||||
app.path()
|
||||
.app_data_dir()
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
.join("quickpanel")
|
||||
.join("files.db")
|
||||
}
|
||||
|
||||
/// 初始化数据库连接(创建表 + 索引)。若已初始化则跳过。
|
||||
pub fn init(app: &AppHandle) {
|
||||
let path = db_path(app);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).ok();
|
||||
}
|
||||
let conn = match Connection::open(&path) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("[quickpanel] 文件索引 DB 初始化失败: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
conn.busy_timeout(std::time::Duration::from_secs(3)).ok();
|
||||
let _ = conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS files (
|
||||
path TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
name_lower TEXT NOT NULL,
|
||||
ext TEXT NOT NULL DEFAULT '',
|
||||
size INTEGER NOT NULL DEFAULT 0,
|
||||
mtime INTEGER NOT NULL DEFAULT 0,
|
||||
is_dir INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_name_lower ON files(name_lower);
|
||||
CREATE INDEX IF NOT EXISTS idx_ext ON files(ext);
|
||||
CREATE TABLE IF NOT EXISTS files_meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);",
|
||||
);
|
||||
|
||||
let mut guard = index_slot().lock().unwrap();
|
||||
*guard = Some(Inner {
|
||||
conn: Mutex::new(conn),
|
||||
});
|
||||
eprintln!("[quickpanel] 文件索引 DB 已就绪: {}", path.display());
|
||||
}
|
||||
|
||||
/// 判断索引是否已初始化
|
||||
fn with_conn<F, R>(f: F) -> Option<R>
|
||||
where
|
||||
F: FnOnce(&Connection) -> R,
|
||||
{
|
||||
let guard = index_slot().lock().unwrap();
|
||||
if let Some(inner) = guard.as_ref() {
|
||||
if let Ok(conn) = inner.conn.lock() {
|
||||
return Some(f(&conn));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 遍历指定目录列表建立索引(全量重建)。
|
||||
/// 返回索引条目数。在 spawn_blocking 中调用。
|
||||
/// 重建完成后自动启动 notify 监听器做增量更新。
|
||||
pub fn build_index(dirs: &[String]) -> Result<i64, String> {
|
||||
// 清空旧数据
|
||||
let cleared = with_conn(|conn| {
|
||||
conn.execute("DELETE FROM files", []).ok()
|
||||
}).unwrap_or(None);
|
||||
|
||||
if cleared.is_none() {
|
||||
return Err("文件索引未初始化".into());
|
||||
}
|
||||
|
||||
let mut count = 0i64;
|
||||
for dir in dirs {
|
||||
count += walk_and_index(dir);
|
||||
}
|
||||
|
||||
// 记录构建元信息
|
||||
let now = now_secs();
|
||||
let dirs_json = serde_json::to_string(dirs).unwrap_or_default();
|
||||
let _ = with_conn(|conn| {
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO files_meta (key, value) VALUES ('last_built_at', ?1)",
|
||||
params![now.to_string()],
|
||||
).ok();
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO files_meta (key, value) VALUES ('last_built_dirs', ?1)",
|
||||
params![dirs_json],
|
||||
).ok()
|
||||
});
|
||||
|
||||
// 启动/刷新 notify 监听器
|
||||
start_watcher(dirs);
|
||||
|
||||
eprintln!("[quickpanel] 文件索引完成,共 {} 条", count);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// 遍历单个目录并写入索引,返回新增条目数
|
||||
fn walk_and_index(dir: &str) -> i64 {
|
||||
let path = Path::new(dir);
|
||||
if !path.exists() {
|
||||
return 0;
|
||||
}
|
||||
let mut count = 0i64;
|
||||
for entry in WalkDir::new(path)
|
||||
.max_depth(10)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_map(|e| e.ok())
|
||||
{
|
||||
let p = entry.path();
|
||||
if upsert_path(p) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// 将单个路径写入索引(创建/修改)。返回 true 表示已写入。
|
||||
/// 跳过隐藏文件(. 开头)、不存在的路径。
|
||||
fn upsert_path(p: &Path) -> bool {
|
||||
let Some(name_os) = p.file_name() else { return false };
|
||||
let name = name_os.to_string_lossy().to_string();
|
||||
if name.starts_with('.') {
|
||||
return false;
|
||||
}
|
||||
let meta = match std::fs::metadata(p) {
|
||||
Ok(m) => m,
|
||||
Err(_) => return false,
|
||||
};
|
||||
let name_lower = name.to_lowercase();
|
||||
let ext = p.extension()
|
||||
.map(|e| e.to_string_lossy().to_lowercase())
|
||||
.unwrap_or_default();
|
||||
let size = meta.len() as i64;
|
||||
let mtime = meta.modified().ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0);
|
||||
let is_dir = meta.is_dir() as i32;
|
||||
let path_str = p.to_string_lossy().to_string();
|
||||
|
||||
let _ = with_conn(|conn| {
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO files (path, name, name_lower, ext, size, mtime, is_dir)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
|
||||
params![path_str, name, name_lower, ext, size, mtime, is_dir],
|
||||
)
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// 从索引中删除指定路径
|
||||
fn remove_path(p: &Path) {
|
||||
let path_str = p.to_string_lossy().to_string();
|
||||
let _ = with_conn(|conn| {
|
||||
// 删除该路径及其子项(目录被删除时,子文件也失效)
|
||||
conn.execute(
|
||||
"DELETE FROM files WHERE path = ?1 OR path LIKE ?2",
|
||||
params![path_str, format!("{}%", path_str)],
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
/// 搜索文件:name_lower LIKE %query%,按名字长度升序(短名优先)。
|
||||
pub fn search(query: &str, limit: i64) -> Vec<FileRecord> {
|
||||
let like = format!("%{}%", query.to_lowercase());
|
||||
with_conn(|conn| {
|
||||
let mut stmt = match conn.prepare(
|
||||
"SELECT path, name, ext, size, is_dir FROM files
|
||||
WHERE name_lower LIKE ?1
|
||||
ORDER BY LENGTH(name) ASC, name ASC LIMIT ?2",
|
||||
) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return vec![],
|
||||
};
|
||||
stmt.query_map(params![like, limit], |r| {
|
||||
Ok(FileRecord {
|
||||
path: r.get(0)?,
|
||||
name: r.get(1)?,
|
||||
ext: r.get(2)?,
|
||||
size: r.get(3)?,
|
||||
is_dir: r.get::<_, i32>(4)? != 0,
|
||||
})
|
||||
})
|
||||
.map(|r| r.filter_map(|i| i.ok()).collect())
|
||||
.unwrap_or_default()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 索引状态
|
||||
pub fn stats() -> IndexStats {
|
||||
let total = with_conn(|conn| {
|
||||
conn.query_row("SELECT COUNT(*) FROM files", [], |r| r.get::<_, i64>(0))
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.unwrap_or(0);
|
||||
|
||||
let last_built_at = with_conn(|conn| {
|
||||
// query_row 返回 Result<String, Error>,统一处理失败
|
||||
let res: rusqlite::Result<String> = conn.query_row(
|
||||
"SELECT value FROM files_meta WHERE key = 'last_built_at'",
|
||||
[],
|
||||
|r| r.get::<_, String>(0),
|
||||
);
|
||||
res.ok().and_then(|s| s.parse().ok()).unwrap_or(0)
|
||||
})
|
||||
.unwrap_or(0);
|
||||
|
||||
let last_built_dirs = with_conn(|conn| {
|
||||
conn.query_row(
|
||||
"SELECT value FROM files_meta WHERE key = 'last_built_dirs'",
|
||||
[],
|
||||
|r| r.get::<_, String>(0),
|
||||
)
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<Vec<String>>(&s).ok())
|
||||
.unwrap_or_default()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
IndexStats {
|
||||
total,
|
||||
last_built_at,
|
||||
last_built_dirs,
|
||||
}
|
||||
}
|
||||
|
||||
fn now_secs() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
// ===== notify 增量监听 =====
|
||||
|
||||
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
|
||||
|
||||
static WATCHER: std::sync::OnceLock<Mutex<Option<RecommendedWatcher>>> = std::sync::OnceLock::new();
|
||||
|
||||
fn watcher_slot() -> &'static Mutex<Option<RecommendedWatcher>> {
|
||||
WATCHER.get_or_init(|| Mutex::new(None))
|
||||
}
|
||||
|
||||
/// 启动/刷新 notify 监听器。重建索引或修改索引目录后调用。
|
||||
/// 会先停止旧监听器,再为新目录列表添加递归监听。
|
||||
pub fn start_watcher(dirs: &[String]) {
|
||||
// 创建新 watcher(notify v6: recommended_watcher 只接受回调,Config 默认)
|
||||
let mut watcher = match notify::recommended_watcher(
|
||||
move |res: notify::Result<notify::Event>| {
|
||||
if let Ok(event) = res {
|
||||
handle_fs_event(&event);
|
||||
}
|
||||
},
|
||||
) {
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
eprintln!("[quickpanel] notify watcher 创建失败: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// 为每个目录添加递归监听
|
||||
for dir in dirs {
|
||||
let path = Path::new(dir);
|
||||
if !path.exists() {
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = watcher.watch(path, RecursiveMode::Recursive) {
|
||||
eprintln!("[quickpanel] watch {} 失败: {}", dir, e);
|
||||
}
|
||||
}
|
||||
|
||||
// 替换旧 watcher(drop 时自动 unwatch)
|
||||
let mut guard = watcher_slot().lock().unwrap();
|
||||
*guard = Some(watcher);
|
||||
eprintln!("[quickpanel] notify 监听已启动,监听 {} 个目录", dirs.len());
|
||||
}
|
||||
|
||||
/// 处理文件系统事件:创建/修改 → upsert,删除 → remove,重命名 → remove + upsert
|
||||
fn handle_fs_event(event: ¬ify::Event) {
|
||||
match event.kind {
|
||||
EventKind::Create(_) | EventKind::Modify(_) => {
|
||||
for path in &event.paths {
|
||||
if path.exists() {
|
||||
upsert_path(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
EventKind::Remove(_) => {
|
||||
for path in &event.paths {
|
||||
remove_path(path);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// 忽略访问/其他事件
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 停止 notify 监听器
|
||||
pub fn stop_watcher() {
|
||||
let mut guard = watcher_slot().lock().unwrap();
|
||||
*guard = None;
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
//! 应用图标提取:Windows SHGetFileInfo → HICON → RGBA → PNG,带磁盘 + 内存缓存。
|
||||
//!
|
||||
//! 流程:
|
||||
//! 1. 内存缓存命中 → 直接返回 data URL
|
||||
//! 2. 磁盘缓存命中({app_data_dir}/quickpanel/icons/{hash}.png) → 读取并缓存
|
||||
//! 3. 调用 SHGetFileInfoW 提取 HICON → GetDIBits 取 32bit BGRA → 转 RGBA → PNG
|
||||
//! 4. 写入磁盘缓存 + 内存缓存,返回 data URL
|
||||
//!
|
||||
//! 设计取舍:
|
||||
//! - 返回 base64 data URL 而非文件路径,避免独立弹窗窗口的 asset 协议配置问题
|
||||
//! - 磁盘缓存避免重复 Windows API 调用(昂贵),内存缓存避免重复磁盘读取 + 编码
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use base64::Engine as _;
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
// ===== 内存缓存 =====
|
||||
static MEM_CACHE: Mutex<Option<HashMap<String, String>>> = Mutex::new(None);
|
||||
const MEM_CACHE_MAX: usize = 512;
|
||||
|
||||
fn mem_get(path: &str) -> Option<String> {
|
||||
let cache = MEM_CACHE.lock().ok()?;
|
||||
cache.as_ref()?.get(path).cloned()
|
||||
}
|
||||
|
||||
fn mem_put(path: String, url: String) {
|
||||
if let Ok(mut guard) = MEM_CACHE.lock() {
|
||||
let map = guard.get_or_insert_with(HashMap::new);
|
||||
if map.len() >= MEM_CACHE_MAX {
|
||||
// 简单清理:丢弃一半(最早插入的,HashMap 无序,近似随机)
|
||||
let keep = map.len() / 2;
|
||||
let keys: Vec<String> = map.keys().cloned().collect();
|
||||
for k in keys.iter().skip(keep) {
|
||||
map.remove(k);
|
||||
}
|
||||
}
|
||||
map.insert(path, url);
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 磁盘缓存路径 =====
|
||||
fn cache_dir(app: &AppHandle) -> PathBuf {
|
||||
app.path()
|
||||
.app_data_dir()
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
.join("quickpanel")
|
||||
.join("icons")
|
||||
}
|
||||
|
||||
fn path_hash(path: &str) -> String {
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
// 统一小写 + 正斜杠,避免大小写/分隔符差异导致缓存未命中
|
||||
let normalized = path.to_lowercase().replace('\\', "/");
|
||||
let mut hasher = DefaultHasher::new();
|
||||
normalized.hash(&mut hasher);
|
||||
format!("{:016x}", hasher.finish())
|
||||
}
|
||||
|
||||
// ===== 公共 API =====
|
||||
|
||||
/// 获取应用图标 data URL。命中缓存则零开销;未命中则提取 + 编码 + 落盘。
|
||||
/// 返回 Ok(None) 表示提取失败或不支持的平台。
|
||||
pub fn get_icon_data_url(app: &AppHandle, path: &str) -> Option<String> {
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// 规范化路径分隔符:混合 / 和 \ 会导致 SHGetFileInfoW 失败
|
||||
let normalized = path.replace('/', "\\");
|
||||
let path = normalized.as_str();
|
||||
|
||||
// 1. 内存缓存
|
||||
if let Some(url) = mem_get(path) {
|
||||
return Some(url);
|
||||
}
|
||||
|
||||
let dir = cache_dir(app);
|
||||
let hash = path_hash(path);
|
||||
let cache_path = dir.join(format!("{}.png", hash));
|
||||
|
||||
// 2. 磁盘缓存
|
||||
if cache_path.exists() {
|
||||
if let Ok(bytes) = std::fs::read(&cache_path) {
|
||||
let url = png_to_data_url(&bytes);
|
||||
mem_put(path.to_string(), url.clone());
|
||||
return Some(url);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 提取
|
||||
let png = extract_icon_png(path)?;
|
||||
|
||||
// 4. 落盘(失败不影响返回)
|
||||
std::fs::create_dir_all(&dir).ok();
|
||||
std::fs::write(&cache_path, &png).ok();
|
||||
|
||||
// 5. 缓存 + 返回
|
||||
let url = png_to_data_url(&png);
|
||||
mem_put(path.to_string(), url.clone());
|
||||
Some(url)
|
||||
}
|
||||
|
||||
/// 清理整个图标磁盘缓存(设置页可调用)
|
||||
pub fn clear_cache(app: &AppHandle) {
|
||||
let dir = cache_dir(app);
|
||||
if dir.exists() {
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
std::fs::create_dir_all(&dir).ok();
|
||||
}
|
||||
if let Ok(mut guard) = MEM_CACHE.lock() {
|
||||
*guard = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn png_to_data_url(png: &[u8]) -> String {
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(png);
|
||||
format!("data:image/png;base64,{}", b64)
|
||||
}
|
||||
|
||||
// ===== Windows 图标提取 =====
|
||||
|
||||
#[cfg(windows)]
|
||||
fn extract_icon_png(path: &str) -> Option<Vec<u8>> {
|
||||
use std::ffi::OsStr;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::UI::Shell::{
|
||||
SHGetFileInfoW, SHFILEINFOW, SHGFI_ICON, SHGFI_LARGEICON,
|
||||
};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::DestroyIcon;
|
||||
|
||||
unsafe {
|
||||
let wide: Vec<u16> = OsStr::new(path)
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
|
||||
let mut shfi: SHFILEINFOW = std::mem::zeroed();
|
||||
let _ = SHGetFileInfoW(
|
||||
wide.as_ptr(),
|
||||
0,
|
||||
&mut shfi,
|
||||
std::mem::size_of::<SHFILEINFOW>() as u32,
|
||||
SHGFI_ICON | SHGFI_LARGEICON,
|
||||
);
|
||||
|
||||
// hIcon 为 0 表示无图标
|
||||
if shfi.hIcon == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let result = hicon_to_png(shfi.hIcon);
|
||||
let _ = DestroyIcon(shfi.hIcon);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn extract_icon_png(_path: &str) -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// HICON → PNG bytes
|
||||
#[cfg(windows)]
|
||||
fn hicon_to_png(hicon: windows_sys::Win32::UI::WindowsAndMessaging::HICON) -> Option<Vec<u8>> {
|
||||
use windows_sys::Win32::Graphics::Gdi::DeleteObject;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{GetIconInfo, ICONINFO};
|
||||
|
||||
unsafe {
|
||||
let mut icon_info: ICONINFO = std::mem::zeroed();
|
||||
if GetIconInfo(hicon, &mut icon_info) == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let has_color = icon_info.hbmColor != 0;
|
||||
let has_mask = icon_info.hbmMask != 0;
|
||||
|
||||
let result: Option<(Vec<u8>, u32, u32)> = if has_color {
|
||||
// 32-bit BGRA → RGBA
|
||||
let (mut rgba, w, h) = bitmap_to_rgba32(icon_info.hbmColor)?;
|
||||
|
||||
// 检查 alpha 是否全 0(旧式无 alpha 通道图标)
|
||||
let alpha_any = rgba.chunks_exact(4).any(|c| c[3] != 0);
|
||||
if !alpha_any {
|
||||
if has_mask {
|
||||
// 用 mask 补 alpha(白=透明,黑=不透明)
|
||||
let _ = apply_mask_alpha(&mut rgba, w, h, icon_info.hbmMask);
|
||||
} else {
|
||||
// 无 mask,设为全不透明
|
||||
for c in rgba.chunks_exact_mut(4) {
|
||||
c[3] = 255;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some((rgba, w, h))
|
||||
} else {
|
||||
// 无颜色位图:monochrome 图标,罕见且无色,跳过
|
||||
None
|
||||
};
|
||||
|
||||
// 清理 GDI 对象
|
||||
if has_color {
|
||||
let _ = DeleteObject(icon_info.hbmColor);
|
||||
}
|
||||
if has_mask {
|
||||
let _ = DeleteObject(icon_info.hbmMask);
|
||||
}
|
||||
|
||||
let (rgba, w, h) = result?;
|
||||
encode_png(&rgba, w, h)
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取 32-bit 位图为 RGBA(top-down),BGRA→RGBA
|
||||
#[cfg(windows)]
|
||||
fn bitmap_to_rgba32(
|
||||
hbm: windows_sys::Win32::Graphics::Gdi::HBITMAP,
|
||||
) -> Option<(Vec<u8>, u32, u32)> {
|
||||
use windows_sys::Win32::Foundation::HWND;
|
||||
use windows_sys::Win32::Graphics::Gdi::{
|
||||
GetDC, GetDIBits, GetObjectW, BITMAP, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS,
|
||||
ReleaseDC,
|
||||
};
|
||||
|
||||
unsafe {
|
||||
// 取尺寸
|
||||
let mut bmp: BITMAP = std::mem::zeroed();
|
||||
let got = GetObjectW(
|
||||
hbm,
|
||||
std::mem::size_of::<BITMAP>() as i32,
|
||||
&mut bmp as *mut _ as *mut _,
|
||||
);
|
||||
if got == 0 {
|
||||
return None;
|
||||
}
|
||||
let w = bmp.bmWidth as u32;
|
||||
let h = bmp.bmHeight as u32;
|
||||
if w == 0 || h == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// 32-bit top-down DIB
|
||||
let mut bi: BITMAPINFO = std::mem::zeroed();
|
||||
bi.bmiHeader.biSize = std::mem::size_of::<BITMAPINFOHEADER>() as u32;
|
||||
bi.bmiHeader.biWidth = w as i32;
|
||||
bi.bmiHeader.biHeight = -(h as i32); // 负值 = top-down
|
||||
bi.bmiHeader.biPlanes = 1;
|
||||
bi.bmiHeader.biBitCount = 32;
|
||||
bi.bmiHeader.biCompression = BI_RGB;
|
||||
|
||||
let mut pixels = vec![0u8; (w * h * 4) as usize];
|
||||
let hdc = GetDC(0 as HWND);
|
||||
if hdc == 0 {
|
||||
return None;
|
||||
}
|
||||
let ret = GetDIBits(
|
||||
hdc,
|
||||
hbm,
|
||||
0,
|
||||
h,
|
||||
pixels.as_mut_ptr() as *mut _,
|
||||
&mut bi,
|
||||
DIB_RGB_COLORS,
|
||||
);
|
||||
let _ = ReleaseDC(0 as HWND, hdc);
|
||||
if ret == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// BGRA → RGBA
|
||||
for chunk in pixels.chunks_exact_mut(4) {
|
||||
chunk.swap(0, 2);
|
||||
}
|
||||
Some((pixels, w, h))
|
||||
}
|
||||
}
|
||||
|
||||
/// 用 1bpp mask 设置 alpha:mask 白(1)=透明,黑(0)=不透明
|
||||
#[cfg(windows)]
|
||||
fn apply_mask_alpha(
|
||||
rgba: &mut [u8],
|
||||
w: u32,
|
||||
h: u32,
|
||||
hbm_mask: windows_sys::Win32::Graphics::Gdi::HBITMAP,
|
||||
) -> Result<(), ()> {
|
||||
use windows_sys::Win32::Foundation::HWND;
|
||||
use windows_sys::Win32::Graphics::Gdi::{
|
||||
GetDC, GetDIBits, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, ReleaseDC,
|
||||
};
|
||||
|
||||
unsafe {
|
||||
let mut bi: BITMAPINFO = std::mem::zeroed();
|
||||
bi.bmiHeader.biSize = std::mem::size_of::<BITMAPINFOHEADER>() as u32;
|
||||
bi.bmiHeader.biWidth = w as i32;
|
||||
bi.bmiHeader.biHeight = -(h as i32);
|
||||
bi.bmiHeader.biPlanes = 1;
|
||||
bi.bmiHeader.biBitCount = 1;
|
||||
bi.bmiHeader.biCompression = BI_RGB;
|
||||
|
||||
// 1bpp,每行 4 字节对齐
|
||||
let row_bytes = ((w + 31) / 32 * 4) as usize;
|
||||
let mut mask = vec![0u8; row_bytes * h as usize];
|
||||
|
||||
let hdc = GetDC(0 as HWND);
|
||||
if hdc == 0 {
|
||||
return Err(());
|
||||
}
|
||||
let ret = GetDIBits(
|
||||
hdc,
|
||||
hbm_mask,
|
||||
0,
|
||||
h,
|
||||
mask.as_mut_ptr() as *mut _,
|
||||
&mut bi,
|
||||
DIB_RGB_COLORS,
|
||||
);
|
||||
let _ = ReleaseDC(0 as HWND, hdc);
|
||||
if ret == 0 {
|
||||
return Err(());
|
||||
}
|
||||
|
||||
for y in 0..h as usize {
|
||||
for x in 0..w as usize {
|
||||
let byte_idx = y * row_bytes + x / 8;
|
||||
let bit = (mask[byte_idx] >> (7 - (x % 8))) & 1;
|
||||
let alpha = if bit == 1 { 0 } else { 255 };
|
||||
rgba[(y * w as usize + x) * 4 + 3] = alpha;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// RGBA → PNG
|
||||
fn encode_png(rgba: &[u8], w: u32, h: u32) -> Option<Vec<u8>> {
|
||||
use image::{ImageBuffer, RgbaImage};
|
||||
let img: RgbaImage = ImageBuffer::from_raw(w, h, rgba.to_vec())?;
|
||||
let mut buf = std::io::Cursor::new(Vec::new());
|
||||
image::DynamicImage::ImageRgba8(img)
|
||||
.write_to(&mut buf, image::ImageFormat::Png)
|
||||
.ok()?;
|
||||
Some(buf.into_inner())
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! 快速面板模块:全局快捷键唤起的多源命令面板。
|
||||
//!
|
||||
//! Phase 1:窗口骨架(预创建隐藏窗口 + 快捷键 + 失焦隐藏)
|
||||
//! Phase 2:fuzzy + 拼音引擎,command/calc/web/system Provider
|
||||
//! Phase 3:文件索引(walkdir + rusqlite)、应用扫描、剪贴板历史复用
|
||||
|
||||
pub mod app_scanner;
|
||||
pub mod commands;
|
||||
pub mod file_index;
|
||||
pub mod icon_extractor;
|
||||
pub mod popup;
|
||||
|
||||
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_hide_popup, quickpanel_init_file_index, quickpanel_lock_screen,
|
||||
quickpanel_open_file, 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, register_shortcut};
|
||||
@@ -0,0 +1,311 @@
|
||||
//! 快速面板弹窗:全局快捷键唤起的多源命令面板。
|
||||
//!
|
||||
//! 流程(与剪贴板弹窗同构):
|
||||
//! 1. 应用启动 → `ensure_window` 预创建隐藏窗口(屏幕外)
|
||||
//! 2. 全局快捷键按下 → `show_popup` 在鼠标所在显示器中央定位并显示
|
||||
//! 3. 前端 Vue 挂载完成、主题应用后调用 `quickpanel_show_window` 显示窗口
|
||||
//! 4. 前端监听 `quickpanel-show` 事件刷新数据/聚焦输入
|
||||
//! 5. 窗口失焦自动隐藏(保留窗口复用,不销毁)
|
||||
//!
|
||||
//! Win32 API(鼠标/显示器/DPI)复用 clipboard::popup 已 pub use 的实现,
|
||||
//! 避免重复封装。
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder};
|
||||
use tauri::window::{Effect, EffectsBuilder};
|
||||
use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState};
|
||||
|
||||
use crate::clipboard::popup::{get_cursor_pos, get_work_area_at_point, get_dpi_for_point};
|
||||
|
||||
/// 弹窗窗口标签
|
||||
pub const POPUP_LABEL: &str = "quick-panel";
|
||||
|
||||
/// 窗口尺寸(逻辑像素)
|
||||
const WIN_W: f64 = 600.0;
|
||||
const WIN_H: f64 = 420.0;
|
||||
|
||||
/// 当前注册的快捷键(用于注销旧快捷键)
|
||||
static CURRENT_SHORTCUT: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
/// 标志:show_popup 兜底创建路径设为 true,前端 onMounted 回调 show_window 时据此判断是否显示。
|
||||
/// 预创建路径不设置,避免应用启动时弹窗自动弹出。
|
||||
static POPUP_PENDING_SHOW: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// 自定义命令
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CustomCommand {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub command: String,
|
||||
#[serde(default)]
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
/// 快速面板设置
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct QuickPanelSettings {
|
||||
/// 全局快捷键(如 "Alt+Space"),空字符串表示不注册。
|
||||
#[serde(default = "default_shortcut")]
|
||||
pub shortcut: String,
|
||||
/// 唤起位置:center(鼠标所在显示器中央)| cursor(鼠标位置)
|
||||
#[serde(default = "default_popup_position")]
|
||||
pub popup_position: String,
|
||||
/// 默认搜索引擎:google | bing | baidu
|
||||
#[serde(default = "default_search_engine")]
|
||||
pub search_engine: String,
|
||||
/// 文件索引目录列表(空列表表示使用默认:桌面/文档/下载)
|
||||
#[serde(default = "default_index_dirs")]
|
||||
pub index_dirs: Vec<String>,
|
||||
/// 自定义命令列表
|
||||
#[serde(default)]
|
||||
pub custom_commands: Vec<CustomCommand>,
|
||||
}
|
||||
|
||||
fn default_shortcut() -> String {
|
||||
"Alt+Space".to_string()
|
||||
}
|
||||
fn default_popup_position() -> String {
|
||||
"center".to_string()
|
||||
}
|
||||
fn default_search_engine() -> String {
|
||||
"bing".to_string()
|
||||
}
|
||||
fn default_index_dirs() -> Vec<String> {
|
||||
// 桌面/文档/下载目录(延迟到实际使用时解析,避免启动时失败)
|
||||
let mut dirs = Vec::new();
|
||||
if let Some(d) = dirs::desktop_dir() {
|
||||
dirs.push(d.to_string_lossy().to_string());
|
||||
}
|
||||
if let Some(d) = dirs::document_dir() {
|
||||
dirs.push(d.to_string_lossy().to_string());
|
||||
}
|
||||
if let Some(d) = dirs::download_dir() {
|
||||
dirs.push(d.to_string_lossy().to_string());
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
impl Default for QuickPanelSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
shortcut: default_shortcut(),
|
||||
popup_position: default_popup_position(),
|
||||
search_engine: default_search_engine(),
|
||||
index_dirs: default_index_dirs(),
|
||||
custom_commands: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 设置文件路径:{app_data_dir}/quickpanel/settings.json
|
||||
fn settings_path(app: &AppHandle) -> PathBuf {
|
||||
app.path()
|
||||
.app_data_dir()
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
.join("quickpanel")
|
||||
.join("settings.json")
|
||||
}
|
||||
|
||||
/// 读取设置,文件不存在或解析失败返回默认值
|
||||
pub fn load_settings(app: &AppHandle) -> QuickPanelSettings {
|
||||
let path = settings_path(app);
|
||||
std::fs::read_to_string(&path)
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 保存设置到磁盘
|
||||
pub fn save_settings(app: &AppHandle, settings: &QuickPanelSettings) -> Result<(), String> {
|
||||
let path = settings_path(app);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建设置目录失败: {}", e))?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(settings).map_err(|e| format!("序列化设置失败: {}", e))?;
|
||||
std::fs::write(&path, json).map_err(|e| format!("写入设置文件失败: {}", e))
|
||||
}
|
||||
|
||||
/// 解析快捷键字符串为 Shortcut(格式如 "Alt+Space"、"Ctrl+Shift+P")
|
||||
/// 失败返回 None。
|
||||
pub fn parse_shortcut(s: &str) -> Option<Shortcut> {
|
||||
s.trim().parse::<Shortcut>().ok()
|
||||
}
|
||||
|
||||
/// 注册全局快捷键。重复调用会先注销旧快捷键。
|
||||
/// 传入空字符串则仅注销不注册。
|
||||
pub fn register_shortcut(app: &AppHandle, shortcut_str: &str) -> Result<(), String> {
|
||||
// 先注销旧快捷键
|
||||
unregister_shortcut(app);
|
||||
|
||||
if shortcut_str.trim().is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let shortcut = parse_shortcut(shortcut_str)
|
||||
.ok_or_else(|| format!("无效的快捷键: {}", shortcut_str))?;
|
||||
|
||||
let app_handle = app.clone();
|
||||
app.global_shortcut()
|
||||
.on_shortcut(shortcut, move |_app, _shortcut, event| {
|
||||
// 仅在按下时触发(松开不触发)
|
||||
if event.state == ShortcutState::Pressed {
|
||||
show_popup(&app_handle);
|
||||
}
|
||||
})
|
||||
.map_err(|e| format!("注册快捷键失败: {}", e))?;
|
||||
|
||||
if let Ok(mut cur) = CURRENT_SHORTCUT.lock() {
|
||||
*cur = Some(shortcut_str.to_string());
|
||||
}
|
||||
eprintln!("[quickpanel] 已注册快捷键: {}", shortcut_str);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 注销当前快捷键
|
||||
pub fn unregister_shortcut(app: &AppHandle) {
|
||||
if let Ok(cur) = CURRENT_SHORTCUT.lock() {
|
||||
if let Some(ref s) = *cur {
|
||||
if let Some(shortcut) = parse_shortcut(s) {
|
||||
let _ = app.global_shortcut().unregister(shortcut);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(mut cur) = CURRENT_SHORTCUT.lock() {
|
||||
*cur = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// 创建弹窗窗口(隐藏状态)并注册失焦监听。
|
||||
/// 位置默认在屏幕外,show_popup 时会重新定位到鼠标所在显示器中央。
|
||||
/// 预创建后首次按快捷键走"窗口已存在"分支直接 show,避免首次创建的时序问题。
|
||||
fn create_popup_window(app: &AppHandle) {
|
||||
let win = match WebviewWindowBuilder::new(
|
||||
app,
|
||||
POPUP_LABEL,
|
||||
WebviewUrl::App("index.html#quick-panel".into()),
|
||||
)
|
||||
.title("快速面板")
|
||||
.inner_size(WIN_W, WIN_H)
|
||||
.position(-10000.0, -10000.0) // 屏幕外,避免隐藏时一闪
|
||||
.decorations(false)
|
||||
.transparent(true)
|
||||
.shadow(true)
|
||||
.always_on_top(true)
|
||||
.skip_taskbar(true)
|
||||
.resizable(false)
|
||||
.visible(false)
|
||||
.focused(false) // 不抢占焦点,避免创建即触发 Focused(false)
|
||||
.effects(EffectsBuilder::new().effects(vec![Effect::Mica]).build())
|
||||
.build()
|
||||
{
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
eprintln!("[quickpanel] 创建弹窗失败: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// 监听窗口失焦:自动隐藏
|
||||
let app_handle = app.clone();
|
||||
let win_handle = win.clone();
|
||||
win.on_window_event(move |event| {
|
||||
if let tauri::WindowEvent::Focused(false) = event {
|
||||
let _ = win_handle.hide();
|
||||
let _ = app_handle.emit("quickpanel-hide", ());
|
||||
}
|
||||
});
|
||||
|
||||
eprintln!("[quickpanel] 弹窗窗口已预创建(隐藏状态)");
|
||||
}
|
||||
|
||||
/// 应用启动时预创建弹窗窗口(隐藏)。
|
||||
/// 这样首次按快捷键时窗口已存在,直接 show + 定位,避免首次创建时序问题。
|
||||
pub fn ensure_window(app: &AppHandle) {
|
||||
if app.get_webview_window(POPUP_LABEL).is_some() {
|
||||
return;
|
||||
}
|
||||
create_popup_window(app);
|
||||
}
|
||||
|
||||
/// 在指定位置显示弹窗。
|
||||
/// popup_position = "cursor" 时在鼠标位置附近显示,否则在鼠标所在显示器中央显示。
|
||||
/// 窗口不存在则创建(隐藏状态,等前端挂载后调用 show_window 显示)。
|
||||
pub fn show_popup(app: &AppHandle) {
|
||||
let settings = load_settings(app);
|
||||
let cursor_mode = settings.popup_position == "cursor";
|
||||
|
||||
// 获取鼠标位置(物理像素)
|
||||
let (mx, my) = match get_cursor_pos() {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
};
|
||||
|
||||
// 获取光标所在显示器的工作区(物理像素,与 get_cursor_pos 同一坐标系)
|
||||
let (wa_left, wa_top, wa_right, wa_bottom) = get_work_area_at_point(mx, my)
|
||||
.unwrap_or((0, 0, 1920, 1040));
|
||||
|
||||
// 获取光标所在显示器的 DPI,将物理坐标转为逻辑坐标(DIP)
|
||||
let dpi = get_dpi_for_point(mx, my).unwrap_or(96);
|
||||
let scale = dpi as f64 / 96.0;
|
||||
|
||||
let wa_left_l = wa_left as f64 / scale;
|
||||
let wa_top_l = wa_top as f64 / scale;
|
||||
let wa_right_l = wa_right as f64 / scale;
|
||||
let wa_bottom_l = wa_bottom as f64 / scale;
|
||||
|
||||
let (x, y) = if cursor_mode {
|
||||
// 鼠标位置模式:以鼠标为基准偏移,clamp 到工作区内
|
||||
let mx_l = mx as f64 / scale;
|
||||
let my_l = my as f64 / scale;
|
||||
let x = (mx_l + 12.0).min(wa_right_l - WIN_W).max(wa_left_l);
|
||||
let y = (my_l + 12.0).min(wa_bottom_l - WIN_H).max(wa_top_l);
|
||||
(x, y)
|
||||
} else {
|
||||
// 中央模式:窗口居中于鼠标所在显示器工作区
|
||||
let wa_w = wa_right_l - wa_left_l;
|
||||
let wa_h = wa_bottom_l - wa_top_l;
|
||||
(wa_left_l + (wa_w - WIN_W) / 2.0, wa_top_l + (wa_h - WIN_H) / 2.0)
|
||||
};
|
||||
|
||||
// 窗口已存在:移动 + 显示 + 请求焦点
|
||||
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
||||
let _ = win.set_position(tauri::Position::Logical(tauri::LogicalPosition { x, y }));
|
||||
let _ = win.show();
|
||||
let _ = win.set_focus();
|
||||
// 通知前端刷新数据
|
||||
let _ = app.emit("quickpanel-show", ());
|
||||
return;
|
||||
}
|
||||
|
||||
// 兜底:窗口被销毁时重新创建(隐藏),等前端 onMounted 回调 show_window
|
||||
POPUP_PENDING_SHOW.store(true, Ordering::SeqCst);
|
||||
create_popup_window(app);
|
||||
}
|
||||
|
||||
/// 显示已创建的弹窗窗口(由前端 onMounted 后调用)。
|
||||
/// 预创建路径下前端 onMounted 也会调用此函数,但 POPUP_PENDING_SHOW 为 false 时直接跳过,
|
||||
/// 避免应用启动时弹窗自动弹出。仅 show_popup 兜底创建路径才真正显示。
|
||||
pub fn show_window(app: &AppHandle) {
|
||||
if !POPUP_PENDING_SHOW.swap(false, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
||||
let _ = win.show();
|
||||
let _ = win.set_focus();
|
||||
// 通知前端刷新数据
|
||||
let _ = app.emit("quickpanel-show", ());
|
||||
}
|
||||
}
|
||||
|
||||
/// 隐藏弹窗(不销毁,保留复用)
|
||||
pub fn hide_popup(app: &AppHandle) {
|
||||
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
||||
let _ = win.hide();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user