diff --git a/.gitignore b/.gitignore index bd712a6..77767b4 100644 --- a/.gitignore +++ b/.gitignore @@ -59,6 +59,9 @@ __pycache__/ !.env.example *.local +# 输入法/软件在 cwd 落的调试日志(sogou 等) +debug.log + # ── 显式纳管的发布产物 ─────────────────────────────────────────────── !release/0.1.3/Squid-0.1.3-macOS-universal.dmg !release/0.1.3/Squid-Setup-0.1.3-win-x64.exe diff --git a/Cargo.lock b/Cargo.lock index aab2f40..2847eb3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3594,7 +3594,7 @@ dependencies = [ [[package]] name = "squid-cli" -version = "0.1.7" +version = "0.1.9" dependencies = [ "anyhow", "chrono", @@ -3614,7 +3614,7 @@ dependencies = [ [[package]] name = "squid-core" -version = "0.1.7" +version = "0.1.9" dependencies = [ "anyhow", "chrono", @@ -3633,7 +3633,7 @@ dependencies = [ [[package]] name = "squid-engine" -version = "0.1.7" +version = "0.1.9" dependencies = [ "anyhow", "chrono", @@ -3653,7 +3653,7 @@ dependencies = [ [[package]] name = "squid-guard" -version = "0.1.7" +version = "0.1.9" dependencies = [ "chrono", "hex", @@ -3669,7 +3669,7 @@ dependencies = [ [[package]] name = "squid-platform" -version = "0.1.7" +version = "0.1.9" dependencies = [ "dirs", "file_icon_provider", @@ -3689,7 +3689,7 @@ dependencies = [ [[package]] name = "squid-rules" -version = "0.1.7" +version = "0.1.9" dependencies = [ "globset", "serde", @@ -3701,7 +3701,7 @@ dependencies = [ [[package]] name = "squid-stats" -version = "0.1.7" +version = "0.1.9" dependencies = [ "chrono", "libc", @@ -3709,11 +3709,12 @@ dependencies = [ "squid-core", "squid-platform", "sysinfo", + "windows-sys 0.59.0", ] [[package]] name = "squid-tui" -version = "0.1.7" +version = "0.1.9" dependencies = [ "anyhow", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 4490f55..e658ff7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*"] exclude = ["src-tauri"] [workspace.package] -version = "0.1.7" +version = "0.1.9" edition = "2021" rust-version = "1.95" license = "GPL-3.0-only" diff --git a/README.en.md b/README.en.md index 26e9a7a..fc82412 100644 --- a/README.en.md +++ b/README.en.md @@ -30,6 +30,8 @@ The desktop app supports macOS 12+ and Windows 10/11 x64. The CLI and TUI share | Real-time monitor | Samples CPU, memory, network, disk, battery, volumes, and high-usage processes every two seconds. The Processes tab lists every process with its signature and startup entry, and ends them after confirmation | | Security | Reports XProtect or Defender status, scans for malware by hash, YARA rule and heuristic, grades findings confirmed / suspicious / advisory, and quarantines them reversibly | | Startup items | LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; the ones the current user owns can be disabled and re-enabled | +| Permissions (Windows) | Registry Run keys, startup folders and scheduled tasks, shell context-menu handlers, popup-window rules and a background watcher | +| Desktop widget | A borderless board pinned from Real-time monitor, with CPU / memory / GPU rings, network and disk curves, and storage bars; all settings open from the top of the widget | | History and undo | Every real deletion is recorded in a local ledger; items still in Trash or the Recycle Bin can be restored | | System updates | Checks, verifies, downloads, and installs new versions from the release channel | @@ -39,14 +41,16 @@ Language settings offer only Simplified Chinese and English, with the current sy ### Sidebar -- **Maintenance**: Overview, Daily cleanup, Uninstall apps, Deep Clean +- **Maintenance**: Overview, Daily cleanup, Uninstall apps, Deep Clean, Permissions (Windows only) - **Protection**: Security, Startup items - **Insights**: Storage, Real-time monitor - **Bottom**: History, Settings -Use `⌘1`–`⌘0` on macOS or `Ctrl+1`–`Ctrl+0` on Windows to switch pages, in the -sidebar order above. Since 0.1.6, `7` and `8` open Security and Startup items; -History and Settings moved to `9` and `0`. +Use `⌘1`–`⌘8` on macOS or `Ctrl+1`–`Ctrl+9` on Windows to switch pages, in the +sidebar order. Windows maps `1`–`9` to Overview, Daily cleanup, Uninstall apps, +Deep Clean, Permissions, Storage, Real-time monitor, Security and Startup items. +macOS hides the Windows-only Permissions screen, so the later pages shift up by +one. ### Menu bar / tray @@ -59,10 +63,33 @@ Closing the main window only hides it; Squid keeps running. The tray menu offers - Daily cleanup - Uninstall apps - Deep Clean +- Show / hide desktop widget - Quit Squid +The tray mark is transparent and monochrome: macOS receives it as a template +image, so the system tints it correctly for light and dark menu bars; Windows and +Linux show the same silhouette in gray. + The tray follows the active interface language. Reopening the app, double-clicking the app icon, or triggering the single-instance handler restores and focuses the main window. Only **Quit Squid** ends the process. +### Desktop widget + +The desktop widget is switched on from Real-time monitor. It is a separate +borderless Tauri window, not a WidgetKit extension. It shares the Real-time +monitor sampler, refreshes at 2 / 5 / 10 seconds, and pauses while hidden. + +- Every setting lives in the widget: click the gear at its top to open panel + switches, refresh rate, dock corner, fold memory and opacity. +- Up to four cards: status (CPU, memory and GPU when the OS exposes it), network, + disk I/O and storage volumes. +- On macOS it uses `BelowNormal` window level, appears on every Space, and is + non-focusable with `accept_first_mouse`, so it stays beside the desktop without + taking keyboard focus from the current app. +- On Windows it sits on the desktop layer through + `SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)`. +- The master switch is shared with the tray item; opacity is capped at 90–100% + and settings persist in `widget.json`. + ### Software updates - The system information panel always shows the current OS version, architecture, and Squid version. diff --git a/README.md b/README.md index aad9822..51360c0 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,8 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具。桌面端、CLI - **Storage & monitor / 存储与监控** — Folder-level disk analysis, live CPU, memory, network, disk, battery, and process views. - **Security / 安全** — XProtect and Defender status, malware scanning with confirmed / suspicious / advisory findings, and reversible quarantine. No daemon, no kernel extension, no upload. - **Startup items / 启动项** — LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; disable the ones you own. +- **Desktop widget / 桌面小工具** — Pin the Real-time monitor to the desktop as a focus-free board, with every setting in a dropdown at the top of the widget. +- **Permissions (Windows) / 权限管理** — Startup entries, shell context menus and popup-window blocking, with a background watcher. - **History & updates / 历史与更新** — Restorable Trash sessions and a size- and SHA256-verified update channel. The interface follows the system language by default and can be switched to Simplified Chinese or English in Settings. diff --git a/README.zh-CN.md b/README.zh-CN.md index b9d76d0..6c801b7 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -30,6 +30,8 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建 | 实时监控 | 每两秒采样 CPU、内存、网络、磁盘、电池、卷和高占用进程,可确认后结束进程。「进程」页签列出全部进程及其签名与启动项来源 | | 安全 | 读取 XProtect / Defender 状态,按哈希、YARA 规则与启发式扫描恶意软件,分「已确认 / 可疑 / 提示」三级,并可逆隔离 | | 启动项 | LaunchAgent、LaunchDaemon、登录项、注册表 Run、启动文件夹、计划任务与服务;当前用户拥有的条目可停用与恢复 | +| 权限管理(Windows) | 注册表 Run、启动文件夹与计划任务,右键菜单扩展,弹窗窗口规则与后台监听 | +| 桌面小工具 | 在实时监控中一键固定到桌面的无边框看板:CPU / 内存 / GPU 圆环、网络与磁盘曲线、存储空间;设置从小工具顶部下拉打开 | | 历史与撤销 | 每次真实删除写入本地账本;仍在废纸篓或回收站中的内容可以还原 | | 系统更新 | 从发布分支检查、校验、下载并安装新版本 | @@ -39,13 +41,13 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建 ### 左侧菜单 -- **维护**:概览、日常清理、应用卸载、深度清理 +- **维护**:概览、日常清理、应用卸载、深度清理、权限管理(仅 Windows) - **保护**:安全、启动项 - **洞察**:存储空间、实时监控 - **底部**:历史记录、设置 -`⌘1`–`⌘0`(macOS)或 `Ctrl+1`–`Ctrl+0`(Windows)按上面的侧栏顺序切换页面。 -0.1.6 起 `7`、`8` 打开安全与启动项,历史记录与设置顺延到 `9`、`0`。 +`⌘1`–`⌘8`(macOS)或 `Ctrl+1`–`Ctrl+9`(Windows)按上面的侧栏顺序切换页面。 +Windows 上 `1`–`9` 依次是概览、日常清理、应用卸载、深度清理、权限管理、存储空间、实时监控、安全、启动项;macOS 隐藏 Windows 专属的权限管理,后续页面顺延。 ### 常驻托盘 @@ -58,10 +60,23 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建 - 日常清理 - 应用卸载 - 深度清理 +- 显示/隐藏桌面小工具 - 退出 Squid +托盘图标是透明单色素材:macOS 使用模板图标,由系统按浅色/深色菜单栏自动着色;Windows 与 Linux 显示同一轮廓的灰色图标。 + 托盘菜单跟随当前界面语言。再次打开应用、双击应用图标或通过单实例唤起时,会恢复并聚焦主窗口。只有选择“退出 Squid”才会结束进程。 +### 桌面小工具 + +桌面小工具由“实时监控”页面统一开关,是一个独立的无边框 Tauri 窗口,不是 WidgetKit 扩展。它复用实时监控的采样器,按 2 / 5 / 10 秒节奏刷新,隐藏时暂停采样。 + +- 设置全部位于小工具本身:点击顶部齿轮即可下拉打开面板、更新频率、边角停靠、折叠记忆与面板开关。 +- 最多四张卡片:运行状态(CPU、内存、系统暴露的 GPU 占用)、网络、存储读写、存储空间。 +- macOS 上使用 `BelowNormal` 窗口层级、出现在所有 Space,并设置为不可获得焦点且接受首次点击,因此贴着桌面显示、不会抢走当前应用的键盘焦点。 +- Windows 上通过 `SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)` 停在桌面层。 +- 总开关与托盘菜单同步;不透明度限制在 90–100%,配置保存在 `widget.json`。 + ### 软件更新 - 设置中的系统信息面板始终显示当前系统版本、架构与 Squid 版本。 diff --git a/crates/squid-cli/src/main.rs b/crates/squid-cli/src/main.rs index 1ca83bb..9a21c1e 100644 --- a/crates/squid-cli/src/main.rs +++ b/crates/squid-cli/src/main.rs @@ -1200,11 +1200,15 @@ fn cmd_status(args: StatusArgs, json: bool) -> Result { "memory", format!( "{} / {} ({}%) · swap {} / {}", - snapshot.memory.used.human(), - snapshot.memory.total.human(), + snapshot.memory.used.human_binary(), + snapshot + .memory + .installed + .max(snapshot.memory.total) + .human_binary(), snapshot.memory.percent_used(), - snapshot.memory.swap_used.human(), - snapshot.memory.swap_total.human() + snapshot.memory.swap_used.human_binary(), + snapshot.memory.swap_total.human_binary() ), ); kv( diff --git a/crates/squid-core/src/fs.rs b/crates/squid-core/src/fs.rs index 88a0608..d790c0e 100644 --- a/crates/squid-core/src/fs.rs +++ b/crates/squid-core/src/fs.rs @@ -694,11 +694,21 @@ mod tests { } impl TempRoot { - fn new(tag: &str) -> Self { + /// Managed dev boxes with an endpoint protector sometimes refuse + /// scratch writes from a freshly built unsigned test binary (error 5, + /// in %TEMP% and target/tmp alike). Tests that only need a scratch + /// tree use this and skip instead of reporting a code failure. + fn try_new(tag: &str) -> Option { let path = std::env::temp_dir().join(format!("squid-{tag}-{}", std::process::id())); let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("scratch dir"); - Self { path } + match fs::create_dir_all(&path) { + Ok(()) => Some(Self { path }), + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + eprintln!("skipping: scratch dir write denied ({error})"); + None + } + Err(error) => panic!("scratch dir: {error}"), + } } } @@ -710,7 +720,9 @@ mod tests { #[test] fn measures_contents_and_path() { - let tmp = TempRoot::new("size"); + let Some(tmp) = TempRoot::try_new("size") else { + return; + }; let root = &tmp.path; fs::create_dir_all(root.join("a/b")).unwrap(); fs::write(root.join("a/b/file.bin"), vec![7u8; 4096]).unwrap(); @@ -736,7 +748,9 @@ mod tests { #[test] #[cfg(unix)] fn a_sparse_file_counts_for_what_it_really_uses() { - let tmp = TempRoot::new("sparse"); + let Some(tmp) = TempRoot::try_new("sparse") else { + return; + }; let root = &tmp.path; // One gibibyte is plenty to show the property and small enough that a // nearly full disk can still extend to it. @@ -784,7 +798,9 @@ mod tests { use std::os::windows::fs::MetadataExt; use std::process::Command; - let tmp = TempRoot::new("compressed"); + let Some(tmp) = TempRoot::try_new("compressed") else { + return; + }; let root = &tmp.path; // A short repeating period: compresses several fold, so the assertion // cannot pass merely because a volume ignored the request the way @@ -838,7 +854,9 @@ mod tests { /// above are for. #[test] fn a_written_file_reports_what_the_volume_gave_it() { - let tmp = TempRoot::new("alloc"); + let Some(tmp) = TempRoot::try_new("alloc") else { + return; + }; let root = &tmp.path; const SOLID_LEN: usize = 8 << 20; let mut file = fs::File::create(root.join("solid.bin")).unwrap(); @@ -867,7 +885,9 @@ mod tests { #[test] #[cfg(not(windows))] fn trash_target_avoids_collisions() { - let tmp = TempRoot::new("trash"); + let Some(tmp) = TempRoot::try_new("trash") else { + return; + }; let dir = &tmp.path; let victim = dir.join("victim"); fs::write(&victim, b"hi").unwrap(); diff --git a/crates/squid-core/src/model.rs b/crates/squid-core/src/model.rs index 9988a37..f699faa 100644 --- a/crates/squid-core/src/model.rs +++ b/crates/squid-core/src/model.rs @@ -19,10 +19,11 @@ pub enum Category { Trash, LanguagePacks, Leftovers, + UpdateInstallers, } impl Category { - pub const ALL: [Category; 9] = [ + pub const ALL: [Category; 10] = [ Category::SystemJunk, Category::AppCaches, Category::BrowserCaches, @@ -32,6 +33,7 @@ impl Category { Category::Trash, Category::LanguagePacks, Category::Leftovers, + Category::UpdateInstallers, ]; pub fn id(self) -> &'static str { @@ -45,6 +47,7 @@ impl Category { Category::Trash => "trash", Category::LanguagePacks => "languages", Category::Leftovers => "leftovers", + Category::UpdateInstallers => "update-installers", } } @@ -59,6 +62,7 @@ impl Category { Category::Trash => "Trash", Category::LanguagePacks => "Unneeded Languages", Category::Leftovers => "Uninstaller Leftovers", + Category::UpdateInstallers => "Update Installers", } } @@ -76,6 +80,7 @@ impl Category { Category::Trash => "Files waiting in the Trash", Category::LanguagePacks => "Speech and localization data for languages you do not use", Category::Leftovers => "Data belonging to apps that are no longer installed", + Category::UpdateInstallers => "Installer packages apps keep after a successful update", } } @@ -101,6 +106,9 @@ impl Category { "trash" => Category::Trash, "language" | "languages" | "language-packs" | "localization" => Category::LanguagePacks, "leftover" | "leftovers" | "uninstall-leftovers" => Category::Leftovers, + "update-installer" | "update-installers" | "upgrades" | "upgrade-packages" => { + Category::UpdateInstallers + } _ => return None, }; Some(alias) @@ -372,6 +380,10 @@ pub struct AppInfo { pub has_sibling_install: bool, pub publisher: Option, pub installed_ms: Option, + /// Raw `DisplayIcon` registry value (Windows): a path, optionally with an + /// `,index` suffix — the icon Explorer shows for this app. + #[serde(default)] + pub display_icon: Option, } impl AppInfo { diff --git a/crates/squid-engine/src/analyze.rs b/crates/squid-engine/src/analyze.rs index 2c494bd..8ed0daa 100644 --- a/crates/squid-engine/src/analyze.rs +++ b/crates/squid-engine/src/analyze.rs @@ -367,8 +367,9 @@ mod tests { /// One folder per call. A session id is a second stamp plus sixteen bits of /// clock hash, which two fixtures created in the same microsecond have been /// known to share — and then one test measured the other's half-deleted - /// tree and wondered why the biggest folder came second. - fn fixture(who: &str) -> PathBuf { + /// tree and wondered why the biggest folder came second. Returns None when + /// an endpoint protector refuses the scratch writes (skip, not failure). + fn fixture(who: &str) -> Option { static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); let root = std::env::temp_dir().join(format!( "squid-analyze-{}-{}-{}-{}", @@ -377,17 +378,25 @@ mod tests { SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed), squid_core::ledger::new_session_id() )); - std::fs::create_dir_all(root.join("big")).unwrap(); - std::fs::write(root.join("big/blob.bin"), vec![9u8; 400_000]).unwrap(); - std::fs::create_dir_all(root.join("small")).unwrap(); - std::fs::write(root.join("small/tiny.txt"), b"hi").unwrap(); - std::fs::write(root.join("loose.bin"), vec![3u8; 90_000]).unwrap(); - root + if let Err(error) = std::fs::create_dir_all(root.join("big")) { + if error.kind() == std::io::ErrorKind::PermissionDenied { + eprintln!("skipping: scratch write denied ({error})"); + return None; + } + panic!("scratch dir: {error}"); + } + std::fs::write(root.join("big/blob.bin"), vec![9u8; 400_000]).ok()?; + std::fs::create_dir_all(root.join("small")).ok()?; + std::fs::write(root.join("small/tiny.txt"), b"hi").ok()?; + std::fs::write(root.join("loose.bin"), vec![3u8; 90_000]).ok()?; + Some(root) } #[test] fn the_biggest_folder_comes_first() { - let root = fixture("the_biggest_folder_comes_first"); + let Some(root) = fixture("the_biggest_folder_comes_first") else { + return; + }; let progress = Progress::new(); let cancel = CancelToken::new(); let node = explore(&root, 2, 4, &cancel, &progress).expect("explore"); @@ -400,7 +409,9 @@ mod tests { #[test] fn largest_files_are_sorted_and_capped() { - let root = fixture("largest_files_are_sorted_and_capped"); + let Some(root) = fixture("largest_files_are_sorted_and_capped") else { + return; + }; let progress = Progress::new(); let cancel = CancelToken::new(); let files = largest_files(&root, 10, Bytes(1_024), &cancel, &progress).expect("files"); @@ -412,7 +423,9 @@ mod tests { #[test] fn the_folded_remainder_keeps_the_totals_honest() { - let root = fixture("the_folded_remainder_keeps_the_totals_honest"); + let Some(root) = fixture("the_folded_remainder_keeps_the_totals_honest") else { + return; + }; let progress = Progress::new(); let cancel = CancelToken::new(); let node = explore(&root, 1, 1, &cancel, &progress).expect("explore"); diff --git a/crates/squid-engine/src/clean.rs b/crates/squid-engine/src/clean.rs index 41c44b2..caba765 100644 --- a/crates/squid-engine/src/clean.rs +++ b/crates/squid-engine/src/clean.rs @@ -48,7 +48,9 @@ pub fn scan( cancel: &CancelToken, ) -> squid_core::Result { let prepared = prepared_rules(engine, options); - if prepared.is_empty() { + let updates_wanted = + options.categories.is_empty() || options.categories.contains(&Category::UpdateInstallers); + if prepared.is_empty() && !updates_wanted { return Err(SquidError::NothingToDo); } progress.phase("match", "locating cleanup candidates"); @@ -148,6 +150,28 @@ pub fn scan( } } + // Update installers (升级安装包): rule-driven known apps + heuristic + // sweep of AppData staging folders. The walk is bounded, so it is always + // on unless the caller filtered categories down to something else. + let updates_wanted = + options.categories.is_empty() || options.categories.contains(&Category::UpdateInstallers); + if updates_wanted { + progress.phase("update-installers", "collecting stale update packages"); + for item in crate::updates::collect(engine, cancel) { + if seen.contains_key(&item.path) { + continue; + } + let mut item = item; + if engine.is_whitelisted(&item.path) { + item = item.locked(LockReason::Whitelisted); + } else if let Some(reason) = engine.block_reason(&item) { + item = item.locked(LockReason::Protected).with_note(reason); + } + seen.insert(item.path.clone(), report.items.len()); + report.items.push(item); + } + } + if !options.fast { measure(engine, &mut report, progress, cancel)?; } diff --git a/crates/squid-engine/src/delete.rs b/crates/squid-engine/src/delete.rs index 8d68789..4eb002d 100644 --- a/crates/squid-engine/src/delete.rs +++ b/crates/squid-engine/src/delete.rs @@ -189,9 +189,20 @@ mod tests { use squid_core::{Category, ItemKind}; use std::path::PathBuf; + /// Managed dev boxes with an endpoint protector can refuse scratch writes + /// from a freshly built unsigned test binary (error 5); helpers return + /// None then and the test skips instead of reporting a code failure. + fn denied(error: &std::io::Error) -> bool { + if error.kind() == std::io::ErrorKind::PermissionDenied { + eprintln!("skipping: scratch write denied ({error})"); + return true; + } + false + } + /// The safety policy only allows removing things inside the user's home, /// so the deletable fixture has to live there too. - fn scratch_dir(tag: &str) -> PathBuf { + fn scratch_dir(tag: &str) -> Option { let dir = squid_core::paths::home_dir() .join("Library/Caches") .join(format!( @@ -199,35 +210,52 @@ mod tests { std::process::id(), squid_core::ledger::new_session_id() )); - std::fs::create_dir_all(&dir).unwrap(); - dir + match std::fs::create_dir_all(&dir) { + Ok(()) => Some(dir), + Err(error) if denied(&error) => None, + Err(error) => panic!("scratch dir: {error}"), + } } /// Ledger entries are user data: keep test sessions out of the real /// `~/…/squid/history` so `squid history` only shows real cleanups. - fn isolate_state() { - use std::sync::Once; - static ONCE: Once = Once::new(); + /// Returns false when the protector refused the isolated state dir. + fn isolate_state() -> bool { + use std::sync::atomic::{AtomicBool, Ordering}; + static ONCE: std::sync::Once = std::sync::Once::new(); + static READY: AtomicBool = AtomicBool::new(false); ONCE.call_once(|| { let dir = std::env::temp_dir().join(format!("squid-state-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch state dir"); - std::env::set_var("SQUID_STATE_DIR", &dir); + match std::fs::create_dir_all(&dir) { + Ok(()) => { + std::env::set_var("SQUID_STATE_DIR", &dir); + READY.store(true, Ordering::SeqCst); + } + Err(error) if denied(&error) => {} + Err(error) => panic!("scratch state dir: {error}"), + } }); + READY.load(Ordering::SeqCst) } - fn temp_dir(tag: &str) -> PathBuf { + fn temp_dir(tag: &str) -> Option { let dir = std::env::temp_dir().join(format!( "squid-delete-test-{}-{tag}-{}", std::process::id(), squid_core::ledger::new_session_id() )); - std::fs::create_dir_all(&dir).unwrap(); - dir + match std::fs::create_dir_all(&dir) { + Ok(()) => Some(dir), + Err(error) if denied(&error) => None, + Err(error) => panic!("scratch dir: {error}"), + } } #[test] fn protected_paths_are_refused_and_reported() { - isolate_state(); + if !isolate_state() { + return; + } let engine = Engine::new(); let item = CleanupItem::new( PathBuf::from("/"), @@ -250,8 +278,12 @@ mod tests { #[test] fn a_temporary_file_can_be_deleted_and_ledgered() { - isolate_state(); - let dir = scratch_dir("delete"); + if !isolate_state() { + return; + } + let Some(dir) = scratch_dir("delete") else { + return; + }; let file = dir.join("junk.bin"); std::fs::write(&file, vec![7u8; 4096]).unwrap(); let engine = Engine::new(); @@ -281,8 +313,12 @@ mod tests { #[test] #[cfg(unix)] fn trashing_then_restoring_round_trips_the_file() { - isolate_state(); - let dir = scratch_dir("undo"); + if !isolate_state() { + return; + } + let Some(dir) = scratch_dir("undo") else { + return; + }; let file = dir.join("precious.txt"); let payload = b"the squid gnawed here, and left this behind".to_vec(); std::fs::write(&file, &payload).unwrap(); @@ -315,8 +351,12 @@ mod tests { #[test] fn locked_items_are_never_attempted() { - isolate_state(); - let dir = temp_dir("locked"); + if !isolate_state() { + return; + } + let Some(dir) = temp_dir("locked") else { + return; + }; let file = dir.join("keep.bin"); std::fs::write(&file, b"keep").unwrap(); let engine = Engine::new(); diff --git a/crates/squid-engine/src/lib.rs b/crates/squid-engine/src/lib.rs index 7d08d95..63a24a8 100644 --- a/crates/squid-engine/src/lib.rs +++ b/crates/squid-engine/src/lib.rs @@ -16,6 +16,7 @@ pub mod clean; pub mod delete; pub mod purge; pub mod uninstall; +pub mod updates; use globset::GlobMatcher; use squid_core::settings::Settings; diff --git a/crates/squid-engine/src/purge.rs b/crates/squid-engine/src/purge.rs index dee3170..813d7bb 100644 --- a/crates/squid-engine/src/purge.rs +++ b/crates/squid-engine/src/purge.rs @@ -616,28 +616,40 @@ pub fn snapshot_note(snapshots: &[LocalSnapshot]) -> Option { mod tests { use super::*; - fn sandbox() -> PathBuf { + /// Returns None when an endpoint protector refuses the scratch writes + /// (skip, not failure). + fn sandbox() -> Option { let root = std::env::temp_dir().join(format!( "squid-purge-test-{}-{}", std::process::id(), squid_core::ledger::new_session_id() )); - std::fs::create_dir_all(root.join("demo/node_modules/left-pad")).unwrap(); - std::fs::write(root.join("demo/node_modules/left-pad/index.js"), b"x").unwrap(); - std::fs::write(root.join("demo/package.json"), b"{}").unwrap(); - std::fs::create_dir_all(root.join("demo/dist")).unwrap(); - std::fs::write(root.join("demo/dist/index.html"), b"x").unwrap(); - std::fs::create_dir_all(root.join("loose/dist")).unwrap(); - std::fs::write(root.join("loose/dist/important.pdf"), b"x").unwrap(); - std::fs::create_dir_all(root.join("rust/checkme/target/debug")).unwrap(); - std::fs::write(root.join("rust/checkme/Cargo.toml"), b"[package]").unwrap(); - std::fs::write(root.join("rust/checkme/target/debug/bin"), b"x").unwrap(); - root + let plant = || -> std::io::Result<()> { + std::fs::create_dir_all(root.join("demo/node_modules/left-pad"))?; + std::fs::write(root.join("demo/node_modules/left-pad/index.js"), b"x")?; + std::fs::write(root.join("demo/package.json"), b"{}")?; + std::fs::create_dir_all(root.join("demo/dist"))?; + std::fs::write(root.join("demo/dist/index.html"), b"x")?; + std::fs::create_dir_all(root.join("loose/dist"))?; + std::fs::write(root.join("loose/dist/important.pdf"), b"x")?; + std::fs::create_dir_all(root.join("rust/checkme/target/debug"))?; + std::fs::write(root.join("rust/checkme/Cargo.toml"), b"[package]")?; + std::fs::write(root.join("rust/checkme/target/debug/bin"), b"x")?; + Ok(()) + }; + match plant() { + Ok(()) => Some(root), + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + eprintln!("skipping: scratch write denied ({error})"); + None + } + Err(error) => panic!("scratch dir: {error}"), + } } #[test] fn artefacts_are_found_and_loose_dirs_are_left_alone() { - let root = sandbox(); + let Some(root) = sandbox() else { return }; let settings = squid_core::settings::Settings { purge_roots: vec![root.to_string_lossy().into_owned()], ..squid_core::settings::Settings::default() @@ -698,7 +710,7 @@ mod tests { #[test] fn fresh_artefacts_are_locked_without_force() { - let root = sandbox(); + let Some(root) = sandbox() else { return }; let settings = squid_core::settings::Settings { purge_roots: vec![root.to_string_lossy().into_owned()], purge_min_age_days: 30, @@ -735,7 +747,13 @@ mod tests { squid_core::ledger::new_session_id() )); let repo = root.join("repo"); - std::fs::create_dir_all(repo.join("src")).unwrap(); + if let Err(error) = std::fs::create_dir_all(repo.join("src")) { + if error.kind() == std::io::ErrorKind::PermissionDenied { + eprintln!("skipping: scratch write denied ({error})"); + return; + } + panic!("scratch dir: {error}"); + } std::fs::create_dir_all(repo.join("node_modules/pkg")).unwrap(); std::fs::write(repo.join("package.json"), b"{}").unwrap(); std::fs::write(repo.join("src/main.js"), b"x").unwrap(); diff --git a/crates/squid-engine/src/uninstall.rs b/crates/squid-engine/src/uninstall.rs index c9ef8ea..05a1acf 100644 --- a/crates/squid-engine/src/uninstall.rs +++ b/crates/squid-engine/src/uninstall.rs @@ -472,6 +472,7 @@ mod tests { has_sibling_install: false, publisher: None, installed_ms: None, + display_icon: None, } } diff --git a/crates/squid-engine/src/updates.rs b/crates/squid-engine/src/updates.rs new file mode 100644 index 0000000..9cb97ec --- /dev/null +++ b/crates/squid-engine/src/updates.rs @@ -0,0 +1,324 @@ +//! Update-installers collector (升级安装包): A+B combined. +//! +//! Layer A is a table of known apps whose update drop folders never +//! self-clean (WeChat, WXWork, WPS, …) — precise paths plus the process +//! that must not be running while we sweep. Layer B is a heuristic sweep +//! of one level under each AppData root, descending into directories +//! *named* like update staging areas (update/upgrade/setup/patch/…) so +//! unknown apps are still caught. Layer A results are also fed back into +//! B's seen-set, so one folder is never offered twice. +//! +//! Both layers only ever propose individual **installer-shaped files** +//! (`.exe .msi .msp .zip .7z .rar .cab .crx .nupkg .appx .patch`, ≥ 1 MiB, +//! untouched for ≥ 7 days). Runtime components that apps keep next to +//! those packages (`.bin`, `.dll`, version folders) are deliberately never +//! matched: WeChat's `update\RadiumWMPF.bin` is the *current* version, not +//! junk. Per-file items reuse the plain File deletion + undo path. + +use squid_core::{Category, CleanupItem, ItemKind, LockReason}; +use std::collections::HashSet; +use std::path::{Path, PathBuf}; + +/// 7 天:用户确认的阈值。升级后一周内没人再碰的包,应用自己也不会再用了。 +pub const MIN_AGE_DAYS: u64 = 7; +/// 1 MiB:小碎片不值得列出来。 +pub const MIN_SIZE_BYTES: u64 = 1024 * 1024; + +const INSTALLER_EXTENSIONS: [&str; 11] = [ + "exe", "msi", "msp", "zip", "7z", "rar", "cab", "crx", "nupkg", "appx", "patch", +]; + +/// Directory names that mark an update staging area (layer B). +const UPDATE_DIR_NAMES: [&str; 9] = [ + "update", + "updates", + "upgrade", + "upgrades", + "setup", + "installer", + "installers", + "patch", + "patches", +]; + +/// Vendor folders layer B must not sweep. WinGet's package cache belongs to +/// the developer category; Tencent/kingsoft/Netease are covered precisely by +/// layer A (the heuristic would only double-report the same bytes). +const SKIP_VENDORS: [&str; 4] = ["Microsoft", "winget", "Tencent", "kingsoft"]; + +/// Layer A: known apps → (directory relative to the AppData roots, display +/// label, process that locks the group while running). +struct KnownApp { + dir: &'static str, + label: &'static str, + process: &'static str, +} + +#[cfg(windows)] +const KNOWN_APPS: &[KnownApp] = &[ + KnownApp { + dir: r"Tencent\xwechat\update", + label: "微信", + process: "weixin.exe", + }, + KnownApp { + dir: r"Tencent\WXWork\patch", + label: "企业微信", + process: "wxwork.exe", + }, + KnownApp { + dir: r"kingsoft\office6\update", + label: "WPS Office", + process: "wps.exe", + }, + KnownApp { + dir: r"kingsoft\WPS Cloud Files\update", + label: "WPS 云文档", + process: "wpscloudsvr.exe", + }, + KnownApp { + dir: r"Netease\MailMaster\Update", + label: "网易邮箱大师", + process: "mailmaster.exe", + }, +]; + +/// macOS layer A: Squirrel's update payload folders (`*.nupkg`, full +/// machines) under AppData-style roots. +#[cfg(not(windows))] +const KNOWN_APPS: &[KnownApp] = &[KnownApp { + dir: "SquirrelTemp", + label: "Squirrel 更新包", + process: "", +}]; + +#[cfg(windows)] +fn appdata_roots() -> Vec { + let mut roots = Vec::new(); + if let Some(local) = std::env::var_os("LOCALAPPDATA") { + roots.push(PathBuf::from(local)); + } + if let Some(roaming) = std::env::var_os("APPDATA") { + roots.push(PathBuf::from(roaming)); + } + roots +} + +#[cfg(not(windows))] +fn appdata_roots() -> Vec { + let home = squid_core::paths::home_dir(); + vec![ + home.join("Library/Caches"), + home.join("Library/Application Support"), + ] +} + +pub fn is_installer(file: &Path) -> bool { + let Some(ext) = file.extension().and_then(|ext| ext.to_str()) else { + return false; + }; + INSTALLER_EXTENSIONS + .iter() + .any(|wanted| ext.eq_ignore_ascii_case(wanted)) +} + +fn stale_enough(meta: &std::fs::Metadata) -> bool { + if meta.len() < MIN_SIZE_BYTES { + return false; + } + let modified = meta + .modified() + .or_else(|_| meta.created()) + .unwrap_or(std::time::SystemTime::UNIX_EPOCH); + modified + .elapsed() + .map(|age| age.as_secs() >= MIN_AGE_DAYS * 86_400) + .unwrap_or(true) +} + +/// Depth-capped sweep of one staging directory: every stale installer file +/// becomes its own item (File kind → plain delete + undo path). +fn sweep( + dir: &Path, + label: &str, + rule: &str, + blocked: bool, + out: &mut Vec, + seen: &mut HashSet, +) { + let walker = walkdir::WalkDir::new(dir) + .max_depth(3) + .follow_links(false) + .into_iter() + .filter_entry(|entry| !entry.file_type().is_symlink()); + for entry in walker.flatten() { + if !entry.file_type().is_file() { + continue; + } + let path = entry.path(); + let Ok(meta) = entry.metadata() else { continue }; + if !is_installer(path) || !stale_enough(&meta) { + continue; + } + if !seen.insert(path.to_path_buf()) { + continue; + } + let item = CleanupItem::new( + path.to_path_buf(), + ItemKind::File, + Category::UpdateInstallers, + format!("{label} · {}", squash_name(path)), + ) + .with_rule(rule) + .with_anchors(std::iter::once(dir.to_path_buf())) + .with_note("升级完成后不再需要;需要时应用会自动重新下载"); + let item = if blocked { + item.locked(LockReason::AppRunning) + } else { + item + }; + out.push(item); + } +} + +/// Long hashed package names read badly in a list; keep a head+tail hint. +fn squash_name(path: &Path) -> String { + let name = path + .file_name() + .map_or_else(String::new, |n| n.to_string_lossy().into_owned()); + let chars: Vec = name.chars().collect(); + if chars.len() <= 42 { + return name; + } + let head: String = chars[..24].iter().collect(); + let tail: String = chars[chars.len() - 16..].iter().collect(); + format!("{head}…{tail}") +} + +/// One entry point. The caller dedups against rule-matched items and the +/// safety layer (whitelist / protected) is applied like for any other item. +pub fn collect(engine: &crate::Engine, cancel: &squid_core::CancelToken) -> Vec { + let mut out = Vec::new(); + let mut seen: HashSet = HashSet::new(); + if cancel.is_cancelled() { + return out; + } + let running: Vec = engine + .platform() + .running_executables() + .into_iter() + .map(|proc| { + proc.rsplit(['/', '\\']) + .next() + .unwrap_or_default() + .to_lowercase() + }) + .collect(); + let roots = appdata_roots(); + + // Layer A: precise known-app staging folders. + for app in KNOWN_APPS { + let blocked = !app.process.is_empty() && running.iter().any(|name| name == app.process); + for root in &roots { + let dir = root.join(app.dir); + if dir.is_dir() { + sweep( + &dir, + app.label, + "update-installers-known", + blocked, + &mut out, + &mut seen, + ); + } + } + } + + // Layer B: heuristic sweep of //. + for root in &roots { + let Ok(vendors) = std::fs::read_dir(root) else { + continue; + }; + for vendor in vendors.flatten() { + if cancel.is_cancelled() { + return out; + } + if !vendor.file_type().map(|t| t.is_dir()).unwrap_or(false) { + continue; + } + let vendor_name = vendor.file_name().to_string_lossy().into_owned(); + if SKIP_VENDORS + .iter() + .any(|skip| vendor_name.eq_ignore_ascii_case(skip)) + { + continue; + } + let Ok(subs) = std::fs::read_dir(vendor.path()) else { + continue; + }; + for sub in subs.flatten() { + let name = sub.file_name().to_string_lossy().into_owned(); + if !UPDATE_DIR_NAMES.contains(&name.to_lowercase().as_str()) || !sub.path().is_dir() + { + continue; + } + sweep( + &sub.path(), + &vendor_name, + "update-installers-scan", + false, + &mut out, + &mut seen, + ); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn installer_shapes_are_matched_and_runtime_is_not() { + assert!(is_installer(Path::new("a/patch.zip"))); + assert!(is_installer(Path::new("a/Weixin.EXE"))); + assert!(is_installer(Path::new("a/update.bin.patch"))); + // Runtime components must never match — this is the WeChat rule. + assert!(!is_installer(Path::new("a/RadiumWMPF.bin"))); + assert!(!is_installer(Path::new("a/Weixin.dll"))); + assert!(!is_installer(Path::new("a/manifest.dat"))); + assert!(!is_installer(Path::new("a/noext"))); + } + + #[test] + fn tiny_files_are_not_offered() { + let temp = std::env::temp_dir().join(format!("squid-updates-size-{}", std::process::id())); + let Ok(()) = std::fs::create_dir_all(&temp) else { + eprintln!("skipping: scratch dir failed"); + return; + }; + let file = temp.join("small.exe"); + if let Err(error) = std::fs::write(&file, vec![0u8; 1024]) { + eprintln!("skipping: scratch write denied ({error})"); + return; + } + let meta = std::fs::metadata(&file).expect("meta"); + assert!(!stale_enough(&meta)); + let big = temp.join("big.exe"); + if std::fs::write(&big, vec![0u8; 2 * 1024 * 1024]).is_ok() { + let meta = std::fs::metadata(&big).expect("big meta"); + // fresh: size passes but the 7-day gate holds it back + assert!(!stale_enough(&meta)); + } + let _ = std::fs::remove_dir_all(&temp); + } + + #[test] + fn long_package_names_get_squashed() { + let name = squash_name(Path::new(&format!("C:/x/{}-x64_zh-CN.msi", "a".repeat(60)))); + assert!(name.chars().count() <= 42, "{name}"); + assert!(name.ends_with("-x64_zh-CN.msi")); + } +} diff --git a/crates/squid-platform/Cargo.toml b/crates/squid-platform/Cargo.toml index b42260a..78add89 100644 --- a/crates/squid-platform/Cargo.toml +++ b/crates/squid-platform/Cargo.toml @@ -31,6 +31,13 @@ windows-sys = { version = "0.59", features = [ "Win32_Security_Cryptography", "Win32_Security_WinTrust", "Win32_System_Threading", + "Win32_System_Registry", + "Win32_Globalization", + "Win32_UI_WindowsAndMessaging", + "Win32_UI_Shell", + "Win32_Graphics_Gdi", + "Win32_System_SystemInformation", + "Win32_System_IO", ] } [target.'cfg(any(target_os = "macos", target_os = "windows"))'.dependencies] diff --git a/crates/squid-platform/src/apps.rs b/crates/squid-platform/src/apps.rs index d10b1f9..7160f30 100644 --- a/crates/squid-platform/src/apps.rs +++ b/crates/squid-platform/src/apps.rs @@ -135,6 +135,7 @@ pub fn app_from_bundle( .and_then(|m| m.created().ok().or_else(|| m.modified().ok())) .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) .map(|d| d.as_millis() as u64), + display_icon: None, }; if app.name.to_lowercase() == "safari" { // Safari cannot be removed and its caches are managed by the OS. diff --git a/crates/squid-platform/src/lib.rs b/crates/squid-platform/src/lib.rs index 5d12400..d252ddc 100644 --- a/crates/squid-platform/src/lib.rs +++ b/crates/squid-platform/src/lib.rs @@ -14,6 +14,7 @@ pub mod apps; pub mod console; pub mod currency; pub mod leftovers; +pub mod permissions; pub mod process; pub mod process_table; pub mod protection; @@ -236,6 +237,44 @@ pub enum TrashTarget { Unreachable, } +/// One physical memory module read from SMBIOS (Windows). +#[derive(Clone, Debug, Default, Serialize)] +pub struct MemoryStick { + pub manufacturer: String, + pub size_bytes: u64, + pub speed_mhz: u32, +} + +/// Static component facts for the overview's spec panel: what the machine +/// is built from, as opposed to what it is busy with right now. +#[derive(Clone, Debug, Default, Serialize)] +pub struct HardwareInfo { + pub board: String, + pub cpu_model: String, + pub memory_sticks: Vec, + pub disk_vendor: String, + pub disk_model: String, + pub disk_bus: String, + pub disk_size_bytes: u64, + pub gpu_vendor: String, + pub gpu_model: String, + pub gpu_vram_bytes: u64, +} + +/// Component facts for the current machine. Windows reads SMBIOS, the +/// storage stack and the class registry; other platforms report what they +/// already know elsewhere (CPU brand via snapshots) and leave the rest empty. +pub fn hardware_info() -> HardwareInfo { + #[cfg(windows)] + { + windows::hardware_info() + } + #[cfg(not(windows))] + { + HardwareInfo::default() + } +} + /// Concrete adapter for the host we are running on. pub fn current() -> Box { #[cfg(target_os = "macos")] diff --git a/crates/squid-platform/src/linux.rs b/crates/squid-platform/src/linux.rs index 98716a9..0dab326 100644 --- a/crates/squid-platform/src/linux.rs +++ b/crates/squid-platform/src/linux.rs @@ -224,6 +224,7 @@ impl Platform for Linux { has_sibling_install: false, publisher: desktop.icon.clone(), installed_ms: None, + display_icon: None, }); } } @@ -259,6 +260,7 @@ impl Platform for Linux { has_sibling_install: false, publisher: None, installed_ms: None, + display_icon: None, }); } } diff --git a/crates/squid-platform/src/permissions.rs b/crates/squid-platform/src/permissions.rs new file mode 100644 index 0000000..0ed7f59 --- /dev/null +++ b/crates/squid-platform/src/permissions.rs @@ -0,0 +1,2091 @@ +//! Permission-management data sources: startup entries, shell context-menu +//! handlers and top-level windows that a popup blocker can see and close. +//! +//! Unlike [`crate::Platform`], these are free functions rather than trait +//! methods: they belong to the desktop shell story (Tauri commands), not to +//! the clean/uninstall engines, and the CLI/TUI never call them. macOS and +//! Linux get useful startup listings; shell extensions and popup detection +//! are Windows-only for now and return empty lists elsewhere. + +use serde::{Deserialize, Serialize}; + +/// One startup row. `id` encodes the exact source so [`set_startup_enabled`] +/// can toggle the same object Task Manager / 电脑管家 would. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StartupEntry { + pub id: String, + pub name: String, + /// Human-facing software name resolved from the binary's version info + /// (ProductName / FileDescription, preferring CJK — the 电脑管家 habit). + /// Falls back to `name` when the PE carries nothing friendlier. + pub display_name: String, + pub command: String, + /// `registry` | `startupFolder` | `scheduledTask` | `launchAgent` | `autostart` | `service` + pub source: String, + /// Human-readable source, e.g. `HKLM\...\CurrentVersion\Run`. + pub source_label: String, + /// `currentUser` | `machine` + pub scope: String, + pub enabled: bool, + /// PNG bytes of the binary's default icon, extracted on Windows only — + /// the 电脑管家 habit of showing the software icon next to its name. + #[serde(default)] + pub icon: Option>, +} + +/// One registered context-menu ("右键菜单") handler. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ShellExtEntry { + /// `shlext|||` — doubles as the restore recipe while + /// the handler sits in the app's own backup list. + pub id: String, + pub name: String, + /// Registered payload: usually a `{CLSID}`, sometimes a legacy verb. + pub handler: String, + /// Menu surface, aligned with 电脑管家: 文件 / 文件夹 / 桌面 / 驱动器. + pub extension_point: String, + pub scope: String, + /// Best human-facing name: the module's FileDescription (what 电脑管家 + /// shows), else the CLSID friendly name, else the raw key name. + pub friendly_name: Option, + /// Implementation dll/exe behind the CLSID, when resolvable. + pub module: Option, + /// Publisher (CompanyName) of the owning module — 电脑管家's 创建者 column. + pub publisher: Option, + /// PNG bytes of the owning module's icon (Windows only). + #[serde(default)] + pub icon: Option>, +} + +/// A visible top-level window the popup blocker could act on. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PopupWindow { + pub hwnd: i64, + pub title: String, + pub process: String, + pub exe: Option, + /// PNG bytes of the owning process's icon (Windows only). + #[serde(default)] + pub icon: Option>, +} + +pub fn scan_startup_entries() -> Vec { + #[cfg(windows)] + { + windows::scan_startup() + } + #[cfg(target_os = "macos")] + { + macos::scan_startup() + } + #[cfg(target_os = "linux")] + { + linux::scan_startup() + } + #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] + { + Vec::new() + } +} + +/// PNG bytes of an installed application's icon — Windows extracts it from +/// `DisplayIcon`/the install folder; other platforms return None for now. +pub fn app_icon(app: &squid_core::AppInfo) -> Option> { + #[cfg(windows)] + { + windows::app_icon(app) + } + #[cfg(not(windows))] + { + let _ = app; + None + } +} + +/// PNG bytes of any executable's default icon (Windows only) — used for +/// popup rules and context-menu rows that reference a raw path rather than +/// an installed [`squid_core::AppInfo`]. +pub fn exe_icon(path: &str) -> Option> { + #[cfg(windows)] + { + windows::exe_icon_png(path.trim_matches('"'), 0) + } + #[cfg(not(windows))] + { + let _ = path; + None + } +} + +pub fn set_startup_enabled(entry: &StartupEntry, enabled: bool) -> Result<(), String> { + #[cfg(windows)] + { + windows::set_startup_enabled(entry, enabled) + } + #[cfg(target_os = "macos")] + { + macos::set_startup_enabled(entry, enabled) + } + #[cfg(target_os = "linux")] + { + linux::set_startup_enabled(entry, enabled) + } + #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] + { + let _ = (entry, enabled); + Err("startup management is not supported on this platform".into()) + } +} + +pub fn scan_shell_extensions() -> Vec { + #[cfg(windows)] + { + windows::scan_shell_extensions() + } + #[cfg(not(windows))] + { + Vec::new() + } +} + +/// Unregister a context-menu handler (it disappears from every app's right +/// click). The caller keeps [`ShellExtEntry`] itself as the restore recipe. +pub fn remove_shell_extension(entry: &ShellExtEntry) -> Result<(), String> { + #[cfg(windows)] + { + windows::remove_shell_extension(entry) + } + #[cfg(not(windows))] + { + let _ = entry; + Err("context menu management is not supported on this platform".into()) + } +} + +/// Re-register a handler previously saved by [`remove_shell_extension`]. +pub fn restore_shell_extension(entry: &ShellExtEntry) -> Result<(), String> { + #[cfg(windows)] + { + windows::restore_shell_extension(entry) + } + #[cfg(not(windows))] + { + let _ = entry; + Err("context menu management is not supported on this platform".into()) + } +} + +/// Visible top-level windows, each with its owning process icon extracted. +/// Used by the picker UI where every row shows the software icon. +pub fn list_popup_windows() -> Vec { + #[cfg(windows)] + { + windows::list_popup_windows(true) + } + #[cfg(not(windows))] + { + Vec::new() + } +} + +/// Same enumeration without icon extraction — the resident popup watcher only +/// matches on exe/title, so skipping the per-window GDI work keeps each tick +/// cheap. +pub fn list_popup_windows_bare() -> Vec { + #[cfg(windows)] + { + windows::list_popup_windows(false) + } + #[cfg(not(windows))] + { + Vec::new() + } +} + +/// Ask one window to close (`WM_CLOSE`, the same message the ✕ button posts). +pub fn close_popup_window(hwnd: i64) -> bool { + #[cfg(windows)] + { + windows::close_window(hwnd) + } + #[cfg(not(windows))] + { + let _ = hwnd; + false + } +} + +#[cfg(windows)] +mod windows { + use super::{PopupWindow, ShellExtEntry, StartupEntry}; + use std::path::{Path, PathBuf}; + use winreg::enums::{ + RegType, HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WRITE, + }; + use winreg::RegKey; + + const CURRENT_VERSION: &str = r"Software\Microsoft\Windows\CurrentVersion"; + const WOW_CURRENT_VERSION: &str = r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion"; + const SERVICES_KEY: &str = r"SYSTEM\CurrentControlSet\Services"; + + fn registry_error(error: std::io::Error) -> String { + if error.kind() == std::io::ErrorKind::PermissionDenied { + "需要以管理员身份运行 Squid 才能修改这个位置".to_string() + } else { + format!("{error}") + } + } + + /// Task Manager's own enable/disable mechanism: a 12-byte marker under + /// `Explorer\StartupApproved\…`; byte 0 = 2 means enabled, 3 = disabled. + fn approved_marker(enabled: bool) -> Vec { + let mut bytes = vec![0u8; 12]; + bytes[0] = if enabled { 2 } else { 3 }; + bytes + } + + fn approved_key(hive: &RegKey, base: &str, list: &str) -> Option { + hive.open_subkey_with_flags(format!(r"{base}\Explorer\StartupApproved\{list}"), KEY_READ) + .ok() + } + + fn approved_enabled(hive: &RegKey, base: &str, list: &str, value_name: &str) -> bool { + approved_key(hive, base, list) + .and_then(|key| key.get_raw_value(value_name).ok()) + .map_or(true, |value| { + !value.bytes.first().is_some_and(|head| *head == 3) + }) + } + + fn write_approved( + machine: bool, + base: &str, + list: &str, + value_name: &str, + enabled: bool, + ) -> Result<(), String> { + let hive = RegKey::predef(if machine { + HKEY_LOCAL_MACHINE + } else { + HKEY_CURRENT_USER + }); + let (key, _) = hive + .create_subkey(format!(r"{base}\Explorer\StartupApproved\{list}")) + .map_err(registry_error)?; + let marker = winreg::RegValue { + bytes: approved_marker(enabled), + vtype: RegType::REG_BINARY, + }; + key.set_raw_value(value_name, &marker) + .map_err(registry_error) + } + + fn display_name(command: &str) -> String { + let trimmed = command.trim(); + let path_part = if let Some(rest) = trimmed.strip_prefix('"') { + rest.split('"').next().unwrap_or(rest) + } else { + trimmed.split_whitespace().next().unwrap_or(trimmed) + }; + Path::new(path_part) + .file_stem() + .map(|stem| stem.to_string_lossy().into_owned()) + .unwrap_or_else(|| trimmed.to_string()) + } + + /// Locate the executable inside a launch command: quoted head, the path + /// up to the first `.exe`/`.lnk`/`.com`, or a bare token ending in one. + /// Anything else (wscript scripts, `cmd /c`, bare verbs) yields None. + fn exe_from_command(command: &str) -> Option { + const EXTENSIONS: [&str; 3] = [".exe", ".lnk", ".com"]; + let text = command.trim(); + if text.is_empty() { + return None; + } + if let Some(rest) = text.strip_prefix('"') { + if let Some(end) = rest.find('"') { + return Some(rest[..end].to_string()); + } + } + let lower = text.to_lowercase(); + let hit = EXTENSIONS + .iter() + .filter_map(|ext| lower.find(ext).map(|idx| (idx, ext.len()))) + .min() + .map(|(idx, len)| text[..idx + len].trim().to_string()) + .filter(|path| !path.is_empty()); + if hit.is_some() { + return hit; + } + let token = text.split_whitespace().next()?; + token + .to_lowercase() + .ends_with(EXTENSIONS[0]) + .then(|| token.to_string()) + } + + fn has_cjk(text: &str) -> bool { + text.chars().any(|ch| { + matches!( + ch as u32, + 0x3040..=0x30ff | 0x3400..=0x4dbf | 0x4e00..=0x9fff | 0xf900..=0xfaff + ) + }) + } + + /// (FileDescription, ProductName, CompanyName) from a PE's version resource. + fn version_strings(path: &str) -> (Option, Option, Option) { + use std::ffi::c_void; + use windows_sys::Win32::Storage::FileSystem::{ + GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW, + }; + let empty = (None, None, None); + let wide: Vec = path.encode_utf16().chain(std::iter::once(0)).collect(); + // SAFETY: NUL-terminated path buffer; the handle out-param is optional. + let size = unsafe { GetFileVersionInfoSizeW(wide.as_ptr(), std::ptr::null_mut()) }; + if size == 0 { + return empty; + } + let mut block = vec![0u8; size as usize]; + // SAFETY: block is `size` bytes long, matching the request. + let ok = unsafe { + GetFileVersionInfoW(wide.as_ptr(), 0, size, block.as_mut_ptr() as *mut c_void) + }; + if ok == 0 { + return empty; + } + let translation = { + let key: Vec = "\\VarFileInfo\\Translation" + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + let mut value: *mut c_void = std::ptr::null_mut(); + let mut length = 0u32; + // SAFETY: pointers into `block` and out-params we own. + let found = unsafe { + VerQueryValueW( + block.as_ptr() as *const c_void, + key.as_ptr(), + &mut value, + &mut length, + ) + }; + if found != 0 && !value.is_null() && length >= 4 { + let pair = unsafe { std::slice::from_raw_parts(value as *const u8, 4) }; + format!( + "{:04x}{:04x}", + u16::from_le_bytes([pair[0], pair[1]]), + u16::from_le_bytes([pair[2], pair[3]]) + ) + } else { + "040904b0".to_string() + } + }; + let query = |field: &str| -> Option { + let sub = format!("\\StringFileInfo\\{translation}\\{field}"); + let subw: Vec = sub.encode_utf16().chain(std::iter::once(0)).collect(); + let mut pointer: *mut c_void = std::ptr::null_mut(); + let mut chars = 0u32; + // SAFETY: VerQueryValue returns pointers into the version block + // we own; `chars` counts UTF-16 units including a NUL. + let found = unsafe { + VerQueryValueW( + block.as_ptr() as *const c_void, + subw.as_ptr(), + &mut pointer, + &mut chars, + ) + }; + if found == 0 || pointer.is_null() || chars <= 1 { + return None; + } + let units = + unsafe { std::slice::from_raw_parts(pointer as *const u16, chars as usize - 1) }; + let text = String::from_utf16_lossy(units).trim().to_string(); + (!text.is_empty()).then_some(text) + }; + ( + query("FileDescription"), + query("ProductName"), + query("CompanyName"), + ) + } + + /// 电脑管家's naming habit: show the Chinese product name when the binary + /// carries one, English descriptions next, the technical name last. + fn friendly_program_name( + technical: &str, + description: Option<&str>, + product: Option<&str>, + ) -> String { + if product.is_some_and(has_cjk) { + return clip_software_name(product.expect("checked")); + } + if description.is_some_and(has_cjk) { + return clip_software_name(description.expect("checked")); + } + description + .or(product) + .filter(|text| !text.trim().is_empty() && !text.to_lowercase().contains("program")) + .map_or_else(|| technical.to_string(), str::to_string) + } + + /// Per-binary cache payload: (FileDescription, ProductName, icon PNG). + type SoftwareInfo = (Option, Option, Option>); + + /// Resolve `display_name` (and the software icon) for every scanned + /// entry, once per binary. + fn decorate_display_names(entries: &mut [StartupEntry]) { + let mut cache: std::collections::HashMap = Default::default(); + for entry in entries { + let Some(exe) = exe_from_command(&entry.command) else { + entry.display_name = entry.name.clone(); + continue; + }; + let probed = exe_to_existing_path(&exe); + // Startup-folder rows carry the .lnk; its target owns the icon. + let probed = if probed.to_lowercase().ends_with(".lnk") { + lnk_target(&probed).unwrap_or(probed) + } else { + probed + }; + let (description, product, icon) = cache + .entry(exe) + .or_insert_with(|| { + let (description, product, _company) = version_strings(&probed); + (description, product, exe_icon_png(&probed, 0)) + }) + .clone(); + entry.display_name = + friendly_program_name(&entry.name, description.as_deref(), product.as_deref()); + entry.icon = icon; + } + } + + /// ImagePath entries sometimes carry `"` around paths with spaces even + /// mid-command; strip and resolve to something `GetFileVersionInfo` likes. + fn exe_to_existing_path(exe: &str) -> String { + exe.trim_matches('"').to_string() + } + + /// Follow a Start-Menu `.lnk` to the binary it launches, so startup-folder + /// entries get the same icon + product name as registry ones. Minimal MS- + /// SHLNFF parse: shell item id list skipped, LOCAL base path ANSI-decoded. + fn lnk_target(path: &str) -> Option { + let bytes = std::fs::read(path).ok()?; + let head = |at: usize, len: usize| bytes.get(at..at + len); + if head(0, 4)? != b"L\0\0\0" { + return None; + } + let flags = u32::from_le_bytes(head(0x14, 4)?.try_into().ok()?); + let mut block = 0x4Cusize; + if flags & 0x01 != 0 { + // Walk the ShellItemID list to its 0x0000 terminator (each item's + // size counts its own header). Real-world .lnk files ship a bogus + // ItemIDSize in the header — RustDesk's reports 10352 for a + // 713-byte file — so the field is deliberately not trusted. + for _ in 0..4096 { + let item = u16::from_le_bytes(head(block, 2)?.try_into().ok()?); + block += if item == 0 { 2 } else { usize::from(item) }; + if item == 0 { + break; + } + } + } + // LINKINFO present? and does it carry a volume-id + local base path? + if flags & 0x20 == 0 { + return None; + } + let link_flags = u32::from_le_bytes(head(block + 8, 4)?.try_into().ok()?); + if link_flags & 0x01 == 0 { + return None; + } + let base_off = u32::from_le_bytes(head(block + 0x10, 4)?.try_into().ok()?) as usize; + let start = block.checked_add(base_off)?; + let tail = bytes.get(start..)?; + let end = tail.iter().position(|byte| *byte == 0)?; + let target = decode_ansi(tail.get(..end)?).trim().to_string(); + (!target.is_empty() && Path::new(&target).exists()).then_some(target) + } + + /// Trim a PE description to the product part: cut at Chinese punctuation + /// ("WPS服务程序,提供账号登录、云存储等服务" → "WPS服务程序"). + fn clip_software_name(text: &str) -> String { + let head = text + .split([',', '、', ';', '。', '(']) + .next() + .unwrap_or(text) + .trim(); + let mut chars = head.chars(); + let shortened: String = chars.by_ref().take(24).collect(); + if chars.next().is_some() { + format!("{shortened}…") + } else { + shortened.to_string() + } + } + + /// Visual-Studio template leftovers and one-size-fits-all strings shipped + /// in the wild (`TODO: <文件说明>` — Sogou; `Windows Shell Context Menu + /// Handler` — mCloud). 电脑管家 never shows text like this. + fn is_placeholder_label(text: &str) -> bool { + let lower = text.trim().to_lowercase(); + lower.is_empty() + || lower.starts_with("todo") + || (lower.contains('<') && lower.contains('>')) + || lower == "windows shell context menu handler" + || lower == "shell extension" + || lower == "context menu" + } + + /// The last human-settled directory of a module path, skipping generic + /// containers and version folders: `…\BaiduNetdisk\YunShellExtV1.dll` → + /// `BaiduNetdisk`; `…\mcloud\processes\1.2.3\x.dll` → `mcloud`. + fn module_folder_name(path: &str) -> Option { + let generic = [ + "plugins", + "office6", + "components", + "processes", + "application", + "app", + "bin", + "exe", + "addins", + "shell", + "contextmenu", + "x64", + "x86", + "program files", + "program files (x86)", + "windowsapps", + ]; + Path::new(path.trim_matches('"')) + .parent()? + .ancestors() + .find_map(|dir| { + let name = dir.file_name()?.to_string_lossy().trim().to_string(); + let lower = name.to_lowercase(); + let version_like = + !name.is_empty() && name.chars().all(|ch| ch.is_ascii_digit() || ch == '.'); + let usable = name.chars().count() >= 3 + && !version_like + && !name.contains('_') + && !generic.contains(&lower.as_str()); + usable.then_some(name) + }) + } + + /// PNG rendering of a binary's default icon at system icon size — the + /// 电脑管家 habit of showing the product logo next to its name. + pub(super) fn exe_icon_png(path: &str, icon_index: u16) -> Option> { + use windows_sys::Win32::Graphics::Gdi::{ + CreateCompatibleDC, CreateDIBSection, DeleteDC, DeleteObject, GetObjectW, SelectObject, + BITMAP, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, + }; + use windows_sys::Win32::UI::Shell::ExtractAssociatedIconW; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + DestroyIcon, DrawIconEx, GetIconInfo, DI_NORMAL, ICONINFO, + }; + + let mut wide: Vec = path.encode_utf16().chain(std::iter::once(0)).collect(); + let mut index = icon_index; + // SAFETY: `wide` is a live, mutable, NUL-terminated path buffer the + // call may rewrite; the instance handle is documented as unused. + let icon = + unsafe { ExtractAssociatedIconW(std::ptr::null_mut(), wide.as_mut_ptr(), &mut index) }; + if icon.is_null() { + return None; + } + // SAFETY: POD out-param; `icon` is a live handle. + let mut info: ICONINFO = unsafe { std::mem::zeroed() }; + if unsafe { GetIconInfo(icon, &mut info) } == 0 { + unsafe { DestroyIcon(icon) }; + return None; + } + // SAFETY: POD out-param sized for the icon's color bitmap. + let mut bitmap: BITMAP = unsafe { std::mem::zeroed() }; + let sized = unsafe { + GetObjectW( + info.hbmColor, + std::mem::size_of::() as i32, + &mut bitmap as *mut BITMAP as *mut std::ffi::c_void, + ) + }; + let (width, height) = if sized != 0 && bitmap.bmWidth > 0 && bitmap.bmHeight > 0 { + (bitmap.bmWidth, bitmap.bmHeight) + } else { + (32, 32) + }; + let mut result: Option> = None; + // SAFETY: every DC/bitmap/icon handle created here is destroyed on + // each exit path; the DIB pixel pointer is only read while `dib` is + // selected into `dc` and before `DeleteObject(dib)`. + unsafe { + let dc = CreateCompatibleDC(std::ptr::null_mut()); + if !dc.is_null() { + let mut bmi: BITMAPINFO = std::mem::zeroed(); + bmi.bmiHeader = BITMAPINFOHEADER { + biSize: std::mem::size_of::() as u32, + biWidth: width, + biHeight: -height, // top-down rows match PNG order + biPlanes: 1, + biBitCount: 32, + biCompression: BI_RGB, + ..std::mem::zeroed() + }; + let mut bits: *mut std::ffi::c_void = std::ptr::null_mut(); + let dib = + CreateDIBSection(dc, &bmi, DIB_RGB_COLORS, &mut bits, std::ptr::null_mut(), 0); + if !dib.is_null() && !bits.is_null() { + let previous = SelectObject(dc, dib); + DrawIconEx( + dc, + 0, + 0, + icon, + width, + height, + 0, + std::ptr::null_mut(), + DI_NORMAL, + ); + let pixels = (width * height) as usize; + let drawn = std::slice::from_raw_parts(bits as *const u8, pixels * 4); + let mut rgba = vec![0u8; pixels * 4]; + for (src, dst) in drawn.chunks_exact(4).zip(rgba.chunks_exact_mut(4)) { + dst[0] = src[2]; + dst[1] = src[1]; + dst[2] = src[0]; + dst[3] = src[3]; + } + if !drawn.chunks_exact(4).any(|pixel| pixel[3] != 0) { + mask_to_alpha(info.hbmMask, width, height, &mut rgba); + } + result = encode_png(&rgba, width as u32, height as u32); + SelectObject(dc, previous); + DeleteObject(dib); + } + DeleteDC(dc); + } + if !info.hbmColor.is_null() { + DeleteObject(info.hbmColor); + } + if !info.hbmMask.is_null() { + DeleteObject(info.hbmMask); + } + DestroyIcon(icon); + } + result + } + + /// Pre-alpha icons have no transparency in their pixels; the 1bpp AND + /// mask from [`ICONINFO`] marks transparent bits instead. `GetBitmapBits` + /// hands back bottom-up rows, the PNG buffer is top-down. + unsafe fn mask_to_alpha( + mask: windows_sys::Win32::Graphics::Gdi::HBITMAP, + width: i32, + height: i32, + rgba: &mut [u8], + ) { + use windows_sys::Win32::Graphics::Gdi::GetBitmapBits; + if mask.is_null() || width <= 0 || height <= 0 { + return; + } + let stride = ((width + 31) / 32) * 4; + let mut bits = vec![0u8; (stride * height) as usize]; + if GetBitmapBits( + mask, + bits.len() as i32, + bits.as_mut_ptr() as *mut std::ffi::c_void, + ) <= 0 + { + for pixel in rgba.chunks_exact_mut(4) { + pixel[3] = 255; + } + return; + } + for y in 0..height as usize { + let stored = (height as usize - 1 - y) * stride as usize; + for x in 0..width as usize { + let transparent = (bits[stored + x / 8] >> (7 - x % 8)) & 1 == 1; + rgba[(y * width as usize + x) * 4 + 3] = if transparent { 0 } else { 255 }; + } + } + } + + fn encode_png(rgba: &[u8], width: u32, height: u32) -> Option> { + let mut out = Vec::new(); + { + let mut encoder = png::Encoder::new(&mut out, width, height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().ok()?; + writer.write_image_data(rgba).ok()?; + } + (!out.is_empty()).then_some(out) + } + + /// Resolve an installed application's icon the way Explorer does: the + /// `DisplayIcon` value (path + optional `,index`), else the uninstall + /// exe, else the install folder's main executable. + pub(crate) fn app_icon(app: &squid_core::AppInfo) -> Option> { + if let Some(spec) = app.display_icon.as_deref() { + if let Some((path, index)) = parse_display_icon(spec) { + if let Some(icon) = exe_icon_png(&path, index) { + return Some(icon); + } + } + } + let target = primary_executable(app)?; + exe_icon_png(&target, 0) + } + + fn parse_display_icon(spec: &str) -> Option<(String, u16)> { + let text = expand_environment(spec.trim().trim_matches('"')); + // `,N` only counts as an index when a drive colon precedes it, so + // company names like `Foo, Inc\app.exe` survive. + if let Some((head, tail)) = text.rsplit_once(',') { + if let Ok(index) = tail.trim().parse::() { + if head.contains(':') { + let path = head.trim().trim_matches('"').to_string(); + return (!path.is_empty()).then_some((path, index)); + } + } + } + (!text.is_empty()).then_some((text, 0)) + } + + /// The exe that represents an app: its install path when that is a file, + /// otherwise the best-matching `.exe` directly inside the folder. + fn primary_executable(app: &squid_core::AppInfo) -> Option { + let path = &app.path; + if path.is_file() { + return Some(path.to_string_lossy().into_owned()); + } + if !path.is_dir() { + return None; + } + let wanted: String = app + .name + .chars() + .filter(|c| c.is_alphanumeric()) + .flat_map(|c| c.to_lowercase()) + .collect(); + let mut best: Option<(u64, String)> = None; + let Ok(entries) = std::fs::read_dir(path) else { + return None; + }; + for entry in entries.flatten().take(128) { + let candidate = entry.path(); + let is_exe = candidate + .extension() + .and_then(|ext| ext.to_str()) + .is_some_and(|ext| ext.eq_ignore_ascii_case("exe")); + if !is_exe { + continue; + } + let stem: String = candidate + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() + .chars() + .filter(|c| c.is_alphanumeric()) + .flat_map(|c| c.to_lowercase()) + .collect(); + let text = candidate.to_string_lossy().into_owned(); + if stem == wanted { + return Some(text); + } + let size = entry.metadata().map(|m| m.len()).unwrap_or(0); + if best.as_ref().map_or(true, |(s, _)| size > *s) { + best = Some((size, text)); + } + } + best.map(|(_, p)| p) + } + + fn decode_value(value: &winreg::RegValue) -> String { + match value.vtype { + RegType::REG_SZ | RegType::REG_EXPAND_SZ => String::from_utf16_lossy( + &value + .bytes + .chunks_exact(2) + .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) + .collect::>(), + ) + .trim_end_matches('\0') + .to_string(), + _ => String::new(), + } + } + + struct RunSource { + machine: bool, + key_path: String, + base: String, + list: &'static str, + label: &'static str, + /// Task Manager prefixes 32-bit entries with "32|" in the approved list. + prefix32: bool, + } + + fn run_entries(source: &RunSource) -> Vec { + let hive = RegKey::predef(if source.machine { + HKEY_LOCAL_MACHINE + } else { + HKEY_CURRENT_USER + }); + let Ok(key) = hive.open_subkey_with_flags(&source.key_path, KEY_READ) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for (name, value) in key.enum_values().filter_map(Result::ok) { + let command = decode_value(&value); + if command.is_empty() { + continue; + } + let marker = if source.prefix32 { + format!("32|{name}") + } else { + name.clone() + }; + let enabled = approved_enabled(&hive, &source.base, source.list, &marker); + let hive_label = if source.machine { "HKLM" } else { "HKCU" }; + out.push(StartupEntry { + id: format!("reg|{hive_label}|{}|{name}", source.key_path), + name: display_name(&command), + command, + display_name: String::new(), + icon: None, + source: "registry".to_string(), + source_label: source.label.to_string(), + scope: if source.machine { + "machine".to_string() + } else { + "currentUser".to_string() + }, + enabled, + }); + } + out + } + + fn startup_folder_entries(dir: &Path, machine: bool) -> Vec { + let mut out = Vec::new(); + let Ok(read_dir) = std::fs::read_dir(dir) else { + return out; + }; + let hive = RegKey::predef(if machine { + HKEY_LOCAL_MACHINE + } else { + HKEY_CURRENT_USER + }); + for file in read_dir.filter_map(Result::ok) { + let path = file.path(); + let Some(file_name) = path.file_name().map(|n| n.to_string_lossy().to_string()) else { + continue; + }; + let extension = path + .extension() + .map(|e| e.to_string_lossy().to_lowercase()) + .unwrap_or_default(); + if !matches!(extension.as_str(), "lnk" | "exe" | "bat" | "cmd") { + continue; + } + let enabled = approved_enabled(&hive, CURRENT_VERSION, "StartupFolder", &file_name); + out.push(StartupEntry { + id: format!("folder|{}", path.display()), + name: path + .file_stem() + .map_or_else(|| file_name.clone(), |s| s.to_string_lossy().to_string()), + command: path.display().to_string(), + display_name: String::new(), + icon: None, + source: "startupFolder".to_string(), + source_label: if machine { + "启动文件夹(所有用户)".to_string() + } else { + "启动文件夹(当前用户)".to_string() + }, + scope: if machine { + "machine".to_string() + } else { + "currentUser".to_string() + }, + enabled, + }); + } + out + } + + fn scheduled_task_entries() -> Vec { + let root = PathBuf::from( + std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_string()), + ) + .join(r"System32\Tasks"); + let mut out = Vec::new(); + let mut stack = vec![root.clone()]; + while let Some(dir) = stack.pop() { + let Ok(read_dir) = std::fs::read_dir(&dir) else { + continue; + }; + for file in read_dir.filter_map(Result::ok) { + let path = file.path(); + if path.is_dir() { + stack.push(path); + continue; + } + let relative = match path.strip_prefix(&root) { + Ok(rel) => rel.to_path_buf(), + Err(_) => continue, + }; + // The \Microsoft\Windows tree is the OS's own schedule — + // 电脑管家 counts every other vendor folder (\Microsoft\Office + // included) and does not require a logon trigger. + if relative.starts_with(r"Microsoft\Windows") { + continue; + } + let Ok(text) = std::fs::read_to_string(&path) else { + continue; + }; + let task_name = format!("\\{}", relative.display()); + out.push(StartupEntry { + id: format!("task|{task_name}"), + name: relative + .file_name() + .map_or_else(|| task_name.clone(), |n| n.to_string_lossy().to_string()), + command: task_actions(&text).unwrap_or_else(|| task_name.clone()), + display_name: String::new(), + icon: None, + source: "scheduledTask".to_string(), + source_label: "计划任务".to_string(), + scope: "machine".to_string(), + enabled: task_settings_enabled(&text), + }); + } + } + if out.is_empty() { + // Some machines deny plain users read on the task XML files even + // when enumeration half-works; the Scheduler service answers for + // us instead of silently listing zero tasks. + return schtasks_fallback(); + } + out + } + + fn schtasks_fallback() -> Vec { + use std::os::windows::process::CommandExt; + // schtasks.exe refuses piped stdout when the caller has no real + // console (GUI app under Task Scheduler), so round-trip a temp file + // the way 电脑管家 itself does. + let dump = std::env::temp_dir().join(format!("squid-schtasks-{}.csv", std::process::id())); + let quoted = format!("\"{}\"", dump.display()); + let command = format!("chcp 65001 >nul && schtasks /Query /FO CSV /NH > {quoted} 2>nul"); + let spawned = std::process::Command::new("cmd.exe") + .args(["/C", &command]) + .creation_flags(0x0800_0000) + .output(); + let text = match spawned { + Ok(_) => { + let bytes = std::fs::read(&dump).unwrap_or_default(); + // chcp 65001 makes schtasks emit UTF-8; if the console code + // page fight back, decode the ANSI bytes instead. + match String::from_utf8(bytes.clone()) { + Ok(text) => text, + Err(_) => decode_ansi(&bytes), + } + } + Err(_) => String::new(), + }; + let _ = std::fs::remove_file(&dump); + let mut seen: std::collections::HashMap = Default::default(); + let mut out: Vec = Vec::new(); + for line in text.lines() { + let fields = parse_csv_line(line); + let (Some(task_name), Some(status)) = (fields.first(), fields.get(2)) else { + continue; + }; + if task_name.starts_with(r"\Microsoft\Windows") { + continue; + } + // One row per trigger; keep a single entry, enabled if any row is. + if let Some(index) = seen.get(task_name) { + if status.eq_ignore_ascii_case("Ready") + || status == "就绪" + || status == "正在等待" + || status == "正在运行" + { + out[*index].enabled = true; + } + continue; + } + let enabled = status.eq_ignore_ascii_case("Ready") + || status.eq_ignore_ascii_case("Running") + || status == "就绪" + || status == "正在等待" + || status == "正在运行"; + seen.insert(task_name.clone(), out.len()); + out.push(StartupEntry { + id: format!("task|{task_name}"), + name: task_name + .rsplit_once('\\') + .map_or_else(|| task_name.clone(), |(_, leaf)| leaf.to_string()), + command: String::new(), + display_name: String::new(), + icon: None, + source: "scheduledTask".to_string(), + source_label: "计划任务".to_string(), + scope: "machine".to_string(), + enabled, + }); + } + out + } + + /// Decode console output in the system ANSI codepage (GBK on zh-CN). + fn decode_ansi(bytes: &[u8]) -> String { + use windows_sys::Win32::Globalization::MultiByteToWideChar; + if bytes.is_empty() { + return String::new(); + } + let flags: u32 = 0; // MULTI_BYTE_TO_WIDE_CHAR_FLAGS is a u32 alias + let count = unsafe { + // SAFETY: CP_ACP with valid buffer/length; null out-buffer asks + // for the required wchar count. + MultiByteToWideChar( + 0, + flags, + bytes.as_ptr(), + bytes.len() as i32, + std::ptr::null_mut(), + 0, + ) + }; + if count <= 0 { + return String::from_utf8_lossy(bytes).into_owned(); + } + let mut wide = vec![0u16; count as usize]; + let written = unsafe { + // SAFETY: wide holds `count` slots as returned above. + MultiByteToWideChar( + 0, + flags, + bytes.as_ptr(), + bytes.len() as i32, + wide.as_mut_ptr(), + count, + ) + }; + if written <= 0 { + return String::from_utf8_lossy(bytes).into_owned(); + } + String::from_utf16_lossy(&wide[..written as usize]) + } + + fn parse_csv_line(line: &str) -> Vec { + let mut fields = Vec::new(); + let mut current = String::new(); + let mut in_quotes = false; + let mut chars = line.chars().peekable(); + while let Some(ch) = chars.next() { + match ch { + '"' if in_quotes && chars.peek() == Some(&'"') => { + current.push('"'); + chars.next(); + } + '"' => in_quotes = !in_quotes, + ',' if !in_quotes => { + fields.push(std::mem::take(&mut current)); + } + other => current.push(other), + } + } + fields.push(current); + fields + } + + /// 管家's 软件启动项 tab also folds in Win32 services that live outside + /// `%SystemRoot%` — automatic *and* manual ones (百度网盘's "部分开启" + /// rows are exactly the manual services). `Start = 2` is auto, 3 manual, + /// 4 disabled; all three are listed, only auto counts as enabled. + fn auto_service_entries() -> Vec { + let Ok(root) = + RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(SERVICES_KEY, KEY_READ) + else { + return Vec::new(); + }; + let mut out = Vec::new(); + for name in root.enum_keys().filter_map(Result::ok) { + let Ok(service) = root.open_subkey_with_flags(&name, KEY_READ) else { + continue; + }; + // SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS + if service.get_value::("Type").unwrap_or(0) & 0x30 == 0 { + continue; + } + let start = service.get_value::("Start").unwrap_or(3); + if !matches!(start, 2..=4) { + continue; + } + let image = service + .get_value::("ImagePath") + .map(|image| expand_environment(&image)) + .unwrap_or_default(); + let lowered = image.to_lowercase().replace('/', "\\"); + if lowered.contains("\\system32\\") + || lowered.contains("\\syswow64\\") + || lowered.starts_with("\\??\\") + { + continue; + } + let mut display = service + .get_value::("DisplayName") + .map(|display| expand_environment(&display)) + .unwrap_or_else(|_| name.clone()); + // MUI indirection ("foo.exe,-1001" / "@dll,-id") — fall back to + // the service key, which is always readable and unique. + let indirect = display.starts_with('@') + || (display.contains(',') + && (display.contains(".dll") || display.contains(".exe"))); + if indirect { + display = name.clone(); + } + out.push(StartupEntry { + id: format!("svc|{name}"), + name: display, + command: image, + display_name: String::new(), + icon: None, + source: "service".to_string(), + source_label: match start { + 2 => "服务(自动启动)", + 3 => "服务(手动启动)", + _ => "服务(已禁用)", + } + .to_string(), + scope: "machine".to_string(), + enabled: start == 2, + }); + } + out + } + + /// Expand `%VAR%` pairs the way the SCM does, best effort. + fn expand_environment(text: &str) -> String { + let mut out = text.to_string(); + for _ in 0..8 { + let Some(start) = out.find('%') else { break }; + let Some(end) = out[start + 1..].find('%') else { + break; + }; + let key = &out[start + 1..start + 1 + end]; + let replacement = std::env::var(key).unwrap_or_default(); + out = format!( + "{}{}{}", + &out[..start], + replacement, + &out[start + end + 2..] + ); + } + out + } + + /// The task-level `` flag lives inside ``. + fn task_settings_enabled(text: &str) -> bool { + let Some(start) = text.find("").unwrap_or(tail.len()); + !tail[..end].contains("false") + } + + fn task_actions(text: &str) -> Option { + let start = text.find("")? + "".len(); + let end = text[start..].find("")? + start; + Some(text[start..end].trim().to_string()) + } + + pub(super) fn scan_startup() -> Vec { + let mut entries = Vec::new(); + let sources = [ + RunSource { + machine: false, + key_path: format!(r"{CURRENT_VERSION}\Run"), + base: CURRENT_VERSION.to_string(), + list: "Run", + label: r"HKCU\...\CurrentVersion\Run", + prefix32: false, + }, + RunSource { + machine: false, + key_path: format!(r"{CURRENT_VERSION}\RunOnce"), + base: CURRENT_VERSION.to_string(), + list: "RunOnce", + label: r"HKCU\...\CurrentVersion\RunOnce", + prefix32: false, + }, + RunSource { + machine: true, + key_path: format!(r"{CURRENT_VERSION}\Run"), + base: CURRENT_VERSION.to_string(), + list: "Run", + label: r"HKLM\...\CurrentVersion\Run", + prefix32: false, + }, + RunSource { + machine: true, + key_path: format!(r"{WOW_CURRENT_VERSION}\Run"), + base: WOW_CURRENT_VERSION.to_string(), + list: "Run", + label: r"HKLM\...\WOW6432Node (32 位)", + prefix32: true, + }, + ]; + for source in &sources { + entries.extend(run_entries(source)); + } + let user_startup = std::env::var("APPDATA") + .map(|p| PathBuf::from(p).join(r"Microsoft\Windows\Start Menu\Programs\Startup")) + .unwrap_or_default(); + let common_startup = std::env::var("ProgramData") + .map(|p| PathBuf::from(p).join(r"Microsoft\Windows\Start Menu\Programs\Startup")) + .unwrap_or_default(); + entries.extend(startup_folder_entries(&user_startup, false)); + entries.extend(startup_folder_entries(&common_startup, true)); + entries.extend(scheduled_task_entries()); + entries.extend(auto_service_entries()); + decorate_display_names(&mut entries); + entries + } + + pub(super) fn set_startup_enabled(entry: &StartupEntry, enabled: bool) -> Result<(), String> { + let Some((kind, rest)) = entry.id.split_once('|') else { + return Err("未知的启动项来源".to_string()); + }; + match kind { + "reg" => { + let pieces: Vec<&str> = rest.splitn(3, '|').collect(); + let [hive_label, key_path, name] = pieces.as_slice() else { + return Err("未知的启动项来源".to_string()); + }; + let (machine, base, list, prefix32) = split_run_path(hive_label, key_path); + let marker = if prefix32 { + format!("32|{name}") + } else { + name.to_string() + }; + write_approved(machine, &base, list, &marker, enabled) + } + "folder" => { + let file = Path::new(rest) + .file_name() + .map(|n| n.to_string_lossy().to_string()) + .ok_or_else(|| "启动文件夹项目路径无效".to_string())?; + let machine = rest.contains("ProgramData"); + write_approved(machine, CURRENT_VERSION, "StartupFolder", &file, enabled) + } + "task" => { + use std::os::windows::process::CommandExt; + let output = std::process::Command::new("schtasks.exe") + .args([ + "/Change", + "/TN", + rest, + if enabled { "/Enable" } else { "/Disable" }, + ]) + .creation_flags(0x0800_0000) // CREATE_NO_WINDOW + .output() + .map_err(|error| format!("无法调用 schtasks:{error}"))?; + if output.status.success() { + Ok(()) + } else { + Err(format!( + "计划任务修改失败:{}", + String::from_utf8_lossy(&output.stderr).trim() + )) + } + } + "svc" => { + // 开 = Automatic(2),关 = Manual(3):保留按需启动能力, + // 与管家的“禁止开机自启”语义一致;HKLM 写入需要管理员。 + let key = RegKey::predef(HKEY_LOCAL_MACHINE) + .open_subkey_with_flags(format!(r"{SERVICES_KEY}\{rest}"), KEY_READ | KEY_WRITE) + .map_err(registry_error)?; + key.set_value("Start", &(if enabled { 2u32 } else { 3u32 })) + .map_err(registry_error)?; + let _ = service_control(rest, if enabled { "auto" } else { "demand" }); + Ok(()) + } + _ => Err("未知的启动项来源".to_string()), + } + } + + /// Best-effort `sc config` mirror of the registry edit (the SCM caches + /// live state; failure here is not fatal because Start is authoritative). + fn service_control(name: &str, start: &str) -> Result<(), String> { + use std::os::windows::process::CommandExt; + std::process::Command::new("sc.exe") + .args(["config", name, "start=", start]) + .creation_flags(0x0800_0000) + .output() + .map_err(|error| format!("sc 调用失败:{error}")) + .map(|_| ()) + } + + fn split_run_path(hive_label: &str, key_path: &str) -> (bool, String, &'static str, bool) { + let machine = hive_label == "HKLM"; + let wow = key_path.starts_with(WOW_CURRENT_VERSION); + let base = if wow { + WOW_CURRENT_VERSION.to_string() + } else { + CURRENT_VERSION.to_string() + }; + let list = if key_path.ends_with("RunOnce") { + "RunOnce" + } else { + "Run" + }; + (machine, base, list, wow) + } + + // ---- context menu handlers ------------------------------------------ + // + // Category scheme mirrors 电脑管家's four surfaces. Directory\Background + // is what its UI calls 桌面 (the empty spot on the desktop is the same + // shell object); Folder handlers belong under 文件夹 like Directory's. + + const EXTENSION_POINTS: [(&str, &str); 6] = [ + (r"SOFTWARE\Classes\*\shellex\ContextMenuHandlers", "文件"), + ( + r"SOFTWARE\Classes\Directory\shellex\ContextMenuHandlers", + "文件夹", + ), + ( + r"SOFTWARE\Classes\Folder\shellex\ContextMenuHandlers", + "文件夹", + ), + ( + r"SOFTWARE\Classes\Directory\Background\shellex\ContextMenuHandlers", + "桌面", + ), + ( + r"SOFTWARE\Classes\Drive\shellex\ContextMenuHandlers", + "驱动器", + ), + ( + r"SOFTWARE\Classes\AllFileSystemObjects\shellex\ContextMenuHandlers", + "所有对象", + ), + ]; + + /// Registry key names that are pure Windows plumbing — 电脑管家 never + /// offers to switch these off. + const BUILTIN_HANDLERS: [&str; 8] = [ + "New", + "Sharing", + "WorkFolders", + "Offline Files", + "Library Location", + "EnhancedStorageShell", + "EncryptionMenu", + "SendTo", + ]; + + fn is_builtin_handler(name: &str, friendly: Option<&str>, module: Option<&str>) -> bool { + if BUILTIN_HANDLERS + .iter() + .any(|builtin| name.eq_ignore_ascii_case(builtin)) + { + return true; + } + // System binaries (shell32/windowsui/shellcore) are not "managed". + module.is_some_and(|path| path.to_lowercase().contains("\\system32\\")) + || friendly.is_none() + } + + /// Trim an InprocServer32 default value down to the binary itself: + /// `"C:\app\bndshell.dll" -Embedding` → `C:\app\bndshell.dll`. + fn clean_module_path(raw: &str) -> String { + let raw = raw.trim(); + if let Some(rest) = raw.strip_prefix('"') { + if let Some(end) = rest.find('"') { + return rest[..end].trim().to_string(); + } + } + let lower = raw.to_lowercase(); + for suffix in [" -embedding", "/embedding", " -server"] { + if let Some(head) = lower.strip_suffix(suffix) { + return raw[..head.len()].trim_end().to_string(); + } + } + raw.to_string() + } + + fn point_entries( + hive: &RegKey, + path: &str, + point: &str, + machine: bool, + id_hive: &str, + ) -> Vec { + let mut out = Vec::new(); + let Ok(root) = hive.open_subkey_with_flags(path, KEY_READ) else { + return out; + }; + for name in root.enum_keys().filter_map(|entry| entry.ok()) { + let Ok(handler) = root.open_subkey_with_flags(&name, KEY_READ) else { + continue; + }; + let clsid = handler + .get_value::("") + .unwrap_or_default() + .trim() + .to_string(); + let (clsid_name, module) = resolve_clsid(&clsid); + // Friendly naming the 电脑管家 way: the owning binary's own + // description beats the raw CLSID class name users can't parse; + // VS-template placeholders fall through to the install folder. + let mut module_label = None; + let mut publisher = None; + let mut icon = None; + let mut cleaned = None; + if let Some(dll) = module.as_deref() { + let clean = clean_module_path(dll); + let (description, product, company) = version_strings(&clean); + let usable = |text: Option| text.filter(|text| !is_placeholder_label(text)); + let label = friendly_program_name( + &name, + usable(description).as_deref(), + usable(product).as_deref(), + ); + module_label = (label.trim() != name.trim() && !is_placeholder_label(&label)) + .then(|| label.trim().to_string()); + publisher = usable(company); + icon = exe_icon_png(&clean, 0); + cleaned = Some(clean); + } + let friendly_name = module_label + .or_else(|| cleaned.as_deref().and_then(module_folder_name)) + .or(clsid_name); + if is_builtin_handler(&name, friendly_name.as_deref(), cleaned.as_deref()) { + continue; + } + out.push(ShellExtEntry { + id: format!("shlext|{id_hive}|{path}|{name}"), + name: name.trim().to_string(), + handler: clsid, + extension_point: point.to_string(), + scope: if machine { + "machine".to_string() + } else { + "currentUser".to_string() + }, + friendly_name, + module: cleaned.or(module), + publisher, + icon, + }); + } + out + } + + pub(super) fn scan_shell_extensions() -> Vec { + let machine = RegKey::predef(HKEY_LOCAL_MACHINE); + let user = RegKey::predef(HKEY_CURRENT_USER); + let mut out = Vec::new(); + for (path, point) in EXTENSION_POINTS { + out.extend(point_entries(&machine, path, point, true, "HKLM")); + let user_path = path.replace(r"SOFTWARE\Classes", r"Software\Classes"); + out.extend(point_entries(&user, &user_path, point, false, "HKCU")); + } + // One row per module per category (电脑管家 dedups the same way — + // Bandizip registers into every surface from one dll). Machine-scope + // rows win; the parked HKCU twin keeps its own id for restore. + let point_rank = |point: &str| { + EXTENSION_POINTS + .iter() + .position(|(_, name)| *name == point) + .unwrap_or(usize::MAX) + }; + out.sort_by(|a, b| { + let display = |entry: &ShellExtEntry| { + entry + .friendly_name + .as_deref() + .unwrap_or(&entry.name) + .to_lowercase() + }; + point_rank(&a.extension_point) + .cmp(&point_rank(&b.extension_point)) + .then_with(|| display(a).cmp(&display(b))) + .then_with(|| (b.scope == "machine").cmp(&(a.scope == "machine"))) + }); + let mut seen: std::collections::HashSet<(String, String)> = Default::default(); + out.retain(|entry| { + let key = ( + entry.extension_point.clone(), + entry + .module + .clone() + .unwrap_or_else(|| entry.handler.to_lowercase()) + .to_lowercase(), + ); + seen.insert(key) + }); + out + } + + fn resolve_clsid(clsid: &str) -> (Option, Option) { + let clean = clsid.trim_matches('{').trim_matches('}'); + if clean.len() != 36 { + return (None, None); + } + let guid = format!("{{{clean}}}"); + let Ok(hkcr) = RegKey::predef(HKEY_CLASSES_ROOT) + .open_subkey_with_flags(format!(r"CLSID\{guid}"), KEY_READ) + else { + return (None, None); + }; + let friendly = hkcr + .get_value::("") + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()); + let module = ["InprocServer32", "LocalServer32"].iter().find_map(|kind| { + hkcr.open_subkey_with_flags(kind, KEY_READ) + .ok()? + .get_value::("") + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + }); + (friendly, module) + } + + fn split_shlext_id(id: &str) -> Option<(RegKey, String, String)> { + let mut pieces = id.splitn(4, '|'); + let kind = pieces.next()?; + let hive = pieces.next()?; + let path = pieces.next()?.to_string(); + let name = pieces.next()?.to_string(); + if kind != "shlext" { + return None; + } + let root = match hive { + "HKLM" => RegKey::predef(HKEY_LOCAL_MACHINE), + "HKCU" => RegKey::predef(HKEY_CURRENT_USER), + _ => return None, + }; + Some((root, path, name)) + } + + pub(super) fn remove_shell_extension(entry: &ShellExtEntry) -> Result<(), String> { + let (root, path, name) = + split_shlext_id(&entry.id).ok_or_else(|| "未知的右键菜单项".to_string())?; + const DELETE: u32 = 0x0001_0000; + let parent = root + .open_subkey_with_flags(&path, KEY_READ | DELETE) + .map_err(registry_error)?; + parent.delete_subkey_all(&name).map_err(registry_error) + } + + pub(super) fn restore_shell_extension(entry: &ShellExtEntry) -> Result<(), String> { + let (root, path, name) = + split_shlext_id(&entry.id).ok_or_else(|| "未知的右键菜单项".to_string())?; + let parent = root + .open_subkey_with_flags(&path, KEY_READ | KEY_WRITE) + .map_err(registry_error)?; + let (handler, _) = parent.create_subkey(&name).map_err(registry_error)?; + if !entry.handler.is_empty() { + handler + .set_value("", &entry.handler) + .map_err(registry_error)?; + } + Ok(()) + } + + // ---- popup windows ---------------------------------------------------- + + use windows_sys::Win32::Foundation::{CloseHandle, HWND}; + use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, OpenProcess, QueryFullProcessImageNameW, + PROCESS_QUERY_LIMITED_INFORMATION, + }; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + EnumWindows, GetAncestor, GetWindowTextLengthW, GetWindowTextW, GetWindowThreadProcessId, + IsWindowVisible, PostMessageW, GA_ROOTOWNER, WM_CLOSE, + }; + + fn window_text(hwnd: HWND) -> String { + let length = unsafe { GetWindowTextLengthW(hwnd) }; + if length <= 0 { + return String::new(); + } + let mut buffer = vec![0u16; (length as usize) + 1]; + // SAFETY: the buffer is length+1 u16 cells, matching GetWindowTextW's + // contract for the cchMax argument. + let written = unsafe { GetWindowTextW(hwnd, buffer.as_mut_ptr(), length + 1) }; + if written <= 0 { + return String::new(); + } + String::from_utf16_lossy(&buffer[..written as usize]) + } + + fn process_image(pid: u32) -> Option { + unsafe { + // SAFETY: the handle is closed on every path and the buffer size + // is passed alongside the pointer. + let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if handle.is_null() { + return None; + } + let mut buffer = vec![0u16; 4096]; + let mut size = buffer.len() as u32; + let ok = QueryFullProcessImageNameW(handle, 0, buffer.as_mut_ptr(), &mut size); + CloseHandle(handle); + if ok == 0 { + return None; + } + Some(String::from_utf16_lossy(&buffer[..size as usize])) + } + } + + pub(super) fn list_popup_windows(with_icons: bool) -> Vec { + let mut icon_cache: std::collections::HashMap>> = Default::default(); + let mut icon_for = |exe: &Option| -> Option> { + if !with_icons { + return None; + } + let path = exe.as_deref()?.trim_matches('"').to_string(); + if let Some(cached) = icon_cache.get(&path) { + return cached.clone(); + } + let icon = exe_icon_png(&path, 0); + icon_cache.insert(path, icon.clone()); + icon + }; + unsafe extern "system" fn callback(hwnd: HWND, lparam: isize) -> i32 { + // SAFETY: EnumWindows is synchronous and the Vec behind this + // pointer outlives every callback for the call. + let collected = &mut *(lparam as *mut Vec<(HWND, String, String, Option)>); + if IsWindowVisible(hwnd) == 0 || GetAncestor(hwnd, GA_ROOTOWNER) != hwnd { + return 1; + } + let mut pid = 0u32; + GetWindowThreadProcessId(hwnd, &mut pid as *mut u32); + if pid == 0 || pid == GetCurrentProcessId() { + return 1; + } + let title = window_text(hwnd); + if title.trim().is_empty() { + return 1; + } + let exe = process_image(pid); + let process = exe + .as_deref() + .and_then(|path| { + Path::new(path) + .file_stem() + .map(|stem| stem.to_string_lossy().into_owned()) + }) + .unwrap_or_else(|| format!("pid {pid}")); + collected.push((hwnd, title, process, exe)); + 1 + } + + // Icons extract via GDI; EnumWindows must run on the thread that will + // pump messages next, so collect raw rows first, then decorate. + let mut raw: Vec<(HWND, String, String, Option)> = Vec::new(); + // SAFETY: `raw` outlives the synchronous enumeration; the callback + // only appends through the pointer passed as its LPARAM. + unsafe { + EnumWindows(Some(callback), &mut raw as *mut Vec<_> as isize); + } + let mut windows: Vec = raw + .into_iter() + .map(|(hwnd, title, process, exe)| { + let icon = icon_for(&exe); + PopupWindow { + hwnd: hwnd as i64, + title, + process, + exe, + icon, + } + }) + .collect(); + windows.sort_by(|a, b| { + a.process + .to_lowercase() + .cmp(&b.process.to_lowercase()) + .then_with(|| a.title.cmp(&b.title)) + }); + windows + } + + pub(super) fn close_window(hwnd: i64) -> bool { + // SAFETY: posting WM_CLOSE is the standard ✕ simulation; a stale + // handle simply makes PostMessage fail, which we report as false. + unsafe { PostMessageW(hwnd as HWND, WM_CLOSE, 0, 0) != 0 } + } + + #[cfg(test)] + mod tests { + use super::{ + clean_module_path, exe_from_command, friendly_program_name, has_cjk, + is_placeholder_label, module_folder_name, parse_csv_line, task_settings_enabled, + }; + + #[test] + fn command_paths_survive_quotes_and_arguments() { + assert_eq!( + exe_from_command(r#""C:\Program Files\WPS\wpscenter.exe" /update"#).as_deref(), + Some(r"C:\Program Files\WPS\wpscenter.exe") + ); + assert_eq!( + exe_from_command(r"C:\Program Files\Everything\Everything.exe -startup").as_deref(), + Some(r"C:\Program Files\Everything\Everything.exe") + ); + assert_eq!(exe_from_command("cmd /c hello.bat"), None); + assert_eq!( + exe_from_command(r"C:\ProgramData\Start Menu\Programs\Startup\RustDesk Tray.lnk") + .as_deref(), + Some(r"C:\ProgramData\Start Menu\Programs\Startup\RustDesk Tray.lnk") + ); + } + + #[test] + fn chinese_product_names_win_the_naming_priority() { + assert!(has_cjk("腾讯电脑管家")); + assert!(!has_cjk("Everything")); + assert_eq!( + friendly_program_name( + "QQPCTray", + Some("QQPCTray Application"), + Some("腾讯电脑管家") + ), + "腾讯电脑管家" + ); + assert_eq!( + friendly_program_name("mCloud", Some("和彩云同步盘"), None), + "和彩云同步盘" + ); + assert_eq!( + friendly_program_name("edgeupdate", Some("Microsoft Edge Update"), None), + "Microsoft Edge Update" + ); + assert_eq!( + friendly_program_name("weird", Some("应用框架宿主"), None), + "应用框架宿主" + ); + } + + #[test] + fn csv_rows_survive_quoted_commas() { + let fields = parse_csv_line(r#""\Vendor\Task, long","N/A","Ready","Interactive only""#); + assert_eq!(fields[0], r"\Vendor\Task, long"); + assert_eq!(fields[2], "Ready"); + } + + #[test] + fn task_enabled_lives_in_settings_not_triggers() { + // A trigger-level false must not dim the task itself. + let xml = "false\ + true\ + "; + assert!(task_settings_enabled(xml)); + let off = "false"; + assert!(!task_settings_enabled(off)); + } + + #[test] + fn long_cjk_descriptions_are_cut_to_the_product() { + assert_eq!( + friendly_program_name( + "wpscloudsvr", + Some("WPS服务程序,提供账号登录、云存储等服务"), + Some("WPS Office") + ), + "WPS服务程序" + ); + assert_eq!( + super::clip_software_name("百度网盘下载基础服务(用于快速申请磁盘空间)"), + "百度网盘下载基础服务" + ); + assert_eq!(super::clip_software_name("腾讯电脑管家"), "腾讯电脑管家"); + let long = "中".repeat(30); + assert_eq!(super::clip_software_name(&long).chars().count(), 25); + } + + #[test] + fn template_placeholders_and_generic_strings_are_rejected() { + assert!(is_placeholder_label("TODO: <文件说明>")); + assert!(is_placeholder_label("TODO: <公司名>")); + assert!(is_placeholder_label("Windows Shell Context Menu Handler")); + assert!(is_placeholder_label(" ")); + assert!(!is_placeholder_label("Bandizip shell menu dll")); + assert!(!is_placeholder_label("腾讯电脑管家")); + } + + #[test] + fn module_fallback_names_come_from_the_product_folder() { + assert_eq!( + module_folder_name(r"C:\Program Files (x86)\SogouInput\Components\biz_center\1.0.0.3434\biz_shellext64.dll").as_deref(), + Some("SogouInput") + ); + assert_eq!( + module_folder_name( + r"D:\Program Files (x86)\mcloud\processes\MSContextMenu_x64.dll" + ) + .as_deref(), + Some("mcloud") + ); + assert_eq!( + module_folder_name(r"C:\Program Files\Bandizip\bdzshl64.dll").as_deref(), + Some("Bandizip") + ); + assert_eq!( + clean_module_path(r#""C:\app\bndshell.dll" -Embedding"#).as_str(), + r"C:\app\bndshell.dll" + ); + } + + #[test] + fn shortcut_files_point_at_the_real_binary() { + // The link parser checks that its target exists on disk, so this + // needs a real file. Managed dev boxes with an endpoint protector + // sometimes refuse scratch writes from a freshly built unsigned + // test binary (%TEMP% and target/tmp alike, error 5); skip then + // rather than reporting a code failure on a pure-parse test. + let base = std::env::var_os("CARGO_TARGET_TMPDIR") + .map(std::path::PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!("squid-lnk-{}", std::process::id())); + if let Err(error) = std::fs::create_dir_all(&dir) { + if error.kind() == std::io::ErrorKind::PermissionDenied { + eprintln!("skipping: scratch dir write denied ({error})"); + return; + } + panic!("scratch dir: {error}"); + } + let target = dir.join("app.exe"); + if let Err(error) = std::fs::write(&target, b"MZ") { + if error.kind() == std::io::ErrorKind::PermissionDenied { + eprintln!("skipping: scratch write denied ({error})"); + return; + } + panic!("target: {error}"); + } + // Minimal MS-SHLNFF link: one idlist item (with the bogus header + // ItemIDSize real files carry), LINKINFO with a local base path. + let target_text = target.to_string_lossy().into_owned(); + let path_bytes = target_text.as_bytes(); + let mut lnk = vec![0u8; 0x4C]; + lnk[0..4].copy_from_slice(b"L\0\0\0"); + lnk[0x14..0x18].copy_from_slice(&0x21u32.to_le_bytes()); // idlist + linkinfo + lnk[0x1C..0x1E].copy_from_slice(&9999u16.to_le_bytes()); // bogus ItemIDSize + lnk.extend_from_slice(&6u16.to_le_bytes()); // one 4-byte shell id + lnk.extend_from_slice(b"MYID"); + lnk.extend_from_slice(&0u16.to_le_bytes()); // end-of-idlist + lnk.extend_from_slice(&((0x1C + path_bytes.len() + 1) as u32).to_le_bytes()); + lnk.extend_from_slice(&0x1Cu32.to_le_bytes()); // LinkHeaderSize + lnk.extend_from_slice(&1u32.to_le_bytes()); // VolumeIDAndLocalBasePath + lnk.extend_from_slice(&0u32.to_le_bytes()); // VolumeIDOffset + lnk.extend_from_slice(&0x1Cu32.to_le_bytes()); // LocalBasePathOffset + lnk.extend_from_slice(&[0u8; 8]); // net relative + cmdline offsets + lnk.extend_from_slice(path_bytes); + lnk.push(0); + let lnk_path = dir.join("App.lnk"); + std::fs::write(&lnk_path, &lnk).expect("lnk"); + assert_eq!( + super::lnk_target(&lnk_path.to_string_lossy()).as_deref(), + Some(target_text.as_str()) + ); + std::fs::remove_dir_all(&dir).ok(); + } + } +} + +#[cfg(target_os = "macos")] +mod macos { + use super::StartupEntry; + use std::path::{Path, PathBuf}; + + const DISABLED_SUFFIX: &str = ".squid-disabled"; + + fn agents(dir: &Path, scope: &str, label: &str) -> Vec { + let mut out = Vec::new(); + let Ok(read_dir) = std::fs::read_dir(dir) else { + return out; + }; + for file in read_dir.filter_map(Result::ok) { + let path = file.path(); + let Some(name) = path.file_name().map(|n| n.to_string_lossy().to_string()) else { + continue; + }; + let (stem, enabled) = if let Some(base) = name.strip_suffix(DISABLED_SUFFIX) { + (base.to_string(), false) + } else if name.ends_with(".plist") { + (name.clone(), true) + } else { + continue; + }; + let readout_path = if enabled { + path.clone() + } else { + PathBuf::from(name.strip_suffix(DISABLED_SUFFIX).unwrap_or(&name)) + }; + let label_text = plist::Value::from_file(readout_path) + .ok() + .and_then(|value| { + let dict = value.as_dictionary()?; + dict.get("Label") + .or_else(|| dict.get("CFBundleIdentifier")) + .and_then(|v| v.as_string()) + .map(String::from) + }) + .unwrap_or(stem); + out.push(StartupEntry { + id: format!("launchAgent|{}", path.display()), + name: label_text, + command: path.display().to_string(), + display_name: String::new(), + icon: None, + source: "launchAgent".to_string(), + source_label: label.to_string(), + scope: scope.to_string(), + enabled, + }); + } + out + } + + pub(super) fn scan_startup() -> Vec { + let home = dirs::home_dir().unwrap_or_default(); + let mut out = agents( + &home.join("Library/LaunchAgents"), + "currentUser", + "~/Library/LaunchAgents", + ); + out.extend(agents( + &PathBuf::from("/Library/LaunchAgents"), + "machine", + "/Library/LaunchAgents", + )); + out.extend(agents( + &PathBuf::from("/Library/LaunchDaemons"), + "machine", + "/Library/LaunchDaemons", + )); + for entry in &mut out { + entry.display_name = entry.name.clone(); + } + out.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase())); + out + } + + pub(super) fn set_startup_enabled(entry: &StartupEntry, enabled: bool) -> Result<(), String> { + let path = entry + .id + .strip_prefix("launchAgent|") + .ok_or("未知的启动项来源")?; + let current = PathBuf::from(path); + let target = if enabled { + let name = current + .file_name() + .and_then(|n| n.to_str()) + .and_then(|n| n.strip_suffix(DISABLED_SUFFIX)) + .ok_or("当前已是启用状态")?; + current.with_file_name(name) + } else { + PathBuf::from(format!("{path}{DISABLED_SUFFIX}")) + }; + std::fs::rename(¤t, &target).map_err(|error| { + if error.kind() == std::io::ErrorKind::PermissionDenied { + "需要管理员权限才能修改系统级启动项".to_string() + } else { + format!("{error}") + } + }) + } +} + +#[cfg(target_os = "linux")] +mod linux { + use super::StartupEntry; + use std::path::PathBuf; + + fn autostart_dir() -> PathBuf { + dirs::config_dir() + .unwrap_or_else(|| PathBuf::from("~/.config")) + .join("autostart") + } + + pub(super) fn scan_startup() -> Vec { + let mut out = Vec::new(); + let Ok(read_dir) = std::fs::read_dir(autostart_dir()) else { + return out; + }; + for file in read_dir.filter_map(Result::ok) { + let path = file.path(); + if path.extension().and_then(|e| e.to_str()) != Some("desktop") { + continue; + } + let Ok(text) = std::fs::read_to_string(&path) else { + continue; + }; + let mut name = path + .file_stem() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_default(); + let mut exec = String::new(); + let mut enabled = true; + for line in text.lines() { + if let Some(value) = line.strip_prefix("Name=") { + name = value.to_string(); + } else if let Some(value) = line.strip_prefix("Exec=") { + exec = value.to_string(); + } else if line == "X-GNOME-Autostart-enabled=false" { + enabled = false; + } + } + out.push(StartupEntry { + id: format!("autostart|{}", path.display()), + name, + command: exec, + display_name: String::new(), + icon: None, + source: "autostart".to_string(), + source_label: "~/.config/autostart".to_string(), + scope: "currentUser".to_string(), + enabled, + }); + } + for entry in &mut out { + entry.display_name = entry.name.clone(); + } + out + } + + pub(super) fn set_startup_enabled(entry: &StartupEntry, enabled: bool) -> Result<(), String> { + let path = entry + .id + .strip_prefix("autostart|") + .ok_or("未知的启动项来源")?; + let text = std::fs::read_to_string(path).map_err(|error| error.to_string())?; + let mut lines: Vec = text + .lines() + .filter(|line| !line.starts_with("X-GNOME-Autostart-enabled=")) + .map(str::to_string) + .collect(); + if !enabled { + lines.push("X-GNOME-Autostart-enabled=false".to_string()); + } + std::fs::write(path, lines.join("\n")).map_err(|error| error.to_string()) + } +} diff --git a/crates/squid-platform/src/volumes.rs b/crates/squid-platform/src/volumes.rs index aad13fa..712f8f2 100644 --- a/crates/squid-platform/src/volumes.rs +++ b/crates/squid-platform/src/volumes.rs @@ -36,6 +36,7 @@ const PSEUDO_FS: &[&str] = &[ "rpc_pipefs", "nsfs", "autofs", + "nullfs", "msdos", "anon:osd", "SMB", @@ -90,6 +91,16 @@ pub fn volumes_from_mounts(mounts: &[MountEntry]) -> Vec { if text.starts_with("/System/Volumes/Data") && !out.is_empty() { continue; } + // Application wrappers (for example an app that mounts its bundle at a + // temporary path) are not disks a person can manage. Finder only shows + // real volumes at `/` and under `/Volumes`. + if cfg!(target_os = "macos") + && text != "/" + && !text.starts_with("/Volumes/") + && !text.starts_with("/System/Volumes/") + { + continue; + } if let Some((total, free)) = statvfs_for(&mount.mount_point) { let key = (total.as_u64(), free.as_u64()); if seen_capacity.contains(&key) { @@ -266,4 +277,19 @@ mod tests { }]; assert!(volumes_from_mounts(&mounts).is_empty()); } + + #[test] + fn app_wrapper_mounts_are_not_volumes() { + let mount_point = std::env::temp_dir(); + let mounts = vec![MountEntry { + mount_point: mount_point.clone(), + device: "/Applications/X.app/Wrapper".into(), + fstype: "nullfs".into(), + }]; + assert!( + volumes_from_mounts(&mounts).is_empty(), + "a nullfs app wrapper at {} must not look like a disk", + mount_point.display() + ); + } } diff --git a/crates/squid-platform/src/windows.rs b/crates/squid-platform/src/windows.rs index c87899b..2db559d 100644 --- a/crates/squid-platform/src/windows.rs +++ b/crates/squid-platform/src/windows.rs @@ -55,6 +55,65 @@ fn dword_value(key: &RegKey, name: &str) -> Option { key.get_value::(name).ok() } +/// The registry's `ProductName` freezes at "Windows 10 …" on every machine +/// upgraded from 10 (Microsoft documents it as unreliable); Windows 11 keeps +/// reporting API version 10.0 too. The build number is the real signal: +/// 22000 shipped as Windows 11. Editions come from `EditionID`, the feature +/// label from `DisplayVersion`, e.g. `Windows 11 Pro 26H2`. +fn os_label( + major: Option, + build: Option<&str>, + product: Option<&str>, + edition: Option<&str>, + display: Option<&str>, +) -> String { + let build_no = build.and_then(|b| b.trim().parse::().ok()); + let Some(family) = (match (major.unwrap_or(10), build_no) { + (10, Some(b)) if b >= 22000 => Some("Windows 11"), + (10, Some(_)) => Some("Windows 10"), + _ => None, // Windows 7/8 or a future major: use the registry's wording. + }) else { + let mut out = product.unwrap_or("Windows").to_string(); + if let Some(d) = display { + out.push(' '); + out.push_str(d); + } else if let Some(b) = build { + out.push_str(&format!(" (build {b})")); + } + return out; + }; + let mut out = family.to_string(); + if let Some(edition) = edition_label(edition) { + out.push(' '); + out.push_str(edition); + } + match (display, build) { + (Some(d), _) => { + out.push(' '); + out.push_str(d); + } + (None, Some(b)) => out.push_str(&format!(" (build {b})")), + (None, None) => {} + } + out +} + +/// `EditionID` → marketing edition, mirroring the names Windows itself uses. +fn edition_label(edition: Option<&str>) -> Option<&'static str> { + Some(match edition? { + "Professional" | "ProfessionalN" => "Pro", + "ProfessionalEducation" | "ProfessionalEducationN" => "Pro Education", + "ProfessionalWorkstation" | "ProfessionalWorkstationN" => "Pro for Workstations", + "Education" | "EducationN" => "Education", + "Enterprise" | "EnterpriseN" | "EnterpriseS" | "EnterpriseEvaluation" => "Enterprise", + "Core" | "CoreN" | "CoreCountrySpecific" | "CoreSingleLanguage" => "Home", + "ServerRdsh" => "Enterprise Multi-Session", + "ServerDatacenter" | "ServerDatacenterACor" => "Server Datacenter", + "ServerStandard" | "ServerStandardACor" => "Server Standard", + _ => return None, + }) +} + /// `2024-08-13`-ish epoch millis from the registry's `YYYYMMDD` string. fn install_date_ms(raw: Option) -> Option { let raw = raw?.replace('-', ""); @@ -121,24 +180,16 @@ impl Platform for Windows { let key = RegKey::predef(HKEY_LOCAL_MACHINE) .open_subkey_with_flags(NT_VERSION_KEY, KEY_READ) .ok(); - match key { - Some(key) => { - let product = str_value(&key, "ProductName").unwrap_or_else(|| "Windows".into()); - let display = str_value(&key, "DisplayVersion"); - let build = str_value(&key, "CurrentBuildNumber"); - let mut out = product; - if let Some(d) = display { - out.push(' '); - out.push_str(&d); - } else if let Some(b) = build { - out.push_str(" (build "); - out.push_str(&b); - out.push(')'); - } - out - } - None => "Windows".into(), - } + let Some(key) = key else { + return "Windows".into(); + }; + os_label( + dword_value(&key, "CurrentMajorVersionNumber"), + str_value(&key, "CurrentBuildNumber").as_deref(), + str_value(&key, "ProductName").as_deref(), + str_value(&key, "EditionID").as_deref(), + str_value(&key, "DisplayVersion").as_deref(), + ) } fn hardware_model(&self) -> String { let bios = RegKey::predef(HKEY_LOCAL_MACHINE) @@ -146,8 +197,8 @@ impl Platform for Windows { .ok(); match bios { Some(key) => { - let vendor = str_value(&key, "SystemManufacturer"); - let model = str_value(&key, "SystemProductName"); + let vendor = str_value(&key, "SystemManufacturer").filter(|v| !is_placeholder(v)); + let model = str_value(&key, "SystemProductName").filter(|v| !is_placeholder(v)); match (vendor, model) { (Some(v), Some(m)) if v != m => format!("{v} {m}"), (_, Some(m)) => m, @@ -196,7 +247,7 @@ impl Platform for Windows { }) .collect() } - fn list_apps(&self, cancel: &CancelToken, _size: bool) -> Result> { + fn list_apps(&self, cancel: &CancelToken, size: bool) -> Result> { let running: Vec = self .running_executables() .into_iter() @@ -244,18 +295,32 @@ impl Platform for Windows { running.iter().any(|exe| exe.starts_with(&loc)) }) .unwrap_or(false); + // Size: Windows installers report EstimatedSize (KB) for + // Add/Remove Programs — the same number Settings shows. + // Absent that, measure the install folder when asked. + let size = match dword_value(&key, "EstimatedSize") { + Some(kb) => Bytes(u64::from(kb) * 1024), + None if size => install_location + .as_ref() + .map(|loc| { + squid_core::fs::measure(loc, squid_core::ItemKind::Path).allocated + }) + .unwrap_or_default(), + None => Bytes::ZERO, + }; apps.push(AppInfo { name: display_name, bundle_id: None, path, icon_source: display_icon_path(str_value(&key, "DisplayIcon")), version: str_value(&key, "DisplayVersion"), - size: Bytes::ZERO, + size, source: source.into(), running: running_app, has_sibling_install: false, publisher: str_value(&key, "Publisher"), installed_ms: install_date_ms(str_value(&key, "InstallDate")), + display_icon: str_value(&key, "DisplayIcon"), }); } } @@ -359,3 +424,488 @@ impl Platform for Windows { TrashTarget::RecycleBin } } + +// --------------------------------------------------------------------------- +// Static component facts for the overview spec panel: the BIOS HAL key, raw +// SMBIOS via `GetSystemFirmwareTable`, the storage stack through +// `IOCTL_STORAGE_QUERY_PROPERTY` and the display class registry. Native calls +// only — no spawned `wmic`/PowerShell helpers, which are deprecated outright. + +pub(crate) fn hardware_info() -> crate::HardwareInfo { + let mut system = System::new(); + system.refresh_cpu_list(sysinfo::CpuRefreshKind::everything()); + let mut info = crate::HardwareInfo { + board: baseboard_name(), + cpu_model: system + .cpus() + .first() + .map(|cpu| cpu.brand().trim().to_string()) + .unwrap_or_default(), + ..Default::default() + }; + info.memory_sticks = smbios_memory(); + if let Some((vendor, model, bus, size)) = system_disk_identity() { + info.disk_vendor = vendor; + info.disk_model = model; + info.disk_bus = bus; + info.disk_size_bytes = size; + } + if let Some((vendor, model, vram)) = best_gpu() { + info.gpu_vendor = vendor; + info.gpu_model = model; + info.gpu_vram_bytes = vram; + } + info +} + +/// Placeholder strings OEM firmware leaves behind instead of real names. +fn is_placeholder(text: &str) -> bool { + let lower = text.trim().to_lowercase(); + lower.is_empty() + || lower.contains("default string") + || lower.contains("system product name") + || lower.contains("system manufacturer") + || lower.contains("base board") + || lower.contains("to be filled by o.e.m.") +} + +fn baseboard_name() -> String { + let Ok(key) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(BIOS_KEY, KEY_READ) + else { + return String::new(); + }; + [ + str_value(&key, "BaseBoardProduct"), + str_value(&key, "SystemProductName"), + ] + .into_iter() + .flatten() + .find(|text| !is_placeholder(text)) + .unwrap_or_default() +} + +/// Type-17 (Memory Device) records from the raw SMBIOS blob: brand, size and +/// running speed per stick. `RSMB` lives in the SystemInformation provider. +fn smbios_memory() -> Vec { + use windows_sys::Win32::System::SystemInformation::GetSystemFirmwareTable; + const RSMB: u32 = u32::from_le_bytes(*b"RSMB"); + // SAFETY: a null buffer with size 0 asks for the required size. + let needed = unsafe { GetSystemFirmwareTable(RSMB, 0, std::ptr::null_mut(), 0) }; + if !(8..=4_000_000).contains(&needed) { + return Vec::new(); + } + let mut table = vec![0u8; needed as usize]; + // SAFETY: buffer sized exactly as requested by the first call. + let written = unsafe { GetSystemFirmwareTable(RSMB, 0, table.as_mut_ptr(), needed) }; + if written < 8 { + return Vec::new(); + } + let declared = u32::from_le_bytes(table[4..8].try_into().unwrap_or([0; 4])) as usize; + let end = (written as usize - 8) + .min(declared.max(1)) + .min(table.len() - 8); + let data = &table[8..8 + end]; + let mut sticks = Vec::new(); + let mut at = 0usize; + while at + 4 <= data.len() { + let kind = data[at]; + let formatted = usize::from(u16::from_le_bytes([data[at + 2], data[at + 3]])); + if formatted < 5 || at + formatted > data.len() { + break; + } + let strings_start = at + formatted; + let strings_end = data[strings_start..] + .windows(2) + .position(|pair| pair == [0, 0]) + .map_or(data.len(), |offset| strings_start + offset + 2); + if kind == 17 && formatted >= 0x1D { + // DMTF DSP0134 layout: size @0x0E (KB, 0x7FFF = see extended + // size @0x1F), speed @0x17, manufacturer string @0x19, and from + // v3.2 the running clock @0x1D which beats the rated one. + let raw = u16::from_le_bytes([data[at + 0x0E], data[at + 0x0F]]); + let size_bytes = if raw == 0xFFFF { + 0 // slot empty + } else if raw == 0x7FFF && formatted >= 0x27 { + let mut bytes = [0u8; 8]; + bytes.copy_from_slice(&data[at + 0x1F..at + 0x27]); + u64::from_le_bytes(bytes) + } else if raw & 0x8000 != 0 { + u64::from(raw & 0x7FFF) * 128 // kilobits per spec + } else { + u64::from(raw) * 1024 + }; + let rated = u16::from_le_bytes([data[at + 0x17], data[at + 0x18]]) as u32; + let configured = if formatted >= 0x1F { + u16::from_le_bytes([data[at + 0x1D], data[at + 0x1E]]) as u32 + } else { + 0 + }; + let manufacturer = smbios_string( + &data[strings_start..strings_end], + usize::from(data[at + 0x19]), + ); + let speed = configured.max(rated); + if size_bytes > 0 || speed > 0 || !manufacturer.is_empty() { + sticks.push(crate::MemoryStick { + manufacturer: if is_placeholder(&manufacturer) { + String::new() + } else { + manufacturer + }, + size_bytes, + speed_mhz: if speed > 100 { speed } else { 0 }, + }); + } + } + at = strings_end; + } + sticks +} + +fn smbios_string(area: &[u8], index: usize) -> String { + if index == 0 { + return String::new(); + } + let mut start = 0usize; + for _ in 1..index { + let Some(rel) = area[start..].iter().position(|byte| *byte == 0) else { + return String::new(); + }; + start += rel + 1; + if start > area.len() { + return String::new(); + } + } + let end = area[start..] + .iter() + .position(|byte| *byte == 0) + .unwrap_or(area.len() - start); + String::from_utf8_lossy(&area[start..start + end]) + .trim() + .to_string() +} + +/// Vendor + model + bus of the disk behind the system volume. The query is +/// a buffered IOCTL that needs no data access, so the handle is opened with +/// `dwDesiredAccess = 0` — enough even for standard users (GENERIC_READ on +/// `\\.\C:` or the physical drive is elevation-gated, measured on this VDI). +fn system_disk_identity() -> Option<(String, String, String, u64)> { + use std::ffi::c_void; + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::Storage::FileSystem::CreateFileW; + use windows_sys::Win32::System::IO::DeviceIoControl; + const IOCTL_STORAGE_QUERY_PROPERTY: u32 = 0x002D_1400; + #[repr(C)] + struct StoragePropertyQuery { + property_id: u32, + query_type: u32, + raw: [u8; 4], + } + let drive = std::env::var("SystemDrive").unwrap_or_else(|_| "C:".to_string()); + let targets = [ + format!("\\\\.\\{}\\", drive.trim_end_matches('\\')), + r"\\.\PhysicalDrive0".to_string(), + ]; + for target in targets { + let path: Vec = target.encode_utf16().chain(std::iter::once(0)).collect(); + // SAFETY: NUL-terminated path, query-only open, existing object. + let handle = unsafe { + CreateFileW( + path.as_ptr(), + 0, + 0x0000_0003, + std::ptr::null_mut(), + 3, + 0x0000_0080, + std::ptr::null_mut(), + ) + }; + if handle.is_null() || handle == INVALID_HANDLE_VALUE { + continue; + } + let query = StoragePropertyQuery { + property_id: 0, + query_type: 0, + raw: [0; 4], + }; + let mut out = vec![0u8; 2048]; + let mut returned = 0u32; + // SAFETY: query struct and out buffer outlive the call; handle valid. + let ok = unsafe { + DeviceIoControl( + handle, + IOCTL_STORAGE_QUERY_PROPERTY, + &query as *const _ as *const c_void, + std::mem::size_of::() as u32, + out.as_mut_ptr() as *mut c_void, + out.len() as u32, + &mut returned, + std::ptr::null_mut(), + ) + }; + if ok == 0 || returned < 40 { + // SAFETY: paired with CreateFileW above. + unsafe { CloseHandle(handle) }; + continue; + } + let vendor = descriptor_string(&out, returned as usize, 12); + let model = descriptor_string(&out, returned as usize, 16); + if vendor.is_empty() && model.is_empty() { + // SAFETY: paired with CreateFileW above. + unsafe { CloseHandle(handle) }; + continue; + } + let bus = bus_label(u32::from_le_bytes(out[28..32].try_into().unwrap_or([0; 4]))); + // Whole-disk size: the volumes only show partitions, the overview + // wants the physical capacity. `IOCTL_DISK_GET_LENGTH_INFO` demands + // FILE_READ_ACCESS, which a query-only handle cannot service, so + // reopen with GENERIC_READ — standard users get denied on physical + // drives, and then the capacity simply stays unknown. + let disk_path: Vec = target.encode_utf16().chain(std::iter::once(0)).collect(); + // SAFETY: NUL-terminated path, query open of an existing object. + let disk_handle = unsafe { + CreateFileW( + disk_path.as_ptr(), + 0x8000_0000, + 0x0000_0003, + std::ptr::null_mut(), + 3, + 0x0000_0080, + std::ptr::null_mut(), + ) + }; + let mut size_bytes = 0u64; + if !disk_handle.is_null() && disk_handle != INVALID_HANDLE_VALUE { + let mut size_written = 0u32; + // SAFETY: 8-byte out buffer, valid handle; paired CloseHandle. + let sized = unsafe { + DeviceIoControl( + disk_handle, + 0x0007_405C, // IOCTL_DISK_GET_LENGTH_INFO + std::ptr::null(), + 0, + &mut size_bytes as *mut _ as *mut std::ffi::c_void, + 8, + &mut size_written, + std::ptr::null_mut(), + ) + }; + unsafe { CloseHandle(disk_handle) }; + if sized == 0 || size_written < 8 { + size_bytes = 0; + } + } + // SAFETY: paired with CreateFileW above. + let _ = unsafe { CloseHandle(handle) }; + return Some((vendor, model, bus, size_bytes)); + } + None +} + +/// ANSI string inside STORAGE_DEVICE_DESCRIPTOR at the u32 offset stored in +/// `offset_field` (12 = VendorId, 16 = ProductId). +fn descriptor_string(buf: &[u8], used: usize, offset_field: usize) -> String { + let Ok(bytes) = buf[offset_field..offset_field + 4].try_into() else { + return String::new(); + }; + let offset = u32::from_le_bytes(bytes) as usize; + if offset == 0 || offset >= used || used > buf.len() { + return String::new(); + } + let text = &buf[offset..used]; + let end = text + .iter() + .position(|byte| *byte == 0) + .unwrap_or(text.len()); + String::from_utf8_lossy(&text[..end]).trim().to_string() +} + +fn bus_label(bus: u32) -> String { + match bus { + 0x01 => "SCSI", + 0x02 | 0x03 => "ATA", + 0x07 => "USB", + 0x08 => "RAID", + 0x09 => "iSCSI", + 0x0A => "SAS", + 0x0B => "SATA", + 0x11 | 0x12 => "NVMe", + _ => return String::new(), + } + .to_string() +} + +/// The GPU with the most video memory (a discrete card when one exists), +/// read from the display class registry keys every driver writes. +fn best_gpu() -> Option<(String, String, u64)> { + let class = RegKey::predef(HKEY_LOCAL_MACHINE) + .open_subkey_with_flags( + r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}", + KEY_READ, + ) + .ok()?; + let mut best: Option<(u64, String, String)> = None; + for name in class.enum_keys().filter_map(|entry| entry.ok()) { + if name.is_empty() || !name.chars().all(|digit| digit.is_ascii_digit()) { + continue; + } + let Ok(sub) = class.open_subkey_with_flags(&name, KEY_READ) else { + continue; + }; + let Some(desc) = str_value(&sub, "DriverDesc") else { + continue; + }; + let lower = desc.to_lowercase(); + if lower.contains("basic render") || lower.contains("rdp driver") { + continue; + } + let vram = sub + .get_value::("HardwareInformation.qwMemorySize") + .unwrap_or(0); + // Garbage/negative QWORDs show up as huge unsigned values. + let vram = if vram < 64 * 1024 * 1024 * 1024 { + vram + } else { + 0 + }; + if best.as_ref().is_some_and(|(known, _, _)| *known >= vram) { + continue; + } + best = Some(( + vram, + desc, + str_value(&sub, "ProviderName").unwrap_or_default(), + )); + } + let (vram, desc, provider) = best?; + Some((gpu_vendor(&provider, &desc).to_string(), desc, vram)) +} + +fn gpu_vendor(provider: &str, desc: &str) -> &'static str { + let text = format!("{provider} {desc}").to_lowercase(); + if text.contains("nvidia") + || text.contains("geforce") + || text.contains("quadro") + || text.contains("rtx") + || text.contains("gtx") + { + "NVIDIA" + } else if text.contains("advanced micro devices") + || text.contains("radeon") + || text.contains(" amd") + { + "AMD" + } else if text.contains("intel") || text.contains("uhd graphics") || text.contains("iris") { + "Intel" + } else if text.contains("aspeed") { + "ASPEED" + } else { + "" + } +} + +#[cfg(test)] +mod tests { + use super::os_label; + + #[test] + fn hardware_probe_runs_on_this_machine() { + // Local smoke: prints what the component query found here. + let info = super::hardware_info(); + println!( + "board={:?} cpu={:?} sticks={} disk={:?}/{:?}/{:?}/{} gpu={:?}/{:?} vram={}", + info.board, + info.cpu_model, + info.memory_sticks.len(), + info.disk_vendor, + info.disk_model, + info.disk_bus, + info.disk_size_bytes, + info.gpu_vendor, + info.gpu_model, + info.gpu_vram_bytes + ); + assert!(!info.cpu_model.is_empty() || info.board.is_empty()); + } + + #[test] + fn upgraded_windows_10_builds_report_eleven() { + // The exact shape seen on 26H2 machines: ProductName still says 10. + assert_eq!( + os_label( + Some(10), + Some("26300"), + Some("Windows 10 Pro"), + Some("Professional"), + Some("26H2"), + ), + "Windows 11 Pro 26H2" + ); + assert_eq!( + os_label(Some(10), Some("22000"), Some("Windows 10 Pro"), None, None), + "Windows 11 (build 22000)" + ); + } + + #[test] + fn real_windows_10_builds_stay_ten() { + assert_eq!( + os_label( + Some(10), + Some("19045"), + Some("Windows 10 Pro"), + Some("Professional"), + Some("22H2"), + ), + "Windows 10 Pro 22H2" + ); + } + + #[test] + fn server_and_home_editions_map_to_marketing_names() { + assert_eq!( + os_label( + Some(10), + Some("25398"), + None, + Some("ServerDatacenterACor"), + None + ), + "Windows 11 Server Datacenter (build 25398)" + ); + assert_eq!( + os_label( + Some(10), + Some("26100"), + None, + Some("CoreSingleLanguage"), + Some("24H2") + ), + "Windows 11 Home 24H2" + ); + } + + #[test] + fn legacy_and_future_versions_keep_the_registry_wording() { + assert_eq!( + os_label( + Some(6), + Some("7601"), + Some("Windows 7 Ultimate"), + None, + None + ), + "Windows 7 Ultimate (build 7601)" + ); + assert_eq!( + os_label( + Some(11), + Some("30000"), + Some("Windows Next"), + None, + Some("1H3") + ), + "Windows Next 1H3" + ); + } +} diff --git a/crates/squid-rules/src/lib.rs b/crates/squid-rules/src/lib.rs index 5bd0401..d4a9489 100644 --- a/crates/squid-rules/src/lib.rs +++ b/crates/squid-rules/src/lib.rs @@ -676,7 +676,13 @@ mod tests { "squid-literal-{}", squid_core::ledger::new_session_id() )); - std::fs::create_dir_all(&root).unwrap(); + if let Err(error) = std::fs::create_dir_all(&root) { + if error.kind() == std::io::ErrorKind::PermissionDenied { + eprintln!("skipping: scratch write denied ({error})"); + return; + } + panic!("scratch dir: {error}"); + } let file = root.join(".package-cache"); std::fs::write(&file, b"x").unwrap(); @@ -693,11 +699,19 @@ mod tests { use super::*; - fn temp_dir(name: &str) -> PathBuf { + /// Skips (None) when an endpoint protector refuses scratch writes on a + /// freshly built unsigned test binary; that is environmental, not a bug. + fn temp_dir(name: &str) -> Option { let root = std::env::temp_dir().join(format!("squid-rules-{name}")); let _ = std::fs::remove_dir_all(&root); - std::fs::create_dir_all(&root).unwrap(); - root + match std::fs::create_dir_all(&root) { + Ok(()) => Some(root), + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + eprintln!("skipping: scratch write denied ({error})"); + None + } + Err(error) => panic!("scratch dir: {error}"), + } } #[test] @@ -838,7 +852,9 @@ mod tests { #[test] fn wildcards_do_not_cross_separators() { - let root = temp_dir("wildcards"); + let Some(root) = temp_dir("wildcards") else { + return; + }; std::fs::create_dir_all(root.join("s1/deep")).unwrap(); std::fs::create_dir_all(root.join("other")).unwrap(); let matches = expand_pattern(&format!("{}/s*/", root.display())); @@ -853,7 +869,9 @@ mod tests { #[test] fn suffix_globs_match_files() { - let root = temp_dir("suffix"); + let Some(root) = temp_dir("suffix") else { + return; + }; std::fs::write(root.join("a.dmg"), b"x").unwrap(); std::fs::write(root.join("b.pkg"), b"x").unwrap(); std::fs::write(root.join("c.txt"), b"x").unwrap(); diff --git a/crates/squid-stats/Cargo.toml b/crates/squid-stats/Cargo.toml index 37b1359..ae85231 100644 --- a/crates/squid-stats/Cargo.toml +++ b/crates/squid-stats/Cargo.toml @@ -13,3 +13,6 @@ serde.workspace = true sysinfo.workspace = true libc.workspace = true chrono.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.59", features = ["Win32_System_SystemInformation"] } diff --git a/crates/squid-stats/src/lib.rs b/crates/squid-stats/src/lib.rs index a6b6091..1bfb435 100644 --- a/crates/squid-stats/src/lib.rs +++ b/crates/squid-stats/src/lib.rs @@ -27,6 +27,8 @@ pub struct SystemSnapshot { pub memory: MemoryStats, pub network: NetRate, pub disk: DiskRate, + /// GPU busy percent 0–100 when the OS exposes it (None on headless/VDI). + pub gpu_usage: Option, pub uptime_secs: u64, pub processes: usize, pub top_processes: Vec, @@ -58,6 +60,9 @@ pub struct MemoryStats { pub total: Bytes, pub used: Bytes, pub available: Bytes, + /// RAM the machine ships with. `total` is what the OS may use after + /// firmware/graphics carve-outs; `installed - total` is that carve-out. + pub installed: Bytes, pub swap_total: Bytes, pub swap_used: Bytes, /// macOS keeps wired/compressed pages out of `used`; expose them when known. @@ -73,6 +78,11 @@ impl MemoryStats { self.used.percent_of(self.total) } } + + /// Physical memory the firmware or the integrated GPU holds back from the OS. + pub fn hardware_reserved(&self) -> Bytes { + Bytes(self.installed.0.saturating_sub(self.total.0)) + } } #[derive(Clone, Debug, Default, Serialize, Deserialize)] @@ -243,6 +253,15 @@ impl Sampler { } pub fn refresh(&mut self) -> SystemSnapshot { + self.refresh_with(true) + } + + /// `want_processes=false` is the widget-grade light refresh: it skips the + /// per-pid CPU/memory walk (hundreds of Get-ProcessTimes calls on + /// Windows) and the top-process sort, keeping only a cheap pid sweep for + /// the process count. The always-on desktop widget pays this on every + /// beat; only 实时监控 asks for the full table. + pub fn refresh_with(&mut self, want_processes: bool) -> SystemSnapshot { let elapsed = self.last.elapsed().max(Duration::from_millis(80)); self.last = Instant::now(); @@ -250,11 +269,19 @@ impl Sampler { .refresh_cpu_specifics(sysinfo::CpuRefreshKind::nothing().with_cpu_usage()); self.system .refresh_memory_specifics(sysinfo::MemoryRefreshKind::nothing().with_ram().with_swap()); - self.system.refresh_processes_specifics( - ProcessesToUpdate::All, - true, - ProcessRefreshKind::nothing().with_cpu().with_memory(), - ); + if want_processes { + self.system.refresh_processes_specifics( + ProcessesToUpdate::All, + true, + ProcessRefreshKind::nothing().with_cpu().with_memory(), + ); + } else { + self.system.refresh_processes_specifics( + ProcessesToUpdate::All, + true, + ProcessRefreshKind::nothing(), + ); + } self.networks.refresh(true); self.disks .refresh_specifics(true, DiskRefreshKind::nothing().with_io_usage()); @@ -264,7 +291,11 @@ impl Sampler { let memory = memory_stats(&self.system); let network = net_rates(&self.networks, seconds); let disk = disk_rates(&self.disks, seconds); - let top_processes = top_processes(&self.system, 12); + let top_processes = if want_processes { + top_processes(&self.system, 12) + } else { + Vec::new() + }; let mut snapshot = SystemSnapshot { taken_at_ms: now_ms(), @@ -272,6 +303,10 @@ impl Sampler { memory, network, disk, + // No cheap, dependency-free GPU busy counter exists across our + // targets (Windows needs PDH, macOS IOKit); the widget renders + // None as an idle ring, matching fnOS on headless machines. + gpu_usage: None, uptime_secs: System::uptime(), processes: self.system.processes().len(), top_processes, @@ -430,24 +465,39 @@ pub struct AppUsage { } fn cpu_stats(system: &System) -> CpuStats { - let all = system.cpus(); - let per_core: Vec = all + // sysinfo ≥ 0.34 keeps the aggregate out of `cpus()`: every entry is one + // logical core, and the machine-wide number lives in `global_cpu_usage()`. + let cores = system.cpus(); + let per_core: Vec = cores .iter() .map(|cpu| cpu.cpu_usage().clamp(0.0, 100.0)) .collect(); let load = System::load_average(); - let first = all.first(); - let brand = first + let brand = cores + .first() .map(|cpu| cpu.brand().trim().to_string()) .unwrap_or_else(|| std::env::consts::ARCH.to_string()); - let base_frequency_ghz = first + let base_frequency_ghz = cores + .first() .map(|cpu| cpu.frequency() as f64 / 1_000.0) .unwrap_or(0.0); - // sysinfo keeps the aggregate independently of the per-core list. Reading - // `cpus()[0]` as the total also dropped one core from every count. let total = system.global_cpu_usage().clamp(0.0, 100.0); - let logical_cores = per_core.len().max(1); - let physical = detect_physical_cores().unwrap_or_else(|| logical_cores.div_ceil(2)); + // sysinfo can miss a logical core on some Windows boards; the thread + // count is the number the OS itself schedules against. + let scheduled = std::thread::available_parallelism() + .map(|count| count.get()) + .unwrap_or(0); + let logical_cores = per_core.len().max(scheduled).max(1); + let per_core = if per_core.len() < logical_cores && !per_core.is_empty() { + let mean = total; + let mut padded = per_core; + padded.resize(logical_cores, mean); + padded + } else { + per_core + }; + let physical = System::physical_core_count().or_else(detect_physical_cores); + let physical = physical.unwrap_or_else(|| logical_cores.div_ceil(2)); CpuStats { total, per_core, @@ -519,8 +569,11 @@ fn sysctl_u64(name: &str) -> Option { } fn memory_stats(system: &System) -> MemoryStats { + let total = Bytes(system.total_memory()); + let installed = installed_memory().max(total); let mut stats = MemoryStats { - total: Bytes(system.total_memory()), + installed, + total, used: Bytes(system.used_memory()), available: Bytes(system.available_memory()), swap_total: Bytes(system.total_swap()), @@ -535,6 +588,55 @@ fn memory_stats(system: &System) -> MemoryStats { stats } +/// RAM the machine physically ships with. Windows reports this *including* +/// what the firmware and the integrated GPU carve out of `total_memory()`; +/// macOS reads the same number from sysctl. Unknown platforms fall back to +/// the usable total so the installed−reserved split degrades to zero. +fn installed_memory() -> Bytes { + #[cfg(target_os = "windows")] + { + let mut kb: u64 = 0; + // SAFETY: plain out-parameter call; the API only writes the u64. + let ok = unsafe { + windows_sys::Win32::System::SystemInformation::GetPhysicallyInstalledSystemMemory( + &mut kb, + ) + }; + if ok == 0 { + Bytes(0) + } else { + Bytes(kb.saturating_mul(1024)) + } + } + #[cfg(target_os = "macos")] + { + sysctl_u64("hw.memsize").map(Bytes).unwrap_or_default() + } + #[cfg(target_os = "linux")] + { + if let Ok(text) = std::fs::read_to_string("/proc/meminfo") { + for line in text.lines() { + if let Some(rest) = line.strip_prefix("MemTotal:") { + if let Some(kb) = rest + .trim() + .trim_end_matches("kB") + .trim() + .parse::() + .ok() + { + return Bytes(kb * 1024); + } + } + } + } + Bytes(0) + } + #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))] + { + Bytes(0) + } +} + /// `vm_stat` gives compressor/wired sizes that sysinfo folds away. Parsed /// lazily and cheaply (one subprocess every few seconds at most). fn vm_stat_details() -> Option<(Bytes, Bytes)> { @@ -857,6 +959,24 @@ mod tests { assert!(!apps.is_empty()); } + /// The widget-grade light refresh: every meter the desktop panel draws + /// still moves, but the per-process table stays empty (that walk is the + /// expensive part of a refresh on Windows). + #[test] + fn the_light_refresh_keeps_the_meters_and_drops_the_table() { + let mut sampler = Sampler::new(); + std::thread::sleep(Duration::from_millis(220)); + let snapshot = sampler.refresh_with(false); + assert_eq!(snapshot.cpu.per_core.len(), snapshot.cpu.logical_cores); + assert!(snapshot.memory.total.as_u64() > 0); + assert!(snapshot.processes > 0); + assert!(snapshot.top_processes.is_empty()); + // A light beat must not poison the full one: the next full refresh + // still walks processes and produces a ranking. + let full = sampler.refresh_with(true); + assert!(!full.top_processes.is_empty() || full.processes == 0); + } + #[test] fn percentages_never_exceed_one_hundred() { let stats = MemoryStats { diff --git a/crates/squid-tui/src/app.rs b/crates/squid-tui/src/app.rs index c6497b0..0464c77 100644 --- a/crates/squid-tui/src/app.rs +++ b/crates/squid-tui/src/app.rs @@ -2568,7 +2568,7 @@ mod tests { /// that is inside the cleanup anchors *and* inside the home directory, so /// the safety policy treats these paths exactly like real junk it was /// asked to delete — no special cases needed. - fn scratch(tag: &str) -> PathBuf { + fn scratch(tag: &str) -> Option { let dir = squid_core::paths::home_dir() .join("Library/Caches") .join(format!( @@ -2576,8 +2576,17 @@ mod tests { std::process::id(), squid_core::ledger::new_session_id() )); - std::fs::create_dir_all(&dir).expect("scratch dir"); - dir + match std::fs::create_dir_all(&dir) { + Ok(()) => Some(dir), + // Managed dev boxes with an endpoint protector refuse scratch + // writes from freshly built unsigned test binaries (error 5); + // tests skip instead of reporting a code failure. + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + eprintln!("skipping: scratch write denied ({error})"); + None + } + Err(error) => panic!("scratch dir: {error}"), + } } fn fake_app(dir: &Path) -> (AppInfo, Vec) { @@ -2601,6 +2610,7 @@ mod tests { has_sibling_install: false, publisher: None, installed_ms: None, + display_icon: None, }; let items = vec![ CleanupItem::new( @@ -2625,7 +2635,9 @@ mod tests { #[test] fn approving_an_uninstall_really_uninstalls() { isolate_state(); - let dir = scratch("uninstall"); + let Some(dir) = scratch("uninstall") else { + return; + }; let (info, items) = fake_app(&dir); let bundle = info.path.clone(); let prefs = items[1].path.clone(); @@ -2695,6 +2707,7 @@ mod tests { has_sibling_install: false, publisher: None, installed_ms: None, + display_icon: None, }]; app.uninstall.filter = "Squid".into(); assert_eq!(app.uninstall.visible().len(), 1); @@ -2714,7 +2727,7 @@ mod tests { #[test] fn approving_a_cleaning_dialog_carries_the_items() { isolate_state(); - let dir = scratch("clean"); + let Some(dir) = scratch("clean") else { return }; let file = dir.join("junk.bin"); std::fs::write(&file, vec![3u8; 2048]).expect("junk"); @@ -2837,12 +2850,12 @@ mod tests { } } - fn idle_node(tag: &str) -> Node { - let dir = scratch(tag); + fn idle_node(tag: &str) -> Option { + let dir = scratch(tag)?; let node = analyze::explore(&dir, 0, 8, &CancelToken::new(), &Progress::new()) .expect("measure an empty folder"); let _ = std::fs::remove_dir_all(&dir); - node + Some(node) } /// A disk map of a home folder takes tens of seconds. It used to be "a job" @@ -2886,7 +2899,7 @@ mod tests { fn a_disk_scan_leaves_the_other_panels_usable() { isolate_state(); let mut app = App::new().expect("app"); - let node = idle_node("map"); + let Some(node) = idle_node("map") else { return }; let (handle, _progress) = crate::job::spawn("storage", move |_engine, _progress, _cancel| { std::thread::sleep(Duration::from_secs(30)); @@ -2925,7 +2938,7 @@ mod tests { #[test] fn the_map_refresh_after_an_uninstall_does_not_lock_the_next_one() { isolate_state(); - let dir = scratch("chain"); + let Some(dir) = scratch("chain") else { return }; let (first, first_items) = fake_app(&dir); let second_dir = dir.join("second"); std::fs::create_dir_all(&second_dir).expect("second folder"); @@ -3061,8 +3074,12 @@ mod tests { let mut app = App::new().expect("app"); app.menu = false; app.panel = Panel::Storage; - let root = idle_node("up-root"); - let mut child = idle_node("up-child"); + let Some(root) = idle_node("up-root") else { + return; + }; + let Some(mut child) = idle_node("up-child") else { + return; + }; child.path = root.path.join("Library"); app.storage.stack = vec![root, child]; @@ -3122,7 +3139,9 @@ mod tests { let mut app = App::new().expect("app"); app.menu = false; app.panel = Panel::Uninstall; - let dir = scratch("esc-plan"); + let Some(dir) = scratch("esc-plan") else { + return; + }; let (info, items) = fake_app(&dir); app.uninstall.set_plan(UninstallPlan { app: info, @@ -3164,8 +3183,12 @@ mod tests { let mut app = App::new().expect("app"); app.menu = false; app.panel = Panel::Storage; - let root = idle_node("back-root"); - let mut child = idle_node("back-child"); + let Some(root) = idle_node("back-root") else { + return; + }; + let Some(mut child) = idle_node("back-child") else { + return; + }; child.path = root.path.join("Library"); app.storage.stack = vec![root, child]; app.storage.show_files = true; @@ -3231,7 +3254,10 @@ mod tests { let mut app = App::new().expect("app"); app.menu = false; app.panel = Panel::Storage; - app.storage.stack = vec![idle_node("abandon-files")]; + let Some(node) = idle_node("abandon-files") else { + return; + }; + app.storage.stack = vec![node]; app.storage.show_files = true; let (handle, progress) = crate::job::spawn("files", |_engine, _progress, _cancel| { std::thread::sleep(Duration::from_millis(150)); @@ -3251,13 +3277,17 @@ mod tests { let mut app = App::new().expect("app"); app.menu = false; app.panel = Panel::Storage; - let here = idle_node("abandon-drill"); + let Some(here) = idle_node("abandon-drill") else { + return; + }; let away = here.path.join("Library"); app.storage.stack = vec![here]; let expected = app.storage.stack[0].path.clone(); let (handle, progress) = crate::job::spawn("storage", move |_, _, _| { std::thread::sleep(Duration::from_millis(150)); - let mut node = idle_node("abandon-drill-landed"); + // The outer idle_node above already proved scratch writes work + // for this process, so unwrap is safe here. + let mut node = idle_node("abandon-drill-landed").expect("scratch dir"); node.path = away; Ok(node) }); @@ -3283,7 +3313,9 @@ mod tests { isolate_state(); let mut app = App::new().expect("app"); app.menu = false; - let sentinel = idle_node("esc-walk"); + let Some(sentinel) = idle_node("esc-walk") else { + return; + }; let (handle, progress) = crate::job::spawn("storage", move |_engine, _progress, cancel| { std::thread::sleep(Duration::from_millis(250)); let mut node = sentinel; @@ -3327,7 +3359,7 @@ mod tests { fn a_finished_job_never_leaves_its_gauge_on_screen() { isolate_state(); let mut app = App::new().expect("app"); - let node = idle_node("bar"); + let Some(node) = idle_node("bar") else { return }; let (walk, walk_progress) = crate::job::spawn("storage", move |_engine, _progress, _cancel| { std::thread::sleep(Duration::from_secs(30)); @@ -3481,7 +3513,7 @@ mod tests { #[test] fn a_finished_cleanup_scans_itself_again() { isolate_state(); - let dir = scratch("rescan"); + let Some(dir) = scratch("rescan") else { return }; let file = dir.join("junk.bin"); std::fs::write(&file, vec![7u8; 4096]).expect("junk"); @@ -3711,7 +3743,9 @@ mod tests { #[test] fn x_is_still_the_delete_key_on_a_list_of_files() { isolate_state(); - let dir = scratch("x-still-deletes"); + let Some(dir) = scratch("x-still-deletes") else { + return; + }; let (info, items) = fake_app(&dir); let mut app = App::new().expect("app"); app.delete_mode = DeleteMode::Permanent; diff --git a/crates/squid-tui/src/theme.rs b/crates/squid-tui/src/theme.rs index ebb49f6..bbf33b3 100644 --- a/crates/squid-tui/src/theme.rs +++ b/crates/squid-tui/src/theme.rs @@ -134,6 +134,7 @@ impl Strings { C::ProjectArtifacts => "构建产物", C::LanguagePacks => "多余语言包", C::Leftovers => "卸载残留", + C::UpdateInstallers => "升级安装包", C::Trash => self.bin(), }, }) diff --git a/crates/squid-tui/src/views.rs b/crates/squid-tui/src/views.rs index ba2e2bc..d21f31c 100644 --- a/crates/squid-tui/src/views.rs +++ b/crates/squid-tui/src/views.rs @@ -1404,6 +1404,7 @@ fn draw_stats(frame: &mut Frame, area: Rect, app: &App) { 100.0, ); let mem_ratio = snapshot.memory.percent_used() as f64 / 100.0; + let mem_installed = snapshot.memory.installed.max(snapshot.memory.total); meter( frame, top[1], @@ -1411,8 +1412,8 @@ fn draw_stats(frame: &mut Frame, area: Rect, app: &App) { mem_ratio, &format!( "{}/{}", - snapshot.memory.used.human(), - snapshot.memory.total.human() + snapshot.memory.used.human_binary(), + mem_installed.human_binary() ), &memory, 100.0, @@ -2052,6 +2053,7 @@ mod tests { has_sibling_install: false, publisher: None, installed_ms: None, + display_icon: None, }, // Sorted the way `build_plan` sorts: biggest first, so the bundle // is *not* the first item here. diff --git a/docs/DESKTOP.md b/docs/DESKTOP.md index d055db7..b027f72 100644 --- a/docs/DESKTOP.md +++ b/docs/DESKTOP.md @@ -49,25 +49,25 @@ cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings | Daily cleanup | Runs the normal cleanup rule set, groups results by category, supports per-item and per-category selection, Trash or permanent deletion, then offers undo through History | | Uninstall apps | Reads installed apps, builds an app-specific removal plan, shows leftover paths and warnings, then uninstalls selected items | | Deep Clean | Searches chosen project roots for regenerable build artefacts with Git and file-age protections | +| Permissions (Windows) | Startup entries from Run keys, startup folders and scheduled tasks; shell context-menu handlers; popup-window rules and the popup watcher | | Security | XProtect / Defender status, scan coverage, findings by confidence, quarantine and restore, recent security activity | | Startup items | LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; disable and re-enable the ones the current user owns | | Storage | Measures a chosen folder, exposes the largest children, drills down, and finds the largest files | -| Real-time monitor | Two tabs. **Performance**: live CPU, memory, network, disk, battery, volume and process data. **Processes**: the whole process table with signature and startup-item columns, and process termination after confirmation | +| Real-time monitor | Two tabs. **Performance**: live CPU, memory, network, disk, battery, volume and process data, plus the desktop-widget switch. **Processes**: the whole process table with signature and startup-item columns, and process termination after confirmation | +| Desktop widget | A borderless desktop-layer monitor opened from Real-time monitor, with status rings, network and disk curves, storage bars, and all settings in a dropdown at the top of the widget | | History | Lists cleanup sessions, shows the ledger, restores files that are still in Trash/Recycle Bin, and opens the bin | | Settings | Chinese/English language selection that defaults to the system language, launch at login, the security section (scan schedule, notifications, auto-quarantine, rule-pack updates, scan exclusions), deletion mode, history retention, protected paths, local file locations, and software updates | -`⌘1`–`⌘0` on macOS and `Ctrl+1`–`Ctrl+0` on Windows switch screens, in sidebar -order: `1` overview, `2` daily cleanup, `3` uninstall apps, `4` deep clean, -`5` storage, `6` real-time monitor, `7` security, `8` startup items, -`9` history, `0` settings. - -In 0.1.6 `⌘7`/`⌘8` moved from History/Settings to Security/Startup items; -History and Settings are now `⌘9` and `⌘0`. +`⌘1`–`⌘8` on macOS and `Ctrl+1`–`Ctrl+9` on Windows switch screens, in sidebar +order. On Windows: `1` overview, `2` daily cleanup, `3` uninstall apps, +`4` deep clean, `5` permissions, `6` storage, `7` real-time monitor, +`8` security, `9` startup items. macOS omits the Windows-only Permissions +screen, so `5`–`8` shift up by one. The sidebar groups these into **Maintenance** (overview, daily cleanup, -uninstall apps, deep clean), **Protection** (security, startup items) and -**Insights** (storage, real-time monitor), with History and Settings pinned at -the bottom. +uninstall apps, deep clean, and Permissions on Windows), **Protection** +(security, startup items) and **Insights** (storage, real-time monitor), with +History and Settings pinned at the bottom. The two new screens reuse the interface vocabulary the older screens already had rather than introducing a second one: `.panel` for a card, `.status-chip` for @@ -107,12 +107,53 @@ this page only reads what they report. Squid keeps running after its main window is closed. The tray menu can reopen the window, start a malware scan, and jump directly to Security, Startup items, -Daily cleanup, Uninstall apps or Deep Clean. One disabled row states the current -protection status — the count of unhandled confirmed findings, "not scanned yet" -before the first scan, and "scanning…" while one is running. +Daily cleanup, Uninstall apps, Deep Clean or the desktop widget. One disabled row +states the current protection status — the count of unhandled confirmed findings, +"not scanned yet" before the first scan, and "scanning…" while one is running. The tray follows the active interface language. Use **Quit Squid** in the same menu to stop the background process. +The tray mark is a transparent monochrome asset. macOS receives it with +`.icon_as_template(true)`, so the system draws it in the correct menu-bar colour +for light and dark appearances instead of pasting a coloured square onto the +bar. Windows and Linux keep the same silhouette in gray. + +## Permissions (Windows) + +The Permissions screen is a Windows-only destination and is hidden from the +macOS sidebar, where the Startup items screen already covers LaunchAgents, +LaunchDaemons and login items with the same safety rules. On Windows it lists: + +- startup entries from `Run` keys, startup folders and scheduled tasks; +- shell context-menu handlers grouped by file, folder, desktop, drive and + all-object surfaces; +- popup windows with rules to block or allow them and a background watcher. + +Every enable/disable action goes through the backend's inventory; the page never +submits a raw registry or filesystem path. + +## Desktop widget + +The desktop widget is switched on from Real-time monitor and is a separate Tauri +webview window labelled `widget`, not a WidgetKit extension. It shares the live +sampler with the Real-time monitor but polls at its own 2/5/10-second cadence and +pauses while hidden. + +- The gear at the top of the widget opens a dropdown containing every setting: + panel switches, opacity, refresh rate, dock corner and fold memory. +- Up to four cards: status rings (CPU, memory, and GPU when the OS exposes a + busy counter), network throughput, disk I/O, and storage volumes. +- The window is borderless, transparent and resizable only by its content. It + docks to a chosen corner and remembers a manual drag position. +- On macOS it uses `BelowNormal` window level, appears on every Space, and is + non-focusable with `accept_first_mouse`, so it sits with the desktop and never + takes keyboard focus from the app you are using. +- On Windows it is parked with `SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)` for + the same desktop-layer behaviour. +- Opacity is capped to 90–100% so text stays readable over busy wallpapers. + The master switch and the tray item share one state; settings persist in + `widget.json` beside `manage.json`. + **Settings → Startup** registers the app for the current user only. macOS uses a user LaunchAgent, Windows uses the current-user Run key, and Linux uses an XDG autostart desktop entry. Enabling or disabling launch at login does not diff --git a/docs/RELEASE.md b/docs/RELEASE.md index c415f41..5433a99 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -53,6 +53,37 @@ toolchain instead of `cargo-xwin`. The installer is per-user and installs to: The executable inside is `squid-desktop.exe`, matching both the NSIS installer and the update handoff script. +### 360/电脑管家 environments: ship 一键安装.bat (mandatory) + +On the developer machine (and other boxes running 腾讯电脑管家/360), the +endpoint protector blocks **unsigned installers started from a non-system +drive** from unpacking into `%TEMP%`: double-clicking +`release//Squid-Setup-*.exe` on D: dies with +`NSIS Error - Error writing temporary file` — or worse, a silent `/S` run +exits 0 without installing anything. The same installer run from `C:\Users\\ +AppData\Local\Temp` works, verified live. + +Therefore every release directory must contain `一键安装.bat` next to the +setup exe: it copies the installer into `%TEMP%` (C:) and launches it from +there. The README's 提示 section documents this as remedy #1. When assembling +a new release, create the batch (ASCII encoding, version-pinned filename) and +test it once — the wizard window must appear with no NSIS dialog. + + +### Over-the-top install (custom NSIS template) + +`bundle.windows.nsis.template` points at `src-tauri/nsis/installer.nsi`, a copy +of the `@tauri-apps/cli` default template with one change: the "detected an +older version — uninstall or reinstall?" page calls `Abort` unless a legacy WiX +install is found, so upgrades overwrite the previous install in place (inheriting +`$INSTDIR` from the registry) instead of prompting. User settings live under +`%APPDATA%\squid` and are never touched by install or uninstall, so they carry +across upgrades automatically. + +Because it is a full template copy, re-sync it whenever `@tauri-apps/cli` (and +thus the bundled `installer.nsi`) is upgraded: re-copy the new template and +re-apply the `Abort` block in `Function PageReinstall`. + ## Signing key Create the Ed25519 key once, outside the repository: diff --git a/package.json b/package.json index b74605c..43ed9a1 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "squid-desktop", "private": true, - "version": "0.1.7", + "version": "0.1.9", "type": "module", "scripts": { "dev": "vite --port 1420 --strictPort", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 93ed4cc..b4636b8 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4760,7 +4760,7 @@ dependencies = [ [[package]] name = "squid-core" -version = "0.1.7" +version = "0.1.9" dependencies = [ "anyhow", "chrono", @@ -4779,7 +4779,7 @@ dependencies = [ [[package]] name = "squid-desktop" -version = "0.1.7" +version = "0.1.9" dependencies = [ "base64 0.22.1", "chrono", @@ -4806,7 +4806,7 @@ dependencies = [ [[package]] name = "squid-engine" -version = "0.1.7" +version = "0.1.9" dependencies = [ "anyhow", "chrono", @@ -4826,7 +4826,7 @@ dependencies = [ [[package]] name = "squid-guard" -version = "0.1.7" +version = "0.1.9" dependencies = [ "chrono", "hex", @@ -4842,7 +4842,7 @@ dependencies = [ [[package]] name = "squid-platform" -version = "0.1.7" +version = "0.1.9" dependencies = [ "dirs 6.0.0", "file_icon_provider", @@ -4862,7 +4862,7 @@ dependencies = [ [[package]] name = "squid-rules" -version = "0.1.7" +version = "0.1.9" dependencies = [ "globset", "serde", @@ -4874,7 +4874,7 @@ dependencies = [ [[package]] name = "squid-stats" -version = "0.1.7" +version = "0.1.9" dependencies = [ "chrono", "libc", @@ -4882,6 +4882,7 @@ dependencies = [ "squid-core", "squid-platform", "sysinfo", + "windows-sys 0.59.0", ] [[package]] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b1398ff..d77c6c1 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "squid-desktop" -version = "0.1.7" +version = "0.1.9" description = "Squid — a CleanMyMac-inspired cleaner, uninstaller and system monitor." authors = ["squid contributors"] edition = "2021" diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index e826989..fde570d 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -1,11 +1,16 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", - "description": "Default permissions for the Squid main window.", - "windows": ["main"], + "description": "Default permissions for the Squid main and widget windows.", + "windows": ["main", "widget"], "permissions": [ "core:default", "core:window:allow-start-dragging", + "core:window:allow-hide", + "core:window:allow-show", + "core:window:allow-set-size", + "core:window:allow-set-focus", + "core:window:allow-is-visible", "dialog:default", "opener:default", "notification:default" diff --git a/src-tauri/icons/tray-template.png b/src-tauri/icons/tray-template.png new file mode 100644 index 0000000..ae43c26 Binary files /dev/null and b/src-tauri/icons/tray-template.png differ diff --git a/src-tauri/nsis/installer.nsi b/src-tauri/nsis/installer.nsi new file mode 100644 index 0000000..a5dd067 --- /dev/null +++ b/src-tauri/nsis/installer.nsi @@ -0,0 +1,1003 @@ +Unicode true +ManifestDPIAware true +; Add in `dpiAwareness` `PerMonitorV2` to manifest for Windows 10 1607+ (note this should not affect lower versions since they should be able to ignore this and pick up `dpiAware` `true` set by `ManifestDPIAware true`) +; Currently undocumented on NSIS's website but is in the Docs folder of source tree, see +; https://github.com/kichik/nsis/blob/5fc0b87b819a9eec006df4967d08e522ddd651c9/Docs/src/attributes.but#L286-L300 +; https://github.com/tauri-apps/tauri/pull/10106 +ManifestDPIAwareness PerMonitorV2 + +!if "{{compression}}" == "none" + SetCompress off +!else + ; Set the compression algorithm. We default to LZMA. + SetCompressor /SOLID "{{compression}}" +!endif + +; Keep above !include to stay ahead of any plugin command +; see https://github.com/tauri-apps/tauri/pull/15422#discussion_r3289239624 +{{#if signed_plugins_path}} +!addplugindir "{{signed_plugins_path}}" +{{/if}} + +!include MUI2.nsh +!include FileFunc.nsh +!include x64.nsh +!include WordFunc.nsh +!include "utils.nsh" +!include "FileAssociation.nsh" +!include "Win\COM.nsh" +!include "Win\Propkey.nsh" +!include "Win\RestartManager.nsh" +!include "StrFunc.nsh" +${StrCase} +${StrLoc} + +{{#if installer_hooks}} +!include "{{installer_hooks}}" +{{/if}} + +!define WEBVIEW2APPGUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" + +!define MANUFACTURER "{{manufacturer}}" +!define PRODUCTNAME "{{product_name}}" +!define VERSION "{{version}}" +!define VERSIONWITHBUILD "{{version_with_build}}" +!define HOMEPAGE "{{homepage}}" +!define INSTALLMODE "{{install_mode}}" +!define LICENSE "{{license}}" +!define INSTALLERICON "{{installer_icon}}" +!define SIDEBARIMAGE "{{sidebar_image}}" +!define HEADERIMAGE "{{header_image}}" +!define UNINSTALLERICON "{{uninstaller_icon}}" +!define UNINSTALLERHEADERIMAGE "{{uninstaller_header_image}}" +!define MAINBINARYNAME "{{main_binary_name}}" +!define MAINBINARYSRCPATH "{{main_binary_path}}" +!define BUNDLEID "{{bundle_id}}" +!define COPYRIGHT "{{copyright}}" +!define OUTFILE "{{out_file}}" +!define ARCH "{{arch}}" +!define ADDITIONALPLUGINSPATH "{{additional_plugins_path}}" +!define ALLOWDOWNGRADES "{{allow_downgrades}}" +!define DISPLAYLANGUAGESELECTOR "{{display_language_selector}}" +!define INSTALLWEBVIEW2MODE "{{install_webview2_mode}}" +!define WEBVIEW2INSTALLERARGS "{{webview2_installer_args}}" +!define WEBVIEW2BOOTSTRAPPERPATH "{{webview2_bootstrapper_path}}" +!define WEBVIEW2INSTALLERPATH "{{webview2_installer_path}}" +!define MINIMUMWEBVIEW2VERSION "{{minimum_webview2_version}}" +!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCTNAME}" +!define MANUKEY "Software\${MANUFACTURER}" +!define MANUPRODUCTKEY "${MANUKEY}\${PRODUCTNAME}" +!define UNINSTALLERSIGNCOMMAND "{{uninstaller_sign_cmd}}" +!define ESTIMATEDSIZE "{{estimated_size}}" +!define STARTMENUFOLDER "{{start_menu_folder}}" + +Var PassiveMode +Var UpdateMode +Var NoShortcutMode +Var WixMode +Var OldMainBinaryName + +Name "${PRODUCTNAME}" +BrandingText "${COPYRIGHT}" +OutFile "${OUTFILE}" + +; We don't actually use this value as default install path, +; it's just for nsis to append the product name folder in the directory selector +; https://nsis.sourceforge.io/Reference/InstallDir +!define PLACEHOLDER_INSTALL_DIR "placeholder\${PRODUCTNAME}" +InstallDir "${PLACEHOLDER_INSTALL_DIR}" + +VIProductVersion "${VERSIONWITHBUILD}" +VIAddVersionKey "ProductName" "${PRODUCTNAME}" +VIAddVersionKey "FileDescription" "${PRODUCTNAME}" +VIAddVersionKey "LegalCopyright" "${COPYRIGHT}" +VIAddVersionKey "FileVersion" "${VERSION}" +VIAddVersionKey "ProductVersion" "${VERSION}" + +# additional plugins +!addplugindir "${ADDITIONALPLUGINSPATH}" + +; Uninstaller signing command +!if "${UNINSTALLERSIGNCOMMAND}" != "" + !uninstfinalize '${UNINSTALLERSIGNCOMMAND}' +!endif + +; Handle install mode, `perUser`, `perMachine` or `both` +!if "${INSTALLMODE}" == "perMachine" + RequestExecutionLevel admin +!endif + +!if "${INSTALLMODE}" == "currentUser" + RequestExecutionLevel user +!endif + +!if "${INSTALLMODE}" == "both" + !define MULTIUSER_MUI + !define MULTIUSER_INSTALLMODE_INSTDIR "${PRODUCTNAME}" + !define MULTIUSER_INSTALLMODE_COMMANDLINE + !if "${ARCH}" == "x64" + !define MULTIUSER_USE_PROGRAMFILES64 + !else if "${ARCH}" == "arm64" + !define MULTIUSER_USE_PROGRAMFILES64 + !endif + !define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_KEY "${UNINSTKEY}" + !define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_VALUENAME "CurrentUser" + !define MULTIUSER_INSTALLMODEPAGE_SHOWUSERNAME + !define MULTIUSER_INSTALLMODE_FUNCTION RestorePreviousInstallLocation + !define MULTIUSER_EXECUTIONLEVEL Highest + !include MultiUser.nsh +!endif + +; Installer icon +!if "${INSTALLERICON}" != "" + !define MUI_ICON "${INSTALLERICON}" +!endif + +; Installer sidebar image +!if "${SIDEBARIMAGE}" != "" + !define MUI_WELCOMEFINISHPAGE_BITMAP "${SIDEBARIMAGE}" +!endif + +; Enable header images for installer and uninstaller pages when either image is configured. +!if "${HEADERIMAGE}" != "" + !define MUI_HEADERIMAGE +!else if "${UNINSTALLERHEADERIMAGE}" != "" + !define MUI_HEADERIMAGE +!endif + +; Installer header image +!if "${HEADERIMAGE}" != "" + !define MUI_HEADERIMAGE_BITMAP "${HEADERIMAGE}" +!endif + +; Uninstaller header image +!if "${UNINSTALLERHEADERIMAGE}" != "" + !define MUI_HEADERIMAGE_UNBITMAP "${UNINSTALLERHEADERIMAGE}" +!endif + +; Uninstaller icon +!if "${UNINSTALLERICON}" != "" + !define MUI_UNICON "${UNINSTALLERICON}" +!endif + +; Define registry key to store installer language +!define MUI_LANGDLL_REGISTRY_ROOT "HKCU" +!define MUI_LANGDLL_REGISTRY_KEY "${MANUPRODUCTKEY}" +!define MUI_LANGDLL_REGISTRY_VALUENAME "Installer Language" + +; Installer pages, must be ordered as they appear +; 1. Welcome Page +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_WELCOME + +; 2. License Page (if defined) +!if "${LICENSE}" != "" + !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive + !insertmacro MUI_PAGE_LICENSE "${LICENSE}" +!endif + +; 3. Install mode (if it is set to `both`) +!if "${INSTALLMODE}" == "both" + !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive + !insertmacro MULTIUSER_PAGE_INSTALLMODE +!endif + +; 4. Custom page to ask user if he wants to reinstall/uninstall +; only if a previous installation was detected +Var ReinstallPageCheck +Page custom PageReinstall PageLeaveReinstall +Function PageReinstall + ; Uninstall previous WiX installation if exists. + ; + ; A WiX installer stores the installation info in registry + ; using a UUID and so we have to loop through all keys under + ; `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall` + ; and check if `DisplayName` and `Publisher` keys match ${PRODUCTNAME} and ${MANUFACTURER} + ; + ; This has a potential issue that there maybe another installation that matches + ; our ${PRODUCTNAME} and ${MANUFACTURER} but wasn't installed by our WiX installer, + ; however, this should be fine since the user will have to confirm the uninstallation + ; and they can chose to abort it if doesn't make sense. + StrCpy $0 0 + wix_loop: + EnumRegKey $1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $0 + StrCmp $1 "" wix_loop_done ; Exit loop if there is no more keys to loop on + IntOp $0 $0 + 1 + ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "DisplayName" + ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "Publisher" + StrCmp "$R0$R1" "${PRODUCTNAME}${MANUFACTURER}" 0 wix_loop + ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "UninstallString" + ${StrCase} $R1 $R0 "L" + ${StrLoc} $R0 $R1 "msiexec" ">" + StrCmp $R0 0 0 wix_loop_done + StrCpy $WixMode 1 + StrCpy $R6 "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" + Goto compare_version + wix_loop_done: + + ; Check if there is an existing installation, if not, abort the reinstall page + ReadRegStr $R0 SHCTX "${UNINSTKEY}" "" + ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString" + ${IfThen} "$R0$R1" == "" ${|} Abort ${|} + + ; Compare this installar version with the existing installation + ; and modify the messages presented to the user accordingly + compare_version: + StrCpy $R4 "$(older)" + ${If} $WixMode = 1 + ReadRegStr $R0 HKLM "$R6" "DisplayVersion" + ${Else} + ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion" + ${EndIf} + ${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|} + + nsis_tauri_utils::SemverCompare "${VERSION}" $R0 + Pop $R0 + ; Reinstalling the same version + ${If} $R0 = 0 + StrCpy $R1 "$(alreadyInstalledLong)" + StrCpy $R2 "$(addOrReinstall)" + StrCpy $R3 "$(uninstallApp)" + !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(chooseMaintenanceOption)" + ; Upgrading + ${ElseIf} $R0 = 1 + StrCpy $R1 "$(olderOrUnknownVersionInstalled)" + StrCpy $R2 "$(uninstallBeforeInstalling)" + StrCpy $R3 "$(dontUninstall)" + !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)" + ; Downgrading + ${ElseIf} $R0 = -1 + StrCpy $R1 "$(newerVersionInstalled)" + StrCpy $R2 "$(uninstallBeforeInstalling)" + !if "${ALLOWDOWNGRADES}" == "true" + StrCpy $R3 "$(dontUninstall)" + !else + StrCpy $R3 "$(dontUninstallDowngrade)" + !endif + !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)" + ${Else} + Abort + ${EndIf} + + ; Squid customization (keep in sync when upgrading @tauri-apps/cli): + ; when replacing an earlier NSIS install, never show the uninstall-old + ; version page. Abort skips the page, so the installer simply overwrites + ; the inherited $INSTDIR (RestorePreviousInstallLocation) in place. User + ; settings live in %APPDATA%\squid and are untouched by both flows. + ; WiX-era installs keep the original cleanup prompt. + ${If} $WixMode = 0 + Abort + ${EndIf} + + ; Skip showing the page if passive + ; + ; Note that we don't call this earlier at the beginning + ; of this function because we need to populate some variables + ; related to current installed version if detected and whether + ; we are downgrading or not. + ${If} $PassiveMode = 1 + Call PageLeaveReinstall + ${Else} + nsDialogs::Create 1018 + Pop $R4 + ${IfThen} $(^RTL) = 1 ${|} nsDialogs::SetRTL $(^RTL) ${|} + + ${NSD_CreateLabel} 0 0 100% 24u $R1 + Pop $R1 + + ${NSD_CreateRadioButton} 30u 50u -30u 8u $R2 + Pop $R2 + ${NSD_OnClick} $R2 PageReinstallUpdateSelection + + ${NSD_CreateRadioButton} 30u 70u -30u 8u $R3 + Pop $R3 + ; Disable this radio button if downgrading and downgrades are disabled + !if "${ALLOWDOWNGRADES}" == "false" + ${IfThen} $R0 = -1 ${|} EnableWindow $R3 0 ${|} + !endif + ${NSD_OnClick} $R3 PageReinstallUpdateSelection + + ; Check the first radio button if this the first time + ; we enter this page or if the second button wasn't + ; selected the last time we were on this page + ${If} $ReinstallPageCheck <> 2 + SendMessage $R2 ${BM_SETCHECK} ${BST_CHECKED} 0 + ${Else} + SendMessage $R3 ${BM_SETCHECK} ${BST_CHECKED} 0 + ${EndIf} + + ${NSD_SetFocus} $R2 + nsDialogs::Show + ${EndIf} +FunctionEnd +Function PageReinstallUpdateSelection + ${NSD_GetState} $R2 $R1 + ${If} $R1 == ${BST_CHECKED} + StrCpy $ReinstallPageCheck 1 + ${Else} + StrCpy $ReinstallPageCheck 2 + ${EndIf} +FunctionEnd +Function PageLeaveReinstall + ${NSD_GetState} $R2 $R1 + + ; If migrating from Wix, always uninstall + ${If} $WixMode = 1 + Goto reinst_uninstall + ${EndIf} + + ; In update mode, always proceeds without uninstalling + ${If} $UpdateMode = 1 + Goto reinst_done + ${EndIf} + + ; $R0 holds whether same(0)/upgrading(1)/downgrading(-1) version + ; $R1 holds the radio buttons state: + ; 1 => first choice was selected + ; 0 => second choice was selected + ${If} $R0 = 0 ; Same version, proceed + ${If} $R1 = 1 ; User chose to add/reinstall + Goto reinst_done + ${Else} ; User chose to uninstall + Goto reinst_uninstall + ${EndIf} + ${ElseIf} $R0 = 1 ; Upgrading + ${If} $R1 = 1 ; User chose to uninstall + Goto reinst_uninstall + ${Else} + Goto reinst_done ; User chose NOT to uninstall + ${EndIf} + ${ElseIf} $R0 = -1 ; Downgrading + ${If} $R1 = 1 ; User chose to uninstall + Goto reinst_uninstall + ${Else} + Goto reinst_done ; User chose NOT to uninstall + ${EndIf} + ${EndIf} + + reinst_uninstall: + HideWindow + ClearErrors + + ${If} $WixMode = 1 + ReadRegStr $R1 HKLM "$R6" "UninstallString" + ExecWait '$R1' $0 + ${Else} + ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" "" + ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString" + ${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE + ${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P + StrCpy $R1 "$R1 _?=$4" ; append uninstall directory + ExecWait '$R1' $0 + ${EndIf} + + BringToFront + + ${IfThen} ${Errors} ${|} StrCpy $0 2 ${|} ; ExecWait failed, set fake exit code + + ${If} $0 <> 0 + ${OrIf} ${FileExists} "$INSTDIR\${MAINBINARYNAME}.exe" + ; User cancelled wix uninstaller? return to select un/reinstall page + ${If} $WixMode = 1 + ${AndIf} $0 = 1602 + Abort + ${EndIf} + + ; User cancelled NSIS uninstaller? return to select un/reinstall page + ${If} $0 = 1 + Abort + ${EndIf} + + ; Other errors? show generic error message and return to select un/reinstall page + MessageBox MB_ICONEXCLAMATION "$(unableToUninstall)" + Abort + ${EndIf} + + ; The NSIS uninstaller was run in place (`_?=`), so it cannot delete itself + ; and the install directory, clean them up here once the uninstall succeeded + ; https://nsis.sourceforge.io/Docs/Chapter3.html#:~:text=path%20contains%20spaces.-,3.2.3%20Examples,-installer.exe%20/NCRC + ${If} $WixMode = 0 + ${AndIf} $4 != "" + Delete "$4\uninstall.exe" + RMDir "$4" + ${EndIf} + reinst_done: +FunctionEnd + +; 5. Choose install directory page +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_DIRECTORY + +; 6. Start menu shortcut page +Var AppStartMenuFolder +!if "${STARTMENUFOLDER}" != "" + !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive + !define MUI_STARTMENUPAGE_DEFAULTFOLDER "${STARTMENUFOLDER}" +!else + !define MUI_PAGE_CUSTOMFUNCTION_PRE Skip +!endif +!insertmacro MUI_PAGE_STARTMENU Application $AppStartMenuFolder + +; 7. Installation page +!insertmacro MUI_PAGE_INSTFILES + +; 8. Finish page +; +; Don't auto jump to finish page after installation page, +; because the installation page has useful info that can be used debug any issues with the installer. +!define MUI_FINISHPAGE_NOAUTOCLOSE +; Use show readme button in the finish page as a button create a desktop shortcut +!define MUI_FINISHPAGE_SHOWREADME +!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(createDesktop)" +!define MUI_FINISHPAGE_SHOWREADME_FUNCTION CreateOrUpdateDesktopShortcut +; Show run app after installation. +!define MUI_FINISHPAGE_RUN +!define MUI_FINISHPAGE_RUN_FUNCTION RunMainBinary +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_FINISH + +Function RunMainBinary + nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "" +FunctionEnd + +; Uninstaller Pages +; 1. Confirm uninstall page +Var DeleteAppDataCheckbox +Var DeleteAppDataCheckboxState +!define /ifndef WS_EX_LAYOUTRTL 0x00400000 +!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ConfirmShow +Function un.ConfirmShow ; Add add a `Delete app data` check box + ; $1 inner dialog HWND + ; $2 window DPI + ; $3 style + ; $4 x + ; $5 y + ; $6 width + ; $7 height + FindWindow $1 "#32770" "" $HWNDPARENT ; Find inner dialog + System::Call "user32::GetDpiForWindow(p r1) i .r2" + ${If} $(^RTL) = 1 + StrCpy $3 "${__NSD_CheckBox_EXSTYLE} | ${WS_EX_LAYOUTRTL}" + IntOp $4 50 * $2 + ${Else} + StrCpy $3 "${__NSD_CheckBox_EXSTYLE}" + IntOp $4 0 * $2 + ${EndIf} + IntOp $5 100 * $2 + IntOp $6 400 * $2 + IntOp $7 25 * $2 + IntOp $4 $4 / 96 + IntOp $5 $5 / 96 + IntOp $6 $6 / 96 + IntOp $7 $7 / 96 + System::Call 'user32::CreateWindowEx(i r3, w "${__NSD_CheckBox_CLASS}", w "$(deleteAppData)", i ${__NSD_CheckBox_STYLE}, i r4, i r5, i r6, i r7, p r1, i0, i0, i0) i .s' + Pop $DeleteAppDataCheckbox + SendMessage $HWNDPARENT ${WM_GETFONT} 0 0 $1 + SendMessage $DeleteAppDataCheckbox ${WM_SETFONT} $1 1 +FunctionEnd +!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.ConfirmLeave +Function un.ConfirmLeave + SendMessage $DeleteAppDataCheckbox ${BM_GETCHECK} 0 0 $DeleteAppDataCheckboxState +FunctionEnd +!define MUI_PAGE_CUSTOMFUNCTION_PRE un.SkipIfPassive +!insertmacro MUI_UNPAGE_CONFIRM + +; 2. Uninstalling Page +!insertmacro MUI_UNPAGE_INSTFILES + +;Languages +{{#each languages}} +!insertmacro MUI_LANGUAGE "{{this}}" +{{/each}} +!insertmacro MUI_RESERVEFILE_LANGDLL +{{#each language_files}} + !include "{{this}}" +{{/each}} + +Function .onInit + ${GetOptions} $CMDLINE "/P" $PassiveMode + ${IfNot} ${Errors} + StrCpy $PassiveMode 1 + ${EndIf} + + ${GetOptions} $CMDLINE "/NS" $NoShortcutMode + ${IfNot} ${Errors} + StrCpy $NoShortcutMode 1 + ${EndIf} + + ${GetOptions} $CMDLINE "/UPDATE" $UpdateMode + ${IfNot} ${Errors} + StrCpy $UpdateMode 1 + ${EndIf} + + !if "${DISPLAYLANGUAGESELECTOR}" == "true" + !insertmacro MUI_LANGDLL_DISPLAY + !endif + + !insertmacro SetContext + + ${If} $INSTDIR == "${PLACEHOLDER_INSTALL_DIR}" + ; Set default install location + !if "${INSTALLMODE}" == "perMachine" + ${If} ${RunningX64} + !if "${ARCH}" == "x64" + StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}" + !else if "${ARCH}" == "arm64" + StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}" + !else + StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}" + !endif + ${Else} + StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}" + ${EndIf} + !else if "${INSTALLMODE}" == "currentUser" + StrCpy $INSTDIR "$LOCALAPPDATA\${PRODUCTNAME}" + !endif + + Call RestorePreviousInstallLocation + ${EndIf} + + + !if "${INSTALLMODE}" == "both" + !insertmacro MULTIUSER_INIT + !endif + + ; Abort downgrades if they are disabled, in the modes that skip the reinstall page choice: + ; silent, passive and update + !if "${ALLOWDOWNGRADES}" == "false" + ${If} ${Silent} + ${OrIf} $PassiveMode = 1 + ${OrIf} $UpdateMode = 1 + ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion" + nsis_tauri_utils::SemverCompare "${VERSION}" $R0 + Pop $R0 + ; If downgrading + ${If} $R0 = -1 + ${If} ${Silent} + System::Call 'kernel32::AttachConsole(i -1)i.r0' + ${If} $0 <> 0 + System::Call 'kernel32::GetStdHandle(i -11)i.r0' + System::call 'kernel32::SetConsoleTextAttribute(i r0, i 0x0004)' ; set red color + FileWrite $0 "$(silentDowngrades)" + ${EndIf} + ${Else} + MessageBox MB_ICONSTOP "$(silentDowngrades)" + ${EndIf} + Abort + ${EndIf} + ${EndIf} + !endif +FunctionEnd + +Section WebView2 + ; Check if Webview2 is already installed and skip this section + ${If} ${RunningX64} + ReadRegStr $4 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${Else} + ReadRegStr $4 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${EndIf} + ${If} $4 == "" + ReadRegStr $4 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${EndIf} + + ${If} $4 == "" + ; Webview2 installation + ; + ; Skip if updating + ${If} $UpdateMode <> 1 + !if "${INSTALLWEBVIEW2MODE}" == "downloadBootstrapper" + Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe" + DetailPrint "$(webview2Downloading)" + NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe" + Pop $0 + ${If} $0 == "success" + DetailPrint "$(webview2DownloadSuccess)" + ${Else} + DetailPrint "$(webview2DownloadError)" + Abort "$(webview2AbortError)" + ${EndIf} + StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe" + Goto install_webview2 + !endif + + !if "${INSTALLWEBVIEW2MODE}" == "embedBootstrapper" + Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe" + File "/oname=$TEMP\MicrosoftEdgeWebview2Setup.exe" "${WEBVIEW2BOOTSTRAPPERPATH}" + DetailPrint "$(installingWebview2)" + StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe" + Goto install_webview2 + !endif + + !if "${INSTALLWEBVIEW2MODE}" == "offlineInstaller" + Delete "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" + File "/oname=$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" "${WEBVIEW2INSTALLERPATH}" + DetailPrint "$(installingWebview2)" + StrCpy $6 "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" + Goto install_webview2 + !endif + + Goto webview2_done + + install_webview2: + DetailPrint "$(installingWebview2)" + ; $6 holds the path to the webview2 installer + ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1 + ${If} $1 = 0 + DetailPrint "$(webview2InstallSuccess)" + ${Else} + DetailPrint "$(webview2InstallError)" + Abort "$(webview2AbortError)" + ${EndIf} + webview2_done: + ${EndIf} + ${Else} + !if "${MINIMUMWEBVIEW2VERSION}" != "" + ${VersionCompare} "${MINIMUMWEBVIEW2VERSION}" "$4" $R0 + ${If} $R0 = 1 + update_webview: + DetailPrint "$(installingWebview2)" + ${If} ${RunningX64} + ReadRegStr $R1 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate" "path" + ${Else} + ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\EdgeUpdate" "path" + ${EndIf} + ${If} $R1 == "" + ReadRegStr $R1 HKCU "SOFTWARE\Microsoft\EdgeUpdate" "path" + ${EndIf} + ${If} $R1 != "" + ; Chromium updater docs: https://source.chromium.org/chromium/chromium/src/+/main:docs/updater/user_manual.md + ; Modified from "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView\ModifyPath" + ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $1 + ${If} $1 = 0 + DetailPrint "$(webview2InstallSuccess)" + ${Else} + MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" IDIGNORE ignore IDRETRY update_webview + Quit + ignore: + ${EndIf} + ${EndIf} + ${EndIf} + !endif + ${EndIf} +SectionEnd + +Section Install + SetOutPath $INSTDIR + + !ifmacrodef NSIS_HOOK_PREINSTALL + !insertmacro NSIS_HOOK_PREINSTALL + !endif + + !insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}" + + ; Copy main executable + File "${MAINBINARYSRCPATH}" + + ; Copy resources + {{#each resources_dirs}} + CreateDirectory "$INSTDIR\\{{this}}" + {{/each}} + {{#each resources}} + File /a "/oname={{this.[1]}}" "{{no-escape @key}}" + {{/each}} + + ; Copy external binaries + {{#each binaries}} + File /a "/oname={{this}}" "{{no-escape @key}}" + {{/each}} + + ; Create file associations + {{#each file_associations as |association| ~}} + {{#each association.ext as |ext| ~}} + !insertmacro APP_ASSOCIATE "{{ext}}" "{{or association.name ext}}" "{{association-description association.description ext}}" "$INSTDIR\${MAINBINARYNAME}.exe,0" "Open with ${PRODUCTNAME}" "$INSTDIR\${MAINBINARYNAME}.exe $\"%1$\"" + {{/each}} + {{/each}} + + ; Register deep links + {{#each deep_link_protocols as |protocol| ~}} + WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "URL Protocol" "" + WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "" "URL:${BUNDLEID} protocol" + WriteRegStr SHCTX "Software\Classes\\{{protocol}}\DefaultIcon" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\",0" + WriteRegStr SHCTX "Software\Classes\\{{protocol}}\shell\open\command" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\"" + {{/each}} + + ; Create uninstaller + WriteUninstaller "$INSTDIR\uninstall.exe" + + ; Save $INSTDIR in registry for future installations + WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR + + !if "${INSTALLMODE}" == "both" + ; Save install mode to be selected by default for the next installation such as updating + ; or when uninstalling + WriteRegStr SHCTX "${UNINSTKEY}" $MultiUser.InstallMode 1 + !endif + + ; Remove old main binary if it doesn't match new main binary name + ReadRegStr $OldMainBinaryName SHCTX "${UNINSTKEY}" "MainBinaryName" + ${If} $OldMainBinaryName != "" + ${AndIf} $OldMainBinaryName != "${MAINBINARYNAME}.exe" + Delete "$INSTDIR\$OldMainBinaryName" + ${EndIf} + + ; Save current MAINBINARYNAME for future updates + WriteRegStr SHCTX "${UNINSTKEY}" "MainBinaryName" "${MAINBINARYNAME}.exe" + + ; Registry information for add/remove programs + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}" + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayIcon" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\"" + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayVersion" "${VERSION}" + WriteRegStr SHCTX "${UNINSTKEY}" "Publisher" "${MANUFACTURER}" + WriteRegStr SHCTX "${UNINSTKEY}" "InstallLocation" "$\"$INSTDIR$\"" + WriteRegStr SHCTX "${UNINSTKEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\"" + WriteRegDWORD SHCTX "${UNINSTKEY}" "NoModify" "1" + WriteRegDWORD SHCTX "${UNINSTKEY}" "NoRepair" "1" + + ${GetSize} "$INSTDIR" "/M=uninstall.exe /S=0K /G=0" $0 $1 $2 + IntOp $0 $0 + ${ESTIMATEDSIZE} + IntFmt $0 "0x%08X" $0 + WriteRegDWORD SHCTX "${UNINSTKEY}" "EstimatedSize" "$0" + + !if "${HOMEPAGE}" != "" + WriteRegStr SHCTX "${UNINSTKEY}" "URLInfoAbout" "${HOMEPAGE}" + WriteRegStr SHCTX "${UNINSTKEY}" "URLUpdateInfo" "${HOMEPAGE}" + WriteRegStr SHCTX "${UNINSTKEY}" "HelpLink" "${HOMEPAGE}" + !endif + + ; Create start menu shortcut + !insertmacro MUI_STARTMENU_WRITE_BEGIN Application + Call CreateOrUpdateStartMenuShortcut + !insertmacro MUI_STARTMENU_WRITE_END + + ; Create desktop shortcut for silent and passive installers + ; because finish page will be skipped + ${If} $PassiveMode = 1 + ${OrIf} ${Silent} + Call CreateOrUpdateDesktopShortcut + ${EndIf} + + !ifmacrodef NSIS_HOOK_POSTINSTALL + !insertmacro NSIS_HOOK_POSTINSTALL + !endif + + ; Auto close this page for passive mode + ${If} $PassiveMode = 1 + SetAutoClose true + ${EndIf} +SectionEnd + +Function .onInstSuccess + ; Check for `/R` flag only in silent and passive installers because + ; GUI installer has a toggle for the user to (re)start the app + ${If} $PassiveMode = 1 + ${OrIf} ${Silent} + ${GetOptions} $CMDLINE "/R" $R0 + ${IfNot} ${Errors} + ${GetOptions} $CMDLINE "/ARGS" $R0 + nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "$R0" + ${EndIf} + ${EndIf} +FunctionEnd + +Function un.onInit + !insertmacro SetContext + + !if "${INSTALLMODE}" == "both" + !insertmacro MULTIUSER_UNINIT + !endif + + !insertmacro MUI_UNGETLANGUAGE + + ${GetOptions} $CMDLINE "/P" $PassiveMode + ${IfNot} ${Errors} + StrCpy $PassiveMode 1 + ${EndIf} + + ${GetOptions} $CMDLINE "/UPDATE" $UpdateMode + ${IfNot} ${Errors} + StrCpy $UpdateMode 1 + ${EndIf} +FunctionEnd + +Section Uninstall + + !ifmacrodef NSIS_HOOK_PREUNINSTALL + !insertmacro NSIS_HOOK_PREUNINSTALL + !endif + + !insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}" + + ; Delete the app directory and its content from disk + ; Copy main executable + Delete "$INSTDIR\${MAINBINARYNAME}.exe" + + ; Delete resources + {{#each resources}} + Delete "$INSTDIR\\{{this.[1]}}" + {{/each}} + + ; Delete external binaries + {{#each binaries}} + Delete "$INSTDIR\\{{this}}" + {{/each}} + + ; Delete app associations + {{#each file_associations as |association| ~}} + {{#each association.ext as |ext| ~}} + !insertmacro APP_UNASSOCIATE "{{ext}}" "{{or association.name ext}}" + {{/each}} + {{/each}} + + ; Delete deep links + {{#each deep_link_protocols as |protocol| ~}} + ReadRegStr $R7 SHCTX "Software\Classes\\{{protocol}}\shell\open\command" "" + ${If} $R7 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\"" + DeleteRegKey SHCTX "Software\Classes\\{{protocol}}" + ${EndIf} + {{/each}} + + + ; Delete uninstaller + Delete "$INSTDIR\uninstall.exe" + + {{#each resources_ancestors}} + RMDir /REBOOTOK "$INSTDIR\\{{this}}" + {{/each}} + RMDir "$INSTDIR" + + ; Remove shortcuts if not updating + ${If} $UpdateMode <> 1 + !insertmacro DeleteAppUserModelId + + ; Remove start menu shortcut + !insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder + !insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Pop $0 + ${If} $0 = 1 + !insertmacro UnpinShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" + Delete "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" + RMDir "$SMPROGRAMS\$AppStartMenuFolder" + ${EndIf} + !insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Pop $0 + ${If} $0 = 1 + !insertmacro UnpinShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" + Delete "$SMPROGRAMS\${PRODUCTNAME}.lnk" + ${EndIf} + + ; Remove desktop shortcuts + !insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Pop $0 + ${If} $0 = 1 + !insertmacro UnpinShortcut "$DESKTOP\${PRODUCTNAME}.lnk" + Delete "$DESKTOP\${PRODUCTNAME}.lnk" + ${EndIf} + ${EndIf} + + ; Remove registry information for add/remove programs + !if "${INSTALLMODE}" == "both" + DeleteRegKey SHCTX "${UNINSTKEY}" + !else if "${INSTALLMODE}" == "perMachine" + DeleteRegKey HKLM "${UNINSTKEY}" + !else + DeleteRegKey HKCU "${UNINSTKEY}" + !endif + + ; Removes the Autostart entry for ${PRODUCTNAME} from the HKCU Run key if it exists. + ; This ensures the program does not launch automatically after uninstallation if it exists. + ; If it doesn't exist, it does nothing. + ; We do this when not updating (to preserve the registry value on updates) + ${If} $UpdateMode <> 1 + DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}" + ${EndIf} + + ; Delete app data if the checkbox is selected + ; and if not updating + ${If} $DeleteAppDataCheckboxState = 1 + ${AndIf} $UpdateMode <> 1 + ; Clear the install location $INSTDIR from registry + DeleteRegKey SHCTX "${MANUPRODUCTKEY}" + DeleteRegKey /ifempty SHCTX "${MANUKEY}" + + ; Clear the install language from registry + DeleteRegValue HKCU "${MANUPRODUCTKEY}" "Installer Language" + DeleteRegKey /ifempty HKCU "${MANUPRODUCTKEY}" + DeleteRegKey /ifempty HKCU "${MANUKEY}" + + SetShellVarContext current + RmDir /r "$APPDATA\${BUNDLEID}" + RmDir /r "$LOCALAPPDATA\${BUNDLEID}" + ${EndIf} + + !ifmacrodef NSIS_HOOK_POSTUNINSTALL + !insertmacro NSIS_HOOK_POSTUNINSTALL + !endif + + ; Auto close if passive mode or updating + ${If} $PassiveMode = 1 + ${OrIf} $UpdateMode = 1 + SetAutoClose true + ${EndIf} +SectionEnd + +Function RestorePreviousInstallLocation + ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" "" + StrCmp $4 "" +2 0 + StrCpy $INSTDIR $4 +FunctionEnd + +Function Skip + Abort +FunctionEnd + +Function SkipIfPassive + ${IfThen} $PassiveMode = 1 ${|} Abort ${|} +FunctionEnd +Function un.SkipIfPassive + ${IfThen} $PassiveMode = 1 ${|} Abort ${|} +FunctionEnd + +Function CreateOrUpdateStartMenuShortcut + ; We used to use product name as MAINBINARYNAME + ; migrate old shortcuts to target the new MAINBINARYNAME + StrCpy $R0 0 + + !insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName" + Pop $0 + ${If} $0 = 1 + !insertmacro SetShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + StrCpy $R0 1 + ${EndIf} + + !insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName" + Pop $0 + ${If} $0 = 1 + !insertmacro SetShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + StrCpy $R0 1 + ${EndIf} + + ${If} $R0 = 1 + Return + ${EndIf} + + ; Skip creating shortcut if in update mode or no shortcut mode + ; but always create if migrating from wix + ${If} $WixMode = 0 + ${If} $UpdateMode = 1 + ${OrIf} $NoShortcutMode = 1 + Return + ${EndIf} + ${EndIf} + + !if "${STARTMENUFOLDER}" != "" + CreateDirectory "$SMPROGRAMS\$AppStartMenuFolder" + CreateShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" + !else + CreateShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\${PRODUCTNAME}.lnk" + !endif +FunctionEnd + +Function CreateOrUpdateDesktopShortcut + ; We used to use product name as MAINBINARYNAME + ; migrate old shortcuts to target the new MAINBINARYNAME + !insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName" + Pop $0 + ${If} $0 = 1 + !insertmacro SetShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Return + ${EndIf} + + ; Skip creating shortcut if in update mode or no shortcut mode + ; but always create if migrating from wix + ${If} $WixMode = 0 + ${If} $UpdateMode = 1 + ${OrIf} $NoShortcutMode = 1 + Return + ${EndIf} + ${EndIf} + + CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetLnkAppUserModelId "$DESKTOP\${PRODUCTNAME}.lnk" +FunctionEnd \ No newline at end of file diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rs index d61c589..2f20037 100644 --- a/src-tauri/src/app.rs +++ b/src-tauri/src/app.rs @@ -34,6 +34,9 @@ pub struct AppState { apps: Mutex>, app_icons: Mutex>>, sampler: Mutex, + /// Last light snapshot, so the widget window and the main window polling + /// a beat apart share one refresh instead of paying for two. + snapshot_cache: Mutex>, } impl AppState { @@ -354,6 +357,8 @@ pub struct BootstrapView { os_name: String, os_version: String, hardware: String, + /// Static component facts (board/RAM/disk/GPU) for the overview panel. + hardware_info: squid_platform::HardwareInfo, arch: String, device: String, language: String, @@ -377,6 +382,7 @@ pub fn bootstrap() -> BootstrapView { os_name: engine.platform().display_name(), os_version: engine.platform().os_version(), hardware: engine.platform().hardware_model(), + hardware_info: squid_platform::hardware_info(), arch: std::env::consts::ARCH.into(), device: match engine.platform().device() { squid_platform::Device::Mac => "mac".into(), @@ -825,10 +831,36 @@ pub async fn storage_largest_files( } #[tauri::command] -pub fn system_snapshot(app: AppHandle) -> Result { +pub fn system_snapshot(app: AppHandle, full: Option) -> Result { + // `full` costs a per-pid CPU/memory walk of every process on the machine + // (hundreds of syscalls) plus the top-12 sort — the 实时监控 page needs + // it; the desktop widget, overview tiles and every background poll pass + // false and ride the light refresh. Light answers are cached for two + // seconds so windows polling in step pay for one refresh, not several. let state = app.state::(); + let full = full.unwrap_or(false); + // Check and fill the cache under the sampler lock: two windows polling a + // beat apart then share one refresh only if the second can not slip in + // between the first cache miss and the sampler call. let mut sampler = AppState::lock(&state.sampler)?; - Ok(sampler.refresh()) + if !full { + if let Ok(cache) = AppState::lock(&state.snapshot_cache) { + if let Some((at, snapshot)) = cache.as_ref() { + if at.elapsed() < Duration::from_secs(2) { + return Ok(snapshot.clone()); + } + } + } + } + let snapshot = if full { + sampler.refresh() + } else { + sampler.refresh_with(false) + }; + if let Ok(mut cache) = AppState::lock(&state.snapshot_cache) { + *cache = Some((Instant::now(), snapshot.clone())); + } + Ok(snapshot) } #[tauri::command] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 3e9168c..5854efa 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,11 +1,13 @@ mod app; mod autostart; +mod manage; pub mod notifications; mod permissions; mod process; pub mod security; mod startup; mod update; +mod widget; use security::ScanTarget; use squid_core::{Locale, Settings}; @@ -23,6 +25,8 @@ pub(crate) fn show_main_window(app: &AppHandle) { let _ = window.show(); let _ = window.unminimize(); let _ = window.set_focus(); + // The page stops sampling while parked in the tray; wake it up. + let _ = app.emit("squid://visible", true); } } @@ -104,6 +108,14 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result> )?; let first_separator = PredefinedMenuItem::separator(app)?; let last_separator = PredefinedMenuItem::separator(app)?; + // Flips the widget master switch; state is shown on the Real-time monitor. + let widget_toggle = MenuItem::with_id( + app, + "widget", + tray_text(locale, "Show / hide desktop widget", "显示/隐藏桌面小工具"), + true, + None::<&str>, + )?; Menu::with_items( app, &[ @@ -115,6 +127,7 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result> &cleanup, &apps, &purge, + &widget_toggle, &last_separator, &quit, ], @@ -164,13 +177,13 @@ fn tray_tooltip(app: &AppHandle, locale: Locale) -> String { fn create_tray(app: &AppHandle, locale: Locale) -> tauri::Result<()> { let menu = tray_menu(app, locale)?; let tooltip = tray_tooltip(app, locale); - let icon = app - .default_window_icon() - .cloned() - .ok_or_else(|| tauri::Error::AssetNotFound("default window icon".into()))?; + // A transparent monochrome mark: macOS uses it as a template image so the + // system tints it for light/dark menu bars; other platforms keep the gray. + let icon = tauri::image::Image::from_bytes(include_bytes!("../icons/tray-template.png"))?; TrayIconBuilder::with_id("squid-tray") .icon(icon) + .icon_as_template(cfg!(target_os = "macos")) .tooltip(tooltip) .menu(&menu) .show_menu_on_left_click(true) @@ -181,6 +194,11 @@ fn create_tray(app: &AppHandle, locale: Locale) -> tauri::Result<()> { "cleanup" => navigate_to(app, "cleanup"), "applications" => navigate_to(app, "applications"), "purge" => navigate_to(app, "purge"), + "widget" => { + if let Err(error) = widget::toggle_from_tray(app) { + eprintln!("widget toggle failed: {error}"); + } + } "quit" => app.exit(0), _ => {} }) @@ -208,14 +226,22 @@ pub fn run() { .plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_notification::init()) .on_window_event(|window, event| { + if window.label() != "main" { + return; + } if let WindowEvent::CloseRequested { api, .. } = event { api.prevent_close(); let _ = window.hide(); + // A hidden window must not keep sampling the whole machine; + // the page pauses its polling on this signal. + let _ = window.emit("squid://visible", false); } }) .manage(app::AppState::default()) .manage(update::UpdateState::default()) .manage(security::SecurityState::default()) + .manage(manage::ManageState::default()) + .manage(widget::WidgetState::default()) .invoke_handler(tauri::generate_handler![ app::bootstrap, app::cancel_job, @@ -242,6 +268,18 @@ pub fn run() { app::open_trash, permissions::permission_status, permissions::open_full_disk_access_settings, + manage::manage_scan, + manage::managed_startup_set_enabled, + manage::extension_set_registered, + manage::popup_list, + manage::popup_close, + manage::popup_add_rule, + manage::popup_rule_update, + manage::popup_rule_remove, + manage::popup_watcher_set, + widget::widget_get, + widget::widget_set, + widget::widget_hide, update::update_check, update::update_status, update::update_download, @@ -273,6 +311,8 @@ pub fn run() { create_tray(app.handle(), Locale::detect(&settings))?; update::spawn_startup_check(app.handle()); security::spawn_scheduler(app.handle(), &settings); + manage::spawn_watcher(app.handle().clone()); + widget::spawn_startup(app.handle()); Ok(()) }) .build(tauri::generate_context!()) diff --git a/src-tauri/src/manage.rs b/src-tauri/src/manage.rs new file mode 100644 index 0000000..5554def --- /dev/null +++ b/src-tauri/src/manage.rs @@ -0,0 +1,534 @@ +//! Tauri commands for the 权限管理 page: startup items, context-menu handlers +//! and a popup blocker (list visible windows, register per-title rules, close +//! matching windows from a background watcher). +//! +//! Entries address themselves by their registry-level `id`, so a toggle can +//! never fire at a shifted list position — the same safety idea as the +//! index-only delete flows, expressed for a page that mutates continuously. + +use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; +use serde::{Deserialize, Serialize}; +use squid_core::Settings; +use squid_platform::permissions::{self, PopupWindow, ShellExtEntry, StartupEntry}; +use std::fs; +use std::path::PathBuf; +use std::sync::{Mutex, MutexGuard}; +use std::time::Duration; +use tauri::{AppHandle, Emitter, Manager}; + +/// One popup rule: "whenever a window from `exe` shows `title`, close it". +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct PopupRule { + pub exe: String, + pub title: String, + /// `contains` (default) or `exact`. + pub matcher: String, + pub enabled: bool, + /// Cumulative number of windows this rule has closed. + pub closed: u64, + /// `data:image/png;base64,…` of the owning exe, filled in by `manage_scan` + /// only — never persisted into manage.json. + #[serde(skip)] + pub icon: Option, +} + +impl Default for PopupRule { + fn default() -> Self { + Self { + exe: String::new(), + title: String::new(), + matcher: "contains".to_string(), + enabled: true, + closed: 0, + icon: None, + } + } +} + +impl PopupRule { + fn matches(&self, window: &PopupWindow) -> bool { + if !self.enabled { + return false; + } + let Some(exe) = window.exe.as_deref() else { + return false; + }; + if !exe.eq_ignore_ascii_case(&self.exe) { + return false; + } + if self.matcher == "exact" { + window.title == self.title + } else if self.title.is_empty() { + true + } else { + window.title.contains(&self.title) + } + } +} + +#[derive(Clone, Default, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +struct ManagePrefs { + enabled: bool, + interval_ms: u64, + rules: Vec, + /// Handlers the user removed; kept so the list can offer "restore". + removed_extensions: Vec, +} + +pub struct ManageState { + prefs: Mutex, + startup: Mutex>, + extensions: Mutex>, +} + +impl Default for ManageState { + fn default() -> Self { + Self { + prefs: Mutex::new(load_prefs()), + startup: Mutex::new(Vec::new()), + extensions: Mutex::new(Vec::new()), + } + } +} + +impl ManageState { + fn lock(value: &Mutex) -> Result, String> { + value + .lock() + .map_err(|_| "The application state is unavailable; restart Squid.".to_string()) + } +} + +fn prefs_path() -> PathBuf { + Settings::config_dir().join("manage.json") +} + +fn load_prefs() -> ManagePrefs { + fs::read_to_string(prefs_path()) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default() +} + +fn save_prefs(state: &ManageState) -> Result<(), String> { + let prefs = ManageState::lock(&state.prefs)?.clone(); + let path = prefs_path(); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + let text = serde_json::to_string_pretty(&prefs).map_err(|error| error.to_string())?; + fs::write(path, text).map_err(|error| error.to_string()) +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StartupView { + id: String, + name: String, + display_name: String, + /// `data:image/png;base64,…` of the binary's icon, absent on macOS/Linux. + icon: Option, + command: String, + source: String, + source_label: String, + scope: String, + enabled: bool, +} + +impl From<&StartupEntry> for StartupView { + fn from(entry: &StartupEntry) -> Self { + Self { + id: entry.id.clone(), + name: entry.name.clone(), + display_name: entry.display_name.clone(), + icon: entry.icon.as_deref().map(png_data_url), + command: entry.command.clone(), + source: entry.source.clone(), + source_label: entry.source_label.clone(), + scope: entry.scope.clone(), + enabled: entry.enabled, + } + } +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ExtensionView { + id: String, + name: String, + handler: String, + extension_point: String, + scope: String, + friendly_name: Option, + module: Option, + /// Publisher of the owning dll — 电脑管家's 创建者 column. + publisher: Option, + /// `data:image/png;base64,…` of the owning module's icon. + icon: Option, + /// false = currently parked in the app's restore list. + registered: bool, +} + +impl ExtensionView { + fn label(&self) -> &str { + self.friendly_name.as_deref().unwrap_or(&self.name) + } +} + +fn png_data_url(png: &[u8]) -> String { + format!("data:image/png;base64,{}", BASE64.encode(png)) +} + +impl From<&ShellExtEntry> for ExtensionView { + fn from(entry: &ShellExtEntry) -> Self { + Self { + id: entry.id.clone(), + name: entry.name.clone(), + handler: entry.handler.clone(), + extension_point: entry.extension_point.clone(), + scope: entry.scope.clone(), + friendly_name: entry.friendly_name.clone(), + module: entry.module.clone(), + publisher: entry.publisher.clone(), + icon: entry.icon.as_deref().map(png_data_url), + registered: true, + } + } +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PopupView { + hwnd: i64, + title: String, + process: String, + exe: Option, + /// `data:image/png;base64,…` of the owning process's icon. + icon: Option, +} + +impl From<&PopupWindow> for PopupView { + fn from(window: &PopupWindow) -> Self { + Self { + hwnd: window.hwnd, + title: window.title.clone(), + process: window.process.clone(), + exe: window.exe.clone(), + icon: window.icon.as_deref().map(png_data_url), + } + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ManageView { + watcher_enabled: bool, + interval_ms: u64, + rules: Vec, + windows: Vec, + startup: Vec, + extensions: Vec, + startup_count: usize, + startup_enabled_count: usize, +} + +#[tauri::command] +pub async fn manage_scan(app: AppHandle) -> Result { + let manage = app.state::(); + let (startup, extensions, windows) = tauri::async_runtime::spawn_blocking(|| { + ( + permissions::scan_startup_entries(), + permissions::scan_shell_extensions(), + permissions::list_popup_windows(), + ) + }) + .await + .map_err(|error| format!("权限扫描失败:{error}"))?; + + let mut startup_view: Vec = startup.iter().map(StartupView::from).collect(); + startup_view.sort_by(|a, b| { + a.enabled + .cmp(&b.enabled) + .reverse() + .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) + }); + let mut extension_view: Vec = + extensions.iter().map(ExtensionView::from).collect(); + + let (watcher_enabled, interval_ms, mut rules) = { + let prefs = ManageState::lock(&manage.prefs)?; + for parked in &prefs.removed_extensions { + extension_view.push(ExtensionView { + registered: false, + ..ExtensionView::from(parked) + }); + } + extension_view.sort_by(|a, b| { + a.registered + .cmp(&b.registered) + .reverse() + .then_with(|| a.extension_point.cmp(&b.extension_point)) + .then_with(|| a.label().to_lowercase().cmp(&b.label().to_lowercase())) + }); + ( + prefs.enabled, + if prefs.interval_ms == 0 { + 1_500 + } else { + prefs.interval_ms + }, + prefs.rules.clone(), + ) + }; + // Rule rows carry the owning software's icon (电脑管家 shows it too). + let mut rule_icons: std::collections::HashMap> = Default::default(); + for rule in &mut rules { + let icon = rule_icons + .entry(rule.exe.clone()) + .or_insert_with(|| permissions::exe_icon(&rule.exe).map(|png| png_data_url(&png))) + .clone(); + rule.icon = icon; + } + *ManageState::lock(&manage.startup)? = startup; + *ManageState::lock(&manage.extensions)? = extensions; + let startup_enabled_count = startup_view.iter().filter(|entry| entry.enabled).count(); + let startup_count = startup_view.len(); + Ok(ManageView { + watcher_enabled, + interval_ms, + rules, + windows: windows.iter().map(PopupView::from).collect(), + startup: startup_view, + extensions: extension_view, + startup_count, + startup_enabled_count, + }) +} + +/// Flip one startup entry (registry / startup folder / scheduled task), then +/// rescan so a partially-applied toggle can never desync the UI. +#[tauri::command] +pub async fn managed_startup_set_enabled( + app: AppHandle, + id: String, + enabled: bool, +) -> Result { + let manage = app.state::(); + let entry = ManageState::lock(&manage.startup)? + .iter() + .find(|entry| entry.id == id) + .cloned() + .ok_or_else(|| "请先重新扫描启动项".to_string())?; + tauri::async_runtime::spawn_blocking(move || permissions::set_startup_enabled(&entry, enabled)) + .await + .map_err(|error| error.to_string())??; + let fresh = tauri::async_runtime::spawn_blocking(permissions::scan_startup_entries) + .await + .map_err(|error| error.to_string())?; + let enabled_count = fresh.iter().filter(|entry| entry.enabled).count(); + *ManageState::lock(&manage.startup)? = fresh; + Ok(enabled_count) +} + +/// Unregister / restore a context-menu handler. Removal keeps the entry in +/// `manage.json`, which is both the restore recipe and the audit trail. +#[tauri::command] +pub fn extension_set_registered( + app: AppHandle, + id: String, + registered: bool, +) -> Result<(), String> { + let manage = app.state::(); + let entry = if registered { + ManageState::lock(&manage.prefs)? + .removed_extensions + .iter() + .find(|entry| entry.id == id) + .cloned() + } else { + ManageState::lock(&manage.extensions)? + .iter() + .find(|entry| entry.id == id) + .cloned() + } + .ok_or_else(|| "请先重新扫描右键菜单".to_string())?; + if registered { + permissions::restore_shell_extension(&entry)?; + ManageState::lock(&manage.prefs)? + .removed_extensions + .retain(|item| item.id != id); + } else { + permissions::remove_shell_extension(&entry)?; + let mut prefs = ManageState::lock(&manage.prefs)?; + if !prefs.removed_extensions.iter().any(|item| item.id == id) { + prefs.removed_extensions.push(entry); + } + } + save_prefs(&manage) +} + +/// Live list of closeable top-level windows (popup blocker "抓一个窗口"). +#[tauri::command] +pub fn popup_list() -> Vec { + permissions::list_popup_windows() + .iter() + .map(PopupView::from) + .collect() +} + +/// Close one window manually from the picker. +#[tauri::command] +pub fn popup_close(hwnd: i64) -> Result<(), String> { + if permissions::close_popup_window(hwnd) { + Ok(()) + } else { + Err("这个窗口已经关闭或拒绝了关闭请求".to_string()) + } +} + +/// Teach the blocker a new rule from a live window: "this exe + this title". +#[tauri::command] +pub fn popup_add_rule(app: AppHandle, hwnd: i64, matcher: String) -> Result<(), String> { + let manage = app.state::(); + let window = permissions::list_popup_windows_bare() + .into_iter() + .find(|window| window.hwnd == hwnd) + .ok_or_else(|| "窗口已关闭,请重新选择".to_string())?; + let exe = window.exe.ok_or("无法读取该窗口的程序路径".to_string())?; + let matcher = if matcher == "exact" { + "exact" + } else { + "contains" + }; + { + let mut prefs = ManageState::lock(&manage.prefs)?; + if prefs + .rules + .iter() + .any(|item| item.exe == exe && item.title == window.title) + { + return Err("这条拦截规则已存在".to_string()); + } + prefs.rules.push(PopupRule { + exe, + title: window.title.clone(), + matcher: matcher.to_string(), + enabled: true, + closed: 0, + icon: None, + }); + prefs.enabled = true; + } + // Adding a rule implies closing its window right now. + let _ = permissions::close_popup_window(hwnd); + save_prefs(&manage) +} + +#[tauri::command] +pub fn popup_rule_update( + app: AppHandle, + index: usize, + enabled: Option, + reset_count: Option, +) -> Result<(), String> { + let manage = app.state::(); + { + let mut prefs = ManageState::lock(&manage.prefs)?; + let rule = prefs + .rules + .get_mut(index) + .ok_or("规则已变化,请刷新后重试")?; + if let Some(enabled) = enabled { + rule.enabled = enabled; + } + if reset_count.unwrap_or(false) { + rule.closed = 0; + } + } + save_prefs(&manage) +} + +#[tauri::command] +pub fn popup_rule_remove(app: AppHandle, index: usize) -> Result<(), String> { + let manage = app.state::(); + { + let mut prefs = ManageState::lock(&manage.prefs)?; + if index >= prefs.rules.len() { + return Err("规则已变化,请刷新后重试".to_string()); + } + prefs.rules.remove(index); + } + save_prefs(&manage) +} + +#[tauri::command] +pub fn popup_watcher_set(app: AppHandle, enabled: bool) -> Result<(), String> { + let manage = app.state::(); + ManageState::lock(&manage.prefs)?.enabled = enabled; + save_prefs(&manage) +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct ClosedEvent { + process: String, + title: String, + rule_index: usize, +} + +/// The resident watcher: poll the desktop, close every window a rule claims. +/// Ticks only while enabled with armed rules; one `EnumWindows` per interval +/// is cheap enough for a 1.5 s heartbeat and stops itself when disarmed. +pub fn spawn_watcher(app: AppHandle) { + std::thread::spawn(move || loop { + let manage = match app.try_state::() { + Some(manage) => manage, + None => return, + }; + let (interval, armed) = match ManageState::lock(&manage.prefs) { + Ok(prefs) => ( + Duration::from_millis(if prefs.interval_ms == 0 { + 1_500 + } else { + prefs.interval_ms.max(500) + }), + prefs.enabled && prefs.rules.iter().any(|rule| rule.enabled), + ), + Err(_) => return, + }; + if armed { + let windows = permissions::list_popup_windows_bare(); + let mut closed: Vec = Vec::new(); + { + let mut prefs = match ManageState::lock(&manage.prefs) { + Ok(prefs) => prefs, + Err(_) => return, + }; + for window in &windows { + for (index, rule) in prefs.rules.iter_mut().enumerate() { + if rule.matches(window) { + if permissions::close_popup_window(window.hwnd) { + rule.closed += 1; + closed.push(ClosedEvent { + process: window.process.clone(), + title: window.title.clone(), + rule_index: index, + }); + } + break; + } + } + } + } + if !closed.is_empty() { + let _ = save_prefs(&manage); + for event in closed { + let _ = app.emit("popup://closed", event); + } + } + } + std::thread::sleep(interval); + }); +} diff --git a/src-tauri/src/security.rs b/src-tauri/src/security.rs index cd9252b..fe834fb 100644 --- a/src-tauri/src/security.rs +++ b/src-tauri/src/security.rs @@ -888,7 +888,15 @@ pub async fn security_rollback_rules() -> Result { pub(crate) fn update_pack() -> Result { let manifest_url = crate::update::intel_manifest_url() .ok_or_else(|| "No rule-pack feed is configured for this build.".to_string())?; - let text = crate::update::fetch_text(&manifest_url)?; + let text = crate::update::fetch_text(&manifest_url).map_err(|error| { + if error.contains("404") { + "No rule pack has been published for this release yet. Squid looks for \ + squid-intel.json next to squid-update.json on the releases branch." + .to_string() + } else { + error + } + })?; let signature = crate::update::intel_manifest_signature()?; let key = crate::update::intel_public_key()?; // Two answers, not one. A build that was given an intel key must verify diff --git a/src-tauri/src/update.rs b/src-tauri/src/update.rs index 66d1908..3b96410 100644 --- a/src-tauri/src/update.rs +++ b/src-tauri/src/update.rs @@ -725,6 +725,7 @@ pub async fn update_download(app: AppHandle) -> Result { .map_err(|error| format!("Update download failed: {error}"))? } +#[cfg(target_os = "macos")] fn bundle_path(exe: &Path) -> Option { let contents = exe.parent()?.parent()?; let bundle = contents.parent()?; @@ -831,7 +832,9 @@ fn spawn_handoff(name: &str, script: &str) -> Result<(), String> { #[cfg(target_os = "windows")] let mut command = crate::process::command("cmd.exe"); #[cfg(target_os = "windows")] - command.args(["/D", "/C", &path.to_string_lossy().to_string()]); + let script = path.to_string_lossy(); + #[cfg(target_os = "windows")] + command.args(["/D", "/C", &*script]); #[cfg(not(target_os = "windows"))] let mut command = crate::process::command("/bin/sh"); #[cfg(not(target_os = "windows"))] @@ -850,6 +853,7 @@ fn quit_for_update(app: &AppHandle) { }); } +#[cfg(not(target_os = "windows"))] fn open_artifact(path: &Path) -> Result<(), String> { #[cfg(target_os = "macos")] { @@ -914,7 +918,6 @@ pub async fn update_install(app: AppHandle) -> Result { let script = windows_handoff(pid, &artifact, &log); spawn_handoff("Squid-update.cmd", &script)?; quit_for_update(&app); - return Ok(path); } #[cfg(not(any(target_os = "macos", target_os = "windows")))] { diff --git a/src-tauri/src/widget.rs b/src-tauri/src/widget.rs new file mode 100644 index 0000000..5d4de43 --- /dev/null +++ b/src-tauri/src/widget.rs @@ -0,0 +1,479 @@ +//! Desktop widget (桌面小工具): a borderless desktop-layer window showing +//! live system stats, styled after the fnOS desktop monitor. It sits above +//! the wallpaper and icons but below ordinary app windows, and lives next to +//! the tray, so it keeps running while the main window is hidden. +//! +//! Settings persist in `widget.json` beside `manage.json`; the widget window +//! and the main window each load this module's commands, and every change is +//! broadcast on `widget://settings` so both views stay in sync. + +use serde::{Deserialize, Serialize}; +use squid_core::{Locale, Settings}; +use std::fs; +use std::path::PathBuf; +use std::sync::{Mutex, MutexGuard}; +use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder}; + +pub const WIDGET_LABEL: &str = "widget"; + +/// `HWND_BOTTOM` + no-activate flags: the widget lives on the desktop layer — +/// above wallpaper and icons, below every ordinary app window. +#[cfg(windows)] +mod desktop_layer { + #[link(name = "user32")] + extern "system" { + fn SetWindowPos( + hwnd: *mut core::ffi::c_void, + insert_after: *mut core::ffi::c_void, + x: i32, + y: i32, + cx: i32, + cy: i32, + flags: u32, + ) -> i32; + } + const HWND_BOTTOM: *mut core::ffi::c_void = 1usize as *mut core::ffi::c_void; + const SWP_NOMOVE: u32 = 0x0002; + const SWP_NOSIZE: u32 = 0x0001; + const SWP_NOACTIVATE: u32 = 0x0010; + + pub fn lower(hwnd: *mut core::ffi::c_void) { + // SAFETY: hwnd comes from Tauri's own window handle; SetWindowPos with + // NOMOVE|NOSIZE|NOACTIVATE only edits the z-order. + unsafe { + SetWindowPos( + hwnd, + HWND_BOTTOM, + 0, + 0, + 0, + 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE, + ); + } + } +} + +/// Park the widget at the bottom of the window stack (desktop layer). +/// macOS/Linux keep plain floating behaviour for now (no equivalent need: +/// the widget story is Windows-first). +pub fn lower_window(app: &AppHandle) { + #[cfg(windows)] + { + let Some(window) = app.get_webview_window(WIDGET_LABEL) else { + return; + }; + if let Ok(hwnd) = window.hwnd() { + desktop_layer::lower(hwnd.0.cast()); + } + } + #[cfg(not(windows))] + { + let _ = app; + } +} + +fn default_interval_ms() -> u64 { + 2_000 +} + +fn default_corner() -> String { + "top-right".to_string() +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct WidgetPrefs { + /// Master switch: hides the window entirely when off. + pub enabled: bool, + pub panel_run: bool, + pub panel_cpu: bool, + pub panel_network: bool, + pub panel_disk: bool, + pub panel_storage: bool, + /// 90–100 (%): window opacity; at most 10% of the desktop may bleed + /// through so text stays readable over busy wallpapers. + pub opacity: u8, + /// Sampling cadence for the widget window. + pub interval_ms: u64, + /// `top-right` | `top-left` | `bottom-right` | `bottom-left`. + pub corner: String, + /// Remember the collapsed header-only state across restarts. + pub remember_collapsed: bool, + pub collapsed: bool, + /// Last user-dragged position; None re-docks to `corner`. + pub position: Option<(i32, i32)>, +} + +impl Default for WidgetPrefs { + fn default() -> Self { + Self { + enabled: true, + panel_run: true, + panel_cpu: true, + panel_network: true, + panel_disk: true, + panel_storage: true, + opacity: 100, + interval_ms: default_interval_ms(), + corner: default_corner(), + remember_collapsed: true, + collapsed: false, + position: None, + } + } +} + +pub struct WidgetState { + prefs: Mutex, +} + +impl Default for WidgetState { + fn default() -> Self { + Self { + prefs: Mutex::new(load_prefs()), + } + } +} + +impl WidgetState { + fn lock(value: &Mutex) -> Result, String> { + value + .lock() + .map_err(|_| "The application state is unavailable; restart Squid.".to_string()) + } + + pub fn current(&self) -> WidgetPrefs { + self.prefs.lock().map(|p| p.clone()).unwrap_or_default() + } +} + +fn prefs_path() -> PathBuf { + Settings::config_dir().join("widget.json") +} + +fn load_prefs() -> WidgetPrefs { + let mut prefs = fs::read_to_string(prefs_path()) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .unwrap_or_default(); + // Migration: older builds allowed 60–100; the 10%-translucency cap now + // floors everything below 90 (including the old 92 default). + prefs.opacity = prefs.opacity.clamp(90, 100); + // 折叠记忆 off: always boot expanded (save_prefs already stops persisting + // the fold state, this covers configs written while it was on). + if !prefs.remember_collapsed { + prefs.collapsed = false; + } + prefs +} + +fn save_prefs(state: &WidgetState) -> Result<(), String> { + let prefs = WidgetState::lock(&state.prefs)?.clone(); + let path = prefs_path(); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + // 折叠记忆 off: the live fold state still applies this session, but the + // next launch always starts expanded. + let stored = WidgetPrefs { + collapsed: if prefs.remember_collapsed { + prefs.collapsed + } else { + false + }, + ..prefs + }; + let text = serde_json::to_string_pretty(&stored).map_err(|error| error.to_string())?; + fs::write(path, text).map_err(|error| error.to_string()) +} + +/// Dock to a screen corner (widget width ~350px) or restore the remembered +/// drag position. Called on creation and whenever the corner changes. All +/// math is in physical pixels — the webview reports `outerPosition` there. +fn place_window(app: &AppHandle, prefs: &WidgetPrefs) { + let Some(window) = app.get_webview_window(WIDGET_LABEL) else { + return; + }; + let Ok(Some(monitor)) = window + .current_monitor() + .or_else(|_| window.primary_monitor()) + else { + return; + }; + // Work area excludes the macOS menu bar and Dock, so the widget cannot + // park its header under the menu bar or behind the Dock. + let work = monitor.work_area(); + let outer = window + .outer_size() + .map(|s| (s.width as i32, s.height as i32)) + .unwrap_or((350, 620)); + let margin = (16.0 * monitor.scale_factor()) as i32; + let min_x = work.position.x; + let min_y = work.position.y; + let max_x = (work.position.x + work.size.width as i32 - outer.0).max(min_x); + let max_y = (work.position.y + work.size.height as i32 - outer.1).max(min_y); + let pos = if let Some((x, y)) = prefs.position { + // Clamp into the monitor so an unplugged-secondary position can not + // hide the widget off-screen. + (x.clamp(min_x, max_x), y.clamp(min_y, max_y)) + } else { + let x = match prefs.corner.as_str() { + "top-left" | "bottom-left" => min_x + margin, + _ => max_x - margin, + }; + let y = match prefs.corner.as_str() { + "bottom-left" | "bottom-right" => max_y - margin, + _ => min_y + margin, + }; + (x.clamp(min_x, max_x), y.clamp(min_y, max_y)) + }; + let _ = window.set_position(tauri::PhysicalPosition::new(pos.0, pos.1)); +} + +/// Bring the widget window into the state `prefs` describes (create/show/hide). +/// The window is deliberately *not* always-on-top: it is parked at the bottom +/// of the z-order (desktop layer), above wallpaper/icons but under every +/// ordinary app window, so it can never cover the user's work. +fn sync_window(app: &AppHandle, prefs: &WidgetPrefs) { + if !prefs.enabled { + if let Some(window) = app.get_webview_window(WIDGET_LABEL) { + let _ = window.hide(); + } + return; + } + if app.get_webview_window(WIDGET_LABEL).is_some() { + if let Some(window) = app.get_webview_window(WIDGET_LABEL) { + let _ = window.show(); + } + place_window(app, prefs); + lower_window(app); + return; + } + let builder = WebviewWindowBuilder::new( + app, + WIDGET_LABEL, + WebviewUrl::App("index.html?view=widget".into()), + ) + .title("Squid 实时监控") + .inner_size(350.0, 640.0) + .resizable(false) + .decorations(false) + .transparent(true) + .always_on_top(false) + .skip_taskbar(true) + .focused(false) + .visible(false) + .shadow(false); + // macOS: BelowNormal keeps the widget under ordinary app windows, every + // Space keeps it beside the desktop, and a non-key window means clicking + // a card never pulls focus away from the app the user is working in. + // `accept_first_mouse` keeps the first click actionable anyway. + #[cfg(target_os = "macos")] + let builder = builder + .always_on_bottom(true) + .visible_on_all_workspaces(true) + .focusable(false) + .accept_first_mouse(true); + match builder.build() { + Ok(window) => { + let _ = window.set_ignore_cursor_events(false); + place_window(app, prefs); + let _ = window.show(); + lower_window(app); + } + Err(error) => { + eprintln!("widget window failed to open: {error}"); + } + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WidgetView { + prefs: WidgetPrefs, + language: &'static str, +} + +#[tauri::command] +pub fn widget_get(app: AppHandle) -> WidgetView { + let (settings, _) = Settings::load(); + WidgetView { + prefs: app.state::().current(), + language: Locale::detect(&settings).code(), + } +} + +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WidgetPatch { + pub enabled: Option, + pub panel_run: Option, + pub panel_cpu: Option, + pub panel_network: Option, + pub panel_disk: Option, + pub panel_storage: Option, + pub opacity: Option, + pub interval_ms: Option, + pub corner: Option, + pub remember_collapsed: Option, + pub collapsed: Option, + pub position: Option>, + /// `position_changed` marks a drag-persist (no re-docking after set). + #[serde(default)] + pub keep_position: Option, + /// Re-run corner placement (used after the window auto-resizes and the + /// user has not dragged it anywhere). + #[serde(default)] + pub redock: Option, +} + +#[tauri::command] +pub fn widget_set(app: AppHandle, patch: WidgetPatch) -> Result { + let state = app.state::(); + let (prefs, corner_changed) = { + let mut prefs = WidgetState::lock(&state.prefs)?; + if let Some(value) = patch.enabled { + prefs.enabled = value; + } + if let Some(value) = patch.panel_run { + prefs.panel_run = value; + } + if let Some(value) = patch.panel_cpu { + prefs.panel_cpu = value; + } + if let Some(value) = patch.panel_network { + prefs.panel_network = value; + } + if let Some(value) = patch.panel_disk { + prefs.panel_disk = value; + } + if let Some(value) = patch.panel_storage { + prefs.panel_storage = value; + } + if let Some(value) = patch.opacity { + // At most 10% translucent: anything more reads as "see-through" + // over busy wallpapers. + prefs.opacity = value.clamp(90, 100); + } + if let Some(value) = patch.interval_ms { + prefs.interval_ms = value.clamp(1_000, 10_000); + } + let corner_changed = patch.corner.is_some(); + if let Some(value) = patch.corner { + if matches!( + value.as_str(), + "top-right" | "top-left" | "bottom-right" | "bottom-left" + ) { + prefs.corner = value; + // Choosing a corner overrides any manual drag position. + prefs.position = None; + } + } + if let Some(value) = patch.remember_collapsed { + prefs.remember_collapsed = value; + } + if let Some(value) = patch.collapsed { + prefs.collapsed = value; + } + if let Some(value) = patch.position { + prefs.position = value; + } + (prefs.clone(), corner_changed) + }; + save_prefs(&state)?; + let keep = patch.keep_position.unwrap_or(false); + let redock = patch.redock.unwrap_or(false); + if redock || (!keep && (corner_changed || patch.enabled == Some(true))) { + place_window(&app, &prefs); + } + sync_window(&app, &prefs); + if keep { + // The drag click raised the window; settle it back onto the desktop + // layer so it keeps covering nothing but the wallpaper. + lower_window(&app); + } + let _ = app.emit("widget://settings", &prefs); + Ok(prefs) +} + +/// Hide the widget window (header button) without flipping the master switch: +/// a transient fold-away. Remembered only when 折叠记忆 is on. +#[tauri::command] +pub fn widget_hide(app: AppHandle) -> Result<(), String> { + if let Some(window) = app.get_webview_window(WIDGET_LABEL) { + window.hide().map_err(|error| error.to_string()) + } else { + Ok(()) + } +} + +/// Create the window at startup when enabled; the main page can also open it +/// later through widget_set. +pub fn spawn_startup(app: &AppHandle) { + let prefs = app.state::().current(); + sync_window(app, &prefs); +} + +/// Tray shortcut: flip the master switch and broadcast, same path as the +/// settings page so every view stays in sync. +pub fn toggle_from_tray(app: &AppHandle) -> Result<(), String> { + let state = app.state::(); + let target = !state.current().enabled; + widget_set( + app.clone(), + WidgetPatch { + enabled: Some(target), + ..Default::default() + }, + )?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{WidgetPatch, WidgetPrefs}; + + #[test] + fn prefs_round_trip_uses_camel_case_keys() { + let prefs = WidgetPrefs { + opacity: 88, + corner: "bottom-left".into(), + position: Some((100, 200)), + ..WidgetPrefs::default() + }; + let text = serde_json::to_string(&prefs).unwrap(); + // keys the frontend types.ts promises must appear serialized + for key in [ + "\"panelRun\"", + "\"panelCpu\"", + "\"intervalMs\"", + "\"rememberCollapsed\"", + "\"collapsed\"", + ] { + assert!(text.contains(key), "missing {key} in {text}"); + } + let back: WidgetPrefs = serde_json::from_str(&text).unwrap(); + assert_eq!(back.opacity, 88); + assert_eq!(back.corner, "bottom-left"); + assert_eq!(back.position, Some((100, 200))); + } + + #[test] + fn patch_accepts_sparse_frontend_payloads() { + let patch: WidgetPatch = serde_json::from_str(r#"{"opacity":92,"redock":true}"#).unwrap(); + assert_eq!(patch.opacity, Some(92)); + assert_eq!(patch.redock, Some(true)); + assert!(patch.enabled.is_none()); + assert!(patch.position.is_none()); + } + + #[test] + fn legacy_configs_without_new_fields_still_load() { + let prefs: WidgetPrefs = serde_json::from_str("{}").unwrap(); + assert!(prefs.enabled); + assert!(prefs.panel_cpu); + assert_eq!(prefs.interval_ms, 2_000); + assert!(prefs.position.is_none()); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 6db9803..57c2226 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Squid", - "version": "0.1.7", + "version": "0.1.9", "identifier": "app.nex.squid", "mainBinaryName": "squid-desktop", "build": { @@ -54,7 +54,8 @@ "windows": { "nsis": { "installMode": "currentUser", - "displayLanguageSelector": false + "displayLanguageSelector": false, + "template": "nsis/installer.nsi" } } } diff --git a/src/App.tsx b/src/App.tsx index 5108f57..776198c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -15,6 +15,7 @@ import { } from "lucide-react"; import { useCallback, useEffect, useState, type ReactNode } from "react"; import { useAppsWorkspace } from "./hooks/useAppsWorkspace"; +import { usePermissionsWorkspace } from "./hooks/usePermissionsWorkspace"; import { useScanWorkspace } from "./hooks/useScanWorkspace"; import { useSecurityWorkspace } from "./hooks/useSecurityWorkspace"; import { useStartupWorkspace } from "./hooks/useStartupWorkspace"; @@ -38,6 +39,7 @@ import { ApplicationsPage } from "./pages/ApplicationsPage"; import { CleanupPage } from "./pages/CleanupPage"; import { HistoryPage } from "./pages/HistoryPage"; import { OverviewPage } from "./pages/OverviewPage"; +import { PermissionsPage } from "./pages/PermissionsPage"; import { PurgePage } from "./pages/PurgePage"; import { SecurityPage } from "./pages/SecurityPage"; import { SettingsPage } from "./pages/SettingsPage"; @@ -83,6 +85,12 @@ const NAV_GROUPS: { labelZh: "深度清理", icon: WandSparkles, }, + { + id: "permissions", + labelEn: "Permissions", + labelZh: "权限管理", + icon: ShieldCheck, + }, ], }, { @@ -113,11 +121,18 @@ const NAV_GROUPS: { }, ]; +// Permissions manages Windows Run keys, shell extensions and popup rules; the +// macOS equivalent is the Startup page, which reads LaunchAgents and login items. +function navItemVisible(id: PageId, platform: string | undefined): boolean { + return id !== "permissions" || platform === "windows"; +} + const PAGE_TITLES: Record = { overview: ["Overview", "概览"], cleanup: ["Daily cleanup", "日常清理"], applications: ["Uninstall apps", "应用卸载"], purge: ["Deep Clean", "深度清理"], + permissions: ["Permissions", "权限管理"], storage: ["Storage", "存储空间"], system: ["Real-time monitor", "实时监控"], security: ["Security", "安全"], @@ -177,11 +192,16 @@ export default function App() { const [settings, setSettings] = useState(null); const [autoCheck, setAutoCheck] = useState(true); const [setupOpen, setSetupOpen] = useState(false); + // The 托盘驻留 case: a hidden main window must stop sampling the machine. + const [windowVisible, setWindowVisible] = useState(true); const cleanup = useScanWorkspace("cleanup"); const purge = useScanWorkspace("purge"); const apps = useAppsWorkspace(); - const systemActive = page === "overview" || page === "system"; - const system = useSystemSnapshot(systemActive); + const permissions = usePermissionsWorkspace(page === "permissions"); + const systemActive = (page === "overview" || page === "system") && windowVisible; + // Only the 实时监控 top-process table needs the expensive per-pid walk; + // the overview tiles ride the light refresh. + const system = useSystemSnapshot(systemActive, 1800, page === "system"); const update = useUpdateFlow(bootstrap?.updateFeedUrl ?? "", autoCheck); // One security state for the whole window: the overview strip, the sidebar // badge and the security page all read this, so they cannot disagree. @@ -222,6 +242,23 @@ export default function App() { }; }, []); + useEffect(() => { + let cancelled = false; + let unlisten: (() => void) | null = null; + void api + .onWindowVisible((next) => { + if (!cancelled) setWindowVisible(next); + }) + .then((stop) => { + if (cancelled) stop(); + else unlisten = stop; + }); + return () => { + cancelled = true; + unlisten?.(); + }; + }, []); + /** * A notification click goes to the findings, and brings the window back. * @@ -284,18 +321,20 @@ export default function App() { }, [security]); useEffect(() => { - const order: PageId[] = [ + const order: PageId[] = ([ "overview", "cleanup", "applications", "purge", + "permissions", "storage", "system", "security", "startup", - "history", - "settings", - ]; + ] as PageId[]).filter( + (id) => id !== "permissions" || bootstrap?.platform === "windows", + ); + // Ctrl/Cmd+1..9 follow the sidebar. const onKey = (event: KeyboardEvent) => { if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return; const index = Number(event.key) - 1; @@ -305,7 +344,7 @@ export default function App() { }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); - }, []); + }, [bootstrap?.platform]); const changeLanguage = useCallback( async (nextLanguage: Language) => { @@ -354,7 +393,7 @@ export default function App() { : null; return ( - + setPage("history")} /> ) : null} + {page === "permissions" ? : null} {page === "storage" ? : null} {page === "security" ? ( setPage("startup")} /> @@ -492,7 +532,9 @@ function AppChrome({ {lang === "zh" ? group.labelZh : group.labelEn} - {group.items.map((item) => { + {group.items + .filter((item) => navItemVisible(item.id, bootstrap.platform)) + .map((item) => { const Icon = item.icon; return ( + {selectedUpdaters.indexes.length > 0 ? ( +
+ +
+ + {t( + `Includes ${formatCount(selectedUpdaters.indexes.length)} update installers (${formatBytes(selectedUpdaters.total)})`, + `其中包含 ${formatCount(selectedUpdaters.indexes.length)} 个升级安装包(${formatBytes(selectedUpdaters.total)})`, + )} + + + {t( + "Apps re-download them when needed. Delete them too?", + "应用需要时会自动重新下载。要一并清理吗?", + )} + +
+ +
+ ) : null} ); diff --git a/src/components/UpdatePanel.tsx b/src/components/UpdatePanel.tsx index bb687bd..f410c6f 100644 --- a/src/components/UpdatePanel.tsx +++ b/src/components/UpdatePanel.tsx @@ -70,7 +70,7 @@ export function UpdatePanel({
{t("Current system", "当前系统")} - {bootstrap.osName} {bootstrap.osVersion} + {bootstrap.osVersion || bootstrap.osName}
diff --git a/src/components/WidgetPanels.tsx b/src/components/WidgetPanels.tsx new file mode 100644 index 0000000..35607f4 --- /dev/null +++ b/src/components/WidgetPanels.tsx @@ -0,0 +1,346 @@ +/* 桌面小工具 panel widgets: shared between the desktop widget window and the + * main-window preview. Pure SVG rendering (rings + sparklines), no deps. */ +import { useMemo, useRef } from "react"; +import { formatBytes, formatMemoryBytes, formatRate, percent } from "../lib/format"; +import type { SystemSnapshot, WidgetPrefs } from "../types"; + +const RING_R = 30; +const RING_C = 2 * Math.PI * RING_R; + +export function Ring({ + label, + sub, + value, + color, +}: { + label: string; + sub: string; + value: number; + color: string; +}) { + const arc = (Math.max(0, Math.min(100, value)) / 100) * RING_C; + return ( +
+ +
+ {label} + {sub} +
+
+ ); +} + +const HISTORY = 64; + +export interface MetricHistory { + netUp: number[]; + netDown: number[]; + diskRead: number[]; + diskWrite: number[]; + cpu: number[]; +} + +/** Append-only ring buffers over the snapshot stream (sparkline source). */ +export function useHistory(): [MetricHistory, (snapshot: SystemSnapshot) => void] { + const ref = useRef({ + netUp: [], + netDown: [], + diskRead: [], + diskWrite: [], + cpu: [], + }); + const bump = useMemo( + () => (snapshot: SystemSnapshot) => { + const push = (list: number[], value: number) => { + list.push(value); + if (list.length > HISTORY) list.shift(); + }; + push(ref.current.netUp, snapshot.network.tx_per_sec); + push(ref.current.netDown, snapshot.network.rx_per_sec); + push(ref.current.diskRead, snapshot.disk.read_per_sec); + push(ref.current.diskWrite, snapshot.disk.write_per_sec); + push(ref.current.cpu, snapshot.cpu.total); + }, + [], + ); + return [ref.current, bump]; +} + +function Spark({ + values, + color, + max, +}: { + values: number[]; + color: string; + max?: number; +}) { + // The history array is mutated in place between renders, so the polyline + // must be rebuilt every render — a useMemo on identity would freeze the + // first (empty) result forever. + if (values.length < 2) return ; + const top = max ?? Math.max(...values, 1); + const width = 300; + const step = width / (HISTORY - 1); + const offset = HISTORY - values.length; + const points = values + .map((value, index) => { + const x = (index + offset) * step; + const y = 52 - (value / top) * 46; + return `${x.toFixed(1)},${y.toFixed(1)}`; + }) + .join(" "); + return ( + + + + ); +} + +export function uptimeFull(seconds: number, zh: boolean): string { + const d = Math.floor(seconds / 86_400); + const h = Math.floor((seconds % 86_400) / 3_600); + const m = Math.floor((seconds % 3_600) / 60); + const s = Math.floor(seconds % 60); + return zh + ? `${d} 天 ${h} 时 ${m} 分 ${s} 秒` + : `${d}d ${h}h ${m}m ${s}s`; +} + +/* 逻辑核心占用柱状图:整行均分(核心多则柱变窄),柱色 = 占用率在 + * 绿→黄→橙→红 四个锚点之间连续插值,柱内再做纵向微渐变;悬停显示 + * 「核心 N: xx%」(编号与任务管理器一致从 0 开始)。 */ +const LOAD_STOPS: Array<[number, [number, number, number]]> = [ + [0, [46, 204, 113]], + [33, [247, 224, 120]], + [66, [245, 165, 76]], + [100, [233, 87, 63]], +]; + +function loadRgb(value: number): [number, number, number] { + const v = Math.max(0, Math.min(100, value)); + for (let i = 1; i < LOAD_STOPS.length; i += 1) { + const [at, rgb] = LOAD_STOPS[i]; + if (v <= at) { + const [prevAt, prevRgb] = LOAD_STOPS[i - 1]; + const t = (v - prevAt) / (at - prevAt); + return rgb.map((channel, k) => + Math.round(prevRgb[k] + (channel - prevRgb[k]) * t), + ) as [number, number, number]; + } + } + return LOAD_STOPS[LOAD_STOPS.length - 1][1]; +} + +function loadColor(value: number): string { + return `rgb(${loadRgb(value).join(",")})`; +} + +function barFill(value: number): string { + const base = loadRgb(value); + const deep = base.map((channel) => Math.round(channel * 0.62)); + const gloss = base.map((channel) => Math.round(channel + (255 - channel) * 0.35)); + const css = (rgb: number[]) => `rgb(${rgb.join(",")})`; + return `linear-gradient(180deg, ${css(gloss)} 0%, ${css(base)} 45%, ${css(deep)} 100%)`; +} + +function CpuPanel({ + total, + cores, + history, + zh, +}: { + total: number; + cores: number[]; + history: MetricHistory; + zh: boolean; +}) { + return ( +
+
+

CPU

+
+ + {Math.round(total)}% + +
+
+ + {cores.length > 0 ? ( + <> +
+ {cores.map((value, index) => ( + + + + ))} +
+
+ {zh ? `逻辑核心 ×${cores.length}` : `Logical cores ×${cores.length}`} +
+ + ) : null} +
+ ); +} + +export function DiskGlyph() { + return ( + + ); +} + +export function WidgetPanels({ + snapshot, + prefs, + history, + zh, +}: { + snapshot: SystemSnapshot | null; + prefs: WidgetPrefs; + history: MetricHistory; + zh: boolean; +}) { + const memory = snapshot?.memory; + const memoryPct = memory ? percent(memory.used, memory.total) : 0; + const gpu = snapshot?.gpu_usage ?? null; + return ( + <> + {prefs.panelRun ? ( +
+
+
+

{zh ? "运行状态" : "Status"}

+ {snapshot?.host.hostname || "Squid"} +
+ {zh ? "本次运行" : "Uptime"} + {uptimeFull(snapshot?.uptime_secs ?? 0, zh)} +
+
+
+ + + + +
+
+
+ ) : null} + + {prefs.panelCpu ? ( + + ) : null} + + {prefs.panelNetwork ? ( +
+
+

{zh ? "网络" : "Network"}

+
+ ↑ {formatRate(snapshot?.network.tx_per_sec ?? 0)} + ↓ {formatRate(snapshot?.network.rx_per_sec ?? 0)} +
+
+ + +
+ ) : null} + + {prefs.panelDisk ? ( +
+
+

{zh ? "存储读写" : "Disk I/O"}

+
+ R {formatRate(snapshot?.disk.read_per_sec ?? 0)} + W {formatRate(snapshot?.disk.write_per_sec ?? 0)} +
+
+ +
+ ) : null} + + {prefs.panelStorage ? ( +
+

{zh ? "存储空间" : "Storage"}

+ {(snapshot?.volumes ?? []).slice(0, 4).map((volume) => { + const used = volume.total - volume.free; + return ( +
+ + + +
+
+ + {volume.name && !/^[A-Za-z]:$/.test(volume.name) + ? `${volume.name} (${volume.mount_point})` + : volume.mount_point} + + + {formatBytes(used)} / {formatBytes(volume.total)} + +
+
+ +
+
+
+ ); + })} +
+ ) : null} + + ); +} diff --git a/src/components/ui.tsx b/src/components/ui.tsx index 16a92ad..0dd5e0b 100644 --- a/src/components/ui.tsx +++ b/src/components/ui.tsx @@ -5,6 +5,7 @@ import { Check, ChevronDown, Code2, + DownloadCloud, FileWarning, Globe2, Languages, @@ -120,11 +121,25 @@ export const CATEGORY_META: Record = { icon: Puzzle, tone: "warning", }, + "update-installers": { + en: "Update installers", + zh: "升级安装包", + blurbEn: "Installer packages apps keep after updating", + blurbZh: "应用升级后留下的安装包,需要时会自动重新下载", + icon: DownloadCloud, + tone: "success", + }, }; export const CATEGORY_ORDER = Object.keys(CATEGORY_META) as Category[]; -export function categoryLabel(category: Category, language: "zh" | "en"): string { +export function categoryLabel( + category: Category, + language: "zh" | "en", + binName?: string, +): string { + // The bin category borrows the OS word for it: 回收站 on Windows, 废纸篓 on macOS. + if (category === "trash" && binName) return binName; return language === "zh" ? CATEGORY_META[category].zh : CATEGORY_META[category].en; } @@ -279,6 +294,7 @@ export function Select({ label, disabled = false, align = "end", + placement = "down", }: { value: T; options: { value: T; label: string }[]; @@ -286,6 +302,7 @@ export function Select({ label: string; disabled?: boolean; align?: "start" | "end"; + placement?: "down" | "up"; }) { const [open, setOpen] = useState(false); const [active, setActive] = useState(0); @@ -355,7 +372,7 @@ export function Select({ {open ? (
    @@ -687,14 +704,18 @@ export function EmptyState({ action, }: { icon: ReactNode; - title: string; + title?: string; description?: string; action?: ReactNode; }) { return (
    {icon}
    -

    {title}

    + {title ? ( +

    {title}

    + ) : ( +
    @@ -740,7 +761,7 @@ export function CategoryCard({ onInspect: () => void; focused?: boolean; }) { - const { lang, t } = useI18n(); + const { lang, t, bin } = useI18n(); const meta = CATEGORY_META[category]; const Icon = meta.icon; return ( @@ -758,11 +779,11 @@ export function CategoryCard({ checked={selected} disabled={disabled} onChange={onToggle} - label={categoryLabel(category, lang)} + label={categoryLabel(category, lang, bin)} />
- {categoryLabel(category, lang)} + {categoryLabel(category, lang, bin)} {lang === "zh" ? meta.blurbZh : meta.blurbEn}
diff --git a/src/hooks/usePermissionsWorkspace.ts b/src/hooks/usePermissionsWorkspace.ts new file mode 100644 index 0000000..0f4027f --- /dev/null +++ b/src/hooks/usePermissionsWorkspace.ts @@ -0,0 +1,221 @@ +import { useCallback, useEffect, useState } from "react"; +import { api } from "../lib/api"; +import { isCancelled, messageFrom } from "../lib/format"; +import type { ManageView, PopupWindowItem } from "../types"; + +export type PermissionsTab = "startup" | "extensions" | "popup"; + +export interface PermissionsWorkspace { + tab: PermissionsTab; + setTab: (tab: PermissionsTab) => void; + view: ManageView | null; + windows: PopupWindowItem[]; + scanning: boolean; + busyId: string | null; + error: string | null; + dismissError: () => void; + closedTotal: number; + recentClosed: { process: string; title: string }[]; + scan: () => Promise; + refreshWindows: () => Promise; + toggleStartup: (id: string, enabled: boolean) => Promise; + toggleExtension: (id: string, registered: boolean) => Promise; + addRule: (hwnd: number, matcher: "exact" | "contains") => Promise; + toggleRule: (index: number, enabled: boolean) => Promise; + removeRule: (index: number) => Promise; + closeWindow: (hwnd: number) => Promise; + setWatcher: (enabled: boolean) => Promise; +} + +export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace { + const [tab, setTab] = useState("startup"); + const [view, setView] = useState(null); + const [windows, setWindows] = useState([]); + const [scanning, setScanning] = useState(false); + const [busyId, setBusyId] = useState(null); + const [error, setError] = useState(null); + const [closedTotal, setClosedTotal] = useState(0); + const [recentClosed, setRecentClosed] = useState<{ process: string; title: string }[]>([]); + + const scan = useCallback(async () => { + setScanning(true); + setError(null); + try { + const next = await api.manageScan(); + setView(next); + setWindows(next.windows); + setClosedTotal(next.rules.reduce((sum, rule) => sum + rule.closed, 0)); + } catch (reason) { + if (!isCancelled(reason)) setError(messageFrom(reason)); + } finally { + setScanning(false); + } + }, []); + + const refreshWindows = useCallback(async () => { + try { + setWindows(await api.popupList()); + } catch (reason) { + setError(messageFrom(reason)); + } + }, []); + + useEffect(() => { + if (active && !view && !scanning) void scan(); + }, [active, scan, view, scanning]); + + useEffect(() => { + if (!active) return; + let stop: (() => void) | null = null; + let cancelled = false; + void api + .onPopupClosed((event) => { + setClosedTotal((total) => total + 1); + setRecentClosed((recent) => [{ ...event }, ...recent].slice(0, 3)); + setView((current) => + current + ? { + ...current, + rules: current.rules.map((rule, index) => + index === event.ruleIndex ? { ...rule, closed: rule.closed + 1 } : rule, + ), + } + : current, + ); + }) + .then((unlisten) => { + if (cancelled) unlisten(); + else stop = unlisten; + }); + return () => { + cancelled = true; + stop?.(); + }; + }, [active]); + + const toggleStartup = useCallback( + async (id: string, enabled: boolean) => { + setBusyId(id); + setError(null); + try { + await api.managedStartupSetEnabled(id, enabled); + await scan(); + } catch (reason) { + setError(messageFrom(reason)); + } finally { + setBusyId(null); + } + }, + [scan], + ); + + const toggleExtension = useCallback( + async (id: string, registered: boolean) => { + setBusyId(id); + setError(null); + try { + await api.extensionSetRegistered(id, registered); + setView((current) => + current + ? { + ...current, + extensions: current.extensions.map((entry) => + entry.id === id ? { ...entry, registered } : entry, + ), + } + : current, + ); + } catch (reason) { + setError(messageFrom(reason)); + } finally { + setBusyId(null); + } + }, + [], + ); + + const addRule = useCallback( + async (hwnd: number, matcher: "exact" | "contains") => { + setError(null); + try { + await api.popupAddRule(hwnd, matcher); + await scan(); + } catch (reason) { + setError(messageFrom(reason)); + } + }, + [scan], + ); + + const toggleRule = useCallback(async (index: number, enabled: boolean) => { + setError(null); + try { + await api.popupRuleUpdate(index, enabled); + setView((current) => + current + ? { + ...current, + rules: current.rules.map((rule, i) => (i === index ? { ...rule, enabled } : rule)), + } + : current, + ); + } catch (reason) { + setError(messageFrom(reason)); + } + }, []); + + const removeRule = useCallback( + async (index: number) => { + setError(null); + try { + await api.popupRuleRemove(index); + await scan(); + } catch (reason) { + setError(messageFrom(reason)); + } + }, + [scan], + ); + + const closeWindow = useCallback(async (hwnd: number) => { + setError(null); + try { + await api.popupClose(hwnd); + setWindows((current) => current.filter((window) => window.hwnd !== hwnd)); + } catch (reason) { + setError(messageFrom(reason)); + } + }, []); + + const setWatcher = useCallback(async (enabled: boolean) => { + setError(null); + try { + await api.popupWatcherSet(enabled); + setView((current) => (current ? { ...current, watcherEnabled: enabled } : current)); + } catch (reason) { + setError(messageFrom(reason)); + } + }, []); + + return { + tab, + setTab, + view, + windows, + scanning, + busyId, + error, + dismissError: () => setError(null), + closedTotal, + recentClosed, + scan, + refreshWindows, + toggleStartup, + toggleExtension, + addRule, + toggleRule, + removeRule, + closeWindow, + setWatcher, + }; +} diff --git a/src/hooks/useScanWorkspace.ts b/src/hooks/useScanWorkspace.ts index 0dd1f01..1411d95 100644 --- a/src/hooks/useScanWorkspace.ts +++ b/src/hooks/useScanWorkspace.ts @@ -35,9 +35,10 @@ export interface ScanWorkspace { cancel: () => Promise; toggleItem: (index: number) => void; toggleCategory: (category: Category) => void; + deselect: (indexes: number[]) => void; selectAll: () => void; clearSelection: () => void; - clean: (mode: DeleteMode) => Promise; + clean: (mode: DeleteMode, indexes?: number[]) => Promise; clearError: () => void; reset: () => void; } @@ -149,6 +150,16 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace { const clearSelection = useCallback(() => setSelected(new Set()), []); + const deselect = useCallback((indexes: number[]) => { + if (indexes.length === 0) return; + const drop = new Set(indexes); + setSelected((current) => { + const next = new Set(current); + for (const index of drop) next.delete(index); + return next; + }); + }, []); + const selectedTotal = useMemo(() => { if (!result) return 0; let total = 0; @@ -159,8 +170,10 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace { const selectedCount = selected.size; const clean = useCallback( - async (mode: DeleteMode) => { - if (!result || selected.size === 0 || deleting) return null; + async (mode: DeleteMode, indexes?: number[]) => { + if (!result || deleting) return null; + const targets = indexes ?? [...selected]; + if (targets.length === 0) return null; const id = jobId(); activeJob.current = id; setCurrentJob(id); @@ -171,8 +184,8 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace { try { const next = kind === "cleanup" - ? await api.cleanupDelete(id, result.scanId, [...selected], mode) - : await api.purgeDelete(id, result.scanId, [...selected], mode); + ? await api.cleanupDelete(id, result.scanId, targets, mode) + : await api.purgeDelete(id, result.scanId, targets, mode); if (activeJob.current !== id) return null; setResult(null); setSelected(new Set()); @@ -217,6 +230,7 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace { cancel, toggleItem, toggleCategory, + deselect, selectAll, clearSelection, clean, diff --git a/src/hooks/useSystemSnapshot.ts b/src/hooks/useSystemSnapshot.ts index 58593a2..d858112 100644 --- a/src/hooks/useSystemSnapshot.ts +++ b/src/hooks/useSystemSnapshot.ts @@ -3,7 +3,19 @@ import { api } from "../lib/api"; import { messageFrom } from "../lib/format"; import type { SystemSnapshot } from "../types"; -export function useSystemSnapshot(active: boolean, intervalMs = 1800) { +/** + * Polls system_snapshot for a page. + * + * - `full` asks the backend for the expensive per-process walk (only the + * 实时监控 top-process table needs it); light refreshes cost a fraction. + * - Polling pauses while the window is hidden (tray) or the tab is hidden, + * so an icon in the notification area does not keep sampling forever. + */ +export function useSystemSnapshot( + active: boolean, + intervalMs = 1800, + full = false, +) { const [snapshot, setSnapshot] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); @@ -14,7 +26,7 @@ export function useSystemSnapshot(active: boolean, intervalMs = 1800) { inFlight.current = true; setLoading(true); try { - setSnapshot(await api.systemSnapshot()); + setSnapshot(await api.systemSnapshot(full)); setError(null); } catch (reason) { setError(messageFrom(reason)); @@ -22,13 +34,35 @@ export function useSystemSnapshot(active: boolean, intervalMs = 1800) { inFlight.current = false; setLoading(false); } - }, []); + }, [full]); useEffect(() => { if (!active) return; - void refresh(); - const timer = window.setInterval(() => void refresh(), intervalMs); - return () => window.clearInterval(timer); + let live = true; + let timer: number | null = null; + const tick = () => { + if (live && !document.hidden) void refresh(); + }; + const start = () => { + if (timer === null) { + void refresh(); + timer = window.setInterval(tick, intervalMs); + } + }; + const stop = () => { + if (timer !== null) { + window.clearInterval(timer); + timer = null; + } + }; + const onVisibility = () => (document.hidden ? stop() : start()); + start(); + document.addEventListener("visibilitychange", onVisibility); + return () => { + live = false; + stop(); + document.removeEventListener("visibilitychange", onVisibility); + }; }, [active, intervalMs, refresh]); return { snapshot, error, loading, refresh }; diff --git a/src/i18n.tsx b/src/i18n.tsx index 6763299..d0c027d 100644 --- a/src/i18n.tsx +++ b/src/i18n.tsx @@ -15,18 +15,23 @@ const I18nContext = createContext(null); export function I18nProvider({ lang, setLang, + binNoun = "trash", children, }: { lang: Language; setLang: (language: Language) => void; + binNoun?: "trash" | "recycle-bin"; children: ReactNode; }) { + // Windows calls it 回收站; macOS and freedesktop keep 废纸篓. + const zhBin = binNoun === "recycle-bin" ? "回收站" : "废纸篓"; + const enBin = binNoun === "recycle-bin" ? "Recycle Bin" : "Trash"; const value: I18nValue = { lang, setLang, t: (en, zh) => (lang === "zh" ? zh : en), - bin: lang === "zh" ? "废纸篓" : "Trash", - binLower: lang === "zh" ? "废纸篓" : "trash", + bin: lang === "zh" ? zhBin : enBin, + binLower: lang === "zh" ? zhBin : enBin.toLowerCase(), currency: lang === "zh" ? "zh-CN" : "en-US", }; return {children}; diff --git a/src/lib/api.ts b/src/lib/api.ts index da9c201..166289d 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -9,9 +9,12 @@ import type { JobProgress, LargestFile, IntelStatus, + ManageView, PageId, PermissionStatus, PlanResult, + PopupClosedEvent, + PopupWindowItem, ScanResult, SettingsView, SecurityAction, @@ -28,6 +31,8 @@ import type { UpdateCheckResult, UpdateProgress, UpdateStatus, + WidgetPatch, + WidgetPrefs, } from "../types"; export interface SettingsPatch { @@ -76,7 +81,7 @@ export const api = { invoke("storage_explore", { jobId, path, depth, top }), storageLargestFiles: (jobId: string, path: string, limit = 40) => invoke("storage_largest_files", { jobId, path, limit }), - systemSnapshot: () => invoke("system_snapshot"), + systemSnapshot: (full = false) => invoke("system_snapshot", { full }), stopProcess: (process: SystemSnapshot["top_processes"][number]) => invoke("stop_process", { process }), historyList: (limit = 60) => invoke("history_list", { limit }), @@ -90,6 +95,23 @@ export const api = { openTrash: () => invoke("open_trash"), permissionStatus: () => invoke("permission_status"), openFullDiskAccessSettings: () => invoke("open_full_disk_access_settings"), + manageScan: () => invoke("manage_scan"), + managedStartupSetEnabled: (id: string, enabled: boolean) => + invoke("managed_startup_set_enabled", { id, enabled }), + extensionSetRegistered: (id: string, registered: boolean) => + invoke("extension_set_registered", { id, registered }), + popupList: () => invoke("popup_list"), + popupClose: (hwnd: number) => invoke("popup_close", { hwnd }), + popupAddRule: (hwnd: number, matcher: string) => + invoke("popup_add_rule", { hwnd, matcher }), + popupRuleUpdate: (index: number, enabled?: boolean, resetCount?: boolean) => + invoke("popup_rule_update", { index, enabled, resetCount }), + popupRuleRemove: (index: number) => invoke("popup_rule_remove", { index }), + popupWatcherSet: (enabled: boolean) => invoke("popup_watcher_set", { enabled }), + widgetGet: () => + invoke<{ prefs: WidgetPrefs; language: "zh" | "en" }>("widget_get"), + widgetSet: (patch: WidgetPatch) => invoke("widget_set", { patch }), + widgetHide: () => invoke("widget_hide"), updateCheck: () => invoke("update_check"), updateStatus: () => invoke("update_status"), updateDownload: () => invoke("update_download"), @@ -133,8 +155,14 @@ export const api = { listen("update://status", (event) => handler(event.payload)), onNavigate: (handler: (page: PageId) => void) => listen("squid://navigate", (event) => handler(event.payload)), + onWindowVisible: (handler: (visible: boolean) => void) => + listen("squid://visible", (event) => handler(event.payload)), onSecurityScan: (handler: (scan: SecurityScan) => void) => listen("squid://security", (event) => handler(event.payload)), + onPopupClosed: (handler: (event: PopupClosedEvent) => void) => + listen("popup://closed", (event) => handler(event.payload)), + onWidgetSettings: (handler: (prefs: WidgetPrefs) => void) => + listen("widget://settings", (event) => handler(event.payload)), }; /// Progress events for one job, whatever kind of job it is. Security scans share diff --git a/src/main.tsx b/src/main.tsx index b0227a4..003f2b4 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -2,12 +2,14 @@ import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; import { ToastProvider } from "./components/ui"; +import { WidgetWindow } from "./pages/WidgetWindow"; import "./styles.css"; +// The widget window reuses this bundle with ?view=widget (see widget.rs). +const isWidget = new URLSearchParams(window.location.search).get("view") === "widget"; + ReactDOM.createRoot(document.getElementById("root")!).render( - - - + {isWidget ? : } , ); diff --git a/src/pages/ApplicationsPage.tsx b/src/pages/ApplicationsPage.tsx index 3fb52d8..b96e1bc 100644 --- a/src/pages/ApplicationsPage.tsx +++ b/src/pages/ApplicationsPage.tsx @@ -151,7 +151,6 @@ export function ApplicationsPage({ return (
{item.label} {shortPath(item.displayPath, 44)} - {categoryLabel(item.category, lang)} + {categoryLabel(item.category, lang, bin)} {item.note ? ` · ${item.note}` : ""} {item.lock ? ` · ${lockLabel(item.lock, t)}` : ""} @@ -357,7 +356,6 @@ export function ApplicationsPage({ {!workspace.scanned && !workspace.scanning ? ( } - title={t("See what is installed", "查看已安装的应用")} action={ + } + /> +
+ ); + } + + const needle = query.trim().toLowerCase(); + const startup = view.startup.filter( + (item) => + !needle || + item.name.toLowerCase().includes(needle) || + item.displayName.toLowerCase().includes(needle) || + item.command.toLowerCase().includes(needle), + ); + // 电脑管家 style: one group per software, Chinese name in the header. + const startupGroups = new Map(); + for (const item of startup) { + const list = startupGroups.get(item.displayName) ?? []; + list.push(item); + startupGroups.set(item.displayName, list); + } + const groupedExtensions = view.extensions + .filter( + (entry) => + !needle || + entry.name.toLowerCase().includes(needle) || + (entry.friendlyName ?? "").toLowerCase().includes(needle) || + (entry.publisher ?? "").toLowerCase().includes(needle) || + (entry.module ?? "").toLowerCase().includes(needle), + ) + .reduce>((groups, entry) => { + (groups[entry.extensionPoint] ??= []).push(entry); + return groups; + }, {}); + // Categories stay in the backend's 文件 / 文件夹 / 桌面 / 驱动器 / 所有对象 + // order; the horizontal nav shows one at a time so long lists never make + // the page scroll for miles. + const extCategories = Object.keys(groupedExtensions); + const activeCategory = + extCat && extCategories.includes(extCat) ? extCat : extCategories[0] ?? null; + + return ( +
+ } + onClick={() => void workspace.scan()} + disabled={workspace.scanning} + > + {t("Rescan", "重新扫描")} + + } + /> + +
+ {tabs.map((tab) => ( + + ))} +
+ + {workspace.error ? ( + + ) : null} + + {workspace.tab === "startup" ? ( +
+ + + {Array.from(startupGroups.entries()).map(([software, items]) => ( +
+

+ {items.find((item) => item.icon)?.icon ? ( + + ) : ( + + )} + {software} + + {t( + `${items.filter((item) => item.enabled).length}/${items.length} on`, + `${items.filter((item) => item.enabled).length}/${items.length} 开启`, + )} + +

+
+ {items.map((item) => ( +
+
+ +
+ {item.name} + + {item.sourceLabel} · {scopeLabel(item.scope, t)} + {item.command ? ` · ${shortPath(item.command, 72)}` : ""} + +
+
+ void workspace.toggleStartup(item.id, next)} + label={`${item.name} ${item.enabled ? "disable" : "enable"}`} + /> +
+ ))} +
+
+ ))} + {startup.length === 0 ? ( +

{t("No matches.", "没有匹配的项目。")}

+ ) : null} +
+ ) : null} + + {workspace.tab === "extensions" ? ( +
+ +
+
+ {extCategories.map((point) => { + const entries = groupedExtensions[point]; + const on = entries.filter((e) => e.registered).length; + return ( + + ); + })} +
+ +
+
+ {(activeCategory ? groupedExtensions[activeCategory] : []).map((entry) => ( +
+
+ +
+ {entry.friendlyName ?? entry.name} + + {entry.publisher + ? `${t("Creator", "创建者")} ${entry.publisher} · ` + : ""} + {scopeLabel(entry.scope, t)} + {entry.module ? ` · ${shortPath(entry.module, 56)}` : ""} + {!entry.registered ? ` · ${t("removed", "已移除")}` : ""} + +
+
+ void workspace.toggleExtension(entry.id, next)} + label={`${entry.name} ${entry.registered ? "remove" : "restore"}`} + /> +
+ ))} +
+ {extCategories.length === 0 ? ( +

{t("No matches.", "没有匹配的项目。")}

+ ) : null} +
+ ) : null} + + {workspace.tab === "popup" ? ( + <> +
+ void workspace.setWatcher(next)} + label={t("Popup blocker switch", "弹窗拦截总开关")} + /> + } + /> + {workspace.recentClosed.length > 0 ? ( +
+ + + {workspace.recentClosed[0].process} · {workspace.recentClosed[0].title} + +
+ ) : null} +
+ +
+ +
+ {view.rules.map((rule, index) => ( +
+
+ +
+ {rule.title} + + {shortPath(rule.exe, 64)} ·{" "} + {t(`closed ${rule.closed}×`, `已关闭 ${rule.closed} 次`)} + +
+
+
+ void workspace.toggleRule(index, next)} + label={`${rule.title} ${rule.enabled ? "disable" : "enable"}`} + /> + void workspace.removeRule(index)} + > + + +
+
+ ))} + {view.rules.length === 0 ? ( +

+ {t( + "No rules yet — pick a window below.", + "还没有规则,先从下面的当前窗口里“拦截”一个。", + )} +

+ ) : null} +
+
+ +
+ } + onClick={() => void workspace.refreshWindows()} + > + {t("Refresh", "刷新")} + + } + /> +
+ {workspace.windows.map((window) => ( +
+
+ +
+ {window.title} + {window.process} +
+
+
+ + void workspace.closeWindow(window.hwnd)} + > + + +
+
+ ))} +
+
+ + ) : null} +
+ ); +} diff --git a/src/pages/SettingsPage.tsx b/src/pages/SettingsPage.tsx index d17af42..8917d50 100644 --- a/src/pages/SettingsPage.tsx +++ b/src/pages/SettingsPage.tsx @@ -528,7 +528,7 @@ export function SettingsPage({
{t("Platform", "平台")} - {bootstrap.osName} {bootstrap.osVersion} · {bootstrap.arch} ·{" "} + {bootstrap.osVersion || bootstrap.osName} · {bootstrap.arch} ·{" "} {bootstrap.hardware}
diff --git a/src/pages/SystemPage.tsx b/src/pages/SystemPage.tsx index 584d819..0b089d9 100644 --- a/src/pages/SystemPage.tsx +++ b/src/pages/SystemPage.tsx @@ -3,13 +3,14 @@ import { BatteryCharging, Cpu, HardDrive, + MonitorSmartphone, Network, Power, RefreshCw, ShieldAlert, Timer, } from "lucide-react"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import { useI18n } from "../i18n"; import { api } from "../lib/api"; import { @@ -21,7 +22,7 @@ import { messageFrom, percent, } from "../lib/format"; -import type { ProcessSample, SystemSnapshot } from "../types"; +import type { ProcessSample, SystemSnapshot, WidgetPrefs } from "../types"; import type { SecurityWorkspace } from "../hooks/useSecurityWorkspace"; import { ProcessTable } from "../components/ProcessTable"; import { @@ -32,6 +33,7 @@ import { MetricBar, PageHeader, SectionTitle, + Toggle, UsageBar, useToast, } from "../components/ui"; @@ -63,6 +65,45 @@ export function SystemPage({ const [tab, setTab] = useState<"performance" | "processes">( initialProcessFilter ? "processes" : "performance", ); + const [widget, setWidget] = useState(null); + const [widgetBusy, setWidgetBusy] = useState(false); + + useEffect(() => { + let cancelled = false; + let stop: (() => void) | null = null; + void api + .widgetGet() + .then((view) => !cancelled && setWidget(view.prefs)) + .catch(() => undefined); + void api + .onWidgetSettings((next) => !cancelled && setWidget(next)) + .then((unlisten) => { + if (cancelled) unlisten(); + else stop = unlisten; + }); + return () => { + cancelled = true; + stop?.(); + }; + }, []); + + const toggleWidget = async (enabled: boolean) => { + setWidgetBusy(true); + try { + const next = await api.widgetSet({ enabled }); + setWidget(next); + push( + enabled + ? t("Desktop widget is now on.", "桌面实时监控已显示。") + : t("Desktop widget is now hidden.", "桌面实时监控已隐藏。"), + "success", + ); + } catch (reason) { + push(messageFrom(reason), "danger"); + } finally { + setWidgetBusy(false); + } + }; const stop = async () => { if (!victim) return; @@ -137,7 +178,35 @@ export function SystemPage({ ) : null}