Release Squid 0.1.9 with low-CPU desktop monitor

Merge the dev monitor optimizations on top of the unreleased 0.1.8 desktop work: shared light snapshots, visibility-aware polling, CPU history/per-core panel, and a resize/redock guard that stops the widget IPC loop.

Also carries the desktop widget, permissions/security, storage-volume fixes, update-installer cleanup category, tray template icon, and Windows Recycle Bin wording.
main
mula.liu 2026-11-19 10:21:43 +08:00
parent 8490f9213c
commit cea60cc6c1
65 changed files with 8523 additions and 257 deletions

3
.gitignore vendored
View File

@ -59,6 +59,9 @@ __pycache__/
!.env.example
*.local
# 输入法/软件在 cwd 落的调试日志(sogou 等)
debug.log
# ── 显式纳管的发布产物 ───────────────────────────────────────────────
!release/0.1.3/Squid-0.1.3-macOS-universal.dmg
!release/0.1.3/Squid-Setup-0.1.3-win-x64.exe

17
Cargo.lock generated
View File

@ -3594,7 +3594,7 @@ dependencies = [
[[package]]
name = "squid-cli"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"anyhow",
"chrono",
@ -3614,7 +3614,7 @@ dependencies = [
[[package]]
name = "squid-core"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"anyhow",
"chrono",
@ -3633,7 +3633,7 @@ dependencies = [
[[package]]
name = "squid-engine"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"anyhow",
"chrono",
@ -3653,7 +3653,7 @@ dependencies = [
[[package]]
name = "squid-guard"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"chrono",
"hex",
@ -3669,7 +3669,7 @@ dependencies = [
[[package]]
name = "squid-platform"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"dirs",
"file_icon_provider",
@ -3689,7 +3689,7 @@ dependencies = [
[[package]]
name = "squid-rules"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"globset",
"serde",
@ -3701,7 +3701,7 @@ dependencies = [
[[package]]
name = "squid-stats"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"chrono",
"libc",
@ -3709,11 +3709,12 @@ dependencies = [
"squid-core",
"squid-platform",
"sysinfo",
"windows-sys 0.59.0",
]
[[package]]
name = "squid-tui"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"anyhow",
"chrono",

View File

@ -4,7 +4,7 @@ members = ["crates/*"]
exclude = ["src-tauri"]
[workspace.package]
version = "0.1.7"
version = "0.1.9"
edition = "2021"
rust-version = "1.95"
license = "GPL-3.0-only"

View File

@ -30,6 +30,8 @@ The desktop app supports macOS 12+ and Windows 10/11 x64. The CLI and TUI share
| Real-time monitor | Samples CPU, memory, network, disk, battery, volumes, and high-usage processes every two seconds. The Processes tab lists every process with its signature and startup entry, and ends them after confirmation |
| Security | Reports XProtect or Defender status, scans for malware by hash, YARA rule and heuristic, grades findings confirmed / suspicious / advisory, and quarantines them reversibly |
| Startup items | LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; the ones the current user owns can be disabled and re-enabled |
| Permissions (Windows) | Registry Run keys, startup folders and scheduled tasks, shell context-menu handlers, popup-window rules and a background watcher |
| Desktop widget | A borderless board pinned from Real-time monitor, with CPU / memory / GPU rings, network and disk curves, and storage bars; all settings open from the top of the widget |
| History and undo | Every real deletion is recorded in a local ledger; items still in Trash or the Recycle Bin can be restored |
| System updates | Checks, verifies, downloads, and installs new versions from the release channel |
@ -39,14 +41,16 @@ Language settings offer only Simplified Chinese and English, with the current sy
### Sidebar
- **Maintenance**: Overview, Daily cleanup, Uninstall apps, Deep Clean
- **Maintenance**: Overview, Daily cleanup, Uninstall apps, Deep Clean, Permissions (Windows only)
- **Protection**: Security, Startup items
- **Insights**: Storage, Real-time monitor
- **Bottom**: History, Settings
Use `⌘1`–`⌘0` on macOS or `Ctrl+1`–`Ctrl+0` on Windows to switch pages, in the
sidebar order above. Since 0.1.6, `7` and `8` open Security and Startup items;
History and Settings moved to `9` and `0`.
Use `⌘1`–`⌘8` on macOS or `Ctrl+1`–`Ctrl+9` on Windows to switch pages, in the
sidebar order. Windows maps `1`–`9` to Overview, Daily cleanup, Uninstall apps,
Deep Clean, Permissions, Storage, Real-time monitor, Security and Startup items.
macOS hides the Windows-only Permissions screen, so the later pages shift up by
one.
### Menu bar / tray
@ -59,10 +63,33 @@ Closing the main window only hides it; Squid keeps running. The tray menu offers
- Daily cleanup
- Uninstall apps
- Deep Clean
- Show / hide desktop widget
- Quit Squid
The tray mark is transparent and monochrome: macOS receives it as a template
image, so the system tints it correctly for light and dark menu bars; Windows and
Linux show the same silhouette in gray.
The tray follows the active interface language. Reopening the app, double-clicking the app icon, or triggering the single-instance handler restores and focuses the main window. Only **Quit Squid** ends the process.
### Desktop widget
The desktop widget is switched on from Real-time monitor. It is a separate
borderless Tauri window, not a WidgetKit extension. It shares the Real-time
monitor sampler, refreshes at 2 / 5 / 10 seconds, and pauses while hidden.
- Every setting lives in the widget: click the gear at its top to open panel
switches, refresh rate, dock corner, fold memory and opacity.
- Up to four cards: status (CPU, memory and GPU when the OS exposes it), network,
disk I/O and storage volumes.
- On macOS it uses `BelowNormal` window level, appears on every Space, and is
non-focusable with `accept_first_mouse`, so it stays beside the desktop without
taking keyboard focus from the current app.
- On Windows it sits on the desktop layer through
`SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)`.
- The master switch is shared with the tray item; opacity is capped at 90–100%
and settings persist in `widget.json`.
### Software updates
- The system information panel always shows the current OS version, architecture, and Squid version.

View File

@ -16,6 +16,8 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具。桌面端、CLI
- **Storage & monitor / 存储与监控** — Folder-level disk analysis, live CPU, memory, network, disk, battery, and process views.
- **Security / 安全** — XProtect and Defender status, malware scanning with confirmed / suspicious / advisory findings, and reversible quarantine. No daemon, no kernel extension, no upload.
- **Startup items / 启动项** — LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; disable the ones you own.
- **Desktop widget / 桌面小工具** — Pin the Real-time monitor to the desktop as a focus-free board, with every setting in a dropdown at the top of the widget.
- **Permissions (Windows) / 权限管理** — Startup entries, shell context menus and popup-window blocking, with a background watcher.
- **History & updates / 历史与更新** — Restorable Trash sessions and a size- and SHA256-verified update channel.
The interface follows the system language by default and can be switched to Simplified Chinese or English in Settings.

View File

@ -30,6 +30,8 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建
| 实时监控 | 每两秒采样 CPU、内存、网络、磁盘、电池、卷和高占用进程,可确认后结束进程。「进程」页签列出全部进程及其签名与启动项来源 |
| 安全 | 读取 XProtect / Defender 状态,按哈希、YARA 规则与启发式扫描恶意软件,分「已确认 / 可疑 / 提示」三级,并可逆隔离 |
| 启动项 | LaunchAgent、LaunchDaemon、登录项、注册表 Run、启动文件夹、计划任务与服务;当前用户拥有的条目可停用与恢复 |
| 权限管理(Windows) | 注册表 Run、启动文件夹与计划任务,右键菜单扩展,弹窗窗口规则与后台监听 |
| 桌面小工具 | 在实时监控中一键固定到桌面的无边框看板:CPU / 内存 / GPU 圆环、网络与磁盘曲线、存储空间;设置从小工具顶部下拉打开 |
| 历史与撤销 | 每次真实删除写入本地账本;仍在废纸篓或回收站中的内容可以还原 |
| 系统更新 | 从发布分支检查、校验、下载并安装新版本 |
@ -39,13 +41,13 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建
### 左侧菜单
- **维护**:概览、日常清理、应用卸载、深度清理
- **维护**:概览、日常清理、应用卸载、深度清理、权限管理(仅 Windows)
- **保护**:安全、启动项
- **洞察**:存储空间、实时监控
- **底部**:历史记录、设置
`⌘1`–`⌘0`(macOS)或 `Ctrl+1`–`Ctrl+0`(Windows)按上面的侧栏顺序切换页面。
0.1.6 起 `7`、`8` 打开安全与启动项,历史记录与设置顺延到 `9`、`0`。
`⌘1`–`⌘8`(macOS)或 `Ctrl+1`–`Ctrl+9`(Windows)按上面的侧栏顺序切换页面。
Windows 上 `1`–`9` 依次是概览、日常清理、应用卸载、深度清理、权限管理、存储空间、实时监控、安全、启动项;macOS 隐藏 Windows 专属的权限管理,后续页面顺延。
### 常驻托盘
@ -58,10 +60,23 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建
- 日常清理
- 应用卸载
- 深度清理
- 显示/隐藏桌面小工具
- 退出 Squid
托盘图标是透明单色素材:macOS 使用模板图标,由系统按浅色/深色菜单栏自动着色;Windows 与 Linux 显示同一轮廓的灰色图标。
托盘菜单跟随当前界面语言。再次打开应用、双击应用图标或通过单实例唤起时,会恢复并聚焦主窗口。只有选择“退出 Squid”才会结束进程。
### 桌面小工具
桌面小工具由“实时监控”页面统一开关,是一个独立的无边框 Tauri 窗口,不是 WidgetKit 扩展。它复用实时监控的采样器,按 2 / 5 / 10 秒节奏刷新,隐藏时暂停采样。
- 设置全部位于小工具本身:点击顶部齿轮即可下拉打开面板、更新频率、边角停靠、折叠记忆与面板开关。
- 最多四张卡片:运行状态(CPU、内存、系统暴露的 GPU 占用)、网络、存储读写、存储空间。
- macOS 上使用 `BelowNormal` 窗口层级、出现在所有 Space,并设置为不可获得焦点且接受首次点击,因此贴着桌面显示、不会抢走当前应用的键盘焦点。
- Windows 上通过 `SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)` 停在桌面层。
- 总开关与托盘菜单同步;不透明度限制在 90–100%,配置保存在 `widget.json`。
### 软件更新
- 设置中的系统信息面板始终显示当前系统版本、架构与 Squid 版本。

View File

@ -1200,11 +1200,15 @@ fn cmd_status(args: StatusArgs, json: bool) -> Result<i32> {
"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(

View File

@ -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<Self> {
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();

View File

@ -19,10 +19,11 @@ pub enum Category {
Trash,
LanguagePacks,
Leftovers,
UpdateInstallers,
}
impl Category {
pub const ALL: [Category; 9] = [
pub const ALL: [Category; 10] = [
Category::SystemJunk,
Category::AppCaches,
Category::BrowserCaches,
@ -32,6 +33,7 @@ impl Category {
Category::Trash,
Category::LanguagePacks,
Category::Leftovers,
Category::UpdateInstallers,
];
pub fn id(self) -> &'static str {
@ -45,6 +47,7 @@ impl Category {
Category::Trash => "trash",
Category::LanguagePacks => "languages",
Category::Leftovers => "leftovers",
Category::UpdateInstallers => "update-installers",
}
}
@ -59,6 +62,7 @@ impl Category {
Category::Trash => "Trash",
Category::LanguagePacks => "Unneeded Languages",
Category::Leftovers => "Uninstaller Leftovers",
Category::UpdateInstallers => "Update Installers",
}
}
@ -76,6 +80,7 @@ impl Category {
Category::Trash => "Files waiting in the Trash",
Category::LanguagePacks => "Speech and localization data for languages you do not use",
Category::Leftovers => "Data belonging to apps that are no longer installed",
Category::UpdateInstallers => "Installer packages apps keep after a successful update",
}
}
@ -101,6 +106,9 @@ impl Category {
"trash" => Category::Trash,
"language" | "languages" | "language-packs" | "localization" => Category::LanguagePacks,
"leftover" | "leftovers" | "uninstall-leftovers" => Category::Leftovers,
"update-installer" | "update-installers" | "upgrades" | "upgrade-packages" => {
Category::UpdateInstallers
}
_ => return None,
};
Some(alias)
@ -372,6 +380,10 @@ pub struct AppInfo {
pub has_sibling_install: bool,
pub publisher: Option<String>,
pub installed_ms: Option<u64>,
/// 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<String>,
}
impl AppInfo {

View File

@ -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<PathBuf> {
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");

View File

@ -48,7 +48,9 @@ pub fn scan(
cancel: &CancelToken,
) -> squid_core::Result<ScanReport> {
let prepared = prepared_rules(engine, options);
if prepared.is_empty() {
let updates_wanted =
options.categories.is_empty() || options.categories.contains(&Category::UpdateInstallers);
if prepared.is_empty() && !updates_wanted {
return Err(SquidError::NothingToDo);
}
progress.phase("match", "locating cleanup candidates");
@ -148,6 +150,28 @@ pub fn scan(
}
}
// Update installers (升级安装包): rule-driven known apps + heuristic
// sweep of AppData staging folders. The walk is bounded, so it is always
// on unless the caller filtered categories down to something else.
let updates_wanted =
options.categories.is_empty() || options.categories.contains(&Category::UpdateInstallers);
if updates_wanted {
progress.phase("update-installers", "collecting stale update packages");
for item in crate::updates::collect(engine, cancel) {
if seen.contains_key(&item.path) {
continue;
}
let mut item = item;
if engine.is_whitelisted(&item.path) {
item = item.locked(LockReason::Whitelisted);
} else if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
}
seen.insert(item.path.clone(), report.items.len());
report.items.push(item);
}
}
if !options.fast {
measure(engine, &mut report, progress, cancel)?;
}

View File

@ -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<PathBuf> {
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<PathBuf> {
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();

View File

@ -16,6 +16,7 @@ pub mod clean;
pub mod delete;
pub mod purge;
pub mod uninstall;
pub mod updates;
use globset::GlobMatcher;
use squid_core::settings::Settings;

View File

@ -616,28 +616,40 @@ pub fn snapshot_note(snapshots: &[LocalSnapshot]) -> Option<String> {
mod tests {
use super::*;
fn sandbox() -> PathBuf {
/// Returns None when an endpoint protector refuses the scratch writes
/// (skip, not failure).
fn sandbox() -> Option<PathBuf> {
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();

View File

@ -472,6 +472,7 @@ mod tests {
has_sibling_install: false,
publisher: None,
installed_ms: None,
display_icon: None,
}
}

View File

@ -0,0 +1,324 @@
//! Update-installers collector (升级安装包): A+B combined.
//!
//! Layer A is a table of known apps whose update drop folders never
//! self-clean (WeChat, WXWork, WPS, …) — precise paths plus the process
//! that must not be running while we sweep. Layer B is a heuristic sweep
//! of one level under each AppData root, descending into directories
//! *named* like update staging areas (update/upgrade/setup/patch/…) so
//! unknown apps are still caught. Layer A results are also fed back into
//! B's seen-set, so one folder is never offered twice.
//!
//! Both layers only ever propose individual **installer-shaped files**
//! (`.exe .msi .msp .zip .7z .rar .cab .crx .nupkg .appx .patch`, ≥ 1 MiB,
//! untouched for ≥ 7 days). Runtime components that apps keep next to
//! those packages (`.bin`, `.dll`, version folders) are deliberately never
//! matched: WeChat's `update\RadiumWMPF.bin` is the *current* version, not
//! junk. Per-file items reuse the plain File deletion + undo path.
use squid_core::{Category, CleanupItem, ItemKind, LockReason};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
/// 7 天:用户确认的阈值。升级后一周内没人再碰的包,应用自己也不会再用了。
pub const MIN_AGE_DAYS: u64 = 7;
/// 1 MiB:小碎片不值得列出来。
pub const MIN_SIZE_BYTES: u64 = 1024 * 1024;
const INSTALLER_EXTENSIONS: [&str; 11] = [
"exe", "msi", "msp", "zip", "7z", "rar", "cab", "crx", "nupkg", "appx", "patch",
];
/// Directory names that mark an update staging area (layer B).
const UPDATE_DIR_NAMES: [&str; 9] = [
"update",
"updates",
"upgrade",
"upgrades",
"setup",
"installer",
"installers",
"patch",
"patches",
];
/// Vendor folders layer B must not sweep. WinGet's package cache belongs to
/// the developer category; Tencent/kingsoft/Netease are covered precisely by
/// layer A (the heuristic would only double-report the same bytes).
const SKIP_VENDORS: [&str; 4] = ["Microsoft", "winget", "Tencent", "kingsoft"];
/// Layer A: known apps → (directory relative to the AppData roots, display
/// label, process that locks the group while running).
struct KnownApp {
dir: &'static str,
label: &'static str,
process: &'static str,
}
#[cfg(windows)]
const KNOWN_APPS: &[KnownApp] = &[
KnownApp {
dir: r"Tencent\xwechat\update",
label: "微信",
process: "weixin.exe",
},
KnownApp {
dir: r"Tencent\WXWork\patch",
label: "企业微信",
process: "wxwork.exe",
},
KnownApp {
dir: r"kingsoft\office6\update",
label: "WPS Office",
process: "wps.exe",
},
KnownApp {
dir: r"kingsoft\WPS Cloud Files\update",
label: "WPS 云文档",
process: "wpscloudsvr.exe",
},
KnownApp {
dir: r"Netease\MailMaster\Update",
label: "网易邮箱大师",
process: "mailmaster.exe",
},
];
/// macOS layer A: Squirrel's update payload folders (`*.nupkg`, full
/// machines) under AppData-style roots.
#[cfg(not(windows))]
const KNOWN_APPS: &[KnownApp] = &[KnownApp {
dir: "SquirrelTemp",
label: "Squirrel 更新包",
process: "",
}];
#[cfg(windows)]
fn appdata_roots() -> Vec<PathBuf> {
let mut roots = Vec::new();
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
roots.push(PathBuf::from(local));
}
if let Some(roaming) = std::env::var_os("APPDATA") {
roots.push(PathBuf::from(roaming));
}
roots
}
#[cfg(not(windows))]
fn appdata_roots() -> Vec<PathBuf> {
let home = squid_core::paths::home_dir();
vec![
home.join("Library/Caches"),
home.join("Library/Application Support"),
]
}
pub fn is_installer(file: &Path) -> bool {
let Some(ext) = file.extension().and_then(|ext| ext.to_str()) else {
return false;
};
INSTALLER_EXTENSIONS
.iter()
.any(|wanted| ext.eq_ignore_ascii_case(wanted))
}
fn stale_enough(meta: &std::fs::Metadata) -> bool {
if meta.len() < MIN_SIZE_BYTES {
return false;
}
let modified = meta
.modified()
.or_else(|_| meta.created())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
modified
.elapsed()
.map(|age| age.as_secs() >= MIN_AGE_DAYS * 86_400)
.unwrap_or(true)
}
/// Depth-capped sweep of one staging directory: every stale installer file
/// becomes its own item (File kind → plain delete + undo path).
fn sweep(
dir: &Path,
label: &str,
rule: &str,
blocked: bool,
out: &mut Vec<CleanupItem>,
seen: &mut HashSet<PathBuf>,
) {
let walker = walkdir::WalkDir::new(dir)
.max_depth(3)
.follow_links(false)
.into_iter()
.filter_entry(|entry| !entry.file_type().is_symlink());
for entry in walker.flatten() {
if !entry.file_type().is_file() {
continue;
}
let path = entry.path();
let Ok(meta) = entry.metadata() else { continue };
if !is_installer(path) || !stale_enough(&meta) {
continue;
}
if !seen.insert(path.to_path_buf()) {
continue;
}
let item = CleanupItem::new(
path.to_path_buf(),
ItemKind::File,
Category::UpdateInstallers,
format!("{label} · {}", squash_name(path)),
)
.with_rule(rule)
.with_anchors(std::iter::once(dir.to_path_buf()))
.with_note("升级完成后不再需要;需要时应用会自动重新下载");
let item = if blocked {
item.locked(LockReason::AppRunning)
} else {
item
};
out.push(item);
}
}
/// Long hashed package names read badly in a list; keep a head+tail hint.
fn squash_name(path: &Path) -> String {
let name = path
.file_name()
.map_or_else(String::new, |n| n.to_string_lossy().into_owned());
let chars: Vec<char> = name.chars().collect();
if chars.len() <= 42 {
return name;
}
let head: String = chars[..24].iter().collect();
let tail: String = chars[chars.len() - 16..].iter().collect();
format!("{head}…{tail}")
}
/// One entry point. The caller dedups against rule-matched items and the
/// safety layer (whitelist / protected) is applied like for any other item.
pub fn collect(engine: &crate::Engine, cancel: &squid_core::CancelToken) -> Vec<CleanupItem> {
let mut out = Vec::new();
let mut seen: HashSet<PathBuf> = HashSet::new();
if cancel.is_cancelled() {
return out;
}
let running: Vec<String> = engine
.platform()
.running_executables()
.into_iter()
.map(|proc| {
proc.rsplit(['/', '\\'])
.next()
.unwrap_or_default()
.to_lowercase()
})
.collect();
let roots = appdata_roots();
// Layer A: precise known-app staging folders.
for app in KNOWN_APPS {
let blocked = !app.process.is_empty() && running.iter().any(|name| name == app.process);
for root in &roots {
let dir = root.join(app.dir);
if dir.is_dir() {
sweep(
&dir,
app.label,
"update-installers-known",
blocked,
&mut out,
&mut seen,
);
}
}
}
// Layer B: heuristic sweep of <AppDataRoot>/<vendor>/<update-dir>.
for root in &roots {
let Ok(vendors) = std::fs::read_dir(root) else {
continue;
};
for vendor in vendors.flatten() {
if cancel.is_cancelled() {
return out;
}
if !vendor.file_type().map(|t| t.is_dir()).unwrap_or(false) {
continue;
}
let vendor_name = vendor.file_name().to_string_lossy().into_owned();
if SKIP_VENDORS
.iter()
.any(|skip| vendor_name.eq_ignore_ascii_case(skip))
{
continue;
}
let Ok(subs) = std::fs::read_dir(vendor.path()) else {
continue;
};
for sub in subs.flatten() {
let name = sub.file_name().to_string_lossy().into_owned();
if !UPDATE_DIR_NAMES.contains(&name.to_lowercase().as_str()) || !sub.path().is_dir()
{
continue;
}
sweep(
&sub.path(),
&vendor_name,
"update-installers-scan",
false,
&mut out,
&mut seen,
);
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn installer_shapes_are_matched_and_runtime_is_not() {
assert!(is_installer(Path::new("a/patch.zip")));
assert!(is_installer(Path::new("a/Weixin.EXE")));
assert!(is_installer(Path::new("a/update.bin.patch")));
// Runtime components must never match — this is the WeChat rule.
assert!(!is_installer(Path::new("a/RadiumWMPF.bin")));
assert!(!is_installer(Path::new("a/Weixin.dll")));
assert!(!is_installer(Path::new("a/manifest.dat")));
assert!(!is_installer(Path::new("a/noext")));
}
#[test]
fn tiny_files_are_not_offered() {
let temp = std::env::temp_dir().join(format!("squid-updates-size-{}", std::process::id()));
let Ok(()) = std::fs::create_dir_all(&temp) else {
eprintln!("skipping: scratch dir failed");
return;
};
let file = temp.join("small.exe");
if let Err(error) = std::fs::write(&file, vec![0u8; 1024]) {
eprintln!("skipping: scratch write denied ({error})");
return;
}
let meta = std::fs::metadata(&file).expect("meta");
assert!(!stale_enough(&meta));
let big = temp.join("big.exe");
if std::fs::write(&big, vec![0u8; 2 * 1024 * 1024]).is_ok() {
let meta = std::fs::metadata(&big).expect("big meta");
// fresh: size passes but the 7-day gate holds it back
assert!(!stale_enough(&meta));
}
let _ = std::fs::remove_dir_all(&temp);
}
#[test]
fn long_package_names_get_squashed() {
let name = squash_name(Path::new(&format!("C:/x/{}-x64_zh-CN.msi", "a".repeat(60))));
assert!(name.chars().count() <= 42, "{name}");
assert!(name.ends_with("-x64_zh-CN.msi"));
}
}

View File

@ -31,6 +31,13 @@ windows-sys = { version = "0.59", features = [
"Win32_Security_Cryptography",
"Win32_Security_WinTrust",
"Win32_System_Threading",
"Win32_System_Registry",
"Win32_Globalization",
"Win32_UI_WindowsAndMessaging",
"Win32_UI_Shell",
"Win32_Graphics_Gdi",
"Win32_System_SystemInformation",
"Win32_System_IO",
] }
[target.'cfg(any(target_os = "macos", target_os = "windows"))'.dependencies]

View File

@ -135,6 +135,7 @@ pub fn app_from_bundle(
.and_then(|m| m.created().ok().or_else(|| m.modified().ok()))
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64),
display_icon: None,
};
if app.name.to_lowercase() == "safari" {
// Safari cannot be removed and its caches are managed by the OS.

View File

@ -14,6 +14,7 @@ pub mod apps;
pub mod console;
pub mod currency;
pub mod leftovers;
pub mod permissions;
pub mod process;
pub mod process_table;
pub mod protection;
@ -236,6 +237,44 @@ pub enum TrashTarget {
Unreachable,
}
/// One physical memory module read from SMBIOS (Windows).
#[derive(Clone, Debug, Default, Serialize)]
pub struct MemoryStick {
pub manufacturer: String,
pub size_bytes: u64,
pub speed_mhz: u32,
}
/// Static component facts for the overview's spec panel: what the machine
/// is built from, as opposed to what it is busy with right now.
#[derive(Clone, Debug, Default, Serialize)]
pub struct HardwareInfo {
pub board: String,
pub cpu_model: String,
pub memory_sticks: Vec<MemoryStick>,
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<dyn Platform> {
#[cfg(target_os = "macos")]

View File

@ -224,6 +224,7 @@ impl Platform for Linux {
has_sibling_install: false,
publisher: desktop.icon.clone(),
installed_ms: None,
display_icon: None,
});
}
}
@ -259,6 +260,7 @@ impl Platform for Linux {
has_sibling_install: false,
publisher: None,
installed_ms: None,
display_icon: None,
});
}
}

File diff suppressed because it is too large Load Diff

View File

@ -36,6 +36,7 @@ const PSEUDO_FS: &[&str] = &[
"rpc_pipefs",
"nsfs",
"autofs",
"nullfs",
"msdos",
"anon:osd",
"SMB",
@ -90,6 +91,16 @@ pub fn volumes_from_mounts(mounts: &[MountEntry]) -> Vec<Volume> {
if text.starts_with("/System/Volumes/Data") && !out.is_empty() {
continue;
}
// Application wrappers (for example an app that mounts its bundle at a
// temporary path) are not disks a person can manage. Finder only shows
// real volumes at `/` and under `/Volumes`.
if cfg!(target_os = "macos")
&& text != "/"
&& !text.starts_with("/Volumes/")
&& !text.starts_with("/System/Volumes/")
{
continue;
}
if let Some((total, free)) = statvfs_for(&mount.mount_point) {
let key = (total.as_u64(), free.as_u64());
if seen_capacity.contains(&key) {
@ -266,4 +277,19 @@ mod tests {
}];
assert!(volumes_from_mounts(&mounts).is_empty());
}
#[test]
fn app_wrapper_mounts_are_not_volumes() {
let mount_point = std::env::temp_dir();
let mounts = vec![MountEntry {
mount_point: mount_point.clone(),
device: "/Applications/X.app/Wrapper".into(),
fstype: "nullfs".into(),
}];
assert!(
volumes_from_mounts(&mounts).is_empty(),
"a nullfs app wrapper at {} must not look like a disk",
mount_point.display()
);
}
}

View File

@ -55,6 +55,65 @@ fn dword_value(key: &RegKey, name: &str) -> Option<u32> {
key.get_value::<u32, _>(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<u32>,
build: Option<&str>,
product: Option<&str>,
edition: Option<&str>,
display: Option<&str>,
) -> String {
let build_no = build.and_then(|b| b.trim().parse::<u32>().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<String>) -> Option<u64> {
let raw = raw?.replace('-', "");
@ -121,24 +180,16 @@ impl Platform for Windows {
let key = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey_with_flags(NT_VERSION_KEY, KEY_READ)
.ok();
match key {
Some(key) => {
let product = str_value(&key, "ProductName").unwrap_or_else(|| "Windows".into());
let display = str_value(&key, "DisplayVersion");
let build = str_value(&key, "CurrentBuildNumber");
let mut out = product;
if let Some(d) = display {
out.push(' ');
out.push_str(&d);
} else if let Some(b) = build {
out.push_str(" (build ");
out.push_str(&b);
out.push(')');
}
out
}
None => "Windows".into(),
}
let Some(key) = key else {
return "Windows".into();
};
os_label(
dword_value(&key, "CurrentMajorVersionNumber"),
str_value(&key, "CurrentBuildNumber").as_deref(),
str_value(&key, "ProductName").as_deref(),
str_value(&key, "EditionID").as_deref(),
str_value(&key, "DisplayVersion").as_deref(),
)
}
fn hardware_model(&self) -> String {
let bios = RegKey::predef(HKEY_LOCAL_MACHINE)
@ -146,8 +197,8 @@ impl Platform for Windows {
.ok();
match bios {
Some(key) => {
let vendor = str_value(&key, "SystemManufacturer");
let model = str_value(&key, "SystemProductName");
let vendor = str_value(&key, "SystemManufacturer").filter(|v| !is_placeholder(v));
let model = str_value(&key, "SystemProductName").filter(|v| !is_placeholder(v));
match (vendor, model) {
(Some(v), Some(m)) if v != m => format!("{v} {m}"),
(_, Some(m)) => m,
@ -196,7 +247,7 @@ impl Platform for Windows {
})
.collect()
}
fn list_apps(&self, cancel: &CancelToken, _size: bool) -> Result<Vec<AppInfo>> {
fn list_apps(&self, cancel: &CancelToken, size: bool) -> Result<Vec<AppInfo>> {
let running: Vec<String> = self
.running_executables()
.into_iter()
@ -244,18 +295,32 @@ impl Platform for Windows {
running.iter().any(|exe| exe.starts_with(&loc))
})
.unwrap_or(false);
// Size: Windows installers report EstimatedSize (KB) for
// Add/Remove Programs — the same number Settings shows.
// Absent that, measure the install folder when asked.
let size = match dword_value(&key, "EstimatedSize") {
Some(kb) => Bytes(u64::from(kb) * 1024),
None if size => install_location
.as_ref()
.map(|loc| {
squid_core::fs::measure(loc, squid_core::ItemKind::Path).allocated
})
.unwrap_or_default(),
None => Bytes::ZERO,
};
apps.push(AppInfo {
name: display_name,
bundle_id: None,
path,
icon_source: display_icon_path(str_value(&key, "DisplayIcon")),
version: str_value(&key, "DisplayVersion"),
size: Bytes::ZERO,
size,
source: source.into(),
running: running_app,
has_sibling_install: false,
publisher: str_value(&key, "Publisher"),
installed_ms: install_date_ms(str_value(&key, "InstallDate")),
display_icon: str_value(&key, "DisplayIcon"),
});
}
}
@ -359,3 +424,488 @@ impl Platform for Windows {
TrashTarget::RecycleBin
}
}
// ---------------------------------------------------------------------------
// Static component facts for the overview spec panel: the BIOS HAL key, raw
// SMBIOS via `GetSystemFirmwareTable`, the storage stack through
// `IOCTL_STORAGE_QUERY_PROPERTY` and the display class registry. Native calls
// only — no spawned `wmic`/PowerShell helpers, which are deprecated outright.
pub(crate) fn hardware_info() -> crate::HardwareInfo {
let mut system = System::new();
system.refresh_cpu_list(sysinfo::CpuRefreshKind::everything());
let mut info = crate::HardwareInfo {
board: baseboard_name(),
cpu_model: system
.cpus()
.first()
.map(|cpu| cpu.brand().trim().to_string())
.unwrap_or_default(),
..Default::default()
};
info.memory_sticks = smbios_memory();
if let Some((vendor, model, bus, size)) = system_disk_identity() {
info.disk_vendor = vendor;
info.disk_model = model;
info.disk_bus = bus;
info.disk_size_bytes = size;
}
if let Some((vendor, model, vram)) = best_gpu() {
info.gpu_vendor = vendor;
info.gpu_model = model;
info.gpu_vram_bytes = vram;
}
info
}
/// Placeholder strings OEM firmware leaves behind instead of real names.
fn is_placeholder(text: &str) -> bool {
let lower = text.trim().to_lowercase();
lower.is_empty()
|| lower.contains("default string")
|| lower.contains("system product name")
|| lower.contains("system manufacturer")
|| lower.contains("base board")
|| lower.contains("to be filled by o.e.m.")
}
fn baseboard_name() -> String {
let Ok(key) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(BIOS_KEY, KEY_READ)
else {
return String::new();
};
[
str_value(&key, "BaseBoardProduct"),
str_value(&key, "SystemProductName"),
]
.into_iter()
.flatten()
.find(|text| !is_placeholder(text))
.unwrap_or_default()
}
/// Type-17 (Memory Device) records from the raw SMBIOS blob: brand, size and
/// running speed per stick. `RSMB` lives in the SystemInformation provider.
fn smbios_memory() -> Vec<crate::MemoryStick> {
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<u16> = 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::<StoragePropertyQuery>() 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<u16> = 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::<u64, _>("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"
);
}
}

View File

@ -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<PathBuf> {
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();

View File

@ -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"] }

View File

@ -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<f32>,
pub uptime_secs: u64,
pub processes: usize,
pub top_processes: Vec<ProcessSample>,
@ -58,6 +60,9 @@ pub struct MemoryStats {
pub total: Bytes,
pub used: Bytes,
pub available: Bytes,
/// RAM the machine ships with. `total` is what the OS may use after
/// firmware/graphics carve-outs; `installed - total` is that carve-out.
pub installed: Bytes,
pub swap_total: Bytes,
pub swap_used: Bytes,
/// macOS keeps wired/compressed pages out of `used`; expose them when known.
@ -73,6 +78,11 @@ impl MemoryStats {
self.used.percent_of(self.total)
}
}
/// Physical memory the firmware or the integrated GPU holds back from the OS.
pub fn hardware_reserved(&self) -> Bytes {
Bytes(self.installed.0.saturating_sub(self.total.0))
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@ -243,6 +253,15 @@ impl Sampler {
}
pub fn refresh(&mut self) -> SystemSnapshot {
self.refresh_with(true)
}
/// `want_processes=false` is the widget-grade light refresh: it skips the
/// per-pid CPU/memory walk (hundreds of Get-ProcessTimes calls on
/// Windows) and the top-process sort, keeping only a cheap pid sweep for
/// the process count. The always-on desktop widget pays this on every
/// beat; only 实时监控 asks for the full table.
pub fn refresh_with(&mut self, want_processes: bool) -> SystemSnapshot {
let elapsed = self.last.elapsed().max(Duration::from_millis(80));
self.last = Instant::now();
@ -250,11 +269,19 @@ impl Sampler {
.refresh_cpu_specifics(sysinfo::CpuRefreshKind::nothing().with_cpu_usage());
self.system
.refresh_memory_specifics(sysinfo::MemoryRefreshKind::nothing().with_ram().with_swap());
self.system.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::nothing().with_cpu().with_memory(),
);
if want_processes {
self.system.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::nothing().with_cpu().with_memory(),
);
} else {
self.system.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::nothing(),
);
}
self.networks.refresh(true);
self.disks
.refresh_specifics(true, DiskRefreshKind::nothing().with_io_usage());
@ -264,7 +291,11 @@ impl Sampler {
let memory = memory_stats(&self.system);
let network = net_rates(&self.networks, seconds);
let disk = disk_rates(&self.disks, seconds);
let top_processes = top_processes(&self.system, 12);
let top_processes = if want_processes {
top_processes(&self.system, 12)
} else {
Vec::new()
};
let mut snapshot = SystemSnapshot {
taken_at_ms: now_ms(),
@ -272,6 +303,10 @@ impl Sampler {
memory,
network,
disk,
// No cheap, dependency-free GPU busy counter exists across our
// targets (Windows needs PDH, macOS IOKit); the widget renders
// None as an idle ring, matching fnOS on headless machines.
gpu_usage: None,
uptime_secs: System::uptime(),
processes: self.system.processes().len(),
top_processes,
@ -430,24 +465,39 @@ pub struct AppUsage {
}
fn cpu_stats(system: &System) -> CpuStats {
let all = system.cpus();
let per_core: Vec<f32> = all
// sysinfo ≥ 0.34 keeps the aggregate out of `cpus()`: every entry is one
// logical core, and the machine-wide number lives in `global_cpu_usage()`.
let cores = system.cpus();
let per_core: Vec<f32> = cores
.iter()
.map(|cpu| cpu.cpu_usage().clamp(0.0, 100.0))
.collect();
let load = System::load_average();
let first = all.first();
let brand = first
let brand = cores
.first()
.map(|cpu| cpu.brand().trim().to_string())
.unwrap_or_else(|| std::env::consts::ARCH.to_string());
let base_frequency_ghz = first
let base_frequency_ghz = cores
.first()
.map(|cpu| cpu.frequency() as f64 / 1_000.0)
.unwrap_or(0.0);
// sysinfo keeps the aggregate independently of the per-core list. Reading
// `cpus()[0]` as the total also dropped one core from every count.
let total = system.global_cpu_usage().clamp(0.0, 100.0);
let logical_cores = per_core.len().max(1);
let physical = detect_physical_cores().unwrap_or_else(|| logical_cores.div_ceil(2));
// sysinfo can miss a logical core on some Windows boards; the thread
// count is the number the OS itself schedules against.
let scheduled = std::thread::available_parallelism()
.map(|count| count.get())
.unwrap_or(0);
let logical_cores = per_core.len().max(scheduled).max(1);
let per_core = if per_core.len() < logical_cores && !per_core.is_empty() {
let mean = total;
let mut padded = per_core;
padded.resize(logical_cores, mean);
padded
} else {
per_core
};
let physical = System::physical_core_count().or_else(detect_physical_cores);
let physical = physical.unwrap_or_else(|| logical_cores.div_ceil(2));
CpuStats {
total,
per_core,
@ -519,8 +569,11 @@ fn sysctl_u64(name: &str) -> Option<u64> {
}
fn memory_stats(system: &System) -> MemoryStats {
let total = Bytes(system.total_memory());
let installed = installed_memory().max(total);
let mut stats = MemoryStats {
total: Bytes(system.total_memory()),
installed,
total,
used: Bytes(system.used_memory()),
available: Bytes(system.available_memory()),
swap_total: Bytes(system.total_swap()),
@ -535,6 +588,55 @@ fn memory_stats(system: &System) -> MemoryStats {
stats
}
/// RAM the machine physically ships with. Windows reports this *including*
/// what the firmware and the integrated GPU carve out of `total_memory()`;
/// macOS reads the same number from sysctl. Unknown platforms fall back to
/// the usable total so the installed−reserved split degrades to zero.
fn installed_memory() -> Bytes {
#[cfg(target_os = "windows")]
{
let mut kb: u64 = 0;
// SAFETY: plain out-parameter call; the API only writes the u64.
let ok = unsafe {
windows_sys::Win32::System::SystemInformation::GetPhysicallyInstalledSystemMemory(
&mut kb,
)
};
if ok == 0 {
Bytes(0)
} else {
Bytes(kb.saturating_mul(1024))
}
}
#[cfg(target_os = "macos")]
{
sysctl_u64("hw.memsize").map(Bytes).unwrap_or_default()
}
#[cfg(target_os = "linux")]
{
if let Ok(text) = std::fs::read_to_string("/proc/meminfo") {
for line in text.lines() {
if let Some(rest) = line.strip_prefix("MemTotal:") {
if let Some(kb) = rest
.trim()
.trim_end_matches("kB")
.trim()
.parse::<u64>()
.ok()
{
return Bytes(kb * 1024);
}
}
}
}
Bytes(0)
}
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
{
Bytes(0)
}
}
/// `vm_stat` gives compressor/wired sizes that sysinfo folds away. Parsed
/// lazily and cheaply (one subprocess every few seconds at most).
fn vm_stat_details() -> Option<(Bytes, Bytes)> {
@ -857,6 +959,24 @@ mod tests {
assert!(!apps.is_empty());
}
/// The widget-grade light refresh: every meter the desktop panel draws
/// still moves, but the per-process table stays empty (that walk is the
/// expensive part of a refresh on Windows).
#[test]
fn the_light_refresh_keeps_the_meters_and_drops_the_table() {
let mut sampler = Sampler::new();
std::thread::sleep(Duration::from_millis(220));
let snapshot = sampler.refresh_with(false);
assert_eq!(snapshot.cpu.per_core.len(), snapshot.cpu.logical_cores);
assert!(snapshot.memory.total.as_u64() > 0);
assert!(snapshot.processes > 0);
assert!(snapshot.top_processes.is_empty());
// A light beat must not poison the full one: the next full refresh
// still walks processes and produces a ranking.
let full = sampler.refresh_with(true);
assert!(!full.top_processes.is_empty() || full.processes == 0);
}
#[test]
fn percentages_never_exceed_one_hundred() {
let stats = MemoryStats {

View File

@ -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<PathBuf> {
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<CleanupItem>) {
@ -2601,6 +2610,7 @@ mod tests {
has_sibling_install: false,
publisher: None,
installed_ms: None,
display_icon: None,
};
let items = vec![
CleanupItem::new(
@ -2625,7 +2635,9 @@ mod tests {
#[test]
fn approving_an_uninstall_really_uninstalls() {
isolate_state();
let dir = scratch("uninstall");
let Some(dir) = scratch("uninstall") else {
return;
};
let (info, items) = fake_app(&dir);
let bundle = info.path.clone();
let prefs = items[1].path.clone();
@ -2695,6 +2707,7 @@ mod tests {
has_sibling_install: false,
publisher: None,
installed_ms: None,
display_icon: None,
}];
app.uninstall.filter = "Squid".into();
assert_eq!(app.uninstall.visible().len(), 1);
@ -2714,7 +2727,7 @@ mod tests {
#[test]
fn approving_a_cleaning_dialog_carries_the_items() {
isolate_state();
let dir = scratch("clean");
let Some(dir) = scratch("clean") else { return };
let file = dir.join("junk.bin");
std::fs::write(&file, vec![3u8; 2048]).expect("junk");
@ -2837,12 +2850,12 @@ mod tests {
}
}
fn idle_node(tag: &str) -> Node {
let dir = scratch(tag);
fn idle_node(tag: &str) -> Option<Node> {
let dir = scratch(tag)?;
let node = analyze::explore(&dir, 0, 8, &CancelToken::new(), &Progress::new())
.expect("measure an empty folder");
let _ = std::fs::remove_dir_all(&dir);
node
Some(node)
}
/// A disk map of a home folder takes tens of seconds. It used to be "a job"
@ -2886,7 +2899,7 @@ mod tests {
fn a_disk_scan_leaves_the_other_panels_usable() {
isolate_state();
let mut app = App::new().expect("app");
let node = idle_node("map");
let Some(node) = idle_node("map") else { return };
let (handle, _progress) =
crate::job::spawn("storage", move |_engine, _progress, _cancel| {
std::thread::sleep(Duration::from_secs(30));
@ -2925,7 +2938,7 @@ mod tests {
#[test]
fn the_map_refresh_after_an_uninstall_does_not_lock_the_next_one() {
isolate_state();
let dir = scratch("chain");
let Some(dir) = scratch("chain") else { return };
let (first, first_items) = fake_app(&dir);
let second_dir = dir.join("second");
std::fs::create_dir_all(&second_dir).expect("second folder");
@ -3061,8 +3074,12 @@ mod tests {
let mut app = App::new().expect("app");
app.menu = false;
app.panel = Panel::Storage;
let root = idle_node("up-root");
let mut child = idle_node("up-child");
let Some(root) = idle_node("up-root") else {
return;
};
let Some(mut child) = idle_node("up-child") else {
return;
};
child.path = root.path.join("Library");
app.storage.stack = vec![root, child];
@ -3122,7 +3139,9 @@ mod tests {
let mut app = App::new().expect("app");
app.menu = false;
app.panel = Panel::Uninstall;
let dir = scratch("esc-plan");
let Some(dir) = scratch("esc-plan") else {
return;
};
let (info, items) = fake_app(&dir);
app.uninstall.set_plan(UninstallPlan {
app: info,
@ -3164,8 +3183,12 @@ mod tests {
let mut app = App::new().expect("app");
app.menu = false;
app.panel = Panel::Storage;
let root = idle_node("back-root");
let mut child = idle_node("back-child");
let Some(root) = idle_node("back-root") else {
return;
};
let Some(mut child) = idle_node("back-child") else {
return;
};
child.path = root.path.join("Library");
app.storage.stack = vec![root, child];
app.storage.show_files = true;
@ -3231,7 +3254,10 @@ mod tests {
let mut app = App::new().expect("app");
app.menu = false;
app.panel = Panel::Storage;
app.storage.stack = vec![idle_node("abandon-files")];
let Some(node) = idle_node("abandon-files") else {
return;
};
app.storage.stack = vec![node];
app.storage.show_files = true;
let (handle, progress) = crate::job::spawn("files", |_engine, _progress, _cancel| {
std::thread::sleep(Duration::from_millis(150));
@ -3251,13 +3277,17 @@ mod tests {
let mut app = App::new().expect("app");
app.menu = false;
app.panel = Panel::Storage;
let here = idle_node("abandon-drill");
let Some(here) = idle_node("abandon-drill") else {
return;
};
let away = here.path.join("Library");
app.storage.stack = vec![here];
let expected = app.storage.stack[0].path.clone();
let (handle, progress) = crate::job::spawn("storage", move |_, _, _| {
std::thread::sleep(Duration::from_millis(150));
let mut node = idle_node("abandon-drill-landed");
// The outer idle_node above already proved scratch writes work
// for this process, so unwrap is safe here.
let mut node = idle_node("abandon-drill-landed").expect("scratch dir");
node.path = away;
Ok(node)
});
@ -3283,7 +3313,9 @@ mod tests {
isolate_state();
let mut app = App::new().expect("app");
app.menu = false;
let sentinel = idle_node("esc-walk");
let Some(sentinel) = idle_node("esc-walk") else {
return;
};
let (handle, progress) = crate::job::spawn("storage", move |_engine, _progress, cancel| {
std::thread::sleep(Duration::from_millis(250));
let mut node = sentinel;
@ -3327,7 +3359,7 @@ mod tests {
fn a_finished_job_never_leaves_its_gauge_on_screen() {
isolate_state();
let mut app = App::new().expect("app");
let node = idle_node("bar");
let Some(node) = idle_node("bar") else { return };
let (walk, walk_progress) =
crate::job::spawn("storage", move |_engine, _progress, _cancel| {
std::thread::sleep(Duration::from_secs(30));
@ -3481,7 +3513,7 @@ mod tests {
#[test]
fn a_finished_cleanup_scans_itself_again() {
isolate_state();
let dir = scratch("rescan");
let Some(dir) = scratch("rescan") else { return };
let file = dir.join("junk.bin");
std::fs::write(&file, vec![7u8; 4096]).expect("junk");
@ -3711,7 +3743,9 @@ mod tests {
#[test]
fn x_is_still_the_delete_key_on_a_list_of_files() {
isolate_state();
let dir = scratch("x-still-deletes");
let Some(dir) = scratch("x-still-deletes") else {
return;
};
let (info, items) = fake_app(&dir);
let mut app = App::new().expect("app");
app.delete_mode = DeleteMode::Permanent;

View File

@ -134,6 +134,7 @@ impl Strings {
C::ProjectArtifacts => "构建产物",
C::LanguagePacks => "多余语言包",
C::Leftovers => "卸载残留",
C::UpdateInstallers => "升级安装包",
C::Trash => self.bin(),
},
})

View File

@ -1404,6 +1404,7 @@ fn draw_stats(frame: &mut Frame, area: Rect, app: &App) {
100.0,
);
let mem_ratio = snapshot.memory.percent_used() as f64 / 100.0;
let mem_installed = snapshot.memory.installed.max(snapshot.memory.total);
meter(
frame,
top[1],
@ -1411,8 +1412,8 @@ fn draw_stats(frame: &mut Frame, area: Rect, app: &App) {
mem_ratio,
&format!(
"{}/{}",
snapshot.memory.used.human(),
snapshot.memory.total.human()
snapshot.memory.used.human_binary(),
mem_installed.human_binary()
),
&memory,
100.0,
@ -2052,6 +2053,7 @@ mod tests {
has_sibling_install: false,
publisher: None,
installed_ms: None,
display_icon: None,
},
// Sorted the way `build_plan` sorts: biggest first, so the bundle
// is *not* the first item here.

View File

@ -49,25 +49,25 @@ cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
| Daily cleanup | Runs the normal cleanup rule set, groups results by category, supports per-item and per-category selection, Trash or permanent deletion, then offers undo through History |
| Uninstall apps | Reads installed apps, builds an app-specific removal plan, shows leftover paths and warnings, then uninstalls selected items |
| Deep Clean | Searches chosen project roots for regenerable build artefacts with Git and file-age protections |
| Permissions (Windows) | Startup entries from Run keys, startup folders and scheduled tasks; shell context-menu handlers; popup-window rules and the popup watcher |
| Security | XProtect / Defender status, scan coverage, findings by confidence, quarantine and restore, recent security activity |
| Startup items | LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; disable and re-enable the ones the current user owns |
| Storage | Measures a chosen folder, exposes the largest children, drills down, and finds the largest files |
| Real-time monitor | Two tabs. **Performance**: live CPU, memory, network, disk, battery, volume and process data. **Processes**: the whole process table with signature and startup-item columns, and process termination after confirmation |
| Real-time monitor | Two tabs. **Performance**: live CPU, memory, network, disk, battery, volume and process data, plus the desktop-widget switch. **Processes**: the whole process table with signature and startup-item columns, and process termination after confirmation |
| Desktop widget | A borderless desktop-layer monitor opened from Real-time monitor, with status rings, network and disk curves, storage bars, and all settings in a dropdown at the top of the widget |
| History | Lists cleanup sessions, shows the ledger, restores files that are still in Trash/Recycle Bin, and opens the bin |
| Settings | Chinese/English language selection that defaults to the system language, launch at login, the security section (scan schedule, notifications, auto-quarantine, rule-pack updates, scan exclusions), deletion mode, history retention, protected paths, local file locations, and software updates |
`⌘1`–`⌘0` on macOS and `Ctrl+1`–`Ctrl+0` on Windows switch screens, in sidebar
order: `1` overview, `2` daily cleanup, `3` uninstall apps, `4` deep clean,
`5` storage, `6` real-time monitor, `7` security, `8` startup items,
`9` history, `0` settings.
In 0.1.6 `⌘7`/`⌘8` moved from History/Settings to Security/Startup items;
History and Settings are now `⌘9` and `⌘0`.
`⌘1`–`⌘8` on macOS and `Ctrl+1`–`Ctrl+9` on Windows switch screens, in sidebar
order. On Windows: `1` overview, `2` daily cleanup, `3` uninstall apps,
`4` deep clean, `5` permissions, `6` storage, `7` real-time monitor,
`8` security, `9` startup items. macOS omits the Windows-only Permissions
screen, so `5`–`8` shift up by one.
The sidebar groups these into **Maintenance** (overview, daily cleanup,
uninstall apps, deep clean), **Protection** (security, startup items) and
**Insights** (storage, real-time monitor), with History and Settings pinned at
the bottom.
uninstall apps, deep clean, and Permissions on Windows), **Protection**
(security, startup items) and **Insights** (storage, real-time monitor), with
History and Settings pinned at the bottom.
The two new screens reuse the interface vocabulary the older screens already
had rather than introducing a second one: `.panel` for a card, `.status-chip` for
@ -107,12 +107,53 @@ this page only reads what they report.
Squid keeps running after its main window is closed. The tray menu can reopen
the window, start a malware scan, and jump directly to Security, Startup items,
Daily cleanup, Uninstall apps or Deep Clean. One disabled row states the current
protection status — the count of unhandled confirmed findings, "not scanned yet"
before the first scan, and "scanning…" while one is running.
Daily cleanup, Uninstall apps, Deep Clean or the desktop widget. One disabled row
states the current protection status — the count of unhandled confirmed findings,
"not scanned yet" before the first scan, and "scanning…" while one is running.
The tray follows the active interface language. Use **Quit Squid** in the same
menu to stop the background process.
The tray mark is a transparent monochrome asset. macOS receives it with
`.icon_as_template(true)`, so the system draws it in the correct menu-bar colour
for light and dark appearances instead of pasting a coloured square onto the
bar. Windows and Linux keep the same silhouette in gray.
## Permissions (Windows)
The Permissions screen is a Windows-only destination and is hidden from the
macOS sidebar, where the Startup items screen already covers LaunchAgents,
LaunchDaemons and login items with the same safety rules. On Windows it lists:
- startup entries from `Run` keys, startup folders and scheduled tasks;
- shell context-menu handlers grouped by file, folder, desktop, drive and
all-object surfaces;
- popup windows with rules to block or allow them and a background watcher.
Every enable/disable action goes through the backend's inventory; the page never
submits a raw registry or filesystem path.
## Desktop widget
The desktop widget is switched on from Real-time monitor and is a separate Tauri
webview window labelled `widget`, not a WidgetKit extension. It shares the live
sampler with the Real-time monitor but polls at its own 2/5/10-second cadence and
pauses while hidden.
- The gear at the top of the widget opens a dropdown containing every setting:
panel switches, opacity, refresh rate, dock corner and fold memory.
- Up to four cards: status rings (CPU, memory, and GPU when the OS exposes a
busy counter), network throughput, disk I/O, and storage volumes.
- The window is borderless, transparent and resizable only by its content. It
docks to a chosen corner and remembers a manual drag position.
- On macOS it uses `BelowNormal` window level, appears on every Space, and is
non-focusable with `accept_first_mouse`, so it sits with the desktop and never
takes keyboard focus from the app you are using.
- On Windows it is parked with `SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)` for
the same desktop-layer behaviour.
- Opacity is capped to 90–100% so text stays readable over busy wallpapers.
The master switch and the tray item share one state; settings persist in
`widget.json` beside `manage.json`.
**Settings → Startup** registers the app for the current user only. macOS
uses a user LaunchAgent, Windows uses the current-user Run key, and Linux uses
an XDG autostart desktop entry. Enabling or disabling launch at login does not

View File

@ -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/<ver>/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\<u>\
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:

View File

@ -1,7 +1,7 @@
{
"name": "squid-desktop",
"private": true,
"version": "0.1.7",
"version": "0.1.9",
"type": "module",
"scripts": {
"dev": "vite --port 1420 --strictPort",

15
src-tauri/Cargo.lock generated
View File

@ -4760,7 +4760,7 @@ dependencies = [
[[package]]
name = "squid-core"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"anyhow",
"chrono",
@ -4779,7 +4779,7 @@ dependencies = [
[[package]]
name = "squid-desktop"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"base64 0.22.1",
"chrono",
@ -4806,7 +4806,7 @@ dependencies = [
[[package]]
name = "squid-engine"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"anyhow",
"chrono",
@ -4826,7 +4826,7 @@ dependencies = [
[[package]]
name = "squid-guard"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"chrono",
"hex",
@ -4842,7 +4842,7 @@ dependencies = [
[[package]]
name = "squid-platform"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"dirs 6.0.0",
"file_icon_provider",
@ -4862,7 +4862,7 @@ dependencies = [
[[package]]
name = "squid-rules"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"globset",
"serde",
@ -4874,7 +4874,7 @@ dependencies = [
[[package]]
name = "squid-stats"
version = "0.1.7"
version = "0.1.9"
dependencies = [
"chrono",
"libc",
@ -4882,6 +4882,7 @@ dependencies = [
"squid-core",
"squid-platform",
"sysinfo",
"windows-sys 0.59.0",
]
[[package]]

View File

@ -1,6 +1,6 @@
[package]
name = "squid-desktop"
version = "0.1.7"
version = "0.1.9"
description = "Squid — a CleanMyMac-inspired cleaner, uninstaller and system monitor."
authors = ["squid contributors"]
edition = "2021"

View File

@ -1,11 +1,16 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Default permissions for the Squid main window.",
"windows": ["main"],
"description": "Default permissions for the Squid main and widget windows.",
"windows": ["main", "widget"],
"permissions": [
"core:default",
"core:window:allow-start-dragging",
"core:window:allow-hide",
"core:window:allow-show",
"core:window:allow-set-size",
"core:window:allow-set-focus",
"core:window:allow-is-visible",
"dialog:default",
"opener:default",
"notification:default"

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

File diff suppressed because it is too large Load Diff

View File

@ -34,6 +34,9 @@ pub struct AppState {
apps: Mutex<Vec<AppInfo>>,
app_icons: Mutex<HashMap<String, Option<String>>>,
sampler: Mutex<Sampler>,
/// Last light snapshot, so the widget window and the main window polling
/// a beat apart share one refresh instead of paying for two.
snapshot_cache: Mutex<Option<(Instant, squid_stats::SystemSnapshot)>>,
}
impl AppState {
@ -354,6 +357,8 @@ pub struct BootstrapView {
os_name: String,
os_version: String,
hardware: String,
/// Static component facts (board/RAM/disk/GPU) for the overview panel.
hardware_info: squid_platform::HardwareInfo,
arch: String,
device: String,
language: String,
@ -377,6 +382,7 @@ pub fn bootstrap() -> BootstrapView {
os_name: engine.platform().display_name(),
os_version: engine.platform().os_version(),
hardware: engine.platform().hardware_model(),
hardware_info: squid_platform::hardware_info(),
arch: std::env::consts::ARCH.into(),
device: match engine.platform().device() {
squid_platform::Device::Mac => "mac".into(),
@ -825,10 +831,36 @@ pub async fn storage_largest_files(
}
#[tauri::command]
pub fn system_snapshot(app: AppHandle) -> Result<SystemSnapshot, String> {
pub fn system_snapshot(app: AppHandle, full: Option<bool>) -> Result<SystemSnapshot, String> {
// `full` costs a per-pid CPU/memory walk of every process on the machine
// (hundreds of syscalls) plus the top-12 sort — the 实时监控 page needs
// it; the desktop widget, overview tiles and every background poll pass
// false and ride the light refresh. Light answers are cached for two
// seconds so windows polling in step pay for one refresh, not several.
let state = app.state::<AppState>();
let full = full.unwrap_or(false);
// Check and fill the cache under the sampler lock: two windows polling a
// beat apart then share one refresh only if the second can not slip in
// between the first cache miss and the sampler call.
let mut sampler = AppState::lock(&state.sampler)?;
Ok(sampler.refresh())
if !full {
if let Ok(cache) = AppState::lock(&state.snapshot_cache) {
if let Some((at, snapshot)) = cache.as_ref() {
if at.elapsed() < Duration::from_secs(2) {
return Ok(snapshot.clone());
}
}
}
}
let snapshot = if full {
sampler.refresh()
} else {
sampler.refresh_with(false)
};
if let Ok(mut cache) = AppState::lock(&state.snapshot_cache) {
*cache = Some((Instant::now(), snapshot.clone()));
}
Ok(snapshot)
}
#[tauri::command]

View File

@ -1,11 +1,13 @@
mod app;
mod autostart;
mod manage;
pub mod notifications;
mod permissions;
mod process;
pub mod security;
mod startup;
mod update;
mod widget;
use security::ScanTarget;
use squid_core::{Locale, Settings};
@ -23,6 +25,8 @@ pub(crate) fn show_main_window(app: &AppHandle) {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
// The page stops sampling while parked in the tray; wake it up.
let _ = app.emit("squid://visible", true);
}
}
@ -104,6 +108,14 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result<Menu<tauri::Wry>>
)?;
let first_separator = PredefinedMenuItem::separator(app)?;
let last_separator = PredefinedMenuItem::separator(app)?;
// Flips the widget master switch; state is shown on the Real-time monitor.
let widget_toggle = MenuItem::with_id(
app,
"widget",
tray_text(locale, "Show / hide desktop widget", "显示/隐藏桌面小工具"),
true,
None::<&str>,
)?;
Menu::with_items(
app,
&[
@ -115,6 +127,7 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result<Menu<tauri::Wry>>
&cleanup,
&apps,
&purge,
&widget_toggle,
&last_separator,
&quit,
],
@ -164,13 +177,13 @@ fn tray_tooltip(app: &AppHandle, locale: Locale) -> String {
fn create_tray(app: &AppHandle, locale: Locale) -> tauri::Result<()> {
let menu = tray_menu(app, locale)?;
let tooltip = tray_tooltip(app, locale);
let icon = app
.default_window_icon()
.cloned()
.ok_or_else(|| tauri::Error::AssetNotFound("default window icon".into()))?;
// A transparent monochrome mark: macOS uses it as a template image so the
// system tints it for light/dark menu bars; other platforms keep the gray.
let icon = tauri::image::Image::from_bytes(include_bytes!("../icons/tray-template.png"))?;
TrayIconBuilder::with_id("squid-tray")
.icon(icon)
.icon_as_template(cfg!(target_os = "macos"))
.tooltip(tooltip)
.menu(&menu)
.show_menu_on_left_click(true)
@ -181,6 +194,11 @@ fn create_tray(app: &AppHandle, locale: Locale) -> tauri::Result<()> {
"cleanup" => navigate_to(app, "cleanup"),
"applications" => navigate_to(app, "applications"),
"purge" => navigate_to(app, "purge"),
"widget" => {
if let Err(error) = widget::toggle_from_tray(app) {
eprintln!("widget toggle failed: {error}");
}
}
"quit" => app.exit(0),
_ => {}
})
@ -208,14 +226,22 @@ pub fn run() {
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_notification::init())
.on_window_event(|window, event| {
if window.label() != "main" {
return;
}
if let WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close();
let _ = window.hide();
// A hidden window must not keep sampling the whole machine;
// the page pauses its polling on this signal.
let _ = window.emit("squid://visible", false);
}
})
.manage(app::AppState::default())
.manage(update::UpdateState::default())
.manage(security::SecurityState::default())
.manage(manage::ManageState::default())
.manage(widget::WidgetState::default())
.invoke_handler(tauri::generate_handler![
app::bootstrap,
app::cancel_job,
@ -242,6 +268,18 @@ pub fn run() {
app::open_trash,
permissions::permission_status,
permissions::open_full_disk_access_settings,
manage::manage_scan,
manage::managed_startup_set_enabled,
manage::extension_set_registered,
manage::popup_list,
manage::popup_close,
manage::popup_add_rule,
manage::popup_rule_update,
manage::popup_rule_remove,
manage::popup_watcher_set,
widget::widget_get,
widget::widget_set,
widget::widget_hide,
update::update_check,
update::update_status,
update::update_download,
@ -273,6 +311,8 @@ pub fn run() {
create_tray(app.handle(), Locale::detect(&settings))?;
update::spawn_startup_check(app.handle());
security::spawn_scheduler(app.handle(), &settings);
manage::spawn_watcher(app.handle().clone());
widget::spawn_startup(app.handle());
Ok(())
})
.build(tauri::generate_context!())

View File

@ -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<String>,
}
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<PopupRule>,
/// Handlers the user removed; kept so the list can offer "restore".
removed_extensions: Vec<ShellExtEntry>,
}
pub struct ManageState {
prefs: Mutex<ManagePrefs>,
startup: Mutex<Vec<StartupEntry>>,
extensions: Mutex<Vec<ShellExtEntry>>,
}
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<T>(value: &Mutex<T>) -> Result<MutexGuard<'_, T>, 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<String>,
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<String>,
module: Option<String>,
/// Publisher of the owning dll — 电脑管家's 创建者 column.
publisher: Option<String>,
/// `data:image/png;base64,…` of the owning module's icon.
icon: Option<String>,
/// 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<String>,
/// `data:image/png;base64,…` of the owning process's icon.
icon: Option<String>,
}
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<PopupRule>,
windows: Vec<PopupView>,
startup: Vec<StartupView>,
extensions: Vec<ExtensionView>,
startup_count: usize,
startup_enabled_count: usize,
}
#[tauri::command]
pub async fn manage_scan(app: AppHandle) -> Result<ManageView, String> {
let manage = app.state::<ManageState>();
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<StartupView> = 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<ExtensionView> =
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<String, Option<String>> = Default::default();
for rule in &mut rules {
let icon = rule_icons
.entry(rule.exe.clone())
.or_insert_with(|| permissions::exe_icon(&rule.exe).map(|png| png_data_url(&png)))
.clone();
rule.icon = icon;
}
*ManageState::lock(&manage.startup)? = startup;
*ManageState::lock(&manage.extensions)? = extensions;
let startup_enabled_count = startup_view.iter().filter(|entry| entry.enabled).count();
let startup_count = startup_view.len();
Ok(ManageView {
watcher_enabled,
interval_ms,
rules,
windows: windows.iter().map(PopupView::from).collect(),
startup: startup_view,
extensions: extension_view,
startup_count,
startup_enabled_count,
})
}
/// Flip one startup entry (registry / startup folder / scheduled task), then
/// rescan so a partially-applied toggle can never desync the UI.
#[tauri::command]
pub async fn managed_startup_set_enabled(
app: AppHandle,
id: String,
enabled: bool,
) -> Result<usize, String> {
let manage = app.state::<ManageState>();
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::<ManageState>();
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<PopupView> {
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::<ManageState>();
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<bool>,
reset_count: Option<bool>,
) -> Result<(), String> {
let manage = app.state::<ManageState>();
{
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::<ManageState>();
{
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>();
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::<ManageState>() {
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<ClosedEvent> = 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);
});
}

View File

@ -888,7 +888,15 @@ pub async fn security_rollback_rules() -> Result<IntelStatus, String> {
pub(crate) fn update_pack() -> Result<IntelStatus, String> {
let manifest_url = crate::update::intel_manifest_url()
.ok_or_else(|| "No rule-pack feed is configured for this build.".to_string())?;
let text = crate::update::fetch_text(&manifest_url)?;
let text = crate::update::fetch_text(&manifest_url).map_err(|error| {
if error.contains("404") {
"No rule pack has been published for this release yet. Squid looks for \
squid-intel.json next to squid-update.json on the releases branch."
.to_string()
} else {
error
}
})?;
let signature = crate::update::intel_manifest_signature()?;
let key = crate::update::intel_public_key()?;
// Two answers, not one. A build that was given an intel key must verify

View File

@ -725,6 +725,7 @@ pub async fn update_download(app: AppHandle) -> Result<UpdateStatus, String> {
.map_err(|error| format!("Update download failed: {error}"))?
}
#[cfg(target_os = "macos")]
fn bundle_path(exe: &Path) -> Option<PathBuf> {
let contents = exe.parent()?.parent()?;
let bundle = contents.parent()?;
@ -831,7 +832,9 @@ fn spawn_handoff(name: &str, script: &str) -> Result<(), String> {
#[cfg(target_os = "windows")]
let mut command = crate::process::command("cmd.exe");
#[cfg(target_os = "windows")]
command.args(["/D", "/C", &path.to_string_lossy().to_string()]);
let script = path.to_string_lossy();
#[cfg(target_os = "windows")]
command.args(["/D", "/C", &*script]);
#[cfg(not(target_os = "windows"))]
let mut command = crate::process::command("/bin/sh");
#[cfg(not(target_os = "windows"))]
@ -850,6 +853,7 @@ fn quit_for_update(app: &AppHandle) {
});
}
#[cfg(not(target_os = "windows"))]
fn open_artifact(path: &Path) -> Result<(), String> {
#[cfg(target_os = "macos")]
{
@ -914,7 +918,6 @@ pub async fn update_install(app: AppHandle) -> Result<String, String> {
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")))]
{

View File

@ -0,0 +1,479 @@
//! Desktop widget (桌面小工具): a borderless desktop-layer window showing
//! live system stats, styled after the fnOS desktop monitor. It sits above
//! the wallpaper and icons but below ordinary app windows, and lives next to
//! the tray, so it keeps running while the main window is hidden.
//!
//! Settings persist in `widget.json` beside `manage.json`; the widget window
//! and the main window each load this module's commands, and every change is
//! broadcast on `widget://settings` so both views stay in sync.
use serde::{Deserialize, Serialize};
use squid_core::{Locale, Settings};
use std::fs;
use std::path::PathBuf;
use std::sync::{Mutex, MutexGuard};
use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder};
pub const WIDGET_LABEL: &str = "widget";
/// `HWND_BOTTOM` + no-activate flags: the widget lives on the desktop layer —
/// above wallpaper and icons, below every ordinary app window.
#[cfg(windows)]
mod desktop_layer {
#[link(name = "user32")]
extern "system" {
fn SetWindowPos(
hwnd: *mut core::ffi::c_void,
insert_after: *mut core::ffi::c_void,
x: i32,
y: i32,
cx: i32,
cy: i32,
flags: u32,
) -> i32;
}
const HWND_BOTTOM: *mut core::ffi::c_void = 1usize as *mut core::ffi::c_void;
const SWP_NOMOVE: u32 = 0x0002;
const SWP_NOSIZE: u32 = 0x0001;
const SWP_NOACTIVATE: u32 = 0x0010;
pub fn lower(hwnd: *mut core::ffi::c_void) {
// SAFETY: hwnd comes from Tauri's own window handle; SetWindowPos with
// NOMOVE|NOSIZE|NOACTIVATE only edits the z-order.
unsafe {
SetWindowPos(
hwnd,
HWND_BOTTOM,
0,
0,
0,
0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
);
}
}
}
/// Park the widget at the bottom of the window stack (desktop layer).
/// macOS/Linux keep plain floating behaviour for now (no equivalent need:
/// the widget story is Windows-first).
pub fn lower_window(app: &AppHandle) {
#[cfg(windows)]
{
let Some(window) = app.get_webview_window(WIDGET_LABEL) else {
return;
};
if let Ok(hwnd) = window.hwnd() {
desktop_layer::lower(hwnd.0.cast());
}
}
#[cfg(not(windows))]
{
let _ = app;
}
}
fn default_interval_ms() -> u64 {
2_000
}
fn default_corner() -> String {
"top-right".to_string()
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct WidgetPrefs {
/// Master switch: hides the window entirely when off.
pub enabled: bool,
pub panel_run: bool,
pub panel_cpu: bool,
pub panel_network: bool,
pub panel_disk: bool,
pub panel_storage: bool,
/// 90–100 (%): window opacity; at most 10% of the desktop may bleed
/// through so text stays readable over busy wallpapers.
pub opacity: u8,
/// Sampling cadence for the widget window.
pub interval_ms: u64,
/// `top-right` | `top-left` | `bottom-right` | `bottom-left`.
pub corner: String,
/// Remember the collapsed header-only state across restarts.
pub remember_collapsed: bool,
pub collapsed: bool,
/// Last user-dragged position; None re-docks to `corner`.
pub position: Option<(i32, i32)>,
}
impl Default for WidgetPrefs {
fn default() -> Self {
Self {
enabled: true,
panel_run: true,
panel_cpu: true,
panel_network: true,
panel_disk: true,
panel_storage: true,
opacity: 100,
interval_ms: default_interval_ms(),
corner: default_corner(),
remember_collapsed: true,
collapsed: false,
position: None,
}
}
}
pub struct WidgetState {
prefs: Mutex<WidgetPrefs>,
}
impl Default for WidgetState {
fn default() -> Self {
Self {
prefs: Mutex::new(load_prefs()),
}
}
}
impl WidgetState {
fn lock<T>(value: &Mutex<T>) -> Result<MutexGuard<'_, T>, 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::<WidgetPrefs>(&text).ok())
.unwrap_or_default();
// Migration: older builds allowed 60–100; the 10%-translucency cap now
// floors everything below 90 (including the old 92 default).
prefs.opacity = prefs.opacity.clamp(90, 100);
// 折叠记忆 off: always boot expanded (save_prefs already stops persisting
// the fold state, this covers configs written while it was on).
if !prefs.remember_collapsed {
prefs.collapsed = false;
}
prefs
}
fn save_prefs(state: &WidgetState) -> Result<(), String> {
let prefs = WidgetState::lock(&state.prefs)?.clone();
let path = prefs_path();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|error| error.to_string())?;
}
// 折叠记忆 off: the live fold state still applies this session, but the
// next launch always starts expanded.
let stored = WidgetPrefs {
collapsed: if prefs.remember_collapsed {
prefs.collapsed
} else {
false
},
..prefs
};
let text = serde_json::to_string_pretty(&stored).map_err(|error| error.to_string())?;
fs::write(path, text).map_err(|error| error.to_string())
}
/// Dock to a screen corner (widget width ~350px) or restore the remembered
/// drag position. Called on creation and whenever the corner changes. All
/// math is in physical pixels — the webview reports `outerPosition` there.
fn place_window(app: &AppHandle, prefs: &WidgetPrefs) {
let Some(window) = app.get_webview_window(WIDGET_LABEL) else {
return;
};
let Ok(Some(monitor)) = window
.current_monitor()
.or_else(|_| window.primary_monitor())
else {
return;
};
// Work area excludes the macOS menu bar and Dock, so the widget cannot
// park its header under the menu bar or behind the Dock.
let work = monitor.work_area();
let outer = window
.outer_size()
.map(|s| (s.width as i32, s.height as i32))
.unwrap_or((350, 620));
let margin = (16.0 * monitor.scale_factor()) as i32;
let min_x = work.position.x;
let min_y = work.position.y;
let max_x = (work.position.x + work.size.width as i32 - outer.0).max(min_x);
let max_y = (work.position.y + work.size.height as i32 - outer.1).max(min_y);
let pos = if let Some((x, y)) = prefs.position {
// Clamp into the monitor so an unplugged-secondary position can not
// hide the widget off-screen.
(x.clamp(min_x, max_x), y.clamp(min_y, max_y))
} else {
let x = match prefs.corner.as_str() {
"top-left" | "bottom-left" => min_x + margin,
_ => max_x - margin,
};
let y = match prefs.corner.as_str() {
"bottom-left" | "bottom-right" => max_y - margin,
_ => min_y + margin,
};
(x.clamp(min_x, max_x), y.clamp(min_y, max_y))
};
let _ = window.set_position(tauri::PhysicalPosition::new(pos.0, pos.1));
}
/// Bring the widget window into the state `prefs` describes (create/show/hide).
/// The window is deliberately *not* always-on-top: it is parked at the bottom
/// of the z-order (desktop layer), above wallpaper/icons but under every
/// ordinary app window, so it can never cover the user's work.
fn sync_window(app: &AppHandle, prefs: &WidgetPrefs) {
if !prefs.enabled {
if let Some(window) = app.get_webview_window(WIDGET_LABEL) {
let _ = window.hide();
}
return;
}
if app.get_webview_window(WIDGET_LABEL).is_some() {
if let Some(window) = app.get_webview_window(WIDGET_LABEL) {
let _ = window.show();
}
place_window(app, prefs);
lower_window(app);
return;
}
let builder = WebviewWindowBuilder::new(
app,
WIDGET_LABEL,
WebviewUrl::App("index.html?view=widget".into()),
)
.title("Squid 实时监控")
.inner_size(350.0, 640.0)
.resizable(false)
.decorations(false)
.transparent(true)
.always_on_top(false)
.skip_taskbar(true)
.focused(false)
.visible(false)
.shadow(false);
// macOS: BelowNormal keeps the widget under ordinary app windows, every
// Space keeps it beside the desktop, and a non-key window means clicking
// a card never pulls focus away from the app the user is working in.
// `accept_first_mouse` keeps the first click actionable anyway.
#[cfg(target_os = "macos")]
let builder = builder
.always_on_bottom(true)
.visible_on_all_workspaces(true)
.focusable(false)
.accept_first_mouse(true);
match builder.build() {
Ok(window) => {
let _ = window.set_ignore_cursor_events(false);
place_window(app, prefs);
let _ = window.show();
lower_window(app);
}
Err(error) => {
eprintln!("widget window failed to open: {error}");
}
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WidgetView {
prefs: WidgetPrefs,
language: &'static str,
}
#[tauri::command]
pub fn widget_get(app: AppHandle) -> WidgetView {
let (settings, _) = Settings::load();
WidgetView {
prefs: app.state::<WidgetState>().current(),
language: Locale::detect(&settings).code(),
}
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WidgetPatch {
pub enabled: Option<bool>,
pub panel_run: Option<bool>,
pub panel_cpu: Option<bool>,
pub panel_network: Option<bool>,
pub panel_disk: Option<bool>,
pub panel_storage: Option<bool>,
pub opacity: Option<u8>,
pub interval_ms: Option<u64>,
pub corner: Option<String>,
pub remember_collapsed: Option<bool>,
pub collapsed: Option<bool>,
pub position: Option<Option<(i32, i32)>>,
/// `position_changed` marks a drag-persist (no re-docking after set).
#[serde(default)]
pub keep_position: Option<bool>,
/// Re-run corner placement (used after the window auto-resizes and the
/// user has not dragged it anywhere).
#[serde(default)]
pub redock: Option<bool>,
}
#[tauri::command]
pub fn widget_set(app: AppHandle, patch: WidgetPatch) -> Result<WidgetPrefs, String> {
let state = app.state::<WidgetState>();
let (prefs, corner_changed) = {
let mut prefs = WidgetState::lock(&state.prefs)?;
if let Some(value) = patch.enabled {
prefs.enabled = value;
}
if let Some(value) = patch.panel_run {
prefs.panel_run = value;
}
if let Some(value) = patch.panel_cpu {
prefs.panel_cpu = value;
}
if let Some(value) = patch.panel_network {
prefs.panel_network = value;
}
if let Some(value) = patch.panel_disk {
prefs.panel_disk = value;
}
if let Some(value) = patch.panel_storage {
prefs.panel_storage = value;
}
if let Some(value) = patch.opacity {
// At most 10% translucent: anything more reads as "see-through"
// over busy wallpapers.
prefs.opacity = value.clamp(90, 100);
}
if let Some(value) = patch.interval_ms {
prefs.interval_ms = value.clamp(1_000, 10_000);
}
let corner_changed = patch.corner.is_some();
if let Some(value) = patch.corner {
if matches!(
value.as_str(),
"top-right" | "top-left" | "bottom-right" | "bottom-left"
) {
prefs.corner = value;
// Choosing a corner overrides any manual drag position.
prefs.position = None;
}
}
if let Some(value) = patch.remember_collapsed {
prefs.remember_collapsed = value;
}
if let Some(value) = patch.collapsed {
prefs.collapsed = value;
}
if let Some(value) = patch.position {
prefs.position = value;
}
(prefs.clone(), corner_changed)
};
save_prefs(&state)?;
let keep = patch.keep_position.unwrap_or(false);
let redock = patch.redock.unwrap_or(false);
if redock || (!keep && (corner_changed || patch.enabled == Some(true))) {
place_window(&app, &prefs);
}
sync_window(&app, &prefs);
if keep {
// The drag click raised the window; settle it back onto the desktop
// layer so it keeps covering nothing but the wallpaper.
lower_window(&app);
}
let _ = app.emit("widget://settings", &prefs);
Ok(prefs)
}
/// Hide the widget window (header button) without flipping the master switch:
/// a transient fold-away. Remembered only when 折叠记忆 is on.
#[tauri::command]
pub fn widget_hide(app: AppHandle) -> Result<(), String> {
if let Some(window) = app.get_webview_window(WIDGET_LABEL) {
window.hide().map_err(|error| error.to_string())
} else {
Ok(())
}
}
/// Create the window at startup when enabled; the main page can also open it
/// later through widget_set.
pub fn spawn_startup(app: &AppHandle) {
let prefs = app.state::<WidgetState>().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::<WidgetState>();
let target = !state.current().enabled;
widget_set(
app.clone(),
WidgetPatch {
enabled: Some(target),
..Default::default()
},
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::{WidgetPatch, WidgetPrefs};
#[test]
fn prefs_round_trip_uses_camel_case_keys() {
let prefs = WidgetPrefs {
opacity: 88,
corner: "bottom-left".into(),
position: Some((100, 200)),
..WidgetPrefs::default()
};
let text = serde_json::to_string(&prefs).unwrap();
// keys the frontend types.ts promises must appear serialized
for key in [
"\"panelRun\"",
"\"panelCpu\"",
"\"intervalMs\"",
"\"rememberCollapsed\"",
"\"collapsed\"",
] {
assert!(text.contains(key), "missing {key} in {text}");
}
let back: WidgetPrefs = serde_json::from_str(&text).unwrap();
assert_eq!(back.opacity, 88);
assert_eq!(back.corner, "bottom-left");
assert_eq!(back.position, Some((100, 200)));
}
#[test]
fn patch_accepts_sparse_frontend_payloads() {
let patch: WidgetPatch = serde_json::from_str(r#"{"opacity":92,"redock":true}"#).unwrap();
assert_eq!(patch.opacity, Some(92));
assert_eq!(patch.redock, Some(true));
assert!(patch.enabled.is_none());
assert!(patch.position.is_none());
}
#[test]
fn legacy_configs_without_new_fields_still_load() {
let prefs: WidgetPrefs = serde_json::from_str("{}").unwrap();
assert!(prefs.enabled);
assert!(prefs.panel_cpu);
assert_eq!(prefs.interval_ms, 2_000);
assert!(prefs.position.is_none());
}
}

View File

@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Squid",
"version": "0.1.7",
"version": "0.1.9",
"identifier": "app.nex.squid",
"mainBinaryName": "squid-desktop",
"build": {
@ -54,7 +54,8 @@
"windows": {
"nsis": {
"installMode": "currentUser",
"displayLanguageSelector": false
"displayLanguageSelector": false,
"template": "nsis/installer.nsi"
}
}
}

View File

@ -15,6 +15,7 @@ import {
} from "lucide-react";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { useAppsWorkspace } from "./hooks/useAppsWorkspace";
import { usePermissionsWorkspace } from "./hooks/usePermissionsWorkspace";
import { useScanWorkspace } from "./hooks/useScanWorkspace";
import { useSecurityWorkspace } from "./hooks/useSecurityWorkspace";
import { useStartupWorkspace } from "./hooks/useStartupWorkspace";
@ -38,6 +39,7 @@ import { ApplicationsPage } from "./pages/ApplicationsPage";
import { CleanupPage } from "./pages/CleanupPage";
import { HistoryPage } from "./pages/HistoryPage";
import { OverviewPage } from "./pages/OverviewPage";
import { PermissionsPage } from "./pages/PermissionsPage";
import { PurgePage } from "./pages/PurgePage";
import { SecurityPage } from "./pages/SecurityPage";
import { SettingsPage } from "./pages/SettingsPage";
@ -83,6 +85,12 @@ const NAV_GROUPS: {
labelZh: "深度清理",
icon: WandSparkles,
},
{
id: "permissions",
labelEn: "Permissions",
labelZh: "权限管理",
icon: ShieldCheck,
},
],
},
{
@ -113,11 +121,18 @@ const NAV_GROUPS: {
},
];
// Permissions manages Windows Run keys, shell extensions and popup rules; the
// macOS equivalent is the Startup page, which reads LaunchAgents and login items.
function navItemVisible(id: PageId, platform: string | undefined): boolean {
return id !== "permissions" || platform === "windows";
}
const PAGE_TITLES: Record<PageId, [string, string]> = {
overview: ["Overview", "概览"],
cleanup: ["Daily cleanup", "日常清理"],
applications: ["Uninstall apps", "应用卸载"],
purge: ["Deep Clean", "深度清理"],
permissions: ["Permissions", "权限管理"],
storage: ["Storage", "存储空间"],
system: ["Real-time monitor", "实时监控"],
security: ["Security", "安全"],
@ -177,11 +192,16 @@ export default function App() {
const [settings, setSettings] = useState<SettingsView | null>(null);
const [autoCheck, setAutoCheck] = useState(true);
const [setupOpen, setSetupOpen] = useState(false);
// The 托盘驻留 case: a hidden main window must stop sampling the machine.
const [windowVisible, setWindowVisible] = useState(true);
const cleanup = useScanWorkspace("cleanup");
const purge = useScanWorkspace("purge");
const apps = useAppsWorkspace();
const systemActive = page === "overview" || page === "system";
const system = useSystemSnapshot(systemActive);
const permissions = usePermissionsWorkspace(page === "permissions");
const systemActive = (page === "overview" || page === "system") && windowVisible;
// Only the 实时监控 top-process table needs the expensive per-pid walk;
// the overview tiles ride the light refresh.
const system = useSystemSnapshot(systemActive, 1800, page === "system");
const update = useUpdateFlow(bootstrap?.updateFeedUrl ?? "", autoCheck);
// One security state for the whole window: the overview strip, the sidebar
// badge and the security page all read this, so they cannot disagree.
@ -222,6 +242,23 @@ export default function App() {
};
}, []);
useEffect(() => {
let cancelled = false;
let unlisten: (() => void) | null = null;
void api
.onWindowVisible((next) => {
if (!cancelled) setWindowVisible(next);
})
.then((stop) => {
if (cancelled) stop();
else unlisten = stop;
});
return () => {
cancelled = true;
unlisten?.();
};
}, []);
/**
* A notification click goes to the findings, and brings the window back.
*
@ -284,18 +321,20 @@ export default function App() {
}, [security]);
useEffect(() => {
const order: PageId[] = [
const order: PageId[] = ([
"overview",
"cleanup",
"applications",
"purge",
"permissions",
"storage",
"system",
"security",
"startup",
"history",
"settings",
];
] as PageId[]).filter(
(id) => id !== "permissions" || bootstrap?.platform === "windows",
);
// Ctrl/Cmd+1..9 follow the sidebar.
const onKey = (event: KeyboardEvent) => {
if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return;
const index = Number(event.key) - 1;
@ -305,7 +344,7 @@ export default function App() {
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []);
}, [bootstrap?.platform]);
const changeLanguage = useCallback(
async (nextLanguage: Language) => {
@ -354,7 +393,7 @@ export default function App() {
: null;
return (
<I18nProvider lang={lang} setLang={setLang}>
<I18nProvider lang={lang} setLang={setLang} binNoun={bootstrap.binNoun}>
<AppChrome
bootstrap={bootstrap}
page={page}
@ -388,6 +427,7 @@ export default function App() {
onHistory={() => setPage("history")}
/>
) : null}
{page === "permissions" ? <PermissionsPage workspace={permissions} /> : null}
{page === "storage" ? <StoragePage bootstrap={bootstrap} /> : null}
{page === "security" ? (
<SecurityPage security={security} onOpenStartup={() => setPage("startup")} />
@ -492,7 +532,9 @@ function AppChrome({
<span className="nav-group-label">
{lang === "zh" ? group.labelZh : group.labelEn}
</span>
{group.items.map((item) => {
{group.items
.filter((item) => navItemVisible(item.id, bootstrap.platform))
.map((item) => {
const Icon = item.icon;
return (
<button

View File

@ -1,5 +1,6 @@
import {
ArrowUpRight,
DownloadCloud,
FolderOpen,
LockKeyhole,
RotateCcw,
@ -92,7 +93,7 @@ function ItemRow({
checked: boolean;
onToggle: () => void;
}) {
const { lang, t } = useI18n();
const { lang, t, bin } = useI18n();
const Icon = CATEGORY_META[item.category].icon;
return (
<div
@ -113,7 +114,7 @@ function ItemRow({
<span className="cleanup-row-copy">
<span className="cleanup-row-title">
<strong>{item.label}</strong>
<span className="row-category">{categoryLabel(item.category, lang)}</span>
<span className="row-category">{categoryLabel(item.category, lang, bin)}</span>
</span>
<span className="cleanup-row-path" title={item.displayPath}>
{shortPath(item.displayPath, 90)}
@ -171,6 +172,21 @@ export function CleanupInventory({
}, [focus, result]);
const removables = result?.items.filter((item) => !item.lock).length ?? 0;
// 升级安装包:selection may include stale update packages; the confirm
// dialog offers a one-click "delete everything else, keep these" escape.
const selectedUpdaters = useMemo(() => {
if (!result) return { indexes: [] as number[], total: 0 };
let total = 0;
const indexes: number[] = [];
result.items.forEach((item, index) => {
if (item.category === "update-installers" && workspace.selected.has(index)) {
indexes.push(index);
total += item.onDisk;
}
});
return { indexes, total };
}, [result, workspace.selected]);
if (workspace.scanning) {
return (
<ProgressCard
@ -196,8 +212,8 @@ export function CleanupInventory({
if (!result) return null;
const confirm = async () => {
const summary = await workspace.clean(mode);
const confirm = async (indexes?: number[]) => {
const summary = await workspace.clean(mode, indexes);
setConfirming(false);
if (summary) {
push(
@ -289,7 +305,7 @@ export function CleanupInventory({
<SectionTitle
title={
focus
? categoryLabel(focus, lang)
? categoryLabel(focus, lang, bin)
: t("Everything found in this scan", "本次扫描的全部项目")
}
action={
@ -396,6 +412,43 @@ export function CleanupInventory({
<span>{t("Permanent", "永久")}</span>
</button>
</div>
{selectedUpdaters.indexes.length > 0 ? (
<div className="confirm-updater-banner">
<DownloadCloud size={18} />
<div>
<strong>
{t(
`Includes ${formatCount(selectedUpdaters.indexes.length)} update installers (${formatBytes(selectedUpdaters.total)})`,
`其中包含 ${formatCount(selectedUpdaters.indexes.length)} 个升级安装包(${formatBytes(selectedUpdaters.total)})`,
)}
</strong>
<span>
{t(
"Apps re-download them when needed. Delete them too?",
"应用需要时会自动重新下载。要一并清理吗?",
)}
</span>
</div>
<Button
variant="ghost"
size="sm"
disabled={workspace.deleting}
onClick={() => {
const keep = [...workspace.selected].filter(
(index) => !selectedUpdaters.indexes.includes(index),
);
if (keep.length === 0) {
workspace.deselect(selectedUpdaters.indexes);
setConfirming(false);
return;
}
void confirm(keep);
}}
>
{t("Skip installers, clean rest", "跳过升级包,只删其余")}
</Button>
</div>
) : null}
</ConfirmDialog>
</>
);

View File

@ -70,7 +70,7 @@ export function UpdatePanel({
<div className="update-system-copy">
<small>{t("Current system", "当前系统")}</small>
<strong>
{bootstrap.osName} {bootstrap.osVersion}
{bootstrap.osVersion || bootstrap.osName}
</strong>
</div>
<div className="update-system-facts">

View File

@ -0,0 +1,346 @@
/* 桌面小工具 panel widgets: shared between the desktop widget window and the
* main-window preview. Pure SVG rendering (rings + sparklines), no deps. */
import { useMemo, useRef } from "react";
import { formatBytes, formatMemoryBytes, formatRate, percent } from "../lib/format";
import type { SystemSnapshot, WidgetPrefs } from "../types";
const RING_R = 30;
const RING_C = 2 * Math.PI * RING_R;
export function Ring({
label,
sub,
value,
color,
}: {
label: string;
sub: string;
value: number;
color: string;
}) {
const arc = (Math.max(0, Math.min(100, value)) / 100) * RING_C;
return (
<div className="wd-ring">
<svg width="76" height="76" viewBox="0 0 76 76" aria-hidden="true">
<circle cx="38" cy="38" r={RING_R} fill="none" stroke="#eef1f6" strokeWidth="7" />
<circle
cx="38"
cy="38"
r={RING_R}
fill="none"
stroke={arc > 0 ? color : "#dfe4ec"}
strokeWidth="7"
strokeLinecap="round"
strokeDasharray={`${arc} ${RING_C}`}
transform="rotate(-90 38 38)"
/>
</svg>
<div className="wd-ring-text">
<b>{label}</b>
<span>{sub}</span>
</div>
</div>
);
}
const HISTORY = 64;
export interface MetricHistory {
netUp: number[];
netDown: number[];
diskRead: number[];
diskWrite: number[];
cpu: number[];
}
/** Append-only ring buffers over the snapshot stream (sparkline source). */
export function useHistory(): [MetricHistory, (snapshot: SystemSnapshot) => void] {
const ref = useRef<MetricHistory>({
netUp: [],
netDown: [],
diskRead: [],
diskWrite: [],
cpu: [],
});
const bump = useMemo(
() => (snapshot: SystemSnapshot) => {
const push = (list: number[], value: number) => {
list.push(value);
if (list.length > HISTORY) list.shift();
};
push(ref.current.netUp, snapshot.network.tx_per_sec);
push(ref.current.netDown, snapshot.network.rx_per_sec);
push(ref.current.diskRead, snapshot.disk.read_per_sec);
push(ref.current.diskWrite, snapshot.disk.write_per_sec);
push(ref.current.cpu, snapshot.cpu.total);
},
[],
);
return [ref.current, bump];
}
function Spark({
values,
color,
max,
}: {
values: number[];
color: string;
max?: number;
}) {
// The history array is mutated in place between renders, so the polyline
// must be rebuilt every render — a useMemo on identity would freeze the
// first (empty) result forever.
if (values.length < 2) return <svg className="wd-spark" viewBox="0 0 300 56" />;
const top = max ?? Math.max(...values, 1);
const width = 300;
const step = width / (HISTORY - 1);
const offset = HISTORY - values.length;
const points = values
.map((value, index) => {
const x = (index + offset) * step;
const y = 52 - (value / top) * 46;
return `${x.toFixed(1)},${y.toFixed(1)}`;
})
.join(" ");
return (
<svg className="wd-spark" viewBox="0 0 300 56" preserveAspectRatio="none">
<polyline points={points} fill="none" stroke={color} strokeWidth="1.6" />
</svg>
);
}
export function uptimeFull(seconds: number, zh: boolean): string {
const d = Math.floor(seconds / 86_400);
const h = Math.floor((seconds % 86_400) / 3_600);
const m = Math.floor((seconds % 3_600) / 60);
const s = Math.floor(seconds % 60);
return zh
? `${d} 天 ${h} 时 ${m} 分 ${s} 秒`
: `${d}d ${h}h ${m}m ${s}s`;
}
/* 逻辑核心占用柱状图:整行均分(核心多则柱变窄),柱色 = 占用率在
* 绿→黄→橙→红 四个锚点之间连续插值,柱内再做纵向微渐变;悬停显示
* 「核心 N: xx%」(编号与任务管理器一致从 0 开始)。 */
const LOAD_STOPS: Array<[number, [number, number, number]]> = [
[0, [46, 204, 113]],
[33, [247, 224, 120]],
[66, [245, 165, 76]],
[100, [233, 87, 63]],
];
function loadRgb(value: number): [number, number, number] {
const v = Math.max(0, Math.min(100, value));
for (let i = 1; i < LOAD_STOPS.length; i += 1) {
const [at, rgb] = LOAD_STOPS[i];
if (v <= at) {
const [prevAt, prevRgb] = LOAD_STOPS[i - 1];
const t = (v - prevAt) / (at - prevAt);
return rgb.map((channel, k) =>
Math.round(prevRgb[k] + (channel - prevRgb[k]) * t),
) as [number, number, number];
}
}
return LOAD_STOPS[LOAD_STOPS.length - 1][1];
}
function loadColor(value: number): string {
return `rgb(${loadRgb(value).join(",")})`;
}
function barFill(value: number): string {
const base = loadRgb(value);
const deep = base.map((channel) => Math.round(channel * 0.62));
const gloss = base.map((channel) => Math.round(channel + (255 - channel) * 0.35));
const css = (rgb: number[]) => `rgb(${rgb.join(",")})`;
return `linear-gradient(180deg, ${css(gloss)} 0%, ${css(base)} 45%, ${css(deep)} 100%)`;
}
function CpuPanel({
total,
cores,
history,
zh,
}: {
total: number;
cores: number[];
history: MetricHistory;
zh: boolean;
}) {
return (
<div className="wd-card">
<div className="wd-line-head">
<h4>CPU</h4>
<div className="wd-rate">
<b className="wd-cpu-total" style={{ color: loadColor(total) }}>
{Math.round(total)}%
</b>
</div>
</div>
<Spark values={history.cpu} color="#2f6bff" max={100} />
{cores.length > 0 ? (
<>
<div className="wd-bars">
{cores.map((value, index) => (
<span
key={index}
className="wd-bar"
title={`${zh ? "核心" : "Core"} ${index}: ${Math.round(value)}%`}
>
<i
style={{
height: `${Math.max(8, Math.min(100, value))}%`,
background: barFill(value),
}}
/>
</span>
))}
</div>
<div className="wd-bars-caption">
{zh ? `逻辑核心 ×${cores.length}` : `Logical cores ×${cores.length}`}
</div>
</>
) : null}
</div>
);
}
export function DiskGlyph() {
return (
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<rect x="3" y="4" width="18" height="16" rx="3" fill="#5a6b80" />
<rect x="3" y="4" width="18" height="7" rx="3" fill="#7f90a6" />
<circle cx="17" cy="16" r="4" fill="#16b364" />
<path
d="m15.3 16 1.2 1.2 2.2-2.4"
stroke="#fff"
strokeWidth="1.3"
fill="none"
strokeLinecap="round"
/>
</svg>
);
}
export function WidgetPanels({
snapshot,
prefs,
history,
zh,
}: {
snapshot: SystemSnapshot | null;
prefs: WidgetPrefs;
history: MetricHistory;
zh: boolean;
}) {
const memory = snapshot?.memory;
const memoryPct = memory ? percent(memory.used, memory.total) : 0;
const gpu = snapshot?.gpu_usage ?? null;
return (
<>
{prefs.panelRun ? (
<div className="wd-card">
<div className="wd-run">
<div className="wd-run-left">
<h4>{zh ? "运行状态" : "Status"}</h4>
<strong>{snapshot?.host.hostname || "Squid"}</strong>
<div className="wd-uptime">
<span>{zh ? "本次运行" : "Uptime"}</span>
<b>{uptimeFull(snapshot?.uptime_secs ?? 0, zh)}</b>
</div>
</div>
<div className="wd-rings">
<Ring
label="CPU"
sub={`${Math.round(snapshot?.cpu.total ?? 0)}%`}
value={snapshot?.cpu.total ?? 0}
color="#f2571c"
/>
<Ring
label={zh ? "内存" : "Mem"}
sub={memory ? formatMemoryBytes(memory.used) : "—"}
value={memoryPct}
color="#2f6bff"
/>
<span />
<Ring
label="GPU"
sub={gpu === null ? "—" : `${Math.round(gpu)}%`}
value={gpu ?? 0}
color="#2f6bff"
/>
</div>
</div>
</div>
) : null}
{prefs.panelCpu ? (
<CpuPanel
total={snapshot?.cpu.total ?? 0}
cores={snapshot?.cpu.per_core ?? []}
history={history}
zh={zh}
/>
) : null}
{prefs.panelNetwork ? (
<div className="wd-card">
<div className="wd-line-head">
<h4>{zh ? "网络" : "Network"}</h4>
<div className="wd-rate">
<b className="up">↑ {formatRate(snapshot?.network.tx_per_sec ?? 0)}</b>
<b className="down">↓ {formatRate(snapshot?.network.rx_per_sec ?? 0)}</b>
</div>
</div>
<Spark values={history.netUp} color="#16b364" />
<Spark values={history.netDown} color="#2f6bff" />
</div>
) : null}
{prefs.panelDisk ? (
<div className="wd-card">
<div className="wd-line-head">
<h4>{zh ? "存储读写" : "Disk I/O"}</h4>
<div className="wd-rate">
<b className="up">R {formatRate(snapshot?.disk.read_per_sec ?? 0)}</b>
<b className="down">W {formatRate(snapshot?.disk.write_per_sec ?? 0)}</b>
</div>
</div>
<Spark values={history.diskRead} color="#16b364" />
</div>
) : null}
{prefs.panelStorage ? (
<div className="wd-card">
<h4 className="wd-pad">{zh ? "存储空间" : "Storage"}</h4>
{(snapshot?.volumes ?? []).slice(0, 4).map((volume) => {
const used = volume.total - volume.free;
return (
<div className="wd-vol" key={volume.mount_point}>
<span className="wd-vol-ico">
<DiskGlyph />
</span>
<div className="wd-vol-body">
<div className="wd-vol-top">
<span>
{volume.name && !/^[A-Za-z]:$/.test(volume.name)
? `${volume.name} (${volume.mount_point})`
: volume.mount_point}
</span>
<b>
{formatBytes(used)} / {formatBytes(volume.total)}
</b>
</div>
<div className="wd-vol-bar">
<i style={{ width: `${percent(used, volume.total)}%` }} />
</div>
</div>
</div>
);
})}
</div>
) : null}
</>
);
}

View File

@ -5,6 +5,7 @@ import {
Check,
ChevronDown,
Code2,
DownloadCloud,
FileWarning,
Globe2,
Languages,
@ -120,11 +121,25 @@ export const CATEGORY_META: Record<Category, CategoryMeta> = {
icon: Puzzle,
tone: "warning",
},
"update-installers": {
en: "Update installers",
zh: "升级安装包",
blurbEn: "Installer packages apps keep after updating",
blurbZh: "应用升级后留下的安装包,需要时会自动重新下载",
icon: DownloadCloud,
tone: "success",
},
};
export const CATEGORY_ORDER = Object.keys(CATEGORY_META) as Category[];
export function categoryLabel(category: Category, language: "zh" | "en"): string {
export function categoryLabel(
category: Category,
language: "zh" | "en",
binName?: string,
): string {
// The bin category borrows the OS word for it: 回收站 on Windows, 废纸篓 on macOS.
if (category === "trash" && binName) return binName;
return language === "zh" ? CATEGORY_META[category].zh : CATEGORY_META[category].en;
}
@ -279,6 +294,7 @@ export function Select<T extends string | number>({
label,
disabled = false,
align = "end",
placement = "down",
}: {
value: T;
options: { value: T; label: string }[];
@ -286,6 +302,7 @@ export function Select<T extends string | number>({
label: string;
disabled?: boolean;
align?: "start" | "end";
placement?: "down" | "up";
}) {
const [open, setOpen] = useState(false);
const [active, setActive] = useState(0);
@ -355,7 +372,7 @@ export function Select<T extends string | number>({
</button>
{open ? (
<ul
className={`select-menu is-${align}`}
className={`select-menu is-${align} is-${placement}`}
role="listbox"
aria-label={label}
>
@ -687,14 +704,18 @@ export function EmptyState({
action,
}: {
icon: ReactNode;
title: string;
title?: string;
description?: string;
action?: ReactNode;
}) {
return (
<div className="empty-state">
<div className="empty-icon">{icon}</div>
<h2>{title}</h2>
{title ? (
<h2>{title}</h2>
) : (
<span className="empty-title-spacer" aria-hidden="true" />
)}
{description ? <p>{description}</p> : null}
{action}
</div>
@ -740,7 +761,7 @@ export function CategoryCard({
onInspect: () => void;
focused?: boolean;
}) {
const { lang, t } = useI18n();
const { lang, t, bin } = useI18n();
const meta = CATEGORY_META[category];
const Icon = meta.icon;
return (
@ -758,11 +779,11 @@ export function CategoryCard({
checked={selected}
disabled={disabled}
onChange={onToggle}
label={categoryLabel(category, lang)}
label={categoryLabel(category, lang, bin)}
/>
</div>
<div className="category-copy">
<strong>{categoryLabel(category, lang)}</strong>
<strong>{categoryLabel(category, lang, bin)}</strong>
<span>{lang === "zh" ? meta.blurbZh : meta.blurbEn}</span>
</div>
<div className="category-card-foot">

View File

@ -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<void>;
refreshWindows: () => Promise<void>;
toggleStartup: (id: string, enabled: boolean) => Promise<void>;
toggleExtension: (id: string, registered: boolean) => Promise<void>;
addRule: (hwnd: number, matcher: "exact" | "contains") => Promise<void>;
toggleRule: (index: number, enabled: boolean) => Promise<void>;
removeRule: (index: number) => Promise<void>;
closeWindow: (hwnd: number) => Promise<void>;
setWatcher: (enabled: boolean) => Promise<void>;
}
export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace {
const [tab, setTab] = useState<PermissionsTab>("startup");
const [view, setView] = useState<ManageView | null>(null);
const [windows, setWindows] = useState<PopupWindowItem[]>([]);
const [scanning, setScanning] = useState(false);
const [busyId, setBusyId] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [closedTotal, setClosedTotal] = useState(0);
const [recentClosed, setRecentClosed] = useState<{ process: string; title: string }[]>([]);
const scan = useCallback(async () => {
setScanning(true);
setError(null);
try {
const next = await api.manageScan();
setView(next);
setWindows(next.windows);
setClosedTotal(next.rules.reduce((sum, rule) => sum + rule.closed, 0));
} catch (reason) {
if (!isCancelled(reason)) setError(messageFrom(reason));
} finally {
setScanning(false);
}
}, []);
const refreshWindows = useCallback(async () => {
try {
setWindows(await api.popupList());
} catch (reason) {
setError(messageFrom(reason));
}
}, []);
useEffect(() => {
if (active && !view && !scanning) void scan();
}, [active, scan, view, scanning]);
useEffect(() => {
if (!active) return;
let stop: (() => void) | null = null;
let cancelled = false;
void api
.onPopupClosed((event) => {
setClosedTotal((total) => total + 1);
setRecentClosed((recent) => [{ ...event }, ...recent].slice(0, 3));
setView((current) =>
current
? {
...current,
rules: current.rules.map((rule, index) =>
index === event.ruleIndex ? { ...rule, closed: rule.closed + 1 } : rule,
),
}
: current,
);
})
.then((unlisten) => {
if (cancelled) unlisten();
else stop = unlisten;
});
return () => {
cancelled = true;
stop?.();
};
}, [active]);
const toggleStartup = useCallback(
async (id: string, enabled: boolean) => {
setBusyId(id);
setError(null);
try {
await api.managedStartupSetEnabled(id, enabled);
await scan();
} catch (reason) {
setError(messageFrom(reason));
} finally {
setBusyId(null);
}
},
[scan],
);
const toggleExtension = useCallback(
async (id: string, registered: boolean) => {
setBusyId(id);
setError(null);
try {
await api.extensionSetRegistered(id, registered);
setView((current) =>
current
? {
...current,
extensions: current.extensions.map((entry) =>
entry.id === id ? { ...entry, registered } : entry,
),
}
: current,
);
} catch (reason) {
setError(messageFrom(reason));
} finally {
setBusyId(null);
}
},
[],
);
const addRule = useCallback(
async (hwnd: number, matcher: "exact" | "contains") => {
setError(null);
try {
await api.popupAddRule(hwnd, matcher);
await scan();
} catch (reason) {
setError(messageFrom(reason));
}
},
[scan],
);
const toggleRule = useCallback(async (index: number, enabled: boolean) => {
setError(null);
try {
await api.popupRuleUpdate(index, enabled);
setView((current) =>
current
? {
...current,
rules: current.rules.map((rule, i) => (i === index ? { ...rule, enabled } : rule)),
}
: current,
);
} catch (reason) {
setError(messageFrom(reason));
}
}, []);
const removeRule = useCallback(
async (index: number) => {
setError(null);
try {
await api.popupRuleRemove(index);
await scan();
} catch (reason) {
setError(messageFrom(reason));
}
},
[scan],
);
const closeWindow = useCallback(async (hwnd: number) => {
setError(null);
try {
await api.popupClose(hwnd);
setWindows((current) => current.filter((window) => window.hwnd !== hwnd));
} catch (reason) {
setError(messageFrom(reason));
}
}, []);
const setWatcher = useCallback(async (enabled: boolean) => {
setError(null);
try {
await api.popupWatcherSet(enabled);
setView((current) => (current ? { ...current, watcherEnabled: enabled } : current));
} catch (reason) {
setError(messageFrom(reason));
}
}, []);
return {
tab,
setTab,
view,
windows,
scanning,
busyId,
error,
dismissError: () => setError(null),
closedTotal,
recentClosed,
scan,
refreshWindows,
toggleStartup,
toggleExtension,
addRule,
toggleRule,
removeRule,
closeWindow,
setWatcher,
};
}

View File

@ -35,9 +35,10 @@ export interface ScanWorkspace {
cancel: () => Promise<void>;
toggleItem: (index: number) => void;
toggleCategory: (category: Category) => void;
deselect: (indexes: number[]) => void;
selectAll: () => void;
clearSelection: () => void;
clean: (mode: DeleteMode) => Promise<DeleteResult | null>;
clean: (mode: DeleteMode, indexes?: number[]) => Promise<DeleteResult | null>;
clearError: () => void;
reset: () => void;
}
@ -149,6 +150,16 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
const clearSelection = useCallback(() => setSelected(new Set()), []);
const deselect = useCallback((indexes: number[]) => {
if (indexes.length === 0) return;
const drop = new Set(indexes);
setSelected((current) => {
const next = new Set(current);
for (const index of drop) next.delete(index);
return next;
});
}, []);
const selectedTotal = useMemo(() => {
if (!result) return 0;
let total = 0;
@ -159,8 +170,10 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
const selectedCount = selected.size;
const clean = useCallback(
async (mode: DeleteMode) => {
if (!result || selected.size === 0 || deleting) return null;
async (mode: DeleteMode, indexes?: number[]) => {
if (!result || deleting) return null;
const targets = indexes ?? [...selected];
if (targets.length === 0) return null;
const id = jobId();
activeJob.current = id;
setCurrentJob(id);
@ -171,8 +184,8 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
try {
const next =
kind === "cleanup"
? await api.cleanupDelete(id, result.scanId, [...selected], mode)
: await api.purgeDelete(id, result.scanId, [...selected], mode);
? await api.cleanupDelete(id, result.scanId, targets, mode)
: await api.purgeDelete(id, result.scanId, targets, mode);
if (activeJob.current !== id) return null;
setResult(null);
setSelected(new Set());
@ -217,6 +230,7 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
cancel,
toggleItem,
toggleCategory,
deselect,
selectAll,
clearSelection,
clean,

View File

@ -3,7 +3,19 @@ import { api } from "../lib/api";
import { messageFrom } from "../lib/format";
import type { SystemSnapshot } from "../types";
export function useSystemSnapshot(active: boolean, intervalMs = 1800) {
/**
* Polls system_snapshot for a page.
*
* - `full` asks the backend for the expensive per-process walk (only the
* 实时监控 top-process table needs it); light refreshes cost a fraction.
* - Polling pauses while the window is hidden (tray) or the tab is hidden,
* so an icon in the notification area does not keep sampling forever.
*/
export function useSystemSnapshot(
active: boolean,
intervalMs = 1800,
full = false,
) {
const [snapshot, setSnapshot] = useState<SystemSnapshot | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
@ -14,7 +26,7 @@ export function useSystemSnapshot(active: boolean, intervalMs = 1800) {
inFlight.current = true;
setLoading(true);
try {
setSnapshot(await api.systemSnapshot());
setSnapshot(await api.systemSnapshot(full));
setError(null);
} catch (reason) {
setError(messageFrom(reason));
@ -22,13 +34,35 @@ export function useSystemSnapshot(active: boolean, intervalMs = 1800) {
inFlight.current = false;
setLoading(false);
}
}, []);
}, [full]);
useEffect(() => {
if (!active) return;
void refresh();
const timer = window.setInterval(() => void refresh(), intervalMs);
return () => window.clearInterval(timer);
let live = true;
let timer: number | null = null;
const tick = () => {
if (live && !document.hidden) void refresh();
};
const start = () => {
if (timer === null) {
void refresh();
timer = window.setInterval(tick, intervalMs);
}
};
const stop = () => {
if (timer !== null) {
window.clearInterval(timer);
timer = null;
}
};
const onVisibility = () => (document.hidden ? stop() : start());
start();
document.addEventListener("visibilitychange", onVisibility);
return () => {
live = false;
stop();
document.removeEventListener("visibilitychange", onVisibility);
};
}, [active, intervalMs, refresh]);
return { snapshot, error, loading, refresh };

View File

@ -15,18 +15,23 @@ const I18nContext = createContext<I18nValue | null>(null);
export function I18nProvider({
lang,
setLang,
binNoun = "trash",
children,
}: {
lang: Language;
setLang: (language: Language) => void;
binNoun?: "trash" | "recycle-bin";
children: ReactNode;
}) {
// Windows calls it 回收站; macOS and freedesktop keep 废纸篓.
const zhBin = binNoun === "recycle-bin" ? "回收站" : "废纸篓";
const enBin = binNoun === "recycle-bin" ? "Recycle Bin" : "Trash";
const value: I18nValue = {
lang,
setLang,
t: (en, zh) => (lang === "zh" ? zh : en),
bin: lang === "zh" ? "废纸篓" : "Trash",
binLower: lang === "zh" ? "废纸篓" : "trash",
bin: lang === "zh" ? zhBin : enBin,
binLower: lang === "zh" ? zhBin : enBin.toLowerCase(),
currency: lang === "zh" ? "zh-CN" : "en-US",
};
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;

View File

@ -9,9 +9,12 @@ import type {
JobProgress,
LargestFile,
IntelStatus,
ManageView,
PageId,
PermissionStatus,
PlanResult,
PopupClosedEvent,
PopupWindowItem,
ScanResult,
SettingsView,
SecurityAction,
@ -28,6 +31,8 @@ import type {
UpdateCheckResult,
UpdateProgress,
UpdateStatus,
WidgetPatch,
WidgetPrefs,
} from "../types";
export interface SettingsPatch {
@ -76,7 +81,7 @@ export const api = {
invoke<StorageNode>("storage_explore", { jobId, path, depth, top }),
storageLargestFiles: (jobId: string, path: string, limit = 40) =>
invoke<LargestFile[]>("storage_largest_files", { jobId, path, limit }),
systemSnapshot: () => invoke<SystemSnapshot>("system_snapshot"),
systemSnapshot: (full = false) => invoke<SystemSnapshot>("system_snapshot", { full }),
stopProcess: (process: SystemSnapshot["top_processes"][number]) =>
invoke<void>("stop_process", { process }),
historyList: (limit = 60) => invoke<HistorySession[]>("history_list", { limit }),
@ -90,6 +95,23 @@ export const api = {
openTrash: () => invoke<void>("open_trash"),
permissionStatus: () => invoke<PermissionStatus>("permission_status"),
openFullDiskAccessSettings: () => invoke<void>("open_full_disk_access_settings"),
manageScan: () => invoke<ManageView>("manage_scan"),
managedStartupSetEnabled: (id: string, enabled: boolean) =>
invoke<number>("managed_startup_set_enabled", { id, enabled }),
extensionSetRegistered: (id: string, registered: boolean) =>
invoke<void>("extension_set_registered", { id, registered }),
popupList: () => invoke<PopupWindowItem[]>("popup_list"),
popupClose: (hwnd: number) => invoke<void>("popup_close", { hwnd }),
popupAddRule: (hwnd: number, matcher: string) =>
invoke<void>("popup_add_rule", { hwnd, matcher }),
popupRuleUpdate: (index: number, enabled?: boolean, resetCount?: boolean) =>
invoke<void>("popup_rule_update", { index, enabled, resetCount }),
popupRuleRemove: (index: number) => invoke<void>("popup_rule_remove", { index }),
popupWatcherSet: (enabled: boolean) => invoke<void>("popup_watcher_set", { enabled }),
widgetGet: () =>
invoke<{ prefs: WidgetPrefs; language: "zh" | "en" }>("widget_get"),
widgetSet: (patch: WidgetPatch) => invoke<WidgetPrefs>("widget_set", { patch }),
widgetHide: () => invoke<void>("widget_hide"),
updateCheck: () => invoke<UpdateCheckResult>("update_check"),
updateStatus: () => invoke<UpdateStatus | null>("update_status"),
updateDownload: () => invoke<UpdateStatus>("update_download"),
@ -133,8 +155,14 @@ export const api = {
listen<UpdateStatus | null>("update://status", (event) => handler(event.payload)),
onNavigate: (handler: (page: PageId) => void) =>
listen<PageId>("squid://navigate", (event) => handler(event.payload)),
onWindowVisible: (handler: (visible: boolean) => void) =>
listen<boolean>("squid://visible", (event) => handler(event.payload)),
onSecurityScan: (handler: (scan: SecurityScan) => void) =>
listen<SecurityScan>("squid://security", (event) => handler(event.payload)),
onPopupClosed: (handler: (event: PopupClosedEvent) => void) =>
listen<PopupClosedEvent>("popup://closed", (event) => handler(event.payload)),
onWidgetSettings: (handler: (prefs: WidgetPrefs) => void) =>
listen<WidgetPrefs>("widget://settings", (event) => handler(event.payload)),
};
/// Progress events for one job, whatever kind of job it is. Security scans share

View File

@ -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(
<React.StrictMode>
<ToastProvider>
<App />
</ToastProvider>
<ToastProvider>{isWidget ? <WidgetWindow /> : <App />}</ToastProvider>
</React.StrictMode>,
);

View File

@ -151,7 +151,6 @@ export function ApplicationsPage({
return (
<div className="page apps-page">
<PageHeader
eyebrow={t("Applications", "应用程序")}
title={t("Uninstall completely.", "卸载,干净彻底。")}
description={t(
"Remove an app together with the caches, preferences and support files it leaves behind.",
@ -314,7 +313,7 @@ export function ApplicationsPage({
<strong>{item.label}</strong>
<span title={item.displayPath}>{shortPath(item.displayPath, 44)}</span>
<small>
{categoryLabel(item.category, lang)}
{categoryLabel(item.category, lang, bin)}
{item.note ? ` · ${item.note}` : ""}
{item.lock ? ` · ${lockLabel(item.lock, t)}` : ""}
</small>
@ -357,7 +356,6 @@ export function ApplicationsPage({
{!workspace.scanned && !workspace.scanning ? (
<EmptyState
icon={<AppWindow size={29} />}
title={t("See what is installed", "查看已安装的应用")}
action={
<Button
variant="primary"

View File

@ -16,7 +16,7 @@ export function CleanupPage({
}) {
const { t } = useI18n();
return (
<div className="page">
<div className="page cleanup-page">
<PageHeader
title={t("Clutter, without the guesswork.", "清理垃圾,不靠猜。")}
description={t(
@ -50,7 +50,6 @@ export function CleanupPage({
{!workspace.result && !workspace.scanning && !workspace.summary ? (
<EmptyState
icon={<Sparkles size={28} />}
title={t("Ready when you are", "随时可以开始")}
action={
<Button
variant="primary"

View File

@ -91,8 +91,8 @@ export function HistoryPage() {
<PageHeader
title={t("Every change, on the record.", "每一次改动,都有记录。")}
description={t(
"Review past cleanups and put files back from the Trash when you change your mind.",
"查看过去的清理记录,改变主意时还可以从废纸篓还原文件。",
`Review past cleanups and put files back from the ${bin} when you change your mind.`,
`查看过去的清理记录,改变主意时还可以从${bin}还原文件。`,
)}
actions={
<Button
@ -169,7 +169,7 @@ export function HistoryPage() {
<small>
{formatDate(session.started, lang)} ·{" "}
{session.mode === "trash"
? t("Moved to Trash", "已移入废纸篓")
? t(`Moved to ${bin}`, `已移入${bin}`)
: t("Permanently removed", "已永久删除")}
</small>
</span>
@ -224,7 +224,7 @@ export function HistoryPage() {
<small>
{entry.category || entry.kind}
{entry.trash_path
? ` · ${t("in Trash", "位于废纸篓")}`
? ` · ${t(`in ${bin}`, `位于${bin}`)}`
: ""}
</small>
</span>
@ -265,8 +265,8 @@ export function HistoryPage() {
: ""
}
note={t(
"Files still in the Trash are returned to their original folders. Anything already emptied is skipped.",
"仍在废纸篓中的文件会回到原位置;已被清空的项目会被跳过。",
`Files still in the ${bin} are returned to their original folders. Anything already emptied is skipped.`,
`仍在${bin}中的文件会回到原位置;已被清空的项目会被跳过。`,
)}
confirmLabel={t("Restore files", "还原文件")}
cancelLabel={t("Cancel", "取消")}

View File

@ -3,16 +3,16 @@ import {
ArrowRight,
Boxes,
ChevronRight,
CircuitBoard,
CircleGauge,
Cpu,
HardDrive,
Laptop,
MemoryStick,
Microchip,
Monitor,
MonitorCog,
ScanSearch,
Sparkles,
WandSparkles,
Waypoints,
} from "lucide-react";
import { useI18n } from "../i18n";
import {
@ -60,19 +60,53 @@ function machineRows(
volume: Volume | null,
t: (en: string, zh: string) => string,
) {
const hardware = bootstrap.hardwareInfo;
const model = bootstrap.hardware.split(" · ")[0]?.trim() || bootstrap.hardware;
const installed = snapshot
? Math.max(snapshot.memory.installed, snapshot.memory.total)
: 0;
const ramBrands = [
...new Set(hardware.memory_sticks.map((stick) => stick.manufacturer).filter(Boolean)),
].join(" / ");
const ramSpeed = hardware.memory_sticks.reduce(
(top, stick) => Math.max(top, stick.speed_mhz),
0,
);
const memory = [
installed ? formatMemoryBytes(installed) : "",
ramBrands,
ramSpeed ? `${ramSpeed} MT/s` : "",
]
.filter(Boolean)
.join(" · ");
const disk = [
[hardware.disk_vendor, hardware.disk_model].filter(Boolean).join(" "),
hardware.disk_size_bytes ? formatBytes(hardware.disk_size_bytes, 0) : "",
hardware.disk_bus,
]
.filter(Boolean)
.join(" · ");
const gpu = [
hardware.gpu_model &&
hardware.gpu_model.toLowerCase().startsWith(hardware.gpu_vendor.toLowerCase())
? hardware.gpu_model
: [hardware.gpu_vendor, hardware.gpu_model].filter(Boolean).join(" "),
hardware.gpu_vram_bytes ? formatBytes(hardware.gpu_vram_bytes, 0) : "",
]
.filter(Boolean)
.join(" · ");
const rows = [
{
key: "os",
icon: Monitor,
icon: MonitorCog,
label: t("Operating system", "操作系统"),
value: bootstrap.osVersion || bootstrap.osName,
},
{
key: "model",
icon: Laptop,
icon: CircuitBoard,
label: t("Computer", "本机型号"),
value: model,
value: hardware.board || model,
},
{
key: "cpu",
@ -86,25 +120,25 @@ function machineRows(
key: "memory",
icon: MemoryStick,
label: t("Memory", "内存"),
value: snapshot
? formatMemoryBytes(snapshot.memory.total)
: t("Reading memory…", "正在读取内存…"),
value: memory || t("Reading memory…", "正在读取内存…"),
},
{
key: "disk",
icon: HardDrive,
label: t("Primary disk", "主硬盘"),
value: volume
? `${volume.name || volume.mount_point} · ${formatBytes(volume.total, 0)} · ${volume.filesystem.toUpperCase()}`
: t("Reading disks…", "正在读取磁盘…"),
value:
disk ||
(volume
? `${volume.name || volume.mount_point} · ${formatBytes(volume.total, 0)} · ${volume.filesystem.toUpperCase()}`
: t("Reading disks…", "正在读取磁盘…")),
},
];
if (snapshot?.host.gpu) {
if (gpu || snapshot?.host.gpu) {
rows.push({
key: "gpu",
icon: Microchip,
icon: Waypoints,
label: t("Graphics", "显卡"),
value: snapshot.host.gpu,
value: gpu || snapshot?.host.gpu || "",
});
}
return rows;
@ -122,13 +156,19 @@ export function OverviewPage({
onNavigate: (page: PageId) => void;
}) {
const { t, lang } = useI18n();
const volume =
snapshot?.volumes.find((candidate) => candidate.is_root) ?? snapshot?.volumes[0] ?? null;
const used = volume ? volume.total - volume.free : 0;
const usedPercent = volume ? percent(used, volume.total) : 0;
const volumes = snapshot?.volumes ?? [];
const rootVolume = volumes.find((candidate) => candidate.is_root) ?? volumes[0] ?? null;
const used = rootVolume ? rootVolume.total - rootVolume.free : 0;
const usedPercent = rootVolume ? percent(used, rootVolume.total) : 0;
const memoryPercent = snapshot
? percent(snapshot.memory.used, snapshot.memory.total)
: 0;
const memoryInstalled = snapshot
? Math.max(snapshot.memory.installed, snapshot.memory.total)
: 0;
const memoryReserved = snapshot
? Math.max(0, memoryInstalled - snapshot.memory.total)
: 0;
const found = cleanup.result
? cleanup.result.items
.filter((item) => !item.lock)
@ -220,7 +260,7 @@ export function OverviewPage({
<aside className="overview-machine">
<span className="machine-title">{t("This machine", "本机配置")}</span>
<div className="machine-list">
{machineRows(bootstrap, snapshot, volume, t).map((row) => {
{machineRows(bootstrap, snapshot, rootVolume, t).map((row) => {
const Icon = row.icon;
return (
<div className="machine-row" key={row.key}>
@ -272,7 +312,7 @@ export function OverviewPage({
<span>
{snapshot
? `${formatMemoryBytes(snapshot.memory.used)} / ${formatMemoryBytes(
snapshot.memory.total,
memoryInstalled,
)}`
: t("Sampling…", "正在采样…")}
</span>
@ -281,7 +321,12 @@ export function OverviewPage({
</div>
<UsageBar used={memoryPercent} total={100} tone="violet" />
<small>
{snapshot?.memory.compressed !== null &&
{memoryReserved > 0
? t(
`Hardware reserved (integrated graphics): ${formatMemoryBytes(memoryReserved)}`,
`硬件保留(含核显):${formatMemoryBytes(memoryReserved)}`,
)
: snapshot?.memory.compressed !== null &&
snapshot?.memory.compressed !== undefined
? t(
`Compressed ${formatMemoryBytes(snapshot.memory.compressed)} · Wired ${formatMemoryBytes(

View File

@ -0,0 +1,458 @@
import { BellRing, RefreshCw, Search, ShieldCheck, Trash2, X } from "lucide-react";
import { useMemo, useState } from "react";
import { useI18n } from "../i18n";
import { shortPath } from "../lib/format";
import type { PermissionsWorkspace } from "../hooks/usePermissionsWorkspace";
import type { ManagedStartupItem } from "../types";
import {
Button,
EmptyState,
IconButton,
InlineError,
PageHeader,
SectionTitle,
Toggle,
} from "../components/ui";
function scopeLabel(scope: string, t: (en: string, zh: string) => string): string {
return scope === "machine" ? t("All users", "所有用户") : t("Current user", "当前用户");
}
// The icon shared by a software group: the first entry that carries one.
function softwareIcon(items: ManagedStartupItem[]): string {
return items.find((item) => item.icon)?.icon ?? "";
}
// 电脑管家 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 }) {
return icon ? (
<img className="perm-row-icon" src={icon} alt="" />
) : (
<span className="perm-row-icon perm-row-icon-fallback" aria-hidden="true">
{label.trim().slice(0, 1).toUpperCase()}
</span>
);
}
export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace }) {
const { t } = useI18n();
const [query, setQuery] = useState("");
const [extCat, setExtCat] = useState<string | null>(null);
const view = workspace.view;
const tabs = useMemo(
() =>
[
{
id: "startup" as const,
label: t("Startup items", "开机启动项"),
count: view?.startupCount ?? 0,
},
{
id: "extensions" as const,
label: t("Context menus", "右键菜单"),
count: view?.extensions.length ?? 0,
},
{
id: "popup" as const,
label: t("Popup blocker", "弹窗拦截"),
count: view?.rules.length ?? 0,
},
],
[t, view],
);
if (!view && workspace.scanning) {
return (
<div className="page">
<PageHeader
eyebrow={t("Permissions", "权限管理")}
title={t("Scanning startup and shell…", "正在扫描开机启动项与右键菜单…")}
description={t(
"Reading registry Run keys, startup folders, scheduled tasks, context menus and open windows.",
"正在读取注册表 Run 键、启动文件夹、计划任务、右键菜单与当前窗口。",
)}
/>
<div className="perm-loading">
<RefreshCw size={18} className="perm-spin" />
<span>{t("One moment…", "请稍候…")}</span>
</div>
</div>
);
}
if (!view) {
return (
<div className="page">
<PageHeader
eyebrow={t("Permissions", "权限管理")}
title={t("Startup, context menus and popups.", "开机启动、右键菜单与弹窗拦截。")}
description={t(
"Everything the shell runs before you ask it to.",
"管理系统在你开口之前就自己运行的东西。",
)}
/>
<EmptyState
icon={<ShieldCheck size={30} />}
title={t("Nothing scanned yet", "还没有扫描结果")}
description={t(
"Squid will list startup entries, context-menu handlers and live windows.",
"Squid 会列出启动项、右键菜单扩展和当前窗口。",
)}
action={
<Button variant="primary" onClick={() => void workspace.scan()}>
{t("Scan now", "立即扫描")}
</Button>
}
/>
</div>
);
}
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<string, typeof startup>();
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<Record<string, typeof view.extensions>>((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 (
<div className="page permissions-page">
<PageHeader
eyebrow={t("Permissions", "权限管理")}
title={t("Startup, context menus and popups.", "开机启动、右键菜单与弹窗拦截。")}
description={t(
"Everything the shell runs before you ask it to.",
"管理系统在你开口之前就自己运行的东西。",
)}
actions={
<Button
variant="secondary"
icon={<RefreshCw size={15} />}
onClick={() => void workspace.scan()}
disabled={workspace.scanning}
>
{t("Rescan", "重新扫描")}
</Button>
}
/>
<div className="perm-tabs" role="tablist">
{tabs.map((tab) => (
<button
key={tab.id}
role="tab"
aria-selected={workspace.tab === tab.id}
className={`perm-tab ${workspace.tab === tab.id ? "is-active" : ""}`}
onClick={() => workspace.setTab(tab.id)}
>
{tab.label}
<b>{tab.count}</b>
</button>
))}
</div>
{workspace.error ? (
<InlineError message={workspace.error} onDismiss={workspace.dismissError} />
) : null}
{workspace.tab === "startup" ? (
<section className="settings-section">
<SectionTitle
title={t("Startup items", "开机启动项")}
subtitle={t(
`${view.startupEnabledCount} of ${view.startupCount} entries start with Windows.`,
`共 ${view.startupCount} 项,其中 ${view.startupEnabledCount} 项已开启。`,
)}
/>
<label className="search-field">
<Search size={14} />
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={t("Filter by name or path…", "按名称或路径筛选…")}
/>
</label>
{Array.from(startupGroups.entries()).map(([software, items]) => (
<div key={software}>
<h4 className="perm-group">
{items.find((item) => item.icon)?.icon ? (
<img className="perm-group-icon" src={softwareIcon(items)} alt="" />
) : (
<span className="perm-group-icon perm-group-icon-fallback" aria-hidden="true">
{software.trim().slice(0, 1).toUpperCase()}
</span>
)}
<span>{software}</span>
<b>
{t(
`${items.filter((item) => item.enabled).length}/${items.length} on`,
`${items.filter((item) => item.enabled).length}/${items.length} 开启`,
)}
</b>
</h4>
<div className="perm-rows">
{items.map((item) => (
<div
className={`settings-row ${workspace.busyId === item.id ? "is-busy" : ""}`}
key={item.id}
>
<div className="perm-row">
<RowIcon icon={item.icon} label={item.displayName} />
<div>
<span>{item.name}</span>
<small title={item.command}>
{item.sourceLabel} · {scopeLabel(item.scope, t)}
{item.command ? ` · ${shortPath(item.command, 72)}` : ""}
</small>
</div>
</div>
<Toggle
checked={item.enabled}
disabled={workspace.busyId !== null}
onChange={(next) => void workspace.toggleStartup(item.id, next)}
label={`${item.name} ${item.enabled ? "disable" : "enable"}`}
/>
</div>
))}
</div>
</div>
))}
{startup.length === 0 ? (
<p className="perm-empty">{t("No matches.", "没有匹配的项目。")}</p>
) : null}
</section>
) : null}
{workspace.tab === "extensions" ? (
<section className="settings-section">
<SectionTitle
title={t("Context menu handlers", "右键菜单扩展")}
subtitle={t(
"Unregistered handlers disappear immediately; Squid keeps a restore recipe for each.",
"取消注册后右键菜单立即消失;Squid 为每一项保留恢复配方。",
)}
/>
<div className="perm-ext-head">
<div className="perm-cats" role="tablist" aria-label={t("Menu surfaces", "菜单位置")}>
{extCategories.map((point) => {
const entries = groupedExtensions[point];
const on = entries.filter((e) => e.registered).length;
return (
<button
key={point}
role="tab"
aria-selected={activeCategory === point}
className={`perm-cat ${activeCategory === point ? "is-active" : ""}`}
onClick={() => setExtCat(point)}
>
{point}
<b>
{on}/{entries.length}
</b>
</button>
);
})}
</div>
<label className="search-field">
<Search size={14} />
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={t("Filter by name, creator or module…", "按名称、创建者或模块筛选…")}
/>
</label>
</div>
<div className="perm-rows">
{(activeCategory ? groupedExtensions[activeCategory] : []).map((entry) => (
<div
className={`settings-row ${!entry.registered ? "is-muted" : ""} ${
workspace.busyId === entry.id ? "is-busy" : ""
}`}
key={entry.id}
>
<div className="perm-row">
<RowIcon icon={entry.icon} label={entry.friendlyName ?? entry.name} />
<div>
<span>{entry.friendlyName ?? entry.name}</span>
<small title={entry.module ?? entry.handler}>
{entry.publisher
? `${t("Creator", "创建者")} ${entry.publisher} · `
: ""}
{scopeLabel(entry.scope, t)}
{entry.module ? ` · ${shortPath(entry.module, 56)}` : ""}
{!entry.registered ? ` · ${t("removed", "已移除")}` : ""}
</small>
</div>
</div>
<Toggle
checked={entry.registered}
disabled={workspace.busyId !== null}
onChange={(next) => void workspace.toggleExtension(entry.id, next)}
label={`${entry.name} ${entry.registered ? "remove" : "restore"}`}
/>
</div>
))}
</div>
{extCategories.length === 0 ? (
<p className="perm-empty">{t("No matches.", "没有匹配的项目。")}</p>
) : null}
</section>
) : null}
{workspace.tab === "popup" ? (
<>
<section className="settings-section">
<SectionTitle
title={t("Popup blocker", "弹窗拦截")}
subtitle={t(
`Blocked ${workspace.closedTotal} popup windows since install.`,
`累计拦截 ${workspace.closedTotal} 次弹窗。`,
)}
action={
<Toggle
checked={view.watcherEnabled}
onChange={(next) => void workspace.setWatcher(next)}
label={t("Popup blocker switch", "弹窗拦截总开关")}
/>
}
/>
{workspace.recentClosed.length > 0 ? (
<div className="perm-recent">
<BellRing size={14} />
<span>
{workspace.recentClosed[0].process} · {workspace.recentClosed[0].title}
</span>
</div>
) : null}
</section>
<section className="settings-section">
<SectionTitle
title={t("Rules", "拦截规则")}
subtitle={t(
"Each rule closes windows from one program whose title contains the text.",
"每条规则会关闭指定程序中标题包含该文字的窗口。",
)}
/>
<div className="perm-rows">
{view.rules.map((rule, index) => (
<div className="settings-row" key={`${rule.exe}-${index}`}>
<div className="perm-row">
<RowIcon icon={rule.icon} label={rule.exe.split(/[\\/]/).pop() ?? rule.exe} />
<div>
<span>{rule.title}</span>
<small title={rule.exe}>
{shortPath(rule.exe, 64)} ·{" "}
{t(`closed ${rule.closed}×`, `已关闭 ${rule.closed} 次`)}
</small>
</div>
</div>
<div className="perm-row-actions">
<Toggle
checked={rule.enabled}
onChange={(next) => void workspace.toggleRule(index, next)}
label={`${rule.title} ${rule.enabled ? "disable" : "enable"}`}
/>
<IconButton
label={t("Remove rule", "删除规则")}
onClick={() => void workspace.removeRule(index)}
>
<Trash2 size={15} />
</IconButton>
</div>
</div>
))}
{view.rules.length === 0 ? (
<p className="perm-empty">
{t(
"No rules yet — pick a window below.",
"还没有规则,先从下面的当前窗口里“拦截”一个。",
)}
</p>
) : null}
</div>
</section>
<section className="settings-section">
<SectionTitle
title={t("Current windows", "当前窗口")}
subtitle={t(
"Refresh, then block a noisy window or close it once.",
"刷新后可直接拦截某个烦人的窗口,或只关闭这一次。",
)}
action={
<Button
variant="ghost"
size="sm"
icon={<RefreshCw size={14} />}
onClick={() => void workspace.refreshWindows()}
>
{t("Refresh", "刷新")}
</Button>
}
/>
<div className="perm-rows">
{workspace.windows.map((window) => (
<div className="settings-row" key={window.hwnd}>
<div className="perm-row">
<RowIcon icon={window.icon} label={window.process} />
<div>
<span>{window.title}</span>
<small title={window.exe ?? undefined}>{window.process}</small>
</div>
</div>
<div className="perm-row-actions">
<Button
size="sm"
variant="secondary"
disabled={!window.exe}
onClick={() => void workspace.addRule(window.hwnd, "contains")}
>
{t("Block", "拦截")}
</Button>
<IconButton
label={t("Close window", "关闭这个窗口")}
onClick={() => void workspace.closeWindow(window.hwnd)}
>
<X size={15} />
</IconButton>
</div>
</div>
))}
</div>
</section>
</>
) : null}
</div>
);
}

View File

@ -528,7 +528,7 @@ export function SettingsPage({
<div>
<strong>{t("Platform", "平台")}</strong>
<code>
{bootstrap.osName} {bootstrap.osVersion} · {bootstrap.arch} ·{" "}
{bootstrap.osVersion || bootstrap.osName} · {bootstrap.arch} ·{" "}
{bootstrap.hardware}
</code>
</div>

View File

@ -3,13 +3,14 @@ import {
BatteryCharging,
Cpu,
HardDrive,
MonitorSmartphone,
Network,
Power,
RefreshCw,
ShieldAlert,
Timer,
} from "lucide-react";
import { useState } from "react";
import { useEffect, useState } from "react";
import { useI18n } from "../i18n";
import { api } from "../lib/api";
import {
@ -21,7 +22,7 @@ import {
messageFrom,
percent,
} from "../lib/format";
import type { ProcessSample, SystemSnapshot } from "../types";
import type { ProcessSample, SystemSnapshot, WidgetPrefs } from "../types";
import type { SecurityWorkspace } from "../hooks/useSecurityWorkspace";
import { ProcessTable } from "../components/ProcessTable";
import {
@ -32,6 +33,7 @@ import {
MetricBar,
PageHeader,
SectionTitle,
Toggle,
UsageBar,
useToast,
} from "../components/ui";
@ -63,6 +65,45 @@ export function SystemPage({
const [tab, setTab] = useState<"performance" | "processes">(
initialProcessFilter ? "processes" : "performance",
);
const [widget, setWidget] = useState<WidgetPrefs | null>(null);
const [widgetBusy, setWidgetBusy] = useState(false);
useEffect(() => {
let cancelled = false;
let stop: (() => void) | null = null;
void api
.widgetGet()
.then((view) => !cancelled && setWidget(view.prefs))
.catch(() => undefined);
void api
.onWidgetSettings((next) => !cancelled && setWidget(next))
.then((unlisten) => {
if (cancelled) unlisten();
else stop = unlisten;
});
return () => {
cancelled = true;
stop?.();
};
}, []);
const toggleWidget = async (enabled: boolean) => {
setWidgetBusy(true);
try {
const next = await api.widgetSet({ enabled });
setWidget(next);
push(
enabled
? t("Desktop widget is now on.", "桌面实时监控已显示。")
: t("Desktop widget is now hidden.", "桌面实时监控已隐藏。"),
"success",
);
} catch (reason) {
push(messageFrom(reason), "danger");
} finally {
setWidgetBusy(false);
}
};
const stop = async () => {
if (!victim) return;
@ -137,7 +178,35 @@ export function SystemPage({
) : null}
<div className="system-performance" hidden={tab !== "performance"}>
<div className="system-gauges">
<section className={`system-widget-bar ${widget?.enabled ? "is-on" : ""}`}>
<span className="system-widget-icon">
<MonitorSmartphone size={18} />
</span>
<div className="system-widget-copy">
<strong>{t("Desktop live monitor", "桌面实时监控")}</strong>
<span>
{t(
"Keep these live stats on your desktop. Open the settings from the top of the widget.",
"把实时数据固定在桌面;设置可在小工具顶部下拉打开。",
)}
</span>
</div>
{widget ? (
<div className="system-widget-switch">
<span>{widget.enabled ? t("On desktop", "已显示") : t("Hidden", "已隐藏")}</span>
<Toggle
checked={widget.enabled}
disabled={widgetBusy}
onChange={(next) => void toggleWidget(next)}
label={t("Desktop live monitor", "桌面实时监控")}
/>
</div>
) : (
<span className="system-widget-loading">{t("Reading…", "读取中…")}</span>
)}
</section>
<div className="system-gauges">
<section className="system-gauge-card">
<div className="system-gauge-head">
<span className="metric-icon tone-primary">
@ -194,7 +263,7 @@ export function SystemPage({
<span>
{snapshot
? `${formatMemoryBytes(snapshot.memory.used)} / ${formatMemoryBytes(
snapshot.memory.total,
Math.max(snapshot.memory.installed, snapshot.memory.total),
)}`
: t("Reading memory…", "正在读取内存…")}
</span>
@ -218,6 +287,19 @@ export function SystemPage({
<span>{t("Used", "已用")}</span>
<strong>{formatMemoryBytes(snapshot?.memory.used ?? 0)}</strong>
</div>
{(snapshot?.memory.installed ?? 0) > (snapshot?.memory.total ?? 0) ? (
<div>
<span>{t("Reserved (GPU)", "硬件保留(含核显)")}</span>
<strong>
{formatMemoryBytes(
Math.max(
0,
(snapshot?.memory.installed ?? 0) - (snapshot?.memory.total ?? 0),
),
)}
</strong>
</div>
) : null}
<div>
<span>{t("Swap", "交换")}</span>
<strong>
@ -393,7 +475,10 @@ export function SystemPage({
<div>
<strong>{snapshot?.host.hostname || t("This computer", "这台电脑")}</strong>
<span>
{[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(" · ")}
</span>

View File

@ -0,0 +1,372 @@
/* The desktop live-monitor window content (index.html?view=widget): header bar
* with settings + collapse, live panels, and the settings dropdown. */
import { Activity, ChevronUp, Settings2 } from "lucide-react";
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 { WidgetCorner, WidgetPrefs } from "../types";
import { WidgetPanels, useHistory } from "../components/WidgetPanels";
import { Select } from "../components/ui";
import type { SystemSnapshot } from "../types";
const PANELS: { key: keyof WidgetPrefs; en: string; zh: string }[] = [
{ key: "panelRun", en: "Status", zh: "运行状态" },
{ key: "panelCpu", en: "CPU", zh: "CPU" },
{ key: "panelNetwork", en: "Network", zh: "网络" },
{ key: "panelDisk", en: "Disk I/O", zh: "存储读写" },
{ key: "panelStorage", en: "Storage", zh: "存储空间" },
];
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 WidgetWindow() {
const [prefs, setPrefs] = useState<WidgetPrefs | null>(null);
const [language, setLanguage] = useState<"zh" | "en">("en");
const [snapshot, setSnapshot] = useState<SystemSnapshot | null>(null);
const [open, setOpen] = useState(false);
const [history, bump] = useHistory();
const windowRef = useRef(getCurrentWindow());
const settingsRef = useRef<HTMLDivElement | null>(null);
const settingsButtonRef = useRef<HTMLButtonElement | null>(null);
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) => {
if (cancelled) return;
setPrefs(view.prefs);
setLanguage(view.language);
})
.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. The widget never shows the per-process
// table, so it rides the light refresh, and an all-collapsed widget goes
// silent until the header is opened again.
const collapsed = Boolean(prefs?.collapsed);
const hasPanels = Boolean(
prefs &&
(prefs.panelRun ||
prefs.panelCpu ||
prefs.panelNetwork ||
prefs.panelDisk ||
prefs.panelStorage),
);
const intervalMs = prefs?.intervalMs ?? 2000;
useEffect(() => {
if (!prefs?.enabled || collapsed || !hasPanels) return;
let live = true;
const tick = async () => {
if (!live) return;
// Desktop-layer windows report `document.hidden` whenever another app
// occludes them; ask Tauri whether the window is actually hidden.
try {
if ((await windowRef.current?.isVisible()) === false) return;
} catch {
/* older runtimes: keep sampling */
}
try {
const next = await api.systemSnapshot(false);
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, collapsed, hasPanels, intervalMs, prefs?.enabled]);
// Last persisted drag position; null while the widget is corner-docked.
const lastPos = useRef<{ x: number; y: number } | null>(null);
const patch = useCallback((values: Parameters<typeof api.widgetSet>[0]) => {
if (values.corner) lastPos.current = null;
void api
.widgetSet(values)
.then(setPrefs)
.catch((reason) => console.error(messageFrom(reason)));
}, []);
// Grow/shrink the window to the stacked cards so transparent space never
// eats desktop clicks (scrollHeight is CSS px == LogicalSize units).
// Only an actual height change may call setSize/redock: setSize answers
// with a resize event that re-arms the observer, and redock round-trips
// through widget_set → widget://settings → setPrefs. Without this gate the
// two effects re-fire each other forever (IPC storm + a config write per
// loop turn — the old "widget costs 3% CPU" bug).
const rootRef = useRef<HTMLDivElement | null>(null);
const lastFit = useRef(0);
const ready = Boolean(prefs);
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 + 12);
if (height === lastFit.current) return;
lastFit.current = height;
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(() => {
lastFit.current = 0;
});
});
};
const observer = new ResizeObserver(fit);
observer.observe(root);
fit();
return () => {
observer.disconnect();
window.cancelAnimationFrame(frame);
};
}, [ready, collapsed, open]);
const toggleCollapsed = () => {
setOpen(false);
patch({ collapsed: !collapsed });
};
const toggleSettings = () => {
if (!open && collapsed) patch({ collapsed: false });
setOpen((value) => !value);
};
useEffect(() => {
if (!open) return;
const close = (event: PointerEvent) => {
const target = event.target as Node;
if (
settingsRef.current?.contains(target) ||
settingsButtonRef.current?.contains(target)
) {
return;
}
setOpen(false);
};
document.addEventListener("pointerdown", close);
return () => document.removeEventListener("pointerdown", close);
}, [open]);
// Persist a dragged position after the pointer settles (the header is a
// native drag region, so poll once shortly after mouseup).
useEffect(() => {
const pressed = { current: null as { x: number; y: number } | null };
const onDown = (event: MouseEvent) => {
const target = event.target as HTMLElement;
if (
!target.closest("[data-tauri-drag-region]") ||
target.closest("button, input, select, .wd-settings")
) {
return;
}
pressed.current = { x: event.screenX, y: event.screenY };
};
const onUp = (event: MouseEvent) => {
const start = pressed.current;
pressed.current = null;
if (!start || Math.hypot(event.screenX - start.x, event.screenY - start.y) < 4) {
return;
}
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("mousedown", onDown);
window.addEventListener("mouseup", onUp);
return () => {
window.removeEventListener("mousedown", onDown);
window.removeEventListener("mouseup", onUp);
};
}, [patch]);
if (!prefs) return <div className="widget widget-loading" />;
const zh = language === "zh";
return (
<div
ref={rootRef}
className="widget widget-window"
style={{ opacity: (prefs.opacity ?? 100) / 100 }}
>
<div className="wd-card wd-head" data-tauri-drag-region>
<span className="wd-brand">
<Activity size={15} />
<b>{zh ? "实时监控" : "Live monitor"}</b>
</span>
<span className="wd-head-spacer" />
<button
ref={settingsButtonRef}
type="button"
className={`wd-head-btn ${open ? "is-active" : ""}`}
aria-label={zh ? "打开设置" : "Open settings"}
title={zh ? "设置" : "Settings"}
onClick={toggleSettings}
>
<Settings2 size={17} />
</button>
<button
type="button"
className={`wd-head-btn wd-chevron ${collapsed ? "is-collapsed" : ""}`}
aria-label={collapsed ? (zh ? "展开" : "Expand") : zh ? "折叠" : "Collapse"}
title={collapsed ? (zh ? "展开" : "Expand") : zh ? "折叠" : "Collapse"}
onClick={toggleCollapsed}
>
<ChevronUp size={18} />
</button>
</div>
{open ? (
<div ref={settingsRef} className="wd-card wd-settings">
<div className="wd-settings-head">
<div>
<h4>{zh ? "实时监控设置" : "Live monitor settings"}</h4>
<span>{zh ? "更改会立即生效" : "Changes apply immediately"}</span>
</div>
<button type="button" className="wd-settings-done" onClick={() => setOpen(false)}>
{zh ? "完成" : "Done"}
</button>
</div>
<div className="wd-settings-section">
<span className="wd-settings-label">{zh ? "面板" : "Panels"}</span>
{PANELS.map((panel) => (
<div className="wd-set-row" key={panel.key}>
<span>{zh ? panel.zh : panel.en}</span>
<button
type="button"
className={`wd-set-toggle ${prefs[panel.key] ? "is-on" : ""}`}
role="switch"
aria-checked={Boolean(prefs[panel.key])}
aria-label={zh ? panel.zh : panel.en}
onClick={() => patch({ [panel.key]: !prefs[panel.key] })}
/>
</div>
))}
</div>
<div className="wd-settings-section">
<span className="wd-settings-label">{zh ? "外观与行为" : "Appearance & behaviour"}</span>
<div className="wd-set-row">
<span>{zh ? "不透明度" : "Opacity"}</span>
<div className="wd-set-control">
<input
className="wd-range"
type="range"
min={90}
max={100}
value={prefs.opacity}
aria-label={zh ? "不透明度" : "Opacity"}
onChange={(event) => patch({ opacity: Number(event.target.value) })}
/>
<b>{prefs.opacity}%</b>
</div>
</div>
<div className="wd-set-row">
<span>{zh ? "更新频率" : "Refresh rate"}</span>
<Select
value={prefs.intervalMs}
label={zh ? "更新频率" : "Refresh rate"}
options={INTERVALS.map((ms) => ({
value: ms,
label: zh ? `${ms / 1000} 秒` : `${ms / 1000} seconds`,
}))}
onChange={(intervalMs) => patch({ intervalMs })}
/>
</div>
<div className="wd-set-row">
<span>{zh ? "显示位置" : "Dock corner"}</span>
<Select
value={prefs.corner}
label={zh ? "显示位置" : "Dock corner"}
placement="up"
options={CORNERS.map((corner) => ({
value: corner.id,
label: zh ? corner.zh : corner.en,
}))}
onChange={(corner) => patch({ corner })}
/>
</div>
<div className="wd-set-row">
<span>{zh ? "记住折叠状态" : "Remember folded state"}</span>
<button
type="button"
className={`wd-set-toggle ${prefs.rememberCollapsed ? "is-on" : ""}`}
role="switch"
aria-checked={prefs.rememberCollapsed}
aria-label={zh ? "记住折叠状态" : "Remember folded state"}
onClick={() =>
patch({ rememberCollapsed: !prefs.rememberCollapsed })
}
/>
</div>
</div>
<button
type="button"
className="wd-close-line"
onClick={() => patch({ enabled: false })}
>
{zh ? "关闭桌面实时监控" : "Turn off desktop monitor"}
</button>
</div>
) : null}
{!collapsed ? (
<WidgetPanels snapshot={snapshot} prefs={prefs} history={history} zh={zh} />
) : null}
{!collapsed && !hasPanels ? (
<div className="wd-card wd-empty">
{zh
? "所有面板都已关闭,点击右上角设置重新开启。"
: "All panels are off. Open Settings at the top right to bring them back."}
</div>
) : null}
</div>
);
}

View File

@ -641,6 +641,13 @@ select:focus-visible,
line-height: var(--nex-leading-body);
}
/* These two pages keep the description's line box so the empty state below
starts at the same place, but the copy itself was removed. */
.cleanup-page .page-header p,
.apps-page .page-header p {
visibility: hidden;
}
.page-header-actions {
display: flex;
flex: 0 0 auto;
@ -2032,6 +2039,12 @@ select:focus-visible,
letter-spacing: -0.025em;
}
.empty-title-spacer {
display: block;
height: 1.35em;
font-size: var(--nex-text-md);
}
.empty-state p,
.plan-placeholder p {
max-width: 440px;
@ -2944,6 +2957,68 @@ select:focus-visible,
font-weight: var(--nex-weight-medium);
}
.system-widget-bar {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 12px;
padding: 12px 15px;
border: 1px solid var(--nex-line);
border-radius: var(--radius-lg);
background:
linear-gradient(110deg, rgba(var(--nex-primary-rgb), 0.06), transparent 44%),
rgba(255, 255, 255, 0.76);
box-shadow: var(--shadow-card);
}
.system-widget-bar.is-on {
border-color: rgba(var(--nex-primary-rgb), 0.25);
}
.system-widget-icon {
display: grid;
flex: 0 0 auto;
width: 34px;
height: 34px;
place-items: center;
border-radius: 10px;
color: var(--nex-primary-strong);
background: rgba(var(--nex-primary-rgb), 0.12);
}
.system-widget-copy {
display: flex;
min-width: 0;
flex: 1;
flex-direction: column;
gap: 2px;
}
.system-widget-copy strong {
color: var(--nex-ink);
font-size: var(--nex-text-2xs);
font-weight: var(--nex-weight-semibold);
}
.system-widget-copy span {
color: var(--nex-muted);
font-size: var(--nex-text-3xs);
line-height: var(--nex-leading-body);
}
.system-widget-switch {
display: flex;
flex: 0 0 auto;
align-items: center;
gap: 9px;
}
.system-widget-switch > span,
.system-widget-loading {
color: var(--nex-muted);
font-size: var(--nex-text-3xs);
}
.system-gauges {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
@ -3913,6 +3988,11 @@ select:focus-visible,
right: 0;
}
.select-menu.is-up {
top: auto;
bottom: calc(100% + 5px);
}
.select-menu button {
display: flex;
align-items: center;
@ -4728,6 +4808,46 @@ select:focus-visible,
box-shadow: 0 3px 8px rgba(89, 51, 34, 0.07);
}
.confirm-updater-banner {
display: flex;
align-items: center;
gap: 10px;
margin-top: 10px;
padding: 10px 12px;
border: 1px solid rgba(23, 122, 84, 0.18);
border-radius: 10px;
background: rgba(23, 122, 84, 0.06);
color: #177a54;
}
.confirm-updater-banner > svg {
flex-shrink: 0;
}
.confirm-updater-banner div {
display: flex;
flex: 1;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.confirm-updater-banner strong {
font-size: var(--nex-text-3xs);
font-weight: var(--nex-weight-semibold);
}
.confirm-updater-banner span {
color: var(--nex-muted);
font-size: var(--nex-text-3xs);
line-height: var(--nex-leading-body);
}
.confirm-updater-banner button {
flex-shrink: 0;
color: #177a54;
}
/* Toast */
.toast-stack {
@ -6043,3 +6163,718 @@ select:focus-visible,
flex-wrap: wrap;
}
}
/* ---- 权限管理 (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: var(--nex-muted);
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(var(--nex-primary-rgb), 0.12);
color: var(--nex-primary-strong);
font-size: var(--nex-text-3xs);
font-weight: var(--nex-weight-semibold);
}
.perm-tab.is-active {
border-color: var(--nex-primary-soft);
background: rgba(var(--nex-primary-rgb), 0.1);
color: var(--nex-primary-strong);
font-weight: var(--nex-weight-medium);
}
.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: var(--nex-muted);
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(var(--nex-primary-rgb), 0.12);
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(var(--nex-primary-rgb), 0.1);
color: var(--nex-primary-strong);
font-weight: var(--nex-weight-medium);
}
.perm-cat.is-active b {
background: rgba(var(--nex-primary-rgb), 0.16);
color: var(--nex-primary-strong);
}
.perm-rows {
display: flex;
flex-direction: column;
}
.perm-rows .settings-row small {
overflow: hidden;
color: var(--nex-muted);
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-strong);
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: rgba(var(--nex-primary-rgb), 0.12);
color: var(--nex-primary-strong);
font-size: 11px;
font-weight: var(--nex-weight-semibold);
}
.perm-group b {
color: var(--nex-muted-soft);
font-size: var(--nex-text-3xs);
font-weight: var(--nex-weight-regular);
}
.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: rgba(var(--nex-primary-rgb), 0.12);
color: var(--nex-primary-strong);
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: var(--nex-muted);
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(var(--nex-primary-rgb), 0.06);
color: var(--nex-ink);
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: var(--nex-muted);
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);
}
}
/* ---- 桌面小工具 (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;
background: rgba(206, 213, 224, 0.9);
color: #1c2430;
}
.widget-window {
position: relative;
box-shadow: none;
font-size: 13px;
}
.widget-loading {
min-height: 80px;
}
.wd-card {
padding: 14px 16px;
border-radius: 18px;
background: #fafbfd;
color: #1c2430;
}
.wd-card h4 {
margin: 0;
font-size: 15px;
font-weight: 700;
letter-spacing: 0.01em;
}
.wd-head {
position: relative;
z-index: 2;
display: flex;
align-items: center;
gap: 4px;
padding: 9px 12px;
}
.wd-brand {
display: inline-flex;
align-items: center;
gap: 7px;
color: #3d4a5c;
}
.wd-brand b {
font-size: 13px;
font-weight: 700;
}
.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-head-btn.is-active {
color: #2f6bff;
background: rgba(47, 107, 255, 0.1);
}
.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;
}
.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;
}
.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;
}
/* CPU card: total % + one full-width row of per-core load bars */
.wd-cpu-total {
color: #16b364;
}
.wd-bars {
display: flex;
gap: 2px;
height: 30px;
margin-top: 10px;
}
.wd-bar {
display: flex;
flex: 1;
align-items: flex-end;
min-width: 0;
overflow: hidden;
border-radius: 3px;
background: #eef1f6;
}
.wd-bar i {
display: block;
width: 100%;
border-radius: 3px;
/* height + background come from the core load (连续渐变 in line) */
}
.wd-bars-caption {
margin-top: 6px;
color: #8b96a5;
font-size: 10px;
}
.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;
}
.wd-settings {
position: absolute;
top: 60px;
right: 10px;
left: 10px;
z-index: 3;
max-height: calc(100vh - 72px);
overflow-y: auto;
padding: 15px 16px 13px;
border: 1px solid rgba(28, 36, 48, 0.08);
box-shadow: 0 20px 55px rgba(24, 32, 45, 0.26), 0 4px 14px rgba(24, 32, 45, 0.12);
animation: wd-drop 0.16s ease-out both;
}
@keyframes wd-drop {
from {
opacity: 0;
transform: translateY(-5px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.wd-settings-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 4px;
}
.wd-settings-head > div {
display: flex;
flex-direction: column;
gap: 2px;
}
.wd-settings-head span {
color: #8a96a6;
font-size: 11px;
}
.wd-settings-done {
padding: 4px 9px;
border-radius: 8px;
background: rgba(47, 107, 255, 0.09);
color: #2f6bff;
font-size: 12px;
font-weight: 600;
}
.wd-settings-section {
margin-top: 10px;
padding-top: 8px;
border-top: 1px solid #eef1f6;
}
.wd-settings-label {
display: block;
padding: 2px 0 3px;
color: #8a96a6;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.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 > span {
min-width: 0;
}
.wd-set-row + .wd-set-row {
border-top: 1px solid #eef1f6;
}
.wd-set-control {
display: flex;
align-items: center;
gap: 7px;
}
.wd-set-control b {
min-width: 31px;
color: #6d798a;
font-size: 11px;
font-weight: 600;
text-align: right;
font-variant-numeric: tabular-nums;
}
.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: 104px;
accent-color: var(--nex-primary);
}
.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);
}
.wd-empty {
color: #6d798a;
font-size: 12px;
line-height: 1.5;
text-align: center;
}

View File

@ -4,6 +4,7 @@ export type PageId =
| "cleanup"
| "applications"
| "purge"
| "permissions"
| "storage"
| "system"
| "security"
@ -21,7 +22,8 @@ export type Category =
| "project-artifacts"
| "trash"
| "language-packs"
| "leftovers";
| "leftovers"
| "update-installers";
export type ItemKind = "path" | "contents" | "file";
export type LockReason =
| "app-running"
@ -95,12 +97,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;
@ -124,6 +147,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 {
@ -181,10 +207,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;
@ -540,3 +568,106 @@ export interface ProcessDetail {
parent: ProcessRow | null;
stopNote: string | null;
}
/* --------------------------------------------------------------- permissions */
export interface ManagedStartupItem {
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: ManagedStartupItem[];
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;
panelCpu: 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;
panelCpu?: 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;
}