diff --git a/.gitignore b/.gitignore index c2416a1..0760418 100644 --- a/.gitignore +++ b/.gitignore @@ -64,3 +64,6 @@ __pycache__/ !release/0.1.3/Squid-Setup-0.1.3-win-x64.exe !release/0.1.4/Squid-0.1.4-macOS-universal.dmg !release/0.1.4/Squid-Setup-0.1.4-win-x64.exe + +# 输入法/软件在 cwd 落的调试日志(sogou 等) +debug.log diff --git a/Cargo.lock b/Cargo.lock index 09f2908..86e1da8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aho-corasick" version = "1.1.5" @@ -94,6 +100,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.2" @@ -225,6 +237,15 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "crc32fast" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -265,7 +286,7 @@ version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" dependencies = [ - "bitflags", + "bitflags 2.13.2", "crossterm_winapi", "mio", "parking_lot", @@ -367,12 +388,32 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + [[package]] name = "foldhash" version = "0.1.5" @@ -590,6 +631,26 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.4" @@ -632,7 +693,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags", + "bitflags 2.13.2", ] [[package]] @@ -701,6 +762,19 @@ dependencies = [ "time", ] +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "powerfmt" version = "0.2.1" @@ -740,7 +814,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" dependencies = [ - "bitflags", + "bitflags 2.13.2", "cassowary", "compact_str", "crossterm", @@ -781,7 +855,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.13.2", ] [[package]] @@ -817,7 +891,7 @@ version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys 0.4.15", @@ -830,7 +904,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys 0.12.1", @@ -953,6 +1027,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "slab" version = "0.4.12" @@ -967,7 +1047,7 @@ checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" [[package]] name = "squid-cli" -version = "0.1.4" +version = "0.1.7" dependencies = [ "anyhow", "chrono", @@ -986,7 +1066,7 @@ dependencies = [ [[package]] name = "squid-core" -version = "0.1.4" +version = "0.1.7" dependencies = [ "anyhow", "chrono", @@ -1005,7 +1085,7 @@ dependencies = [ [[package]] name = "squid-engine" -version = "0.1.4" +version = "0.1.7" dependencies = [ "anyhow", "chrono", @@ -1025,11 +1105,12 @@ dependencies = [ [[package]] name = "squid-platform" -version = "0.1.4" +version = "0.1.7" dependencies = [ "dirs", "libc", "plist", + "png", "rayon", "serde", "squid-core", @@ -1042,7 +1123,7 @@ dependencies = [ [[package]] name = "squid-rules" -version = "0.1.4" +version = "0.1.7" dependencies = [ "globset", "serde", @@ -1054,7 +1135,7 @@ dependencies = [ [[package]] name = "squid-stats" -version = "0.1.4" +version = "0.1.7" dependencies = [ "chrono", "libc", @@ -1062,11 +1143,12 @@ dependencies = [ "squid-core", "squid-platform", "sysinfo", + "windows-sys 0.59.0", ] [[package]] name = "squid-tui" -version = "0.1.4" +version = "0.1.7" dependencies = [ "anyhow", "chrono", @@ -1729,6 +1811,12 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index f74687b..b84dbd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*"] exclude = ["src-tauri"] [workspace.package] -version = "0.1.4" +version = "0.1.9" edition = "2021" rust-version = "1.80" license = "GPL-3.0-only" diff --git a/crates/squid-cli/src/main.rs b/crates/squid-cli/src/main.rs index 876082a..38f535f 100644 --- a/crates/squid-cli/src/main.rs +++ b/crates/squid-cli/src/main.rs @@ -1195,11 +1195,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 fcc2e03..189ff6a 100644 --- a/crates/squid-core/src/model.rs +++ b/crates/squid-core/src/model.rs @@ -368,6 +368,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 2e409f7..2be4723 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/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/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 8361d98..fc4db77 100644 --- a/crates/squid-engine/src/uninstall.rs +++ b/crates/squid-engine/src/uninstall.rs @@ -471,6 +471,7 @@ mod tests { has_sibling_install: false, publisher: None, installed_ms: None, + display_icon: None, } } diff --git a/crates/squid-platform/Cargo.toml b/crates/squid-platform/Cargo.toml index c0e114d..09aa6be 100644 --- a/crates/squid-platform/Cargo.toml +++ b/crates/squid-platform/Cargo.toml @@ -22,4 +22,5 @@ libc.workspace = true [target.'cfg(windows)'.dependencies] winreg = "0.52" sysinfo.workspace = true -windows-sys = { version = "0.59", features = ["Win32_System_Console", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_Security", "Win32_System_Threading"] } +png = "0.17" +windows-sys = { version = "0.59", features = ["Win32_System_Console", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_Security", "Win32_System_Threading", "Win32_System_Registry", "Win32_Globalization", "Win32_UI_WindowsAndMessaging", "Win32_UI_Shell", "Win32_Graphics_Gdi", "Win32_System_SystemInformation", "Win32_System_IO"] } diff --git a/crates/squid-platform/src/apps.rs b/crates/squid-platform/src/apps.rs index 5647a28..b044953 100644 --- a/crates/squid-platform/src/apps.rs +++ b/crates/squid-platform/src/apps.rs @@ -134,6 +134,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 bc53097..3f68ad6 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; #[cfg(unix)] pub mod volumes; @@ -228,6 +229,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 93ea2a0..551b18f 100644 --- a/crates/squid-platform/src/linux.rs +++ b/crates/squid-platform/src/linux.rs @@ -200,6 +200,7 @@ impl Platform for Linux { has_sibling_install: false, publisher: desktop.icon.clone(), installed_ms: None, + display_icon: None, }); } } @@ -234,6 +235,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/windows.rs b/crates/squid-platform/src/windows.rs index 1fb7d69..4c5dd93 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('-', ""); @@ -101,24 +160,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) @@ -126,8 +177,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, @@ -155,7 +206,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() @@ -203,17 +254,31 @@ 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, 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"), }); } } @@ -317,3 +382,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 0eb8b31..80bca7d 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)] @@ -270,6 +280,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, @@ -428,36 +442,39 @@ pub struct AppUsage { } fn cpu_stats(system: &System) -> CpuStats { - // sysinfo puts the aggregate sample in `cpus()[0]`; the tail is one entry - // per logical core. - let all = system.cpus(); - let (aggregate, cores) = all - .split_first() - .map(|(head, tail)| (Some(head), tail)) - .unwrap_or((None, &[])); + // 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 brand = aggregate - .or_else(|| cores.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 = aggregate - .or_else(|| cores.first()) + let base_frequency_ghz = cores + .first() .map(|cpu| cpu.frequency() as f64 / 1_000.0) .unwrap_or(0.0); - let total = aggregate - .map(|cpu| cpu.cpu_usage()) - .unwrap_or_else(|| system.global_cpu_usage()) - .clamp(0.0, 100.0); - let logical_cores = if per_core.is_empty() { - 1 + let total = system.global_cpu_usage().clamp(0.0, 100.0); + // 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.len() + per_core }; - let physical = detect_physical_cores().unwrap_or_else(|| logical_cores.div_ceil(2)); + 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, @@ -529,8 +546,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()), @@ -545,6 +565,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)> { diff --git a/crates/squid-tui/src/app.rs b/crates/squid-tui/src/app.rs index c2cbd1c..af1dda3 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) { @@ -2600,6 +2609,7 @@ mod tests { has_sibling_install: false, publisher: None, installed_ms: None, + display_icon: None, }; let items = vec![ CleanupItem::new( @@ -2624,7 +2634,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(); @@ -2693,6 +2705,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); @@ -2712,7 +2725,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"); @@ -2835,12 +2848,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" @@ -2884,7 +2897,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)); @@ -2923,7 +2936,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"); @@ -3059,8 +3072,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]; @@ -3120,7 +3137,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, @@ -3162,8 +3181,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; @@ -3229,7 +3252,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)); @@ -3249,13 +3275,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) }); @@ -3281,7 +3311,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; @@ -3325,7 +3357,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)); @@ -3479,7 +3511,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"); @@ -3709,7 +3741,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/views.rs b/crates/squid-tui/src/views.rs index 842689c..983b2e5 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, @@ -2051,6 +2052,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/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 2f06f8b..4e0e51e 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "squid-desktop", "private": true, - "version": "0.1.4", + "version": "0.1.9", "type": "module", "scripts": { "dev": "vite --port 1420 --strictPort", diff --git a/release/0.1.6/README-Windows-x64.txt b/release/0.1.6/README-Windows-x64.txt new file mode 100644 index 0000000..92c9511 --- /dev/null +++ b/release/0.1.6/README-Windows-x64.txt @@ -0,0 +1,39 @@ +Squid 0.1.6 - Windows x64 + +系统要求 +-------- +- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。 +- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid + 启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime: + https://developer.microsoft.com/microsoft-edge/webview2/ +- 安装与运行都不需要管理员权限。安装位置为 + %LOCALAPPDATA%\Programs\Squid。 +- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份 + 运行 Squid 才能修改,界面会给出明确提示。 + +安装 +---- +1. 运行 Squid-Setup-0.1.6-win-x64.exe。 +2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。 +3. 卸载请在 Windows“设置 > 应用”中移除 Squid。 + +更新 +---- +Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验 +文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥, +还会验证清单的 Ed25519 签名。 + +校验 +---- +PowerShell: + Get-FileHash .\Squid-Setup-0.1.6-win-x64.exe -Algorithm SHA256 + +提示 +---- +- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标 + 上右键退出),否则安装程序无法替换正在运行的程序文件。 +- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入 + 临时目录,报"NSIS Error - Error writing temporary file"。遇到时请在 + 管家弹窗中选择"允许",或将安装文件加入信任区后重试;也可改用 + 便携包 Squid-0.1.6-portable-win-x64.zip 直接覆盖安装目录中的 + squid-desktop.exe,效果相同。 diff --git a/release/0.1.6/RELEASE_NOTES.md b/release/0.1.6/RELEASE_NOTES.md new file mode 100644 index 0000000..46770a8 --- /dev/null +++ b/release/0.1.6/RELEASE_NOTES.md @@ -0,0 +1,36 @@ +Squid 0.1.6 + +新增 +- 维护组新增「权限管理」页,覆盖开机启动项、软件弹窗拦截、管理右键菜单三大场景。 + - 开机启动项聚合注册表 Run/RunOnce(含 32 位)、启动文件夹、计划任务(自动跳过 + 系统任务)、系统服务四类来源,条目与开关状态和任务管理器、腾讯电脑管家对齐; + 开关直接读写 StartupApproved,不改动启动配置本身。 + - 右键菜单扩展按菜单位置分组列出,取消注册立即生效,并在本地保留恢复配方。 + - 弹窗拦截:列出当前可见的顶层窗口,可对任一窗口一键建立拦截规则;常驻观察者 + 按间隔自动关闭命中窗口,规则累计拦截次数,支持总开关。 +- 启动项与已安装应用显示软件自带的中文名称(优先 ProductName/FileDescription 的 + 本地化名),启动项按软件分组并显示「n/n 开启」,长描述自动在标点处截断。 +- 软件名前显示程序真实图标:启动项分组标题与卸载应用列表均从 DisplayIcon、卸载器 + 或安装目录主程序提取图标(老式图标按 AND 掩码补全透明通道,.lnk 快捷方式解析 + 真实目标程序)。 +- 电脑概览新增「本机配置」:操作系统版本、主板、处理器型号/核数/线程数、内存 + 容量/品牌/频率、主硬盘品牌/型号/容量/接口、显卡品牌/芯片/显存,全部通过 + SMBIOS、存储 IOCTL 与注册表原生读取,无需管理员权限、不额外拉起命令行工具。 + +改进 +- 电脑概览主卡片移除磁盘占用圆环,原位替换为本机配置面板;整页紧凑化,默认 + 1220×800 窗口内完整显示、无需滚动。 +- 存储空间面板列出所有盘符,逐个显示总容量与可用容量。 +- 修复 CPU 核数识别:逻辑核/物理核与每核占用采样正确(不再把核数算少)。 +- 内存按 1024 进制显示,并标注「硬件保留(含核显)」容量。 +- 修复 Windows 版本识别:升级装机注册表 ProductName 停留在 "Windows 10" 的机器, + 现按构建号(≥22000 为 Windows 11)与 EditionID 营销名判定,正确显示如 + "Windows 11 Pro 26H2"。 +- 机器型号过滤 "Default string"、"To be filled by O.E.M." 等占位值。 + +修复 +- 权限管理页签在浅色主题下的激活态文字对比度。 + +已知限制 +- 部分云桌面/虚拟机(SMBIOS 固件表不可用)无法读取内存品牌与频率,此时内存行 + 只显示容量;物理磁盘总容量在标准用户下可能不可读,此时以硬盘型号标注为准。 diff --git a/release/0.1.6/SHA256SUMS.txt b/release/0.1.6/SHA256SUMS.txt new file mode 100644 index 0000000..3f5fea8 --- /dev/null +++ b/release/0.1.6/SHA256SUMS.txt @@ -0,0 +1,2 @@ +5c49e1ea2f37d35218889bf6ad3b917723595c29062c3f13a5cddc11dd57ae2a Squid-Setup-0.1.6-win-x64.exe +2e014d6299e963cc14bd51c669a432652d057696fafffea9d58aaed2cfd8bcbc Squid-0.1.6-portable-win-x64.zip diff --git a/release/0.1.6/Squid-Setup-0.1.6-win-x64.exe b/release/0.1.6/Squid-Setup-0.1.6-win-x64.exe new file mode 100644 index 0000000..1bc424d Binary files /dev/null and b/release/0.1.6/Squid-Setup-0.1.6-win-x64.exe differ diff --git a/release/0.1.6/squid-update.json b/release/0.1.6/squid-update.json new file mode 100644 index 0000000..b12d818 --- /dev/null +++ b/release/0.1.6/squid-update.json @@ -0,0 +1,13 @@ +{ + "schema": 1, + "version": "0.1.6", + "date": "2026-11-08", + "notes": "Squid 0.1.6\n\n新增\n- 维护组新增「权限管理」页,覆盖开机启动项、软件弹窗拦截、管理右键菜单三大场景。\n - 开机启动项聚合注册表 Run/RunOnce(含 32 位)、启动文件夹、计划任务(自动跳过\n 系统任务)、系统服务四类来源,条目与开关状态和任务管理器、腾讯电脑管家对齐;\n 开关直接读写 StartupApproved,不改动启动配置本身。\n - 右键菜单扩展按菜单位置分组列出,取消注册立即生效,并在本地保留恢复配方。\n - 弹窗拦截:列出当前可见的顶层窗口,可对任一窗口一键建立拦截规则;常驻观察者\n 按间隔自动关闭命中窗口,规则累计拦截次数,支持总开关。\n- 启动项与已安装应用显示软件自带的中文名称(优先 ProductName/FileDescription 的\n 本地化名),启动项按软件分组并显示「n/n 开启」,长描述自动在标点处截断。\n- 软件名前显示程序真实图标:启动项分组标题与卸载应用列表均从 DisplayIcon、卸载器\n 或安装目录主程序提取图标(老式图标按 AND 掩码补全透明通道,.lnk 快捷方式解析\n 真实目标程序)。\n- 电脑概览新增「本机配置」:操作系统版本、主板、处理器型号/核数/线程数、内存\n 容量/品牌/频率、主硬盘品牌/型号/容量/接口、显卡品牌/芯片/显存,全部通过\n SMBIOS、存储 IOCTL 与注册表原生读取,无需管理员权限、不额外拉起命令行工具。\n\n改进\n- 电脑概览主卡片移除磁盘占用圆环,原位替换为本机配置面板;整页紧凑化,默认\n 1220×800 窗口内完整显示、无需滚动。\n- 存储空间面板列出所有盘符,逐个显示总容量与可用容量。\n- 修复 CPU 核数识别:逻辑核/物理核与每核占用采样正确(不再把核数算少)。\n- 内存按 1024 进制显示,并标注「硬件保留(含核显)」容量。\n- 修复 Windows 版本识别:升级装机注册表 ProductName 停留在 \"Windows 10\" 的机器,\n 现按构建号(≥22000 为 Windows 11)与 EditionID 营销名判定,正确显示如\n \"Windows 11 Pro 26H2\"。\n- 机器型号过滤 \"Default string\"、\"To be filled by O.E.M.\" 等占位值。\n\n修复\n- 权限管理页签在浅色主题下的激活态文字对比度。\n\n已知限制\n- 部分云桌面/虚拟机(SMBIOS 固件表不可用)无法读取内存品牌与频率,此时内存行\n 只显示容量;物理磁盘总容量在标准用户下可能不可读,此时以硬盘型号标注为准。", + "artifacts": { + "windows": { + "file": "Squid-Setup-0.1.6-win-x64.exe", + "sha256": "5c49e1ea2f37d35218889bf6ad3b917723595c29062c3f13a5cddc11dd57ae2a", + "size": 3510936 + } + } +} \ No newline at end of file diff --git a/release/0.1.7/README-Windows-x64.txt b/release/0.1.7/README-Windows-x64.txt new file mode 100644 index 0000000..65a74bf --- /dev/null +++ b/release/0.1.7/README-Windows-x64.txt @@ -0,0 +1,39 @@ +Squid 0.1.7 - Windows x64 + +系统要求 +-------- +- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。 +- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid + 启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime: + https://developer.microsoft.com/microsoft-edge/webview2/ +- 安装与运行都不需要管理员权限。安装位置为 + %LOCALAPPDATA%\Programs\Squid。 +- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份 + 运行 Squid 才能修改,界面会给出明确提示。 + +安装 +---- +1. 运行 Squid-Setup-0.1.7-win-x64.exe。 +2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。 +3. 卸载请在 Windows“设置 > 应用”中移除 Squid。 + +更新 +---- +Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验 +文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥, +还会验证清单的 Ed25519 签名。 + +校验 +---- +PowerShell: + Get-FileHash .\Squid-Setup-0.1.7-win-x64.exe -Algorithm SHA256 + +提示 +---- +- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标 + 上右键退出),否则安装程序无法替换正在运行的程序文件。 +- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入 + 临时目录,报"NSIS Error - Error writing temporary file"。遇到时请在 + 管家弹窗中选择"允许",或将安装文件加入信任区后重试;也可改用 + 便携包 Squid-0.1.7-portable-win-x64.zip 直接覆盖安装目录中的 + squid-desktop.exe,效果相同。 diff --git a/release/0.1.7/RELEASE_NOTES.md b/release/0.1.7/RELEASE_NOTES.md new file mode 100644 index 0000000..9ab87ed --- /dev/null +++ b/release/0.1.7/RELEASE_NOTES.md @@ -0,0 +1,31 @@ +Squid 0.1.7 更新说明 + +修复 +- 卸载应用:每个应用的大小此前都显示 0 B。现在读取安装器注册表的 + EstimatedSize(与 Windows「设置 > 应用」显示的同口径数值),没有该项 + 时实测安装目录大小。 +- 电脑概览:本机配置面板中主板、处理器等长文本被截断。面板整体左移, + 长值自动换行,全部完整显示。 + +改进 +- 电脑概览:处理器 / 内存 / 存储空间三个指标面板等宽,进度条更纤细并 + 保留左右留白;存储空间为每个盘符显示占用百分比;整页在默认 1220×800 + 窗口内仍无需滚动即可完整查看。 +- 右键菜单管理按腾讯电脑管家的颗粒度重做: + - 分类按真实右键入口划分:文件 / 文件夹 / 桌面 / 驱动器 / 所有对象。 + 其中「桌面」(桌面空白处右键)为新增分类。 + - 每一项显示可读的软件名:优先取模块自身的 FileDescription / + ProductName(中文本地化名优先),遇到「TODO: <文件说明>」这类占位 + 文本自动回退为安装目录名;Windows 内置项(新建、共享、发送到等) + 不再混在列表里。 + - 同一模块在同一分类内自动合并;分类标题显示「已启用/总数」。 + - 参照电脑管家新增「创建者」(CompanyName)信息。 + - 支持按名称、创建者或模块筛选。 +- 凡是涉及第三方软件的地方统一显示该软件的默认图标:开机启动项列表 + 行、右键菜单项、弹窗拦截的当前窗口与拦截规则(启动项分组标题与 + 卸载应用列表沿用 0.1.6)。 + +已知限制 +- 虚拟机 / VDI 环境 SMBIOS 不可用时,内存品牌与频率读不到。 +- 右键菜单分类与数量以本机注册表为准,与电脑管家的策划清单可能略有 + 出入。 diff --git a/release/0.1.7/SHA256SUMS.txt b/release/0.1.7/SHA256SUMS.txt new file mode 100644 index 0000000..4f17fba --- /dev/null +++ b/release/0.1.7/SHA256SUMS.txt @@ -0,0 +1,2 @@ +17fac65b94f08bf76a90be8a5aab72233db7bb5a6368ea64b1c55df836c8910e *Squid-Setup-0.1.7-win-x64.exe +4f4aafb1c1cb7a328f25f4ccbc3a0b46fba1197208cd04b5fe5bac09506b6e18 *Squid-0.1.7-portable-win-x64.zip diff --git a/release/0.1.7/Squid-Setup-0.1.7-win-x64.exe b/release/0.1.7/Squid-Setup-0.1.7-win-x64.exe new file mode 100644 index 0000000..50048ae Binary files /dev/null and b/release/0.1.7/Squid-Setup-0.1.7-win-x64.exe differ diff --git a/release/0.1.7/squid-update.json b/release/0.1.7/squid-update.json new file mode 100644 index 0000000..6de1bfa --- /dev/null +++ b/release/0.1.7/squid-update.json @@ -0,0 +1,15 @@ +{ + "schema": 1, + "version": "0.1.7", + "date": "2026-11-08", + "notes": "Squid 0.1.7 + +Squid 0.1.7 更新说明\n\n修复\n- 卸载应用:每个应用的大小此前都显示 0 B。现在读取安装器注册表的\n EstimatedSize(与 Windows「设置 > 应用」显示的同口径数值),没有该项\n 时实测安装目录大小。\n- 电脑概览:本机配置面板中主板、处理器等长文本被截断。面板整体左移,\n 长值自动换行,全部完整显示。\n\n改进\n- 电脑概览:处理器 / 内存 / 存储空间三个指标面板等宽,进度条更纤细并\n 保留左右留白;存储空间为每个盘符显示占用百分比;整页在默认 1220×800\n 窗口内仍无需滚动即可完整查看。\n- 右键菜单管理按腾讯电脑管家的颗粒度重做:\n - 分类按真实右键入口划分:文件 / 文件夹 / 桌面 / 驱动器 / 所有对象。\n 其中「桌面」(桌面空白处右键)为新增分类。\n - 每一项显示可读的软件名:优先取模块自身的 FileDescription /\n ProductName(中文本地化名优先),遇到「TODO: <文件说明>」这类占位\n 文本自动回退为安装目录名;Windows 内置项(新建、共享、发送到等)\n 不再混在列表里。\n - 同一模块在同一分类内自动合并;分类标题显示「已启用/总数」。\n - 参照电脑管家新增「创建者」(CompanyName)信息。\n - 支持按名称、创建者或模块筛选。\n- 凡是涉及第三方软件的地方统一显示该软件的默认图标:开机启动项列表\n 行、右键菜单项、弹窗拦截的当前窗口与拦截规则(启动项分组标题与\n 卸载应用列表沿用 0.1.6)。\n\n已知限制\n- 虚拟机 / VDI 环境 SMBIOS 不可用时,内存品牌与频率读不到。\n- 右键菜单分类与数量以本机注册表为准,与电脑管家的策划清单可能略有\n 出入。", + "artifacts": { + "windows": { + "file": "Squid-Setup-0.1.7-win-x64.exe", + "sha256": "17fac65b94f08bf76a90be8a5aab72233db7bb5a6368ea64b1c55df836c8910e", + "size": 3512168 + } + } +} \ No newline at end of file diff --git a/release/0.1.8/README-Windows-x64.txt b/release/0.1.8/README-Windows-x64.txt new file mode 100644 index 0000000..7726008 --- /dev/null +++ b/release/0.1.8/README-Windows-x64.txt @@ -0,0 +1,45 @@ +Squid 0.1.8 - Windows x64 + +系统要求 +-------- +- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。 +- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid + 启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime: + https://developer.microsoft.com/microsoft-edge/webview2/ +- 安装与运行都不需要管理员权限。安装位置为 + %LOCALAPPDATA%\Programs\Squid。 +- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份 + 运行 Squid 才能修改,界面会给出明确提示。 + +安装 +---- +1. 运行 Squid-Setup-0.1.8-win-x64.exe。 +2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。 +3. 升级直接覆盖安装,不再询问是否先卸载旧版本;用户配置自动继承。 +4. 卸载请在 Windows“设置 > 应用”中移除 Squid。 + +更新 +---- +Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验 +文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥, +还会验证清单的 Ed25519 签名。 + +校验 +---- +PowerShell: + Get-FileHash .\Squid-Setup-0.1.8-win-x64.exe -Algorithm SHA256 + +提示 +---- +- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标 + 上右键退出),否则安装程序无法替换正在运行的程序文件。 +- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入 + 临时目录,报"NSIS Error - Error writing temporary file"。三种绕法, + 按方便程度排序: + 1) 把 Squid-Setup-*.exe 复制到 C:\Users\<你>\AppData\Local\Temp + 再双击运行(本机验证:管家只拦从非系统盘启动的安装程序); + 2) 管家弹窗出现时选"允许",或将安装文件加入信任区后重试; + 3) 使用便携包 Squid-0.1.8-portable-win-x64.zip,解压后把 Squid 目录 + 内的文件覆盖到安装目录(先退出托盘中的 Squid),效果相同。 +- 桌面小工具在安装后默认开启,会出现在屏幕右上角;可在主程序 + 「桌面小工具」页或托盘菜单中关闭。 diff --git a/release/0.1.8/RELEASE_NOTES.md b/release/0.1.8/RELEASE_NOTES.md new file mode 100644 index 0000000..f5025d7 --- /dev/null +++ b/release/0.1.8/RELEASE_NOTES.md @@ -0,0 +1,23 @@ +Squid 0.1.8 更新说明 + +新增 +- 桌面小工具:仿飞牛资源监控的桌面看板,无边框、置顶、不抢焦点,可拖到屏幕 + 任意位置(默认停靠右上角)。四张面板卡片可独立开关—— + - 运行状态:CPU / 内存 / GPU 占用圆环、设备名、本次运行时长; + - 网络:实时上下行速率与历史曲线; + - 存储读写:磁盘实时读写速率与历史曲线; + - 存储空间:每个盘符的已用 / 总容量进度条。 + 支持不透明度(60–100%)、更新频率(2/5/10 秒)、停靠角、折叠记忆等设置; + 主界面新增「桌面小工具」页统一管理并实时预览,系统托盘也有一键开关。 + 小工具是独立窗口,主窗口关闭进托盘后它照常刷新。 +- 安装程序改为静默覆盖升级:检测到旧版本时不再弹出「先卸载再安装」选择页, + 直接原地覆盖安装目录(继承注册表中的旧安装位置);用户配置存放在 + %APPDATA%\squid,覆盖安装不受影响,自动继承。 + +改进 +- 权限管理 · 右键菜单:五个分类(文件 / 文件夹 / 桌面 / 驱动器 / 所有对象) + 改为横向导航标签,一次只看一个分类,页面不再需要长距离滚动。 + +已知限制 +- GPU 占用在多数 Windows 环境暂无轻量采样接口,圆环显示 0%(接口已预留)。 +- 虚拟机 / VDI 环境 SMBIOS 不可用时,内存品牌与频率读不到。 diff --git a/release/0.1.8/SHA256SUMS.txt b/release/0.1.8/SHA256SUMS.txt new file mode 100644 index 0000000..65e8e0d --- /dev/null +++ b/release/0.1.8/SHA256SUMS.txt @@ -0,0 +1,2 @@ +0ec67ed65b718a48fc60b91ebc68afacafc4f3ce371b293a5575cbd4335cf843 *Squid-Setup-0.1.8-win-x64.exe +94602403c566b7978319568448e4782981d0eb6981566b58240abe3c92f0875c *Squid-0.1.8-portable-win-x64.zip diff --git a/release/0.1.8/Squid-Setup-0.1.8-win-x64.exe b/release/0.1.8/Squid-Setup-0.1.8-win-x64.exe new file mode 100644 index 0000000..72e5d79 Binary files /dev/null and b/release/0.1.8/Squid-Setup-0.1.8-win-x64.exe differ diff --git a/release/0.1.8/squid-update.json b/release/0.1.8/squid-update.json new file mode 100644 index 0000000..4e41b16 --- /dev/null +++ b/release/0.1.8/squid-update.json @@ -0,0 +1,13 @@ +{ + "schema": 1, + "version": "0.1.8", + "date": "2026-11-18", + "notes": "Squid 0.1.8\n\n新增\n- 桌面小工具:仿飞牛资源监控的桌面看板,无边框、置顶、不抢焦点,可拖到屏幕\n 任意位置(默认停靠右上角)。四张面板卡片可独立开关——\n - 运行状态:CPU / 内存 / GPU 占用圆环、设备名、本次运行时长;\n - 网络:实时上下行速率与历史曲线;\n - 存储读写:磁盘实时读写速率与历史曲线;\n - 存储空间:每个盘符的已用 / 总容量进度条。\n 支持不透明度(60–100%)、更新频率(2/5/10 秒)、停靠角、折叠记忆等设置;\n 主界面新增「桌面小工具」页统一管理并实时预览,系统托盘也有一键开关。\n 小工具是独立窗口,主窗口关闭进托盘后它照常刷新。\n- 安装程序改为静默覆盖升级:检测到旧版本时不再弹出「先卸载再安装」选择页,\n 直接原地覆盖安装目录(继承注册表中的旧安装位置);用户配置存放在\n %APPDATA%\\squid,覆盖安装不受影响,自动继承。\n\n改进\n- 权限管理 · 右键菜单:五个分类(文件 / 文件夹 / 桌面 / 驱动器 / 所有对象)\n 改为横向导航标签,一次只看一个分类,页面不再需要长距离滚动。\n\n已知限制\n- GPU 占用在多数 Windows 环境暂无轻量采样接口,圆环显示 0%(接口已预留)。\n- 虚拟机 / VDI 环境 SMBIOS 不可用时,内存品牌与频率读不到。", + "artifacts": { + "windows": { + "file": "Squid-Setup-0.1.8-win-x64.exe", + "sha256": "0ec67ed65b718a48fc60b91ebc68afacafc4f3ce371b293a5575cbd4335cf843", + "size": 3555401 + } + } +} \ No newline at end of file diff --git a/release/0.1.9/README-Windows-x64.txt b/release/0.1.9/README-Windows-x64.txt new file mode 100644 index 0000000..90fe0a9 --- /dev/null +++ b/release/0.1.9/README-Windows-x64.txt @@ -0,0 +1,45 @@ +Squid 0.1.9 - Windows x64 + +系统要求 +-------- +- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。 +- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid + 启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime: + https://developer.microsoft.com/microsoft-edge/webview2/ +- 安装与运行都不需要管理员权限。安装位置为 + %LOCALAPPDATA%\Programs\Squid。 +- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份 + 运行 Squid 才能修改,界面会给出明确提示。 + +安装 +---- +1. 运行 Squid-Setup-0.1.9-win-x64.exe。 +2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。 +3. 升级直接覆盖安装,不再询问是否先卸载旧版本;用户配置自动继承。 +4. 卸载请在 Windows“设置 > 应用”中移除 Squid。 + +更新 +---- +Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验 +文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥, +还会验证清单的 Ed25519 签名。 + +校验 +---- +PowerShell: + Get-FileHash .\Squid-Setup-0.1.9-win-x64.exe -Algorithm SHA256 + +提示 +---- +- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标 + 上右键退出),否则安装程序无法替换正在运行的程序文件。 +- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入 + 临时目录,报"NSIS Error - Error writing temporary file"。三种绕法, + 按方便程度排序: + 1) 双击本目录的「一键安装.bat」——它会把安装包复制到 C 盘临时目录 + 再启动(管家只拦从非系统盘启动的安装程序,此法本机验证有效); + 2) 管家弹窗出现时选"允许",或将安装文件加入信任区后重试; + 3) 使用便携包 Squid-0.1.9-portable-win-x64.zip,解压后把 Squid 目录 + 内的文件覆盖到安装目录(先退出托盘中的 Squid),效果相同。 +- 桌面小工具在安装后默认开启,会出现在屏幕右上角;可在主程序 + 「桌面小工具」页或托盘菜单中关闭。 diff --git a/release/0.1.9/RELEASE_NOTES.md b/release/0.1.9/RELEASE_NOTES.md new file mode 100644 index 0000000..9976a19 --- /dev/null +++ b/release/0.1.9/RELEASE_NOTES.md @@ -0,0 +1,8 @@ +Squid 0.1.9 更新说明 + +修复 +- 桌面小工具不再置顶:改为桌面层窗口,贴在壁纸与桌面图标之上、其他所有软件 + 窗口之下,打开 Office 等应用不会再被小工具遮挡;拖动小工具后也会自动落回 + 桌面层。 +- 桌面小工具透明度收紧:最多 10% 半透明(滑块 90–100,默认 100 完全不透明), + 卡片底色改为不透明白, busy 壁纸不再透出干扰读数;旧设置自动迁移。 diff --git a/release/0.1.9/SHA256SUMS.txt b/release/0.1.9/SHA256SUMS.txt new file mode 100644 index 0000000..025b1a4 --- /dev/null +++ b/release/0.1.9/SHA256SUMS.txt @@ -0,0 +1,2 @@ +d3781dd004f252d6ebb4065f4a1764c05d8c745a6e1376fd8eba2389bd97636e *Squid-Setup-0.1.9-win-x64.exe +ed6e5fb5c1d94b75ce255dde0682ed2dcf5e2cbafc2eba6b68c392f8662a6a40 *Squid-0.1.9-portable-win-x64.zip diff --git a/release/0.1.9/Squid-Setup-0.1.9-win-x64.exe b/release/0.1.9/Squid-Setup-0.1.9-win-x64.exe new file mode 100644 index 0000000..7f91344 Binary files /dev/null and b/release/0.1.9/Squid-Setup-0.1.9-win-x64.exe differ diff --git a/release/0.1.9/squid-update.json b/release/0.1.9/squid-update.json new file mode 100644 index 0000000..e0cbf05 --- /dev/null +++ b/release/0.1.9/squid-update.json @@ -0,0 +1,13 @@ +{ + "schema": 1, + "version": "0.1.9", + "date": "2026-11-18", + "notes": "Squid 0.1.9\n\n修复\n- 桌面小工具不再置顶:改为桌面层窗口,贴在壁纸与桌面图标之上、其他所有软件\n 窗口之下,打开 Office 等应用不会再被小工具遮挡;拖动小工具后也会自动落回\n 桌面层。\n- 桌面小工具透明度收紧:最多 10% 半透明(滑块 90–100,默认 100 完全不透明),\n 卡片底色改为不透明白, busy 壁纸不再透出干扰读数;旧设置自动迁移。", + "artifacts": { + "windows": { + "file": "Squid-Setup-0.1.9-win-x64.exe", + "sha256": "d3781dd004f252d6ebb4065f4a1764c05d8c745a6e1376fd8eba2389bd97636e", + "size": 3543355 + } + } +} \ No newline at end of file diff --git a/release/0.1.9/一键安装.bat b/release/0.1.9/一键安装.bat new file mode 100644 index 0000000..aa7ebc2 --- /dev/null +++ b/release/0.1.9/一键安装.bat @@ -0,0 +1,5 @@ +@echo off +rem 360/QQPC Manager blocks unsigned installers started from non-system +rem drives when they unpack into TEMP. Copy the setup to %TEMP% on C: first. +copy /Y "%~dp0Squid-Setup-0.1.9-win-x64.exe" "%TEMP%\" >nul +start "" "%TEMP%\Squid-Setup-0.1.9-win-x64.exe" diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index b8bccc1..d56bb7c 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1745,7 +1745,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d75e94d66081e4d8dcd098bd8dc5254800fea14a26389b298410158d834de167" dependencies = [ "byteorder", - "png", + "png 0.18.1", ] [[package]] @@ -1868,7 +1868,7 @@ dependencies = [ "byteorder-lite", "moxcms", "num-traits", - "png", + "png 0.18.1", ] [[package]] @@ -2271,7 +2271,7 @@ dependencies = [ "objc2-core-foundation", "objc2-foundation", "once_cell", - "png", + "png 0.18.1", "serde", "thiserror 2.0.21", "windows-sys 0.61.2", @@ -2748,6 +2748,19 @@ dependencies = [ "time", ] +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "png" version = "0.18.1" @@ -3489,7 +3502,7 @@ dependencies = [ [[package]] name = "squid-core" -version = "0.1.4" +version = "0.1.9" dependencies = [ "anyhow", "chrono", @@ -3508,7 +3521,7 @@ dependencies = [ [[package]] name = "squid-desktop" -version = "0.1.4" +version = "0.1.9" dependencies = [ "base64 0.22.1", "chrono", @@ -3532,7 +3545,7 @@ dependencies = [ [[package]] name = "squid-engine" -version = "0.1.4" +version = "0.1.9" dependencies = [ "anyhow", "chrono", @@ -3552,11 +3565,12 @@ dependencies = [ [[package]] name = "squid-platform" -version = "0.1.4" +version = "0.1.9" dependencies = [ "dirs 6.0.0", "libc", "plist", + "png 0.17.16", "rayon", "serde", "squid-core", @@ -3569,7 +3583,7 @@ dependencies = [ [[package]] name = "squid-rules" -version = "0.1.4" +version = "0.1.9" dependencies = [ "globset", "serde", @@ -3581,7 +3595,7 @@ dependencies = [ [[package]] name = "squid-stats" -version = "0.1.4" +version = "0.1.9" dependencies = [ "chrono", "libc", @@ -3589,6 +3603,7 @@ dependencies = [ "squid-core", "squid-platform", "sysinfo", + "windows-sys 0.59.0", ] [[package]] @@ -3871,7 +3886,7 @@ dependencies = [ "ico", "json-patch", "plist", - "png", + "png 0.18.1", "proc-macro2", "quote", "semver", @@ -4419,7 +4434,7 @@ dependencies = [ "objc2-core-graphics", "objc2-foundation", "once_cell", - "png", + "png 0.18.1", "serde", "thiserror 2.0.21", "windows-sys 0.61.2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index fc3b067..cdc735d 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "squid-desktop" -version = "0.1.4" +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 7b03bb0..4627e20 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -1,11 +1,15 @@ { "$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", "dialog:default", "opener:default" ] 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 1aa2f12..d7b1a50 100644 --- a/src-tauri/src/app.rs +++ b/src-tauri/src/app.rs @@ -345,6 +345,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, @@ -368,6 +370,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(), @@ -588,10 +591,18 @@ pub async fn purge_delete( Ok(DeleteResultView::from_outcome(outcome)) } +#[derive(Clone, serde::Serialize)] +pub struct AppEntry { + #[serde(flatten)] + app: AppInfo, + /// `data:image/png;base64,…` of the app's icon (Windows only). + icon: Option, +} + #[derive(Clone, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct AppsView { - apps: Vec, + apps: Vec, total: u64, } @@ -602,18 +613,44 @@ pub async fn apps_scan(app: AppHandle, job_id: String) -> Result> = Default::default(); + let entries = apps + .iter() + .map(|entry| { + let icon = icons + .entry(entry.key()) + .or_insert_with(|| { + squid_platform::permissions::app_icon(entry).map(|png| { + use base64::{engine::general_purpose::STANDARD as B64, Engine as _}; + format!("data:image/png;base64,{}", B64.encode(&png)) + }) + }) + .clone(); + AppEntry { + app: entry.clone(), + icon, + } + }) + .collect::>(); + Ok::<_, String>((apps, entries, total)) }) .await .map_err(|error| format!("Application scan failed: {error}"))?; reporter.finish(); app.state::().finish(&job_id); - let apps = task.map_err(|error| error.to_string())?; - let total = apps.iter().map(|app| app.size.as_u64()).sum(); + let (apps, entries, total) = task?; if let Ok(mut cache) = app.state::().apps.lock() { - *cache = apps.clone(); + *cache = apps; } - Ok(AppsView { apps, total }) + Ok(AppsView { + apps: entries, + total, + }) } #[derive(Clone, serde::Serialize)] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index db3e79a..648c043 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,7 +1,9 @@ mod app; +mod manage; mod permissions; mod process; mod update; +mod widget; use tauri::{ menu::{Menu, MenuItem, PredefinedMenuItem}, @@ -33,6 +35,9 @@ fn create_tray(app: &AppHandle) -> tauri::Result<()> { let quit = MenuItem::with_id(app, "quit", "退出 Squid", true, None::<&str>)?; let first_separator = PredefinedMenuItem::separator(app)?; let last_separator = PredefinedMenuItem::separator(app)?; + // Flips the widget master switch; state is shown on the 桌面小工具 page. + let widget_toggle = + MenuItem::with_id(app, "widget", "显示/隐藏桌面小工具", true, None::<&str>)?; let menu = Menu::with_items( app, &[ @@ -41,6 +46,7 @@ fn create_tray(app: &AppHandle) -> tauri::Result<()> { &cleanup, &apps, &purge, + &widget_toggle, &last_separator, &quit, ], @@ -60,6 +66,11 @@ fn create_tray(app: &AppHandle) -> 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), _ => {} }) @@ -76,6 +87,9 @@ pub fn run() { .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_opener::init()) .on_window_event(|window, event| { + if window.label() != "main" { + return; + } if let WindowEvent::CloseRequested { api, .. } = event { api.prevent_close(); let _ = window.hide(); @@ -83,6 +97,8 @@ pub fn run() { }) .manage(app::AppState::default()) .manage(update::UpdateState::default()) + .manage(manage::ManageState::default()) + .manage(widget::WidgetState::default()) .invoke_handler(tauri::generate_handler![ app::bootstrap, app::cancel_job, @@ -106,6 +122,18 @@ pub fn run() { app::open_trash, permissions::permission_status, permissions::open_full_disk_access_settings, + manage::manage_scan, + manage::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, @@ -116,6 +144,8 @@ pub fn run() { .setup(|app| { create_tray(app.handle())?; update::spawn_startup_check(app.handle()); + 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..6f70f44 --- /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 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/update.rs b/src-tauri/src/update.rs index c22660f..7620a0f 100644 --- a/src-tauri/src/update.rs +++ b/src-tauri/src/update.rs @@ -690,6 +690,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()?; @@ -796,7 +797,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"))] @@ -815,6 +818,7 @@ fn quit_for_update(app: &AppHandle) { }); } +#[cfg(not(target_os = "windows"))] fn open_artifact(path: &Path) -> Result<(), String> { #[cfg(target_os = "macos")] { @@ -879,7 +883,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..9935c91 --- /dev/null +++ b/src-tauri/src/widget.rs @@ -0,0 +1,454 @@ +//! 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::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_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_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.primary_monitor() else { + return; + }; + let size = monitor.size(); + let outer = window + .outer_size() + .map(|s| (s.width as i32, s.height as i32)) + .unwrap_or((350, 620)); + let margin = 16; + 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(0, (size.width as i32 - outer.0).max(0)), + y.clamp(0, (size.height as i32 - outer.1).max(0)), + ) + } else { + let x = match prefs.corner.as_str() { + "top-left" | "bottom-left" => margin, + _ => size.width as i32 - outer.0 - margin, + }; + let y = match prefs.corner.as_str() { + "bottom-left" | "bottom-right" => size.height as i32 - outer.1 - margin, + _ => margin, + }; + (x, 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 + || (!prefs.panel_run && !prefs.panel_network && !prefs.panel_disk && !prefs.panel_storage) + { + 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); + 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, +} + +#[tauri::command] +pub fn widget_get(app: AppHandle) -> WidgetView { + WidgetView { + prefs: app.state::().current(), + } +} + +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WidgetPatch { + pub enabled: Option, + pub panel_run: 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_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\"", + "\"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_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 b869bce..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.4", + "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 d942e6e..d79e346 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -6,6 +6,7 @@ import { Eraser, History, LayoutDashboard, + MonitorSmartphone, RefreshCw, Settings, ShieldCheck, @@ -14,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 { useSystemSnapshot } from "./hooks/useSystemSnapshot"; import { useUpdateFlow } from "./hooks/useUpdateFlow"; @@ -34,10 +36,12 @@ 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 { SettingsPage } from "./pages/SettingsPage"; import { StoragePage } from "./pages/StoragePage"; import { SystemPage } from "./pages/SystemPage"; +import { WidgetPage } from "./pages/WidgetPage"; const NAV_GROUPS: { labelEn: string; @@ -77,6 +81,12 @@ const NAV_GROUPS: { labelZh: "深度清理", icon: WandSparkles, }, + { + id: "permissions", + labelEn: "Permissions", + labelZh: "权限管理", + icon: ShieldCheck, + }, ], }, { @@ -97,6 +107,18 @@ const NAV_GROUPS: { }, ], }, + { + labelEn: "Desktop", + labelZh: "桌面", + items: [ + { + id: "widget", + labelEn: "Desktop widget", + labelZh: "桌面小工具", + icon: MonitorSmartphone, + }, + ], + }, ]; const PAGE_TITLES: Record = { @@ -104,6 +126,8 @@ const PAGE_TITLES: Record = { cleanup: ["Daily cleanup", "日常清理"], applications: ["Uninstall apps", "应用卸载"], purge: ["Deep Clean", "深度清理"], + permissions: ["Permissions", "权限管理"], + widget: ["Desktop widget", "桌面小工具"], storage: ["Storage", "存储空间"], system: ["Real-time monitor", "实时监控"], history: ["History", "历史记录"], @@ -164,6 +188,7 @@ export default function App() { const cleanup = useScanWorkspace("cleanup"); const purge = useScanWorkspace("purge"); const apps = useAppsWorkspace(); + const permissions = usePermissionsWorkspace(page === "permissions"); const systemActive = page === "overview" || page === "system"; const system = useSystemSnapshot(systemActive); const update = useUpdateFlow(bootstrap?.updateFeedUrl ?? "", autoCheck); @@ -212,14 +237,17 @@ export default function App() { "cleanup", "applications", "purge", + "permissions", "storage", "system", "history", "settings", + "widget", ]; + // Ctrl/Cmd+1..9 map in order; the 10th (desktop widget) rides on "0". const onKey = (event: KeyboardEvent) => { if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return; - const index = Number(event.key) - 1; + const index = event.key === "0" ? 9 : Number(event.key) - 1; if (!Number.isInteger(index) || index < 0 || index >= order.length) return; event.preventDefault(); setPage(order[index]); @@ -308,6 +336,8 @@ export default function App() { onHistory={() => setPage("history")} /> ) : null} + {page === "permissions" ? : null} + {page === "widget" ? : null} {page === "storage" ? : null} {page === "system" ? ( {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..bd5c76a --- /dev/null +++ b/src/components/WidgetPanels.tsx @@ -0,0 +1,239 @@ +/* 桌面小工具 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, 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[]; +} + +/** Append-only ring buffers over the snapshot stream (sparkline source). */ +export function useHistory(): [MetricHistory, (snapshot: SystemSnapshot) => void] { + const ref = useRef({ + netUp: [], + netDown: [], + diskRead: [], + diskWrite: [], + }); + 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); + }, + [], + ); + return [ref.current, bump]; +} + +function Spark({ values, color }: { values: number[]; color: string }) { + // 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 = 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`; +} + +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; + return ( + <> + {prefs.panelRun ? ( +
+
+
+

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

