diff --git a/Cargo.lock b/Cargo.lock index e674231..58a79bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1116,7 +1116,7 @@ checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" [[package]] name = "squid-cli" -version = "0.1.11" +version = "0.1.12" dependencies = [ "anyhow", "chrono", @@ -1135,7 +1135,7 @@ dependencies = [ [[package]] name = "squid-core" -version = "0.1.11" +version = "0.1.12" dependencies = [ "anyhow", "chrono", @@ -1154,7 +1154,7 @@ dependencies = [ [[package]] name = "squid-engine" -version = "0.1.11" +version = "0.1.12" dependencies = [ "anyhow", "chrono", @@ -1177,7 +1177,7 @@ dependencies = [ [[package]] name = "squid-platform" -version = "0.1.11" +version = "0.1.12" dependencies = [ "dirs", "libc", @@ -1196,7 +1196,7 @@ dependencies = [ [[package]] name = "squid-rules" -version = "0.1.11" +version = "0.1.12" dependencies = [ "globset", "serde", @@ -1208,7 +1208,7 @@ dependencies = [ [[package]] name = "squid-stats" -version = "0.1.11" +version = "0.1.12" dependencies = [ "chrono", "libc", @@ -1221,7 +1221,7 @@ dependencies = [ [[package]] name = "squid-tui" -version = "0.1.11" +version = "0.1.12" dependencies = [ "anyhow", "chrono", diff --git a/crates/squid-engine/src/analyze.rs b/crates/squid-engine/src/analyze.rs index 9447bc9..c788314 100644 --- a/crates/squid-engine/src/analyze.rs +++ b/crates/squid-engine/src/analyze.rs @@ -376,6 +376,12 @@ pub fn large_files( if !meta.is_file() || meta.len() < min_bytes { continue; } + // The page files are system-managed and permanently locked: + // listing them only teaches users that deleting C:\pagefile.sys + // fails. hiberfil.sys stays — it has a real, actionable switch. + if is_pagefile(&path) { + continue; + } if let Some(wanted) = class { if file_class(&path) != wanted { continue; @@ -404,6 +410,29 @@ pub fn large_files( Ok(found) } +/// The virtual-memory page files. They sit at a volume root, are held open by +/// the kernel and cannot be deleted from Explorer, so a large-file sweep must +/// not offer them. `hiberfil.sys` deliberately stays: turning hibernation off +/// is a real, actionable way to free that space. +fn is_pagefile(path: &Path) -> bool { + // Only the volume-root copies are the system's; a photo named + // pagefile.sys inside a folder stays listed. `C:\pagefile.sys` has + // parent `C:\`, whose own parent is none. + let at_root = path + .parent() + .and_then(|parent| parent.parent()) + .map_or(true, |grand| grand.as_os_str().is_empty()); + if !at_root { + return false; + } + path.file_name() + .map(|name| { + let name = name.to_string_lossy(); + name.eq_ignore_ascii_case("pagefile.sys") || name.eq_ignore_ascii_case("swapfile.sys") + }) + .unwrap_or(false) +} + /// System churn a large-file sweep should not crawl through. fn skip_infra(name: &str) -> bool { const SKIP: &[&str] = &[ @@ -554,4 +583,18 @@ mod tests { assert!(!node.complete); let _ = std::fs::remove_dir_all(&root); } + + #[test] + fn page_files_hide_only_at_the_volume_root() { + // Paths are matched lexically; nothing has to exist on disk. + assert!(is_pagefile(std::path::Path::new(r"C:\pagefile.sys"))); + assert!(is_pagefile(std::path::Path::new(r"C:\swapfile.sys"))); + assert!(is_pagefile(std::path::Path::new(r"D:\PAGEFILE.SYS"))); + // hiberfil stays listed — it has an actionable switch (关闭休眠). + assert!(!is_pagefile(std::path::Path::new(r"C:\hiberfil.sys"))); + // A file that merely carries the name inside a folder is still shown. + assert!(!is_pagefile(std::path::Path::new( + r"C:\Users\me\pagefile.sys" + ))); + } } diff --git a/crates/squid-platform/src/advanced.rs b/crates/squid-platform/src/advanced.rs index 7d651c9..b8a3014 100644 --- a/crates/squid-platform/src/advanced.rs +++ b/crates/squid-platform/src/advanced.rs @@ -42,7 +42,7 @@ pub struct AdvancedEntry { } #[cfg(windows)] -mod windows { +pub(crate) mod windows { use super::AdvancedEntry; use std::path::PathBuf; use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ}; @@ -241,6 +241,31 @@ mod windows { if exes.is_empty() { return; } + let grades = signature_grades(&exes); + for entry in entries.iter_mut() { + let Some(exe) = exe_of(&entry.command) else { + continue; + }; + if let Some((verdict, signer)) = grades.get(&exe.to_ascii_lowercase()) { + entry.signature = verdict.clone(); + entry.signer = signer.clone(); + } else if entry.signature == "pending" { + entry.signature = "unknown".into(); + } + } + } + + /// One PowerShell round-trip grading many binaries at once: + /// lowercase path → (`verdict`, `signer`). Shared with the startup scan so + /// a page never shells out per row. + pub(crate) fn signature_grades( + exes: &[String], + ) -> std::collections::HashMap)> { + let mut grades: std::collections::HashMap)> = + Default::default(); + if exes.is_empty() { + return grades; + } let list = exes .iter() .map(|exe| format!("'{}'", exe.replace('\'', "''"))) @@ -253,11 +278,9 @@ mod windows { .args(["-NoProfile", "-NonInteractive", "-Command", &script]) .output() else { - return; + return grades; }; let text = String::from_utf8_lossy(&output.stdout); - let mut grades: std::collections::HashMap)> = - Default::default(); for line in text.lines() { // Out-String may pad lines; match on containment of the marker. let Some(start) = line.find("@@|") else { @@ -289,17 +312,7 @@ mod windows { }; grades.insert(path.to_ascii_lowercase(), (verdict.into(), signer)); } - for entry in entries.iter_mut() { - let Some(exe) = exe_of(&entry.command) else { - continue; - }; - if let Some((verdict, signer)) = grades.get(&exe.to_ascii_lowercase()) { - entry.signature = verdict.clone(); - entry.signer = signer.clone(); - } else if entry.signature == "pending" { - entry.signature = "unknown".into(); - } - } + grades } } diff --git a/crates/squid-platform/src/permissions.rs b/crates/squid-platform/src/permissions.rs index b76242f..2b9b551 100644 --- a/crates/squid-platform/src/permissions.rs +++ b/crates/squid-platform/src/permissions.rs @@ -38,6 +38,31 @@ pub struct StartupEntry { /// the 电脑管家 habit of showing the software icon next to its name. #[serde(default)] pub icon: Option>, + /// The executable this entry really runs (lnk targets resolved). Empty + /// when the command holds no path at all. + #[serde(default)] + pub target: String, + /// False when `target` does not exist on disk — the program was removed + /// but its autostart config survived: a 残留项 (leftover), removable via + /// [`remove_startup_entry`]. + #[serde(default)] + pub target_exists: bool, + /// When this fires: `boot` | `logon` | `background` | `unknown`, from the + /// registry value / task triggers / service start type. Shown as a chip. + #[serde(default)] + pub trigger: String, + /// Microsoft-signed or living under %SystemRoot% — the UI folds these + /// into a 系统组件 group that 「显示系统项」 can hide. + #[serde(default)] + pub system_item: bool, + /// Digital-signature verdict of `target`: `microsoft` | `vendor` | + /// `unsigned` | `invalid` | `unknown` (nothing resolvable / non-Windows). + /// Filled by the batch signature pass at the end of the scan. + #[serde(default)] + pub signature: String, + /// Subject of the signing certificate when known. + #[serde(default)] + pub signer: Option, } /// One registered context-menu ("右键菜单") handler. @@ -146,6 +171,22 @@ pub fn set_startup_enabled(entry: &StartupEntry, enabled: bool) -> Result<(), St } } +/// Delete a leftover autostart configuration (the program it points at is +/// gone). Only the *registration* disappears — registry value, Startup-folder +/// shortcut, task definition — never a program's files. Services are disabled +/// rather than uninstalled because other software may still reference them. +pub fn remove_startup_entry(entry: &StartupEntry) -> Result<(), String> { + #[cfg(windows)] + { + windows::remove_startup_entry(entry) + } + #[cfg(not(windows))] + { + let _ = entry; + Err("删除启动项仅在 Windows 提供".into()) + } +} + pub fn scan_shell_extensions() -> Vec { #[cfg(windows)] { @@ -525,8 +566,20 @@ mod windows { /// Per-binary cache payload: (FileDescription, ProductName, icon PNG). type SoftwareInfo = (Option, Option, Option>); + /// Whether a launch path is concrete enough to judge: a drive-qualified or + /// UNC path. `foo.exe` alone resolves against *our* working directory, so + /// answering "missing" for it would invent false 残留项. + fn is_absolute_path(path: &str) -> bool { + let trimmed = path.trim_matches('"'); + let bytes = trimmed.as_bytes(); + (bytes.len() > 2 && bytes[1] == b':' && matches!(bytes[2], b'\\' | b'/')) + || trimmed.starts_with(r"\\") + } + /// Resolve `display_name` (and the software icon) for every scanned - /// entry, once per binary. + /// entry, once per binary. Also settles `target` / `target_exists`: the + /// binary the row really runs, and whether it is still on disk (a missing + /// one is a 残留项). fn decorate_display_names(entries: &mut [StartupEntry]) { let vendors = vendor_icon_map(); let mut cache: std::collections::HashMap = Default::default(); @@ -542,6 +595,8 @@ mod windows { } else { probed }; + entry.target = probed.clone(); + entry.target_exists = !is_absolute_path(&probed) || Path::new(&probed).exists(); let (description, product, icon) = cache .entry(probed.clone()) .or_insert_with(|| { @@ -1133,6 +1188,12 @@ mod windows { id: format!("reg|{hive_label}|{}|{name}", source.key_path), name: display_name(&command), command, + target: String::new(), + target_exists: true, + trigger: "logon".to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "registry".to_string(), @@ -1178,6 +1239,12 @@ mod windows { .file_stem() .map_or_else(|| file_name.clone(), |s| s.to_string_lossy().to_string()), command: path.display().to_string(), + target: String::new(), + target_exists: true, + trigger: "logon".to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "startupFolder".to_string(), @@ -1235,6 +1302,12 @@ mod windows { .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()), + target: String::new(), + target_exists: true, + trigger: task_trigger(&text), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "scheduledTask".to_string(), @@ -1312,6 +1385,13 @@ mod windows { .rsplit_once('\\') .map_or_else(|| task_name.clone(), |(_, leaf)| leaf.to_string()), command: String::new(), + target: String::new(), + // Nothing was resolved here, so "missing" would be a lie. + target_exists: true, + trigger: "unknown".to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "scheduledTask".to_string(), @@ -1436,6 +1516,14 @@ mod windows { id: format!("svc|{name}"), name: display, command: image, + target: String::new(), + target_exists: true, + // Automatic services are started by the SCM during boot; + // manual/disabled ones only run on demand. + trigger: if start == 2 { "boot" } else { "background" }.to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "service".to_string(), @@ -1483,6 +1571,21 @@ mod windows { !tail[..end].contains("false") } + /// When a task fires: a BootTrigger runs before anyone logs on, a + /// LogonTrigger at logon, anything else (calendar, event, maintenance) is + /// a background schedule the user does not experience as "startup". + fn task_trigger(text: &str) -> String { + if text.contains("") { + "background".to_string() + } else { + "unknown".to_string() + } + } + fn task_actions(text: &str) -> Option { let start = text.find("")? + "".len(); let end = text[start..].find("")? + start; @@ -1539,9 +1642,44 @@ mod windows { entries.extend(scheduled_task_entries()); entries.extend(auto_service_entries()); decorate_display_names(&mut entries); + enrich_trust(&mut entries); entries } + /// One batched signature grade over every resolved target, then stamp the + /// verdict and fold Microsoft-signed / %SystemRoot% rows into 系统组件 — + /// the same trust table the 进阶启动项 tab shows, shared so a scan pays + /// for one PowerShell process, not one per row. + fn enrich_trust(entries: &mut [StartupEntry]) { + let system_root = std::env::var("SystemRoot") + .unwrap_or_else(|_| r"C:\Windows".to_string()) + .to_lowercase(); + let mut targets: Vec = Vec::new(); + for entry in entries.iter_mut() { + entry.system_item = entry.target.to_lowercase().starts_with(&system_root); + if entry.target_exists + && !entry.target.is_empty() + && !targets + .iter() + .any(|seen| seen.eq_ignore_ascii_case(&entry.target)) + { + targets.push(entry.target.clone()); + } + } + let grades = crate::advanced::windows::signature_grades(&targets); + for entry in entries.iter_mut() { + if let Some((verdict, signer)) = grades.get(&entry.target.to_ascii_lowercase()) { + entry.signature = verdict.clone(); + entry.signer = signer.clone(); + if verdict == "microsoft" { + entry.system_item = true; + } + } else { + entry.signature = "unknown".into(); + } + } + } + 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()); @@ -1672,6 +1810,149 @@ mod windows { .map(|_| ()) } + /// Remove one autostart registration; see the module-level + /// `remove_startup_entry` for the semantics per source kind. + pub(super) fn remove_startup_entry(entry: &StartupEntry) -> 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 hive = RegKey::predef(if machine { + HKEY_LOCAL_MACHINE + } else { + HKEY_CURRENT_USER + }); + let direct = (|| -> std::io::Result<()> { + let key = hive.open_subkey_with_flags(key_path, KEY_READ | KEY_WRITE)?; + key.delete_value(*name) + })(); + if let Err(why) = direct { + if why.kind() != std::io::ErrorKind::PermissionDenied { + return Err(registry_error(why)); + } + run_elevated( + "reg.exe", + &[ + "delete".to_string(), + format!(r"{hive_label}\{key_path}"), + "/v".to_string(), + name.to_string(), + "/f".to_string(), + ], + )?; + if hive + .open_subkey_with_flags(key_path, KEY_READ) + .map(|key| key.get_raw_value(*name).is_ok()) + .unwrap_or(false) + { + return Err("提权删除后启动项仍然存在".to_string()); + } + } + // Task Manager keeps its own approval marker next to the row; + // drop it so the removed name cannot resurface as a ghost. + let marker = if prefix32 { + format!("32|{name}") + } else { + name.to_string() + }; + let _ = hive + .open_subkey_with_flags( + format!(r"{base}\Explorer\StartupApproved\{list}"), + KEY_READ | KEY_WRITE, + ) + .and_then(|key| key.delete_value(&marker)); + Ok(()) + } + "folder" => { + let file = Path::new(rest); + match std::fs::remove_file(file) { + Ok(()) => Ok(()), + Err(why) if why.kind() == std::io::ErrorKind::PermissionDenied => { + run_elevated( + "cmd.exe", + &["/C".to_string(), "del".to_string(), format!("/F /Q {rest}")], + )?; + if file.exists() { + return Err("提权删除后快捷方式仍然存在".to_string()); + } + Ok(()) + } + Err(why) => Err(format!("删除快捷方式失败:{why}")), + } + } + "task" => { + use std::os::windows::process::CommandExt; + let output = std::process::Command::new("schtasks.exe") + .args(["/Delete", "/TN", rest, "/F"]) + .creation_flags(0x0800_0000) + .output() + .map_err(|error| format!("无法调用 schtasks:{error}"))?; + if output.status.success() { + return Ok(()); + } + let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase(); + if stderr.contains("access is denied") + || stderr.contains("access denied") + || stderr.contains("拒绝访问") + { + run_elevated( + "schtasks.exe", + &[ + "/Delete".to_string(), + "/TN".to_string(), + rest.to_string(), + "/F".to_string(), + ], + )?; + return Ok(()); + } + Err(format!( + "删除计划任务失败:{}", + String::from_utf8_lossy(&output.stderr).trim() + )) + } + "svc" => { + // Uninstalling a service outright breaks anything that still + // opens it, so 残留服务 is disabled instead (Start = 4). + set_startup_enabled(entry, false)?; + let key_path = format!(r"{SERVICES_KEY}\{rest}"); + let direct = (|| -> std::io::Result<()> { + let key = RegKey::predef(HKEY_LOCAL_MACHINE) + .open_subkey_with_flags(&key_path, KEY_READ | KEY_WRITE)?; + key.set_value("Start", &4u32) + })(); + if let Err(why) = direct { + if why.kind() != std::io::ErrorKind::PermissionDenied { + return Err(registry_error(why)); + } + run_elevated( + "reg.exe", + &[ + "add".to_string(), + format!(r"HKLM\{key_path}"), + "/v".to_string(), + "Start".to_string(), + "/t".to_string(), + "REG_DWORD".to_string(), + "/d".to_string(), + "4".to_string(), + "/f".to_string(), + ], + )?; + } + let _ = service_control(rest, "disabled"); + Ok(()) + } + _ => Err("这类启动项暂不支持删除".to_string()), + } + } + 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); @@ -2336,6 +2617,12 @@ mod macos { id: format!("launchAgent|{}", path.display()), name: label_text, command: path.display().to_string(), + target: String::new(), + target_exists: true, + trigger: "logon".to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "launchAgent".to_string(), @@ -2441,6 +2728,12 @@ mod linux { id: format!("autostart|{}", path.display()), name, command: exec, + target: String::new(), + target_exists: true, + trigger: "logon".to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "autostart".to_string(), diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 4577bda..ed4dccc 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -158,6 +158,7 @@ pub fn run() { permissions::open_full_disk_access_settings, manage::manage_scan, manage::startup_set_enabled, + manage::startup_remove_entry, manage::advanced_scan, manage::advanced_set_enabled, manage::extension_set_registered, diff --git a/src-tauri/src/manage.rs b/src-tauri/src/manage.rs index 05878e2..7617534 100644 --- a/src-tauri/src/manage.rs +++ b/src-tauri/src/manage.rs @@ -137,6 +137,19 @@ pub struct StartupView { enabled: bool, /// Attributed to a real software product (drives the 其他软件 bucket). named: bool, + /// The binary this row really launches (lnk resolved); empty when unknown. + target: String, + /// False = the target is gone: a 残留项 the UI can offer to delete. + target_exists: bool, + /// `boot` | `logon` | `background` | `unknown`. + trigger: String, + /// Microsoft-signed or under %SystemRoot% — the hideable 系统组件 bucket. + system_item: bool, + /// Signature verdict of `target`: `microsoft` | `vendor` | `unsigned` | + /// `invalid` | `unknown`. + signature: String, + /// Signer subject when the binary carries a certificate. + signer: Option, } impl From<&StartupEntry> for StartupView { @@ -152,6 +165,12 @@ impl From<&StartupEntry> for StartupView { scope: entry.scope.clone(), enabled: entry.enabled, named: entry.named, + target: entry.target.clone(), + target_exists: entry.target_exists, + trigger: entry.trigger.clone(), + system_item: entry.system_item, + signature: entry.signature.clone(), + signer: entry.signer.clone(), } } } @@ -335,6 +354,28 @@ pub async fn startup_set_enabled( Ok(enabled_count) } +/// Delete one autostart registration — aimed at 残留项 whose program is gone. +/// Only the config (registry value / shortcut / task) is removed, never files; +/// services are disabled instead of uninstalled. Returns the new enabled count. +#[tauri::command] +pub async fn startup_remove_entry(app: AppHandle, id: String) -> 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::remove_startup_entry(&entry)) + .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) +} + // ---- 进阶启动项 (advanced startup) ---------------------------------------- /// One advanced row for the UI: registry hooks with signature trust, plus diff --git a/src/hooks/usePermissionsWorkspace.ts b/src/hooks/usePermissionsWorkspace.ts index 27d8d63..a97533b 100644 --- a/src/hooks/usePermissionsWorkspace.ts +++ b/src/hooks/usePermissionsWorkspace.ts @@ -27,6 +27,8 @@ export interface PermissionsWorkspace { toggleStartup: (id: string, enabled: boolean) => Promise; /** 电脑管家's master switch: flip every entry of one software group. */ toggleStartupGroup: (ids: string[], enabled: boolean) => Promise; + /** Delete leftover autostart registrations (config only, never files). */ + removeStartup: (ids: string[]) => Promise; toggleAdvanced: (id: string, enabled: boolean) => Promise; toggleExtension: (id: string, registered: boolean) => Promise; addRule: (hwnd: number, matcher: "exact" | "contains") => Promise; @@ -169,6 +171,35 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace { [push, scan], ); + const removeStartup = useCallback( + async (ids: string[]) => { + if (ids.length === 0) return; + setBusyId(ids[0]); + setError(null); + const failures: string[] = []; + let removed = 0; + try { + for (const id of ids) { + try { + await api.startupRemoveEntry(id); + removed += 1; + } catch (reason) { + failures.push(messageFrom(reason)); + } + } + await scan(); + } finally { + setBusyId(null); + } + if (removed > 0) push(`已删除 ${removed} 个残留启动项`, "success"); + if (failures.length > 0) { + setError(failures[0]); + push(failures[0], "danger"); + } + }, + [push, scan], + ); + const toggleAdvanced = useCallback( async (id: string, enabled: boolean) => { setBusyId(id); @@ -293,6 +324,7 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace { refreshWindows, toggleStartup, toggleStartupGroup, + removeStartup, toggleAdvanced, toggleExtension, addRule, diff --git a/src/lib/api.ts b/src/lib/api.ts index bd5109c..4b40c9b 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -121,6 +121,7 @@ export const api = { manageScan: () => invoke("manage_scan"), startupSetEnabled: (id: string, enabled: boolean) => invoke("startup_set_enabled", { id, enabled }), + startupRemoveEntry: (id: string) => invoke("startup_remove_entry", { id }), advancedScan: () => invoke("advanced_scan"), advancedSetEnabled: (id: string, enabled: boolean) => invoke("advanced_set_enabled", { id, enabled }), diff --git a/src/pages/DuplicateFilesPage.tsx b/src/pages/DuplicateFilesPage.tsx index 767ec72..df76381 100644 --- a/src/pages/DuplicateFilesPage.tsx +++ b/src/pages/DuplicateFilesPage.tsx @@ -68,6 +68,10 @@ function DupGroupCard({ }) { const { t } = useI18n(); const wasted = group.size * (group.copies.length - 1); + // The keeper row is now a normal, checkable copy: ticking it means "this + // group may end up with nothing left". The amber chip keeps saying 保留 so + // the strategy stays visible, and adds a warning when it gets picked. + const keepPicked = picked?.has(keep) ?? false; return (
@@ -79,6 +83,11 @@ function DupGroupCard({ {t("wastes", "重复浪费")} {formatBytes(wasted)} + {keepPicked ? ( + + {t("group will be empty", "本组将一份不剩")} + + ) : null} {group.personal ? ( @@ -105,15 +114,32 @@ function DupGroupCard({ return (
  • onToggle(index, copyIndex)} label={copy.path} /> - {isKeep ? {t("keep", "保留")} : null} + {isKeep ? ( + + {checked ? t("keep · deleting", "保留 · 已勾选删除") : t("keep", "保留")} + + ) : null} + {copy.locked ? ( @@ -192,6 +218,17 @@ export function DuplicateFilesPage({ // Totals next to the toolbar follow the *visible* groups: an ignored group // stops counting toward what the page offers to reclaim. const visibleWasted = groups.reduce((sum, g) => sum + g.size * (g.copies.length - 1), 0); + // Groups whose *kept* copy is checked: deleting those erases the file + // entirely (every copy goes), which the summary strip and confirm dialog + // must call out before anything moves to the Recycle Bin. + const empties = entries.reduce( + (sum, entry) => + sum + + (workspace.picks.get(entry.index)?.has(keepIndexOf(entry.group, workspace.keepStrategy)) + ? 1 + : 0), + 0, + ); // Hub badge: confirmed groups after ignores, or null before a scan. useEffect(() => { @@ -347,6 +384,14 @@ export function DuplicateFilesPage({ {formatCount(groups.length)} {t("groups · duplicate copies", "组 · 重复副本")}{" "} {formatCount(groups.reduce((sum, g) => sum + g.copies.length - 1, 0))} ·{" "} {formatBytes(visibleWasted)} + {empties > 0 ? ( + + {t( + `${formatCount(empties)} group(s) will be fully removed`, + ` · ${formatCount(empties)} 组将一份不剩`, + )} + + ) : null}
  • {confirming ? ( -
    +
    0 ? "is-strict" : ""}`}>
    @@ -374,16 +419,32 @@ export function DuplicateFilesPage({ ? `将 ${workspace.selectedCount} 个副本(${formatBytes(workspace.selectedBytes)})移入回收站?` : `Move ${workspace.selectedCount} copies (${formatBytes(workspace.selectedBytes)}) to the Recycle Bin?`} + {empties > 0 ? ( + + {lang === "zh" + ? `${formatCount(empties)} 组勾选了最后保留版本——这 ${formatCount(empties)} 组将被完全删除!` + : `${formatCount(empties)} group(s) include the kept copy — they will be deleted entirely!`} + + ) : ( + + {t( + "Every group keeps at least one copy; a mis-click is one Undo away from History.", + "每组至少保留一份;误删可从「历史记录 → 撤销」找回。", + )} + + )} {t( - "Every group keeps at least one copy; a mis-click is one Undo away from History.", - "每组至少保留一份;误删可从「历史记录 → 撤销」找回。", + "Deletions land in the Recycle Bin — undo from History.", + "删除一律进回收站,可从「历史记录 → 撤销」找回。", )}
    ) : null} diff --git a/src/pages/LargeFilesPage.tsx b/src/pages/LargeFilesPage.tsx index 097a37a..86ed01c 100644 --- a/src/pages/LargeFilesPage.tsx +++ b/src/pages/LargeFilesPage.tsx @@ -266,8 +266,8 @@ export function LargeFilesPage({ `已选 ${pickedCount} 项 · ${formatBytes(pickedBytes)} → 移入回收站`, ) : t( - "Dormant files (180 days untouched) are tagged; disk images held by Hyper-V/WSL stay locked.", - "长期未修改(180 天+)的文件会带休眠标记;被 Hyper-V/WSL 使用的镜像会锁定。", + "Dormant files (180 days untouched) are tagged; disk images held by Hyper-V/WSL stay locked. Page files are hidden; hiberfil.sys frees via turning hibernation off.", + "长期未修改(180 天+)的文件会带休眠标记;被 Hyper-V/WSL 使用的镜像会锁定。页面文件(pagefile/swapfile)已自动隐藏;hiberfil.sys 可通过关闭休眠释放。", )} diff --git a/src/pages/PermissionsPage.tsx b/src/pages/PermissionsPage.tsx index ced2aa1..fd6c9fc 100644 --- a/src/pages/PermissionsPage.tsx +++ b/src/pages/PermissionsPage.tsx @@ -1,11 +1,23 @@ -import { BellRing, ChevronRight, RefreshCw, Search, ShieldCheck, Trash2, X } from "lucide-react"; +import { + AlertTriangle, + BellRing, + ChevronRight, + FolderOpen, + RefreshCw, + Search, + ShieldCheck, + Trash2, + X, +} from "lucide-react"; import { useMemo, useState } from "react"; import { useI18n } from "../i18n"; +import { api } from "../lib/api"; import { shortPath } from "../lib/format"; import type { PermissionsWorkspace } from "../hooks/usePermissionsWorkspace"; import type { StartupItem } from "../types"; import { Button, + ConfirmDialog, EmptyState, IconButton, InlineError, @@ -23,6 +35,84 @@ function softwareIcon(items: StartupItem[]): string { return items.find((item) => item.icon)?.icon ?? ""; } +// A row whose program binary no longer exists on disk — the config survived +// an uninstall. MangoDisk calls these 残留项 and offers to delete the config. +function isLeftover(item: StartupItem): boolean { + return item.targetExists === false; +} + +// MangoDisk's source-kind chips: compact kind label, the detailed path lives +// in the expanded row. +const SOURCE_KIND: Record = { + registry: ["Registry", "注册表"], + startupFolder: ["Startup folder", "启动文件夹"], + scheduledTask: ["Task", "计划任务"], + service: ["Service", "服务"], + launchAgent: ["LaunchAgent", "LaunchAgent"], + autostart: ["Autostart", "自启动"], +}; + +// When the row fires, phrased the way the user experiences it. +const TRIGGER_LABEL: Record = { + boot: ["On boot", "开机后"], + logon: ["On logon", "登录后"], + background: ["Background", "后台常驻"], +}; + +type SigTone = "microsoft" | "vendor" | "unsigned" | "invalid" | "unknown"; + +function signatureChip( + verdict: string, + t: (en: string, zh: string) => string, +): [string, string] | null { + switch (verdict as SigTone) { + case "microsoft": + return [t("Microsoft", "微软"), "is-microsoft"]; + case "vendor": + return [t("Signed", "签名有效"), "is-vendor"]; + case "unsigned": + return [t("Not signed", "未签名"), "is-unsigned"]; + case "invalid": + return [t("Invalid", "签名无效"), "is-invalid"]; + default: + return null; + } +} + +// The one signature story a group tells: the worst verdict inside it, so a +// group never looks greener than its sketchiest row. +function groupSignature(items: StartupItem[]): string { + const seen = new Set(items.map((item) => item.signature ?? "unknown")); + if (seen.has("invalid")) return "invalid"; + if (seen.has("unsigned")) return "unsigned"; + if (seen.has("vendor")) return "vendor"; + if (seen.has("microsoft")) return "microsoft"; + return "unknown"; +} + +// 残留 / 已启用 / 已禁用 row tag; leftover wins the colour fight. +function statusChip( + item: StartupItem, + t: (en: string, zh: string) => string, +): [string, string] { + if (isLeftover(item)) return [t("Leftover", "残留"), "is-leftover"]; + return item.enabled + ? [t("Enabled", "已启用"), "is-on"] + : [t("Disabled", "已禁用"), "is-off"]; +} + +// 启动文件夹 rows are removable by deleting the shortcut; the folder is a +// nice human landing spot for anything else. +function rowRevealPath(item: StartupItem): string { + const anchor = item.target || item.command; + if (!anchor) return ""; + return anchor.replace(/"$/, "").replace(/^(.*\.(exe|lnk|bat|cmd))\s+/i, "$1"); +} + +// MangoDisk's status filter: a segment with live counts, 残留 included. +type StartupFilter = "all" | "enabled" | "disabled" | "leftover"; + + // 电脑管家 shows the owning software's icon on every row it can attribute to // an installed program; a grey initial covers the leftovers. function RowIcon({ icon, label }: { icon: string | null | undefined; label: string }) { @@ -40,6 +130,9 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace const [query, setQuery] = useState(""); const [openGroups, setOpenGroups] = useState>(new Set()); const [extCat, setExtCat] = useState(null); + const [startupFilter, setStartupFilter] = useState("all"); + const [showSystem, setShowSystem] = useState(false); + const [removingIds, setRemovingIds] = useState(null); const view = workspace.view; const tabs = useMemo( @@ -121,26 +214,56 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace } const needle = query.trim().toLowerCase(); - const startup = view.startup.filter( + const startupSearch = view.startup.filter( (item) => !needle || item.name.toLowerCase().includes(needle) || item.displayName.toLowerCase().includes(needle) || item.command.toLowerCase().includes(needle), ); + // MangoDisk's 显示系统项: Microsoft-signed / %SystemRoot% rows fold into a + // hideable 系统组件 group instead of mixing into the software list. + const systemName = t("System components", "系统组件"); + const startupVisible = showSystem + ? startupSearch + : startupSearch.filter((item) => !item.systemItem); + const leftoverCount = startupVisible.filter(isLeftover).length; + const enabledCount = startupVisible.filter((item) => item.enabled && !isLeftover(item)).length; + const disabledCount = startupVisible.length - enabledCount - leftoverCount; + const counts: Record = { + all: startupVisible.length, + enabled: enabledCount, + disabled: disabledCount, + leftover: leftoverCount, + }; + const startup = startupVisible.filter((item) => + startupFilter === "all" + ? true + : startupFilter === "leftover" + ? isLeftover(item) + : startupFilter === "enabled" + ? item.enabled && !isLeftover(item) + : !item.enabled && !isLeftover(item), + ); // 电脑管家 style: one group per software (Chinese name in the header); // every entry the backend could not attribute to a real product lands in - // a catch-all 其他软件 group, which always sorts last. + // a catch-all 其他软件 group; system rows sink to their own group last. const otherName = t("Other software", "其他软件"); const startupGroups = new Map(); for (const item of startup) { - const key = item.named && item.displayName ? item.displayName : otherName; + const key = item.systemItem + ? systemName + : item.named && item.displayName + ? item.displayName + : otherName; const list = startupGroups.get(key) ?? []; list.push(item); startupGroups.set(key, list); } const orderedGroups = [...startupGroups.entries()].sort( - ([a], [b]) => Number(a === otherName) - Number(b === otherName), + ([a], [b]) => + Number(a === otherName) - Number(b === otherName) || + Number(a === systemName) - Number(b === systemName), ); // Groups start folded (管家 habit): the header carries a master switch // and the status line; expanding shows the per-entry detail. Searching @@ -223,21 +346,65 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace `共 ${view.startupCount} 项,其中 ${view.startupEnabledCount} 项已开启。`, )} /> - +
    +
    + {( + [ + ["all", "All", "全部"], + ["enabled", "Enabled", "已启用"], + ["disabled", "Disabled", "已禁用"], + ["leftover", "Leftover", "残留"], + ] as const + ).map(([id, en, zh]) => ( + + ))} +
    +
    + + +
    +
    {orderedGroups.map(([software, items]) => { - const onCount = items.filter((item) => item.enabled).length; + const onCount = items.filter((item) => item.enabled && !isLeftover(item)).length; const allOn = onCount === items.length; const open = isGroupOpen(software); const groupIds = items.map((item) => item.id); + const leftovers = items.filter(isLeftover); + const sources = [...new Set(items.map((item) => item.source))]; + const triggers = [...new Set(items.map((item) => item.trigger ?? "unknown"))]; + const groupSigChip = signatureChip(groupSignature(items), t); return ( -
    +
    0 && leftovers.length === items.length ? "is-leftover" : "" + }`} + >

    toggleGroupOpen(software)}> {items.find((item) => item.icon)?.icon ? ( @@ -247,6 +414,30 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace )} {software} + + {leftovers.length > 0 ? ( + + {t(`${leftovers.length} leftover`, `${leftovers.length} 个残留`)} + + ) : null} + {sources.map((source) => { + const n = items.filter((item) => item.source === source).length; + return ( + + {t(SOURCE_KIND[source]?.[0] ?? source, SOURCE_KIND[source]?.[1] ?? source)} + {n > 1 ? ×{n} : null} + + ); + })} + {triggers.map((trigger) => ( + + {t(TRIGGER_LABEL[trigger]?.[0] ?? "—", TRIGGER_LABEL[trigger]?.[1] ?? "—")} + + ))} + {groupSigChip ? ( + {groupSigChip[0]} + ) : null} + {allOn ? t("All on", "全部开启") @@ -286,39 +477,131 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace

    {open ? (
    - {items.map((item) => ( -
    -
    -
    - {item.name} - - {item.sourceLabel} · {scopeLabel(item.scope, t)} - {item.command ? ` · ${shortPath(item.command, 72)}` : ""} - + {items.map((item) => { + const [statusText, statusTone] = statusChip(item, t); + const sigChip = signatureChip(item.signature ?? "unknown", t); + const reveal = rowRevealPath(item); + return ( +
    +
    +
    + + {item.name}{" "} + {statusText} + + + {item.sourceLabel} · {scopeLabel(item.scope, t)} + {item.command ? ` · ${shortPath(item.command, 72)}` : ""} + + + {item.command || t("(no command line)", "(无命令行记录)")} + +
    +
    +
    + {sigChip ? ( + + {sigChip[0]} + + ) : null} + {isLeftover(item) ? ( + + ) : null} + {reveal ? ( + void api.revealPath(reveal).catch(() => {})} + > + + + ) : null} + void workspace.toggleStartup(item.id, next)} + label={`${item.name} ${item.enabled ? "disable" : "enable"}`} + />
    - 0 && leftovers.length < items.length ? ( +
    + + + {t( + `${leftovers.length} leftover entries in this group — their programs are gone.`, + `该组有 ${leftovers.length} 个残留项:程序已不存在,只剩启动配置。`, + )} + +
    - ))} + ) : null}
    ) : null}
    ); })} {startup.length === 0 ? ( -

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

    +

    + {counts.all === 0 + ? t("No matches.", "没有匹配的项目。") + : t("Nothing here under this filter.", "当前筛选下没有项目。")} +

    ) : null}
    ) : null} + } + title={t("Delete startup entries?", "删除启动项?")} + message={t( + `Squid removes only the autostart registration (${removingIds?.length ?? 0} item(s)); no program files are touched.`, + `Squid 只删除启动配置(共 ${removingIds?.length ?? 0} 项),不会动任何程序文件。`, + )} + note={t( + "Registry values are deleted; Startup-folder shortcuts are removed; tasks are unscheduled; leftover services are set to disabled.", + "注册表值将被删除;启动文件夹的快捷方式会被移除;计划任务会被注销;残留服务会改为禁用。", + )} + confirmLabel={t("Delete", "删除")} + cancelLabel={t("Cancel", "取消")} + busy={workspace.busyId !== null} + onClose={() => setRemovingIds(null)} + onConfirm={async () => { + if (!removingIds) return; + await workspace.removeStartup(removingIds); + setRemovingIds(null); + }} + /> + {workspace.tab === "extensions" ? (
    svg { + color: #b0563d; +} + +.dup-confirm-warn { + color: #b0563d; +} + .dup-groups { display: flex; flex-direction: column; @@ -8055,6 +8107,171 @@ html.widget-mode body { white-space: nowrap; } +/* ── 开机启动项 MangoDisk 化(筛选段/系统项开关/来源芯片/残留)─────── */ + +.perm-startup-bar { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 10px; + margin-bottom: 12px; +} + +.perm-filter { + display: inline-flex; + padding: 3px; + border: 1px solid var(--nex-line); + border-radius: 11px; + background: rgba(255, 255, 255, 0.55); +} + +.perm-filter-tab { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 13px; + border: 0; + border-radius: 8px; + background: transparent; + color: var(--nex-muted); + font-size: var(--nex-text-2xs); + cursor: pointer; + transition: all 0.14s ease; +} + +.perm-filter-tab b { + padding: 0 7px; + border-radius: 999px; + background: var(--nex-cream); + color: var(--nex-muted); + font-size: var(--nex-text-3xs); + font-weight: var(--nex-weight-semibold); +} + +.perm-filter-tab.is-active { + background: #fff; + color: #2b2620; + font-weight: var(--nex-weight-semibold); + box-shadow: 0 1px 4px rgba(60, 50, 35, 0.12); +} + +.perm-filter-tab.has-leftover b { + background: rgba(194, 84, 56, 0.12); + color: #b0563d; +} + +.perm-startup-tools { + display: flex; + align-items: center; + gap: 12px; +} + +.perm-system-toggle { + display: inline-flex; + align-items: center; + gap: 8px; + color: #6c7a87; + font-size: var(--nex-text-2xs); + white-space: nowrap; + cursor: pointer; +} + +.perm-group-chips { + display: inline-flex; + align-items: center; + gap: 5px; + flex: 0 1 auto; + min-width: 0; + overflow: hidden; +} + +.perm-src-chip { + display: inline-flex; + align-items: center; + gap: 3px; + padding: 1px 8px; + border: 1px solid #ddd6cc; + border-radius: 99px; + background: rgba(140, 140, 140, 0.05); + color: #7d8896; + font-size: var(--nex-text-3xs); + white-space: nowrap; +} + +.perm-src-chip i { + font-style: normal; + color: #aab4c0; +} + +/* 残留 verdict chip — red sibling of .perm-sig. */ +.perm-sig.is-leftover, +.perm-row-tag.is-leftover { + border: 1px solid #e0b3a6; + background: rgba(194, 84, 56, 0.13); + color: #a84e34; + font-weight: var(--nex-weight-semibold); +} + +/* Row status tag (已启用 / 已禁用 / 残留). */ +.perm-row-tag { + margin-left: 6px; + padding: 0 7px; + border: 1px solid #ddd6cc; + border-radius: 99px; + color: #8b94a0; + font-size: var(--nex-text-3xs); + font-style: normal; + vertical-align: 1px; +} + +.perm-row-tag.is-on { + border-color: #bfe0c4; + background: rgba(88, 170, 98, 0.08); + color: #4b8a55; +} + +.perm-row-tag.is-off { + border-color: #ddd6cc; + background: rgba(140, 140, 140, 0.07); + color: #98a2ae; +} + +/* Full command line, third detail line of an expanded row. */ +.perm-row-full { + color: #b0a89c !important; + font-family: var(--nex-font-mono, monospace); + max-width: 100%; +} + +/* A group whose every row is a leftover gets a red frame; single leftover + rows get a faint red wash. */ +.perm-group-card.is-leftover { + border: 1px solid rgba(194, 84, 56, 0.35); +} + +.settings-row.is-leftover-row { + background: rgba(194, 84, 56, 0.045); +} + +/* Summary bar at the bottom of an expanded group with leftovers. */ +.perm-group-leftover-bar { + display: flex; + align-items: center; + gap: 8px; + margin: 4px 0 8px 30px; + padding: 7px 12px; + border: 1px dashed #e0b3a6; + border-radius: 10px; + color: #a84e34; + font-size: var(--nex-text-3xs); +} + +.perm-group-leftover-bar > span { + flex: 1 1 auto; + min-width: 0; +} + /* ── Hub pages(空间清理/系统维护 三页签容器,方案①②)────────────── */ .hub-page .hub-tabs { diff --git a/src/types.ts b/src/types.ts index b59e8fe..f1812dd 100644 --- a/src/types.ts +++ b/src/types.ts @@ -472,6 +472,18 @@ export interface StartupItem { enabled: boolean; /** Attributed to a real product; false lands in the 其他软件 group. */ named: boolean; + /** The binary this row really launches (`.lnk` resolved); "" when unknown. */ + target?: string; + /** False = the program is gone: a 残留项 that can be removed. */ + targetExists?: boolean; + /** When it fires: `boot` | `logon` | `background` | `unknown`. */ + trigger?: string; + /** Microsoft-signed or under %SystemRoot%; hideable 系统组件 bucket. */ + systemItem?: boolean; + /** `microsoft` | `vendor` | `unsigned` | `invalid` | `unknown`. */ + signature?: string; + /** Signer subject when the binary carries a certificate. */ + signer?: string | null; } export interface ShellExtension {