+ {snapshot?.host.hostname || "Squid"} +
+ {zh ? "本次运行" : "Uptime"} + {uptimeFull(snapshot?.uptime_secs ?? 0, zh)} +
+
+
+ + + + +
+
+
+ ) : 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/hooks/usePermissionsWorkspace.ts b/src/hooks/usePermissionsWorkspace.ts new file mode 100644 index 0000000..ac48ac0 --- /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.startupSetEnabled(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/lib/api.ts b/src/lib/api.ts index e7cb36f..5e9ac98 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -8,9 +8,12 @@ import type { HistorySession, JobProgress, LargestFile, + ManageView, PageId, PermissionStatus, PlanResult, + PopupClosedEvent, + PopupWindowItem, ScanResult, SettingsView, StorageNode, @@ -19,6 +22,8 @@ import type { UpdateCheckResult, UpdateProgress, UpdateStatus, + WidgetPatch, + WidgetPrefs, } from "../types"; export interface SettingsPatch { @@ -71,6 +76,22 @@ export const api = { openTrash: () => invoke("open_trash"), permissionStatus: () => invoke("permission_status"), openFullDiskAccessSettings: () => invoke("open_full_disk_access_settings"), + manageScan: () => invoke("manage_scan"), + startupSetEnabled: (id: string, enabled: boolean) => + invoke("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 }>("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"), @@ -86,6 +107,10 @@ export const api = { listen("update://status", (event) => handler(event.payload)), onNavigate: (handler: (page: PageId) => void) => listen("squid://navigate", (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)), }; export async function subscribeJobProgress( diff --git a/src/lib/format.ts b/src/lib/format.ts index 41e1526..c39e6b5 100644 --- a/src/lib/format.ts +++ b/src/lib/format.ts @@ -12,6 +12,22 @@ export function formatBytes(value: number, fractionDigits = 1): string { return `${remaining.toFixed(digits)} ${units[unit]}`; } +/// RAM is sold in powers of two (a "32 GB" stick holds 32 GiB); disks are not. +/// Memory readouts must divide by 1024 or a 32 GiB machine shows "34.4 GB". +export function formatMemory(value: number, fractionDigits = 1): string { + if (!Number.isFinite(value) || value <= 0) return "0 B"; + const units = ["B", "KB", "MB", "GB", "TB"]; + let remaining = value; + let unit = 0; + while (remaining >= 1024 && unit < units.length - 1) { + remaining /= 1024; + unit += 1; + } + if (unit === 0) return `${Math.round(remaining)} B`; + const digits = remaining >= 100 ? 0 : fractionDigits; + return `${remaining.toFixed(digits)} ${units[unit]}`; +} + export function formatBytesExact(value: number): string { if (value <= 0) return "0 B"; const formatted = formatBytes(value, 2); 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 719a5af..4e1f01c 100644 --- a/src/pages/ApplicationsPage.tsx +++ b/src/pages/ApplicationsPage.tsx @@ -41,7 +41,7 @@ function AppRow({ return ( + } + /> +
+ ); + } + + 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 e109709..87f26fd 100644 --- a/src/pages/SettingsPage.tsx +++ b/src/pages/SettingsPage.tsx @@ -480,7 +480,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 2e23d44..75db1fb 100644 --- a/src/pages/SystemPage.tsx +++ b/src/pages/SystemPage.tsx @@ -15,6 +15,7 @@ import { api } from "../lib/api"; import { formatBytes, formatCount, + formatMemory, formatRate, formatUptime, messageFrom, @@ -149,8 +150,8 @@ export function SystemPage({ {t("Memory", "内存")} {snapshot - ? `${formatBytes(snapshot.memory.used)} / ${formatBytes( - snapshot.memory.total, + ? `${formatMemory(snapshot.memory.used)} / ${formatMemory( + Math.max(snapshot.memory.installed, snapshot.memory.total), )}` : t("Reading memory…", "正在读取内存…")} @@ -165,19 +166,32 @@ export function SystemPage({ > {Math.round(memoryPercent)}% - {snapshot ? formatBytes(snapshot.memory.available) : "—"} {t("free", "可用")} + {snapshot ? formatMemory(snapshot.memory.available) : "—"} {t("free", "可用")}
{t("Used", "已用")} - {formatBytes(snapshot?.memory.used ?? 0)} + {formatMemory(snapshot?.memory.used ?? 0)}
+ {(snapshot?.memory.installed ?? 0) > (snapshot?.memory.total ?? 0) ? ( +
+ {t("Reserved (GPU)", "硬件保留(含核显)")} + + {formatMemory( + Math.max( + 0, + (snapshot?.memory.installed ?? 0) - (snapshot?.memory.total ?? 0), + ), + )} + +
+ ) : null}
{t("Swap", "交换")} - {formatBytes(snapshot?.memory.swap_used ?? 0)} - / {formatBytes(snapshot?.memory.swap_total ?? 0)} + {formatMemory(snapshot?.memory.swap_used ?? 0)} + / {formatMemory(snapshot?.memory.swap_total ?? 0)}
@@ -344,7 +358,10 @@ export function SystemPage({
{snapshot?.host.hostname || t("This computer", "这台电脑")} - {[snapshot?.host.os_name, snapshot?.host.os_version, snapshot?.host.arch] + {[ + snapshot?.host.os_version || snapshot?.host.os_name, + snapshot?.host.arch, + ] .filter(Boolean) .join(" · ")} diff --git a/src/pages/WidgetPage.tsx b/src/pages/WidgetPage.tsx new file mode 100644 index 0000000..129d84f --- /dev/null +++ b/src/pages/WidgetPage.tsx @@ -0,0 +1,310 @@ +/* 桌面小工具 management page: master switch, per-panel toggles, appearance & + * behaviour, and a live desktop preview. All edits go through widget_set, so + * the desktop window reacts immediately (and back-syncs via the event). */ +import { useEffect, useState } from "react"; +import { useI18n } from "../i18n"; +import { api } from "../lib/api"; +import { messageFrom } from "../lib/format"; +import type { SystemSnapshot, WidgetCorner, WidgetPrefs } from "../types"; +import { InlineError, PageHeader, SectionTitle, Toggle } from "../components/ui"; +import { WidgetPanels, useHistory } from "../components/WidgetPanels"; + +const CORNERS: { id: WidgetCorner; en: string; zh: string }[] = [ + { id: "top-right", en: "Top right", zh: "右上角" }, + { id: "top-left", en: "Top left", zh: "左上角" }, + { id: "bottom-right", en: "Bottom right", zh: "右下角" }, + { id: "bottom-left", en: "Bottom left", zh: "左下角" }, +]; + +const INTERVALS = [2_000, 5_000, 10_000]; + +export function WidgetPage() { + const { t, lang } = useI18n(); + const zh = lang === "zh"; + const [prefs, setPrefs] = useState(null); + const [snapshot, setSnapshot] = useState(null); + const [error, setError] = useState(null); + const [history, bump] = useHistory(); + + useEffect(() => { + let cancelled = false; + let stop: (() => void) | null = null; + void api + .widgetGet() + .then((view) => !cancelled && setPrefs(view.prefs)) + .catch((reason) => !cancelled && setError(messageFrom(reason))); + void api + .onWidgetSettings((next) => !cancelled && setPrefs(next)) + .then((unlisten) => { + if (cancelled) unlisten(); + else stop = unlisten; + }); + return () => { + cancelled = true; + stop?.(); + }; + }, []); + + // The preview runs on the same live data as the desktop widget. + useEffect(() => { + let live = true; + const tick = async () => { + try { + const next = await api.systemSnapshot(); + if (live) { + setSnapshot(next); + bump(next); + } + } catch { + /* ignore — the widget page is advisory */ + } + }; + void tick(); + const timer = window.setInterval(() => void tick(), 2_000); + return () => { + live = false; + window.clearInterval(timer); + }; + }, [bump]); + + const patch = (values: Parameters[0]) => { + setError(null); + void api + .widgetSet(values) + .then(setPrefs) + .catch((reason) => setError(messageFrom(reason))); + }; + + if (!prefs) return null; + const panels = [ + { + key: "panelRun" as const, + icon: "◔", + name: t("Status rings", "运行状态"), + desc: t( + "CPU / memory / GPU rings, device name and session uptime.", + "CPU / 内存 / GPU 占用圆环、设备名、本次运行时长", + ), + }, + { + key: "panelNetwork" as const, + icon: "⇅", + name: t("Network", "网络"), + desc: t( + "Live up/down throughput with history curves.", + "实时上下行速率与历史曲线", + ), + }, + { + key: "panelDisk" as const, + icon: "⛁", + name: t("Disk I/O", "存储读写"), + desc: t( + "Live disk read/write throughput with history curve.", + "磁盘实时读写速率与历史曲线", + ), + }, + { + key: "panelStorage" as const, + icon: "▾", + name: t("Storage volumes", "存储空间"), + desc: t( + "Used / total bars for every drive.", + "每个盘符的已用 / 总容量进度条", + ), + }, + ]; + return ( +
+ patch({ enabled: next })} + label={t("Desktop widget switch", "桌面小工具总开关")} + /> + } + /> + + {error ? setError(null)} /> : null} + +
+ {t( + "The widget is a borderless desktop-layer window (below your app windows) that never steals focus; it hides itself when every panel or the master switch is off.", + "小工具以无边框的桌面层窗口显示:贴在壁纸上、位于其他软件窗口之下,不抢焦点;关闭全部面板或总开关后窗口自动隐藏。", + )} +
+ +
+
+ +
+ {panels.map((panel) => ( +
+
+ {panel.icon} +
+ {panel.name} + {panel.desc} +
+
+ patch({ [panel.key]: next })} + label={panel.name} + /> +
+ ))} +
+
+ +
+ +
+
+
+
+ {t("Opacity", "不透明度")} + + {t( + "100% is fully solid; at most 10% of the desktop shows through.", + "100% 为完全不透明,最多透出 10% 桌面背景", + )} + +
+
+ patch({ opacity: Number(event.target.value) })} + /> +
+
+
+
+ {t("Refresh rate", "更新频率")} + + {t( + "Sampling interval; higher rates cost a little more power.", + "采样间隔,频率越高越耗电", + )} + +
+
+ +
+
+
+
+ {t("Dock corner", "显示位置")} + + {t( + "Where it lands when opened; drag it anywhere afterwards.", + "初次打开停靠的屏幕角,之后可用鼠标拖到任意位置", + )} + +
+
+ +
+
+
+
+ {t("Remember folded state", "折叠记忆")} + + {t( + "Keep the collapsed/expanded choice across restarts.", + "记住上次是否折叠,重启后保持", + )} + +
+
+ patch({ rememberCollapsed: next })} + label={t("Remember folded state", "折叠记忆")} + /> +
+
+
+
+ +
+ +
+
+
+ + + +
+ {prefs.enabled ? ( + + ) : ( +
+ {t( + "The widget is switched off — flip the master switch to see it on your desktop.", + "小工具已关闭 —— 打开总开关后即可在桌面看到它。", + )} +
+ )} +
+
+
+
+ ); +} diff --git a/src/pages/WidgetWindow.tsx b/src/pages/WidgetWindow.tsx new file mode 100644 index 0000000..744829c --- /dev/null +++ b/src/pages/WidgetWindow.tsx @@ -0,0 +1,221 @@ +/* The 桌面小工具 window content (index.html?view=widget): header bar with + * settings + collapse, live panels, and a compact settings popover that + * writes straight through to widget_set (broadcast keeps the main page in + * sync). */ +import { useCallback, useEffect, useRef, useState } from "react"; +import { getCurrentWindow, LogicalSize } from "@tauri-apps/api/window"; +import { api } from "../lib/api"; +import { messageFrom } from "../lib/format"; +import type { WidgetPrefs } from "../types"; +import { WidgetPanels, useHistory } from "../components/WidgetPanels"; +import type { SystemSnapshot } from "../types"; + +const PANELS: { key: keyof WidgetPrefs; label: string }[] = [ + { key: "panelRun", label: "运行状态" }, + { key: "panelNetwork", label: "网络" }, + { key: "panelDisk", label: "存储读写" }, + { key: "panelStorage", label: "存储空间" }, +]; + +export function WidgetWindow() { + const [prefs, setPrefs] = useState(null); + const [snapshot, setSnapshot] = useState(null); + const [open, setOpen] = useState(false); + const [history, bump] = useHistory(); + const windowRef = useRef(getCurrentWindow()); + + useEffect(() => { + // The window is transparent; punch through the app's opaque body paint. + document.documentElement.classList.add("widget-mode"); + return () => document.documentElement.classList.remove("widget-mode"); + }, []); + + useEffect(() => { + let cancelled = false; + let stop: (() => void) | null = null; + void api + .widgetGet() + .then((view) => !cancelled && setPrefs(view.prefs)) + .catch((reason) => console.error(messageFrom(reason))); + void api + .onWidgetSettings((next) => !cancelled && setPrefs(next)) + .then((unlisten) => { + if (cancelled) unlisten(); + else stop = unlisten; + }); + return () => { + cancelled = true; + stop?.(); + }; + }, []); + + // Poll at the configured cadence; pausing while hidden saves cycles. + const intervalMs = prefs?.intervalMs ?? 2000; + useEffect(() => { + if (!prefs?.enabled) return; + let live = true; + const tick = async () => { + if (!live || document.hidden) return; + try { + const next = await api.systemSnapshot(); + if (live) { + setSnapshot(next); + bump(next); + } + } catch { + /* sampler busy — next beat will catch up */ + } + }; + void tick(); + const timer = window.setInterval(() => void tick(), intervalMs); + return () => { + live = false; + window.clearInterval(timer); + }; + }, [bump, intervalMs, prefs?.enabled]); + + const patch = useCallback((values: Parameters[0]) => { + void api + .widgetSet(values) + .then(setPrefs) + .catch((reason) => console.error(messageFrom(reason))); + }, []); + + const collapsed = Boolean(prefs?.collapsed); + + // Last persisted drag position; null while the widget is corner-docked. + const lastPos = useRef<{ x: number; y: number } | null>(null); + + // Grow/shrink the window to the stacked cards so transparent space never + // eats desktop clicks (scrollHeight is CSS px == LogicalSize units). + const rootRef = useRef(null); + useEffect(() => { + const root = rootRef.current; + if (!root) return; + let frame = 0; + const fit = () => { + window.cancelAnimationFrame(frame); + frame = window.requestAnimationFrame(() => { + const height = Math.max(64, root.scrollHeight + 4); + void windowRef.current + ?.setSize(new LogicalSize(350, height)) + .then(() => { + // Keep the docked corner anchored after the size change. + if (!lastPos.current) void api.widgetSet({ redock: true }).catch(() => undefined); + }) + .catch(() => undefined); + }); + }; + const observer = new ResizeObserver(fit); + observer.observe(root); + fit(); + return () => { + observer.disconnect(); + window.cancelAnimationFrame(frame); + }; + }, [prefs, open, collapsed]); + + const toggleCollapsed = () => { + setOpen(false); + patch({ collapsed: !collapsed }); + }; + + // Persist a dragged position after the pointer settles (the header is a + // native drag region, so poll once shortly after mouseup). + useEffect(() => { + const onUp = () => { + window.setTimeout(() => { + void windowRef.current + ?.outerPosition() + .then((position) => { + const previous = lastPos.current; + if (previous && previous.x === position.x && previous.y === position.y) return; + lastPos.current = position; + patch({ position: [position.x, position.y], keepPosition: true }); + }) + .catch(() => undefined); + }, 350); + }; + window.addEventListener("mouseup", onUp); + return () => window.removeEventListener("mouseup", onUp); + }, [patch]); + + if (!prefs) return
; + return ( +
+
+ + + +
+ + {open && !collapsed ? ( +
+

小部件设置

+ {PANELS.map((panel) => ( +
+ {panel.label} +
+ ))} +
+ 不透明度 + patch({ opacity: Number(event.target.value) })} + /> +
+ +
+ ) : null} + + {!collapsed ? ( + + ) : null} +
+ ); +} diff --git a/src/styles.css b/src/styles.css index ba8bf52..c1cfea0 100644 --- a/src/styles.css +++ b/src/styles.css @@ -4777,3 +4777,857 @@ select:focus-visible, justify-content: flex-end; } } + +/* ---- 权限管理 (permissions page) ---------------------------------------- */ + +.perm-tabs { + display: flex; + gap: 8px; + margin: 6px 0 20px; +} + +.perm-tab { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 9px 18px; + border: 1px solid var(--nex-line); + border-radius: 12px; + background: transparent; + color: #909fad; + font-size: var(--nex-text-sm); + cursor: pointer; + transition: all 0.16s ease; +} + +.perm-tab b { + min-width: 20px; + padding: 1px 7px; + border-radius: 999px; + background: rgba(86, 182, 246, 0.12); + color: var(--nex-primary); + font-size: var(--nex-text-3xs); + font-weight: var(--nex-weight-semibold); +} + +.perm-tab.is-active { + border-color: var(--nex-primary-soft); + background: rgba(86, 182, 246, 0.10); + color: var(--blue-deep); + font-weight: var(--nex-weight-medium); +} + +/* Context-menu categories: horizontal nav instead of stacked sections. */ +.perm-ext-head { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 10px 16px; + margin-bottom: 4px; +} + +.perm-cats { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.perm-cat { + display: inline-flex; + align-items: center; + gap: 7px; + padding: 6px 13px; + border: 1px solid transparent; + border-radius: 10px; + background: transparent; + color: #909fad; + font-size: var(--nex-text-2xs); + cursor: pointer; + transition: all 0.16s ease; +} + +.perm-cat:hover { + color: var(--nex-ink); +} + +.perm-cat b { + min-width: 18px; + padding: 0 6px; + border-radius: 999px; + background: rgba(144, 159, 173, 0.14); + color: inherit; + font-size: var(--nex-text-3xs); + font-weight: var(--nex-weight-semibold); + font-variant-numeric: tabular-nums; +} + +.perm-cat.is-active { + border-color: var(--nex-primary-soft); + background: rgba(86, 182, 246, 0.10); + color: var(--blue-deep); + font-weight: var(--nex-weight-medium); +} + +.perm-cat.is-active b { + background: rgba(86, 182, 246, 0.16); + color: var(--blue-deep); +} + +.perm-rows { + display: flex; + flex-direction: column; +} + +.perm-rows .settings-row small { + overflow: hidden; + color: #909fad; + font-size: var(--nex-text-3xs); + text-overflow: ellipsis; + white-space: nowrap; +} + +.perm-rows .settings-row.is-muted { + opacity: 0.55; +} + +.perm-rows .settings-row.is-busy { + opacity: 0.7; + pointer-events: none; +} + +.perm-group { + display: flex; + align-items: center; + gap: 6px; + margin: 18px 0 2px; + color: var(--nex-primary); + font-size: var(--nex-text-xs); + font-weight: var(--nex-weight-semibold); +} + +.perm-group-icon { + width: 20px; + height: 20px; + border-radius: 5px; + object-fit: contain; + flex: 0 0 auto; +} + +.perm-group-icon-fallback { + display: inline-flex; + align-items: center; + justify-content: center; + background: #d7dfe8; + color: #5c6c7d; + font-size: 11px; + font-weight: var(--nex-weight-semibold); +} + +.perm-group b { + color: #909fad; + font-size: var(--nex-text-3xs); + font-weight: var(--nex-weight-regular); +} + +/* Per-row software icon (电脑管家 shows the app icon on every list row). */ +.settings-row > .perm-row { + display: flex; + flex-direction: row; + align-items: center; + gap: 10px; + min-width: 0; +} + +.perm-row > div { + display: flex; + min-width: 0; + flex-direction: column; + gap: 2px; +} + +.perm-row-icon { + width: 26px; + height: 26px; + border-radius: 6px; + object-fit: contain; + flex: 0 0 auto; + background: #fff; +} + +.perm-row-icon-fallback { + display: inline-flex; + align-items: center; + justify-content: center; + background: #d7dfe8; + color: #5c6c7d; + font-size: 12px; + font-weight: var(--nex-weight-semibold); +} + +.perm-row-actions { + display: flex; + align-items: center; + gap: 10px; + flex-direction: row !important; +} + +.perm-empty { + padding: 14px 0; + color: #6c7a87; + font-size: var(--nex-text-xs); +} + +.perm-recent { + display: flex; + align-items: center; + gap: 8px; + margin-top: 10px; + padding: 9px 14px; + border: 1px solid var(--nex-line); + border-radius: 10px; + background: rgba(86, 182, 246, 0.06); + color: #405d77; + font-size: var(--nex-text-xs); +} + +.perm-recent svg { + color: var(--nex-primary); +} + +.perm-loading { + display: flex; + align-items: center; + gap: 10px; + padding: 40px 0; + color: #909fad; + font-size: var(--nex-text-sm); +} + +.perm-spin { + animation: perm-spin 1.1s linear infinite; + color: var(--nex-primary); +} + +@keyframes perm-spin { + to { + transform: rotate(360deg); + } +} + +/* ---- overview spec panel + drives list + real app icons ---- */ + +/* The gauge is gone; the hero shrinks to its content and the right column + becomes the machine-spec list. */ + +.overview-hero { + /* Specs column takes the larger share so values never truncate, and sits + closer to the centre of the card. */ + grid-template-columns: minmax(0, 0.92fr) minmax(390px, 1.08fr); + align-items: center; + min-height: 0; + padding: 26px 24px 26px 30px; + gap: 18px; +} + +.overview-gauge-wrap { + position: relative; + display: flex; + flex-direction: column; + align-items: stretch; + justify-content: center; + gap: 2px; +} + +.overview-specs { + position: relative; + z-index: 1; + display: grid; + gap: 7px; + width: 100%; +} + +.specs-kicker { + margin-bottom: 2px; + color: var(--nex-muted); + font-size: var(--nex-text-3xs); + font-weight: var(--nex-weight-bold); + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.spec-row { + display: grid; + grid-template-columns: 22px 58px minmax(0, 1fr); + align-items: baseline; + gap: 6px; +} + +.spec-icon { + display: grid; + place-items: center; + width: 22px; + height: 22px; + border-radius: 8px; + align-self: center; + background: rgba(var(--nex-primary-rgb), 0.09); + color: var(--nex-primary); +} + +.spec-label { + color: var(--nex-muted); + font-size: var(--nex-text-3xs); +} + +.spec-row strong { + color: var(--nex-ink-strong); + font-size: var(--nex-text-2xs); + font-weight: var(--nex-weight-bold); + /* Long model strings wrap instead of truncating — the whole point of the + panel is reading the machine's identity. */ + line-height: 1.45; + overflow-wrap: anywhere; +} + +/* Metrics row: three equal panels; usage bars keep breathing room on both + sides instead of spanning the full card width. */ +.overview-metrics { + grid-template-columns: repeat(3, minmax(0, 1fr)); +} + +.overview-metrics .usage-bar { + margin-inline: 12px; +} + +.metric-drives { + align-content: start; +} + +.drive-list { + display: grid; + gap: 9px; + margin-top: 10px; +} + +.drive-row { + display: grid; + gap: 5px; +} + +.metric-drives .usage-bar { + height: 5px; +} + +.drive-line { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 10px; +} + +.drive-line strong { + overflow: hidden; + color: var(--nex-ink); + font-size: var(--nex-text-2xs); + text-overflow: ellipsis; + white-space: nowrap; +} + +.drive-line span { + flex: 0 0 auto; + color: var(--nex-muted); + font-size: var(--nex-text-3xs); +} + +.drive-line .drive-pct { + margin-right: 7px; + color: var(--nex-ink-strong); + font-weight: var(--nex-weight-bold); + font-variant-numeric: tabular-nums; +} + +/* Application list + plan header use the real icon when the scan provided one. */ +.app-glyph img, +.plan-head .app-glyph img { + width: 100%; + height: 100%; + border-radius: inherit; + object-fit: contain; + background: #fff; +} + +.app-glyph:has(img) { + border-color: rgba(48, 87, 126, 0.12); + background: #fff; + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.6); +} + +/* Fit-the-window pass: the default 1220×800 frame should show the whole + overview without a vertical scrollbar. */ +.overview-page { + padding-top: 18px; + padding-bottom: 24px; +} + +.overview-page .page-header { + margin-bottom: 14px; +} + +.overview-page .page-header h1 { + font-size: 25px; +} + +.overview-page .overview-hero { + padding: 20px 24px; +} + +.overview-page .overview-hero h2 { + font-size: 29px; +} + +.overview-page .hero-kicker { + margin-bottom: 9px; +} + +.overview-page .overview-hero-copy > p { + margin-top: 9px; +} + +.overview-page .hero-actions { + margin-top: 14px; +} + +.overview-page .hero-assurances { + margin-top: 12px; +} + +.overview-page .overview-metrics { + margin-top: 14px; +} + +.overview-page .metric-panel { + padding: 12px 14px; +} + +.overview-page .metric-panel-head { + margin-bottom: 9px; +} + +.overview-page .quick-actions { + margin-top: 16px; +} + +.overview-page .quick-card { + padding: 11px 13px; +} + +.overview-page .quick-icon { + width: 36px; + height: 36px; + border-radius: 11px; +} + +.overview-page .section-title { + margin-bottom: 9px; +} + +/* ---- 桌面小工具 (desktop widget) -------------------------------------- */ + +/* The widget window reuses this bundle; punch the opaque app background + through so the rounded card cluster floats over the desktop. */ +html.widget-mode, +html.widget-mode body, +html.widget-mode #root { + height: auto; + min-height: 100%; + background: transparent; +} + +html.widget-mode body { + overflow: hidden; +} + +.widget { + display: flex; + flex-direction: column; + gap: 12px; + width: 350px; + padding: 10px; + border-radius: 26px; + /* 90% solid: at most a whisper of the desktop bleeds through the dock. */ + background: rgba(206, 213, 224, 0.9); + color: #1c2430; +} + +.widget-window { + box-shadow: none; + font-size: 13px; +} + +.widget-loading { + min-height: 80px; +} + +.wd-card { + padding: 14px 16px; + border-radius: 18px; + /* Solid cards: content never competes with the wallpaper behind it. */ + background: #fafbfd; + color: #1c2430; +} + +.wd-card h4 { + margin: 0; + font-size: 15px; + font-weight: 700; + letter-spacing: 0.01em; +} + +.wd-head { + display: flex; + align-items: center; + padding: 9px 12px; +} + +.wd-head-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 30px; + height: 30px; + border-radius: 9px; + background: transparent; + color: #1c2430; + cursor: pointer; + transition: background 0.15s ease; +} + +.wd-head-btn:hover { + background: rgba(28, 36, 48, 0.07); +} + +.wd-chevron svg { + transition: transform 0.18s ease; +} + +.wd-chevron.is-collapsed svg { + transform: rotate(180deg); +} + +.wd-head-dot { + width: 18px; + height: 18px; + border-radius: 6px; + background: #cdd6e2; +} + +.wd-head-spacer { + flex: 1; +} + +/* run-state card: title/uptime full width, ring cluster floats right */ + +.wd-run { + position: relative; + min-height: 170px; +} + +.wd-run-left { + position: absolute; + top: 0; + bottom: 0; + left: 0; + z-index: 1; + display: flex; + width: 160px; + flex-direction: column; + gap: 2px; +} + +.wd-run-left > strong { + font-size: 14px; +} + +.wd-rings { + position: absolute; + top: -2px; + right: -4px; + display: grid; + grid-template-columns: repeat(2, 74px); + gap: 12px 6px; +} + +.wd-ring { + position: relative; + width: 76px; + height: 76px; +} + +.wd-ring-text { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 1px; +} + +.wd-ring-text b { + font-size: 12px; + font-weight: 600; + color: #3d4a5c; +} + +.wd-ring-text span { + font-size: 11px; + color: #8a96a6; +} + +.wd-uptime { + display: flex; + flex-direction: column; + gap: 2px; + margin-top: auto; +} + +.wd-uptime span { + font-size: 12px; + color: #8a96a6; +} + +.wd-uptime b { + font-size: 14px; + font-weight: 700; + white-space: nowrap; +} + +/* chart cards */ + +.wd-line-head { + display: flex; + align-items: flex-start; + justify-content: space-between; +} + +.wd-rate { + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 2px; +} + +.wd-rate b { + font-size: 13px; + font-weight: 700; +} + +.wd-rate .up { + color: #16b364; +} + +.wd-rate .down { + color: #2f6bff; +} + +.wd-spark { + display: block; + width: 100%; + height: 46px; + margin-top: 8px; +} + +.wd-spark + .wd-spark { + margin-top: -34px; +} + +/* storage card */ + +.wd-pad { + margin-bottom: 10px; +} + +.wd-vol { + display: flex; + align-items: center; + gap: 10px; + padding: 9px 0; +} + +.wd-vol + .wd-vol { + border-top: 1px solid #eef1f6; +} + +.wd-vol-ico { + display: flex; + flex: 0 0 auto; +} + +.wd-vol-body { + flex: 1; + min-width: 0; +} + +.wd-vol-top { + display: flex; + justify-content: space-between; + gap: 8px; + font-size: 12px; +} + +.wd-vol-top span { + color: #5a6779; +} + +.wd-vol-top b { + font-weight: 600; + color: #2c3644; + white-space: nowrap; +} + +.wd-vol-bar { + height: 5px; + margin-top: 6px; + border-radius: 999px; + background: #e8ecf2; + overflow: hidden; +} + +.wd-vol-bar i { + display: block; + height: 100%; + border-radius: inherit; + background: #2f6bff; +} + +/* settings popover card inside the widget */ + +.wd-settings h4 { + margin-bottom: 10px; +} + +.wd-set-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 7px 0; + font-size: 13px; + color: #3d4a5c; +} + +.wd-set-row + .wd-set-row { + border-top: 1px solid #eef1f6; +} + +.wd-set-toggle { + position: relative; + flex: 0 0 auto; + width: 36px; + height: 21px; + border-radius: 999px; + background: #d7dde6; + transition: background 0.15s ease; +} + +.wd-set-toggle::after { + content: ""; + position: absolute; + top: 2.5px; + left: 3px; + width: 16px; + height: 16px; + border-radius: 50%; + background: #fff; + box-shadow: 0 1px 3px rgba(20, 30, 50, 0.35); + transition: left 0.15s ease; +} + +.wd-set-toggle.is-on { + background: #2f6bff; +} + +.wd-set-toggle.is-on::after { + left: 17px; +} + +.wd-range { + width: 110px; + accent-color: #2f6bff; +} + +.wd-close-line { + width: 100%; + margin-top: 10px; + padding: 8px 0; + border-radius: 11px; + background: rgba(224, 74, 58, 0.09); + color: #b2402f; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: background 0.15s ease; +} + +.wd-close-line:hover { + background: rgba(224, 74, 58, 0.16); +} + +/* management page */ + +.widget-note { + margin: 4px 0 14px; + padding: 9px 12px; + border-radius: 10px; + background: rgba(47, 107, 255, 0.07); + color: #44546a; + font-size: 12.5px; +} + +.widget-grid { + display: grid; + grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); + gap: 22px; + align-items: start; +} + +.widget-row-ico { + display: inline-flex; + align-items: center; + justify-content: center; + width: 26px; + height: 26px; + border-radius: 7px; + background: rgba(47, 107, 255, 0.1); + color: #2f6bff; + font-size: 13px; +} + +.widget-range { + width: 150px; + accent-color: var(--nex-primary); +} + +.widget-preview-section .section-title { + margin-bottom: 10px; +} + +.widget-preview-stage { + display: flex; + justify-content: center; + padding: 22px 14px; + border-radius: 18px; + background: + radial-gradient(420px 200px at 70% 110%, rgba(120, 140, 170, 0.5), transparent 60%), + linear-gradient(180deg, #131d33, #2c3b55); +} + +.widget-preview { + width: 330px; +} + +.widget-off-hint { + color: #5a6779; + font-size: 12.5px; + text-align: center; +} diff --git a/src/types.ts b/src/types.ts index 02f5664..720d502 100644 --- a/src/types.ts +++ b/src/types.ts @@ -4,6 +4,8 @@ export type PageId = | "cleanup" | "applications" | "purge" + | "permissions" + | "widget" | "storage" | "system" | "history" @@ -92,12 +94,33 @@ export interface PermissionStatus { fullDiskAccess: "granted" | "denied" | "unknown" | "not-required"; } +export interface MemoryStick { + manufacturer: string; + size_bytes: number; + speed_mhz: number; +} + +/** Static component facts, snake_case straight from squid-platform. */ +export interface HardwareInfo { + board: string; + cpu_model: string; + memory_sticks: MemoryStick[]; + disk_vendor: string; + disk_model: string; + disk_bus: string; + disk_size_bytes: number; + gpu_vendor: string; + gpu_model: string; + gpu_vram_bytes: number; +} + export interface Bootstrap { version: string; platform: "macos" | "windows" | "linux" | "unknown"; osName: string; osVersion: string; hardware: string; + hardwareInfo: HardwareInfo; arch: string; device: "mac" | "pc" | "machine"; language: Language; @@ -120,6 +143,9 @@ export interface AppInfo { has_sibling_install: boolean; publisher: string | null; installed_ms: number | null; + display_icon: string | null; + /** data-URL PNG icon (apps_scan only; null when extraction failed). */ + icon?: string | null; } export interface AppsResult { @@ -177,10 +203,12 @@ export interface SystemSnapshot { brand: string; base_frequency_ghz: number; }; + gpu_usage: number | null; memory: { total: number; used: number; available: number; + installed: number; swap_total: number; swap_used: number; compressed: number | null; @@ -290,3 +318,105 @@ export interface UndoResult { restored: number; skipped: number; } + + +// ---- permissions (权限管理) --------------------------------------------- + +export interface StartupItem { + id: string; + name: string; + displayName: string; + /** data-URL PNG of the binary's icon; null on platforms without extraction. */ + icon: string | null; + command: string; + source: string; + sourceLabel: string; + scope: string; + enabled: boolean; +} + +export interface ShellExtension { + id: string; + name: string; + handler: string; + extensionPoint: string; + scope: string; + friendlyName: string | null; + module: string | null; + /** publisher (CompanyName) of the owning dll — 电脑管家's 创建者 column. */ + publisher: string | null; + /** data-URL PNG of the owning module's icon; null without extraction. */ + icon: string | null; + registered: boolean; +} + +export interface PopupWindowItem { + hwnd: number; + title: string; + process: string; + exe: string | null; + /** data-URL PNG of the owning process's icon; null without extraction. */ + icon: string | null; +} + +export interface PopupRuleItem { + exe: string; + title: string; + matcher: string; + enabled: boolean; + closed: number; + /** data-URL PNG of the rule's exe, filled by manage_scan. */ + icon?: string | null; +} + +export interface ManageView { + watcherEnabled: boolean; + intervalMs: number; + rules: PopupRuleItem[]; + windows: PopupWindowItem[]; + startup: StartupItem[]; + extensions: ShellExtension[]; + startupCount: number; + startupEnabledCount: number; +} + +export interface PopupClosedEvent { + process: string; + title: string; + ruleIndex: number; +} + +// ---- desktop widget (桌面小工具) ------------------------------------------ + +export type WidgetCorner = "top-right" | "top-left" | "bottom-right" | "bottom-left"; + +export interface WidgetPrefs { + enabled: boolean; + panelRun: boolean; + panelNetwork: boolean; + panelDisk: boolean; + panelStorage: boolean; + /** 90–100 percent window opacity. */ + opacity: number; + intervalMs: number; + corner: WidgetCorner; + rememberCollapsed: boolean; + collapsed: boolean; + position: [number, number] | null; +} + +export interface WidgetPatch { + enabled?: boolean; + panelRun?: boolean; + panelNetwork?: boolean; + panelDisk?: boolean; + panelStorage?: boolean; + opacity?: number; + intervalMs?: number; + corner?: WidgetCorner; + rememberCollapsed?: boolean; + collapsed?: boolean; + position?: [number, number] | null; + keepPosition?: boolean; + redock?: boolean; +}