Release Squid 0.1.3 with tray support
- Hide up-to-date messaging in the update panel - Simplify primary navigation to Overview, Cleanup, and Applications - Keep Squid running in the tray with cleanup and purge actions - Package macOS, Windows, and update manifest artifactsmain
|
|
@ -7,13 +7,19 @@
|
|||
# ── 构建产物 ─────────────────────────────────────────────────────────
|
||||
# cargo 的输出(debug / release / 各 target triple 都在它下面)。
|
||||
/target/
|
||||
/src-tauri/target/
|
||||
/artifacts/
|
||||
# scripts/release.sh 的产物:通用二进制 + tar.gz + sha256。
|
||||
# 发布走 GitHub Release 附件和 Homebrew formula,不进仓库。
|
||||
/dist/
|
||||
node_modules/
|
||||
.vite/
|
||||
src-tauri/gen/
|
||||
*.tar.gz
|
||||
*.sha256
|
||||
*.dmg
|
||||
*.zip
|
||||
*.exe
|
||||
|
||||
# ── 只读参考代码 ─────────────────────────────────────────────────────
|
||||
# 本地 clone 的第三方参考项目(自带 .git,数百 MB),不打包、不提交、不发版。
|
||||
|
|
@ -52,3 +58,7 @@ __pycache__/
|
|||
.env.*
|
||||
!.env.example
|
||||
*.local
|
||||
|
||||
# ── 显式纳管的发布产物 ───────────────────────────────────────────────
|
||||
!release/0.1.3/Squid-0.1.3-macOS-universal.dmg
|
||||
!release/0.1.3/Squid-Setup-0.1.3-win-x64.exe
|
||||
|
|
|
|||
|
|
@ -51,3 +51,41 @@ windows-build-test:
|
|||
allow_failure: true
|
||||
script:
|
||||
- pwsh -File scripts/ci-windows.ps1
|
||||
|
||||
desktop-frontend:
|
||||
stage: check
|
||||
image: node:22-bookworm
|
||||
cache:
|
||||
key:
|
||||
files: [pnpm-lock.yaml]
|
||||
paths: [.pnpm-store]
|
||||
before_script:
|
||||
- corepack enable
|
||||
- corepack prepare pnpm@8.6.6 --activate
|
||||
- pnpm config set store-dir .pnpm-store
|
||||
script:
|
||||
- pnpm install --frozen-lockfile
|
||||
- pnpm check
|
||||
- pnpm build
|
||||
artifacts:
|
||||
paths:
|
||||
- dist/
|
||||
expire_in: 1 day
|
||||
|
||||
desktop-rust-check:
|
||||
stage: check
|
||||
image: rust:1.85
|
||||
needs:
|
||||
- job: desktop-frontend
|
||||
artifacts: true
|
||||
cache:
|
||||
key:
|
||||
files: [src-tauri/Cargo.lock]
|
||||
paths: [.cargo/registry, .cargo/index, src-tauri/target/]
|
||||
before_script:
|
||||
- apt-get update
|
||||
- apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
|
||||
script:
|
||||
- cargo fmt --manifest-path src-tauri/Cargo.toml -- --check
|
||||
- cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
|
||||
- cargo test --manifest-path src-tauri/Cargo.toml --lib
|
||||
|
|
|
|||
|
|
@ -967,7 +967,7 @@ checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"
|
|||
|
||||
[[package]]
|
||||
name = "squid-cli"
|
||||
version = "0.1.0"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
|
|
@ -986,7 +986,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "squid-core"
|
||||
version = "0.1.0"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
|
|
@ -1005,7 +1005,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "squid-engine"
|
||||
version = "0.1.0"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
|
|
@ -1025,7 +1025,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "squid-platform"
|
||||
version = "0.1.0"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"dirs",
|
||||
"libc",
|
||||
|
|
@ -1042,7 +1042,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "squid-rules"
|
||||
version = "0.1.0"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"globset",
|
||||
"serde",
|
||||
|
|
@ -1054,7 +1054,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "squid-stats"
|
||||
version = "0.1.0"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"libc",
|
||||
|
|
@ -1066,7 +1066,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "squid-tui"
|
||||
version = "0.1.0"
|
||||
version = "0.1.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/*"]
|
||||
exclude = ["src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
version = "0.1.3"
|
||||
edition = "2021"
|
||||
rust-version = "1.80"
|
||||
license = "GPL-3.0-only"
|
||||
|
|
|
|||
38
README.md
|
|
@ -4,16 +4,40 @@ macOS / Windows 磁盘清理与系统监控工具:清理缓存与系统垃圾
|
|||
分析磁盘占用、实时监控资源。命令行与内置 TUI 共用同一套引擎,产物是一个静态二进制,
|
||||
不装后台进程、不写 shell 配置、不需要 root。
|
||||
|
||||
## 桌面应用
|
||||
|
||||
仓库现在同时提供 macOS / Windows 原生桌面程序 **Squid**。桌面端沿用 `nex_shift` 的技术栈
|
||||
(Tauri 2 + React 19 + TypeScript + Vite)和更新通道,直接复用本仓库现有 Rust 清理引擎:
|
||||
|
||||
- 界面:CleanMyMac 风格的概览、清理、应用卸载、深度清理、存储空间、系统状态、历史记录和设置;
|
||||
- 安全:GUI 只能选择后端扫描缓存中的索引,删除前仍由 Rust 引擎重新校验路径、锚点、白名单和锁定状态;
|
||||
- 更新:`releases` 分支中的 `squid-update.json` + 安装包,文件大小与 SHA256 始终校验,可选 Ed25519 清单签名;
|
||||
- 本地化:中英双语,跟随现有 `Settings` 语言偏好。
|
||||
|
||||
开发与构建:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm desktop:dev # 开发窗口
|
||||
pnpm desktop:build # 当前平台安装包
|
||||
bash scripts/build-macos-release.sh
|
||||
bash scripts/build-windows-release.sh
|
||||
```
|
||||
|
||||
完整的桌面架构、权限和发布说明见 [`docs/DESKTOP.md`](docs/DESKTOP.md) 与
|
||||
[`docs/RELEASE.md`](docs/RELEASE.md)。Nex 系列应用的统一主色与设计常量见
|
||||
[`docs/DESIGN.md`](docs/DESIGN.md)。下面的 CLI / TUI 文档仍然有效,三个入口共用同一套扫描与删除核心。
|
||||
|
||||
## 特性
|
||||
|
||||
| 能力 | 说明 | 入口 |
|
||||
| 能力 | 说明 | 桌面 / CLI |
|
||||
| --- | --- | --- |
|
||||
| 清理 | 内置规则 macOS 39 条 / Windows 30 条:应用与浏览器缓存、日志与崩溃报告、Xcode DerivedData、Windows Update 残留、废纸篓 / 回收站等 | `squid clean` |
|
||||
| 卸载 | 按名称定位 App(macOS 扫 `/Applications` 与 bundle id,Windows 读注册表卸载表),本体与散落的偏好、缓存、容器 / AppData 残留一起进入删除计划 | `squid uninstall` |
|
||||
| 深度清理 | `node_modules` 等项目构建产物、磁盘镜像、陈旧安装包与下载 | `squid purge` |
|
||||
| 存储分析 | 体积树与最大文件,可逐层下钻 | `squid analyze`、`state` 存储面板 |
|
||||
| 系统监控 | CPU / 内存 / 网络 / 磁盘 / 电池 / 温度 / 进程,并可结束选中的进程 | `squid status`、`state` 系统面板 |
|
||||
| 历史与撤销 | 每次真实删除写一条 JSON 账本,可将仍在废纸篓 / 回收站里的文件原样放回 | `squid history`、`squid undo` |
|
||||
| 清理 | 内置规则 macOS 39 条 / Windows 30 条:应用与浏览器缓存、日志与崩溃报告、Xcode DerivedData、Windows Update 残留、废纸篓 / 回收站等 | 桌面“清理” / `squid clean` |
|
||||
| 卸载 | 按名称定位 App(macOS 扫 `/Applications` 与 bundle id,Windows 读注册表卸载表),本体与散落的偏好、缓存、容器 / AppData 残留一起进入删除计划 | 桌面“应用程序” / `squid uninstall` |
|
||||
| 深度清理 | `node_modules` 等项目构建产物、磁盘镜像、陈旧安装包与下载 | 桌面“深度清理” / `squid purge` |
|
||||
| 存储分析 | 体积树与最大文件,可逐层下钻 | 桌面“存储空间” / `squid analyze` |
|
||||
| 系统监控 | CPU / 内存 / 网络 / 磁盘 / 电池 / 温度 / 进程,并可结束选中的进程 | 桌面“系统状态” / `squid status` |
|
||||
| 历史与撤销 | 每次真实删除写一条 JSON 账本,可将仍在废纸篓 / 回收站里的文件原样放回 | 桌面“历史记录” / `squid history`、`squid undo` |
|
||||
|
||||
- 语言:Rust 1.80+,workspace 由 7 个 crate 组成
|
||||
- 界面:中英双语文案,跟随系统语言;真彩色 / 256 色 / 无色三档自动适配
|
||||
|
|
|
|||
|
|
@ -33,6 +33,9 @@ pub struct Settings {
|
|||
pub language: Option<String>,
|
||||
/// Number of history sessions to keep.
|
||||
pub history_keep: usize,
|
||||
/// Whether the desktop app's first-run permission card has been dismissed.
|
||||
/// Older configs have no such field and therefore see the card once.
|
||||
pub desktop_setup_reviewed: bool,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
|
|
@ -63,6 +66,7 @@ impl Default for Settings {
|
|||
show_allocated: true,
|
||||
language: None,
|
||||
history_keep: 60,
|
||||
desktop_setup_reviewed: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -477,4 +481,11 @@ mod tests {
|
|||
Locale::detect(&Settings::default())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_existing_config_has_not_reviewed_the_desktop_setup() {
|
||||
let older = "history_keep = 60\n";
|
||||
let restored: Settings = toml::from_str(older).unwrap();
|
||||
assert!(!restored.desktop_setup_reviewed);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -455,16 +455,6 @@ select_by_default = false
|
|||
risky = true
|
||||
note = "Eject instead of deleting; squid never removes a mounted volume."
|
||||
|
||||
[[rule]]
|
||||
id = "old-downloads"
|
||||
category = "system"
|
||||
title = "Downloads older than 30 days"
|
||||
patterns = ["~/Downloads/*.dmg", "~/Downloads/*.pkg", "~/Downloads/*.zip"]
|
||||
mode = "files"
|
||||
os = ["macos"]
|
||||
min_age_days = 30
|
||||
select_by_default = false
|
||||
|
||||
[[rule]]
|
||||
id = "user-trash"
|
||||
category = "trash"
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ use std::collections::VecDeque;
|
|||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use sysinfo::{
|
||||
DiskUsage, Disks, Networks, ProcessRefreshKind, ProcessesToUpdate, RefreshKind, System,
|
||||
DiskRefreshKind, DiskUsage, Disks, Networks, ProcessRefreshKind, ProcessesToUpdate,
|
||||
RefreshKind, System,
|
||||
};
|
||||
|
||||
mod battery;
|
||||
|
|
@ -198,7 +199,13 @@ impl Sampler {
|
|||
);
|
||||
Sampler {
|
||||
networks: Networks::new_with_refreshed_list(),
|
||||
disks: Disks::new_with_refreshed_list(),
|
||||
// Capacity comes from squid-platform's statvfs path. Asking
|
||||
// sysinfo for storage here uses CoreFoundation's
|
||||
// `AvailableCapacityForImportantUsage`, which enumerates every
|
||||
// CacheDelete provider on macOS and can prompt for media access.
|
||||
disks: Disks::new_with_refreshed_list_specifics(
|
||||
DiskRefreshKind::nothing().with_io_usage(),
|
||||
),
|
||||
system,
|
||||
last: Instant::now(),
|
||||
host: HostInfo::gather(),
|
||||
|
|
@ -247,7 +254,8 @@ impl Sampler {
|
|||
ProcessRefreshKind::nothing().with_cpu().with_memory(),
|
||||
);
|
||||
self.networks.refresh(true);
|
||||
self.disks.refresh(true);
|
||||
self.disks
|
||||
.refresh_specifics(true, DiskRefreshKind::nothing().with_io_usage());
|
||||
|
||||
let seconds = elapsed.as_secs_f64();
|
||||
let cpu = cpu_stats(&self.system);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,112 @@
|
|||
# Nex 应用视觉规范
|
||||
|
||||
版本:1.0
|
||||
状态:Nex 系列应用统一标准
|
||||
基准实现:`nex_shift` 的主色系
|
||||
|
||||
## 1. 原则
|
||||
|
||||
Nex 系列应用共用一套暖色品牌体系。Shift 已经使用的橙色是主品牌色,
|
||||
Squid 以及后续 Nex 应用不得再各自定义蓝色或其它颜色的主操作色。
|
||||
|
||||
- 主操作、选中态、焦点环和进度使用 Nex 主色。
|
||||
- 页面底色、卡片和正文使用暖中性色,不使用冷蓝色底。
|
||||
- 绿色、红色、黄色只表达成功、危险和警告,不作为品牌主色。
|
||||
- 分类色可以保留各自的语义色,但不得替代主操作色。
|
||||
- 新界面必须引用 `src/styles.css` 中的 `--nex-*` 常量,不写新的主色十六进制值。
|
||||
|
||||
## 2. 品牌常量
|
||||
|
||||
这些值同时写在 `src/styles.css` 的 `:root` 中,是运行时唯一来源。
|
||||
|
||||
| 常量 | 值 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `--nex-primary` | `#F26A33` | 主按钮、选中态、焦点、进度 |
|
||||
| `--nex-primary-hover` | `#E45C2A` | 主色悬停 |
|
||||
| `--nex-primary-strong` | `#D94F1F` | 主色深阶、主按钮渐变终点 |
|
||||
| `--nex-primary-pressed` | `#C94A1D` | 按下态 |
|
||||
| `--nex-primary-soft` | `#FFF0E7` | 主色浅底、权限提示 |
|
||||
| `--nex-primary-tint` | `#FFF7F2` | 选中卡片、弱高亮 |
|
||||
| `--nex-ink` | `#342019` | 正文 |
|
||||
| `--nex-ink-strong` | `#24120A` | 标题 |
|
||||
| `--nex-muted` | `#7D6256` | 次级文字 |
|
||||
| `--nex-muted-soft` | `#A98F80` | 说明文字 |
|
||||
| `--nex-line` | `rgba(89, 51, 34, 0.10)` | 分隔线 |
|
||||
| `--nex-paper` | `#FBF7F2` | 面板 |
|
||||
| `--nex-cream` | `#FFF6EE` | 浅色表面 |
|
||||
| `--nex-canvas` | `#F5EEE7` | 应用底色 |
|
||||
|
||||
主色高亮需要透明度时使用 `rgba(var(--nex-primary-rgb), α)`,其中
|
||||
`--nex-primary-rgb` 为 `242, 106, 51`。
|
||||
|
||||
## 3. 图标渐变
|
||||
|
||||
应用图标的品牌渐变沿用 Shift:
|
||||
|
||||
- 起点 `#FFB25C`
|
||||
- 中段 `#FF6B35`
|
||||
- 终点 `#C66BFF`
|
||||
|
||||
图标主体的描边和阴影必须使用暖色,不得保留旧版蓝色。
|
||||
|
||||
### 侧栏品牌锁定
|
||||
|
||||
侧栏标识直接使用打包进应用的 `src-tauri/icons/128x128.png`,不得维护第二份
|
||||
图标资源。默认视觉为 37 × 37 px、12 px 圆角。
|
||||
|
||||
- 一级标题固定为 `Squid`,使用 `--nex-text-lg` / `--nex-weight-display`。
|
||||
- 中文二级标题固定为 `给你的电脑洗个澡`;英文为
|
||||
`Give your computer a bath`,使用 `--nex-text-3xs` / `--nex-weight-body`。
|
||||
- 所有 Nex 应用使用同一锁定结构:应用图标、产品名、产品定位短句。
|
||||
|
||||
## 4. 字体规范
|
||||
|
||||
字体与 Shift 使用同一套系统字体栈和字号阶梯。所有新界面必须引用下面的
|
||||
常量,不得再写 7–10px 等阶梯外的字号。
|
||||
|
||||
| 常量 | 值 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `--nex-font-sans` | `-apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif` | 界面正文 |
|
||||
| `--nex-font-mono` | `"SF Mono", "Cascadia Code", ui-monospace, monospace` | 路径、哈希、配置值 |
|
||||
| `--nex-text-3xs` | `11px` | 最小辅助文字与标签 |
|
||||
| `--nex-text-2xs` | `12.5px` | 正文说明、列表文字 |
|
||||
| `--nex-text-xs` | `13.5px` | 面板标题 |
|
||||
| `--nex-text-sm` | `14.5px` | 强调正文 |
|
||||
| `--nex-text-md` | `16px` | 区块标题 |
|
||||
| `--nex-text-lg` | `18px` | 品牌与重点标题 |
|
||||
| `--nex-text-xl` | `21px` | 对话框标题 |
|
||||
| `--nex-text-hero` | `clamp(28px, 3vw, 38px)` | 页面主标题 |
|
||||
|
||||
字重沿用 Shift 的层级:`540` 正文、`620` 中等、`650` 半粗、`680` 粗体、
|
||||
`720` 重体、`760` 品牌展示。对应常量为 `--nex-weight-body`、
|
||||
`--nex-weight-medium`、`--nex-weight-semibold`、`--nex-weight-bold`、
|
||||
`--nex-weight-heavy`、`--nex-weight-display`。
|
||||
|
||||
行高常量:`--nex-leading-tight: 1.1` 用于标题,
|
||||
`--nex-leading-body: 1.55` 用于说明正文。
|
||||
|
||||
## 5. 组件规则
|
||||
|
||||
- 主按钮:`#FF9664 → --nex-primary → --nex-primary-strong` 的暖色渐变。
|
||||
- 次按钮:暖白表面、暖棕文字,悬停时使用主色描边。
|
||||
- 选中卡片:`--nex-primary-tint` 背景与 10% 主色描边。
|
||||
- 焦点环:`rgba(var(--nex-primary-rgb), 0.55)`,宽度 2px。
|
||||
- 进度条、开关、勾选框:主色或主色渐变。
|
||||
- 正文不使用纯黑;标题使用 `--nex-ink-strong`。
|
||||
- 更新面板面向使用者,只展示当前系统版本、版本状态、更新说明、进度与操作;
|
||||
更新地址、安装包文件名和哈希留在后端校验流程中,不进入常规界面。
|
||||
|
||||
## 6. 旧变量兼容
|
||||
|
||||
现有组件仍引用 `--blue`、`--blue-deep`、`--blue-soft`。这三个变量已经
|
||||
分别别名为 `--nex-primary`、`--nex-primary-strong`、`--nex-primary-soft`,
|
||||
因此不会再渲染蓝色。新增代码应直接使用 `--nex-*` 常量;迁移旧组件时
|
||||
可以逐步移除 `--blue-*` 别名,但不得改回独立颜色值。
|
||||
|
||||
## 7. 验收
|
||||
|
||||
- 全应用不出现蓝色主按钮、蓝色选中态或蓝色焦点环。
|
||||
- 页面底色为 `#F5EEE7`,面板为暖白,不使用冷蓝渐变。
|
||||
- Settings、首次启动权限卡和更新面板共享同一套主色。
|
||||
- 应用图标与界面使用同一组暖色品牌常量。
|
||||
- 正文和标签不小于 11px,标题使用统一字号阶梯,不出现 7–10px 的正文。
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
# Squid desktop
|
||||
|
||||
Squid has two native desktop builds, macOS and Windows, built with the same
|
||||
technology stack as `nex_shift`:
|
||||
|
||||
- Tauri 2 shell and updater handoff
|
||||
- React 19 + TypeScript UI
|
||||
- Vite 6 development and asset pipeline
|
||||
- The existing `squid-core`, `squid-engine`, `squid-platform` and `squid-stats`
|
||||
Rust workspace
|
||||
|
||||
The desktop application is a second frontend over the same engine used by the
|
||||
CLI and TUI. It does not maintain a separate cleanup implementation.
|
||||
|
||||
The shared Nex colour and component standard lives in
|
||||
[`DESIGN.md`](DESIGN.md). Squid uses the same primary palette as `nex_shift`.
|
||||
|
||||
## Run locally
|
||||
|
||||
Prerequisites:
|
||||
|
||||
- Node.js 20+ and pnpm
|
||||
- Rust toolchain and Cargo
|
||||
- macOS: Xcode Command Line Tools
|
||||
- Windows: MSVC build tools and WebView2
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm desktop:dev
|
||||
```
|
||||
|
||||
The Vite-only development page cannot call Tauri commands. Use `desktop:dev`
|
||||
when exercising scans, deletes, storage analysis, system data, or updates.
|
||||
|
||||
Useful checks:
|
||||
|
||||
```bash
|
||||
pnpm check
|
||||
pnpm build
|
||||
cargo test --manifest-path src-tauri/Cargo.toml --lib
|
||||
cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
|
||||
```
|
||||
|
||||
## Screens
|
||||
|
||||
| Screen | What it does |
|
||||
| --- | --- |
|
||||
| Computer overview | Smart scan entry, disk health, cleanup result categories and live CPU/memory/storage summaries |
|
||||
| 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 |
|
||||
| Storage | Measures a chosen folder, exposes the largest children, drills down, and finds the largest files |
|
||||
| System | Live CPU, memory, network, disk, battery, volume and process data; process termination asks for confirmation |
|
||||
| History | Lists cleanup sessions, shows the ledger, restores files that are still in Trash/Recycle Bin, and opens the bin |
|
||||
| Settings | Language, deletion mode, history retention, protected paths, local file locations, and software updates |
|
||||
|
||||
`⌘1`–`⌘8` on macOS and `Ctrl+1`–`Ctrl+8` on Windows switch screens.
|
||||
|
||||
## Tray
|
||||
|
||||
Squid keeps running after its main window is closed. The tray menu can reopen
|
||||
the window and jump directly to Daily cleanup, Uninstall apps or Deep Clean.
|
||||
Use **Quit Squid** in the same menu to stop the background process.
|
||||
|
||||
## Safety boundary
|
||||
|
||||
The UI never submits a path for deletion. A scan returns an array of items and a
|
||||
process-local scan ID. Delete commands accept only indices into that cached scan
|
||||
or removal plan. The Rust command layer then:
|
||||
|
||||
1. Rejects out-of-range indices.
|
||||
2. Forces locked items to remain unselected.
|
||||
3. Reconstructs the same `CleanupItem` set the scanner produced.
|
||||
4. Calls `squid-engine::delete`, which re-validates ownership, safety anchors,
|
||||
protected locations and the user whitelist before removing anything.
|
||||
|
||||
Locked items remain visible but cannot be selected. A permanent delete always
|
||||
requires the confirm sheet; the default mode comes from the same `Settings`
|
||||
file used by the CLI and TUI.
|
||||
|
||||
## Storage permissions on macOS
|
||||
|
||||
Squid measures file metadata only. The normal cleanup scan does not cover
|
||||
`~/Downloads`, and disk capacity is read with `statvfs` rather than through
|
||||
CoreFoundation's CacheDelete-aware volume API, so neither path asks for access
|
||||
to downloads or the media library.
|
||||
|
||||
Full Disk Access is optional. On first launch Squid shows one setup card that
|
||||
reports whether the app can read TCC-protected locations such as Safari, Mail and
|
||||
Messages data. It does not force a permission prompt and does not block the app:
|
||||
without access those locations are skipped. The same status and a link to
|
||||
**System Settings › Privacy & Security › Full Disk Access** remain in
|
||||
**Settings › System permissions**. The check runs again when the window regains
|
||||
focus, and the card can be reopened by setting `desktop_setup_reviewed = false`
|
||||
in `config.toml`.
|
||||
|
||||
Folder-dependent tools remain explicit. Storage analysis starts only after you
|
||||
choose a folder. macOS may still show a folder permission prompt when a folder
|
||||
you selected contains protected locations. Deny any access you do not want
|
||||
Squid to have; the rest of the application still works. Deep Clean's default
|
||||
project roots can include Desktop and Documents, so edit that list before
|
||||
scanning if you do not want those prompts.
|
||||
|
||||
## Updates
|
||||
|
||||
The update implementation mirrors `nex_shift`:
|
||||
|
||||
- A build derives its feed from the git `origin` remote or `SQUID_UPDATE_URL`.
|
||||
- The feed is an orphan `releases` branch containing installers and
|
||||
`squid-update.json`.
|
||||
- The manifest always provides exact byte size and SHA256; both are checked
|
||||
before an installer can run.
|
||||
- A build made with `SQUID_UPDATE_PUBKEY` additionally requires and verifies
|
||||
`squid-update.sig`, a detached Ed25519 signature over the manifest's exact
|
||||
bytes.
|
||||
- The application checks at most once a day when automatic checks are enabled;
|
||||
the last-check day lives in `updates.json`.
|
||||
- macOS mounts the DMG after exit and swaps `Squid.app` with rollback on failure.
|
||||
- Windows waits for `squid-desktop.exe` to exit, runs the same NSIS installer
|
||||
silently, then relaunches it from `%LOCALAPPDATA%\Programs\Squid`.
|
||||
|
||||
See [`RELEASE.md`](RELEASE.md) for the publishing commands, artifact names, and
|
||||
signing setup.
|
||||
|
||||
## Native CLI remains separate
|
||||
|
||||
The desktop binary is `squid-desktop`. The existing `squid` binary continues to
|
||||
contain the CLI/TUI and is not replaced by the desktop package. Both use the same
|
||||
configuration and history directories, so a cleanup made in either entry point
|
||||
appears in the other one's history.
|
||||
|
|
@ -0,0 +1,175 @@
|
|||
# Desktop release and update channel
|
||||
|
||||
Squid uses the same release model as `nex_shift`: a git branch is the update
|
||||
server. No object storage or release API is required.
|
||||
|
||||
## Artifact names
|
||||
|
||||
Both installers must carry the exact version from `src-tauri/tauri.conf.json`:
|
||||
|
||||
```text
|
||||
artifacts/Squid-<version>-macOS-universal.dmg
|
||||
artifacts/Squid-Setup-<version>-win-x64.exe
|
||||
```
|
||||
|
||||
Additional readmes and checksum files may travel with them, but
|
||||
`scripts/publish-release.sh` rejects any other installer-like file. This prevents
|
||||
an old DMG or stale EXE from silently entering a new release.
|
||||
|
||||
## macOS
|
||||
|
||||
```bash
|
||||
scripts/build-macos-release.sh
|
||||
```
|
||||
|
||||
The script installs both Apple Rust targets, builds a universal app and DMG,
|
||||
verifies the code signature and image, then copies the result to the versioned
|
||||
artifact name. Use `--skip-build` to re-verify and repackage an existing build.
|
||||
|
||||
For distribution outside local testing, replace the ad-hoc identity in
|
||||
`src-tauri/tauri.conf.json` with a Developer ID identity and notarize the app.
|
||||
The CI configuration does not hold Apple credentials.
|
||||
|
||||
## Windows
|
||||
|
||||
On macOS:
|
||||
|
||||
```bash
|
||||
pnpm add -g cargo-xwin
|
||||
scripts/build-windows-release.sh
|
||||
```
|
||||
|
||||
The script builds the React bundle for the WebView2 target, cross-compiles
|
||||
`x86_64-pc-windows-msvc`, checks the PE machine and embedded frontend, then uses
|
||||
NSIS to produce `Squid-Setup-<version>-win-x64.exe`.
|
||||
|
||||
On Windows, run the same script from Git Bash or MSYS2. It uses the native MSVC
|
||||
toolchain instead of `cargo-xwin`. The installer is per-user and installs to:
|
||||
|
||||
```text
|
||||
%LOCALAPPDATA%\Programs\Squid
|
||||
```
|
||||
|
||||
The executable inside is `squid-desktop.exe`, matching both the NSIS installer
|
||||
and the update handoff script.
|
||||
|
||||
## Signing key
|
||||
|
||||
Create the Ed25519 key once, outside the repository:
|
||||
|
||||
```bash
|
||||
python3 -m pip install cryptography
|
||||
python3 scripts/release-key.py keygen ~/.config/squid-release/release.ed25519
|
||||
```
|
||||
|
||||
Build with the public key so the binary refuses a manifest that is missing or
|
||||
incorrectly signed:
|
||||
|
||||
```bash
|
||||
export SQUID_RELEASE_KEY=~/.config/squid-release/release.ed25519
|
||||
scripts/build-macos-release.sh
|
||||
scripts/build-windows-release.sh
|
||||
```
|
||||
|
||||
Both build scripts derive `SQUID_UPDATE_PUBKEY` from
|
||||
`${SQUID_RELEASE_KEY%.ed25519}.pub`. Keep the private key out of git.
|
||||
|
||||
## Publish
|
||||
|
||||
Build both installers first. The publish script rebuilds the `releases` branch
|
||||
as one fresh root commit, so old installers never accumulate in history:
|
||||
|
||||
```bash
|
||||
scripts/publish-release.sh \
|
||||
--notes RELEASE_NOTES.md \
|
||||
--key ~/.config/squid-release/release.ed25519
|
||||
```
|
||||
|
||||
Useful checks:
|
||||
|
||||
```bash
|
||||
scripts/publish-release.sh --dry-run --key ~/.config/squid-release/release.ed25519
|
||||
scripts/publish-release.sh --no-push --key ~/.config/squid-release/release.ed25519
|
||||
```
|
||||
|
||||
The branch contains:
|
||||
|
||||
```text
|
||||
squid-update.json
|
||||
squid-update.sig
|
||||
Squid-<version>-macOS-universal.dmg
|
||||
Squid-Setup-<version>-win-x64.exe
|
||||
```
|
||||
|
||||
## Feed URL
|
||||
|
||||
`src-tauri/build.rs` derives the manifest URL from `origin`:
|
||||
|
||||
| Remote | Feed |
|
||||
| --- | --- |
|
||||
| Gitea / Forgejo | `https://host/owner/repo/raw/branch/releases/squid-update.json` |
|
||||
| GitHub | `https://github.com/owner/repo/raw/releases/squid-update.json` |
|
||||
| GitLab | `https://gitlab.example/owner/repo/-/raw/releases/squid-update.json` |
|
||||
|
||||
`SQUID_UPDATE_URL` overrides it at build time. The same variable at runtime
|
||||
overrides the baked value, which is useful for staging feeds:
|
||||
|
||||
```bash
|
||||
SQUID_UPDATE_URL=https://host/owner/repo/raw/branch/staging/squid-update.json \
|
||||
open Squid.app
|
||||
```
|
||||
|
||||
## Manifest
|
||||
|
||||
Schema version 1:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": 1,
|
||||
"version": "0.2.0",
|
||||
"date": "2026-11-03",
|
||||
"notes": "Release notes shown in Settings.",
|
||||
"artifacts": {
|
||||
"macos": {
|
||||
"file": "Squid-0.2.0-macOS-universal.dmg",
|
||||
"sha256": "<64 lowercase hex characters>",
|
||||
"size": 123456789
|
||||
},
|
||||
"windows": {
|
||||
"file": "Squid-Setup-0.2.0-win-x64.exe",
|
||||
"sha256": "<64 lowercase hex characters>",
|
||||
"size": 45678901
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Windows ARM64 first looks for `windows-arm64`, then falls back to `windows`.
|
||||
Unknown artifact keys are ignored. A larger manifest schema is refused.
|
||||
|
||||
## Update flow and trust
|
||||
|
||||
1. The app fetches the manifest from the release branch.
|
||||
2. If the build has a public key, `squid-update.sig` must verify over the
|
||||
manifest's exact bytes.
|
||||
3. Version comparison follows semver, including prerelease precedence.
|
||||
4. The platform installer is downloaded to a temporary directory.
|
||||
5. Exact byte size and SHA256 are checked. Any mismatch deletes the download.
|
||||
6. Only a verified file can reach **Install and restart**.
|
||||
7. The helper waits for Squid to exit, applies the update, and reopens the app.
|
||||
|
||||
The signature proves the manifest came from the release key. SHA256 and size
|
||||
prove the downloaded installer is the file that manifest names. HTTPS protects
|
||||
the transport; it is not treated as a substitute for either check.
|
||||
|
||||
## Version bump
|
||||
|
||||
Keep these four values equal:
|
||||
|
||||
- `Cargo.toml` workspace version
|
||||
- `src-tauri/Cargo.toml`
|
||||
- `src-tauri/tauri.conf.json`
|
||||
- `package.json`
|
||||
|
||||
Then run frontend checks, Rust tests (including `src-tauri`), build both
|
||||
installers, and publish.
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#f5eee7" />
|
||||
<title>Squid</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
{
|
||||
"name": "squid-desktop",
|
||||
"private": true,
|
||||
"version": "0.1.3",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --port 1420 --strictPort",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"check": "tsc --noEmit",
|
||||
"tauri": "tauri",
|
||||
"desktop:dev": "tauri dev",
|
||||
"desktop:build": "tauri build",
|
||||
"mac:release": "bash scripts/build-macos-release.sh",
|
||||
"windows:release": "bash scripts/build-windows-release.sh"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.12.4",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.3",
|
||||
"@tauri-apps/plugin-opener": "^2.7.2",
|
||||
"lucide-react": "^0.468.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2.12.3",
|
||||
"@types/react": "^19.1.0",
|
||||
"@types/react-dom": "^19.1.0",
|
||||
"@vitejs/plugin-react": "^4.4.0",
|
||||
"typescript": "~5.8.3",
|
||||
"vite": "^6.3.0"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
Squid 0.1.3 - Windows x64
|
||||
|
||||
系统要求
|
||||
--------
|
||||
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
|
||||
- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid
|
||||
启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime:
|
||||
https://developer.microsoft.com/microsoft-edge/webview2/
|
||||
- 安装与运行都不需要管理员权限。安装位置为
|
||||
%LOCALAPPDATA%\Programs\Squid。
|
||||
|
||||
安装
|
||||
----
|
||||
1. 运行 Squid-Setup-0.1.3-win-x64.exe。
|
||||
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
|
||||
3. 卸载请在 Windows“设置 > 应用”中移除 Squid。
|
||||
|
||||
更新
|
||||
----
|
||||
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
|
||||
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
|
||||
还会验证清单的 Ed25519 签名。
|
||||
|
||||
校验
|
||||
----
|
||||
PowerShell:
|
||||
Get-FileHash .\Squid-Setup-0.1.3-win-x64.exe -Algorithm SHA256
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
d44c41f88496652384380ceca1bff24656acb815f78fc32a57a35f29dce5c6d7 Squid-0.1.3-macOS-universal.dmg
|
||||
64619e91347b64c3fa3e1ac69b1148667e06c920e756a473b370a4abaf82de2b Squid-Setup-0.1.3-win-x64.exe
|
||||
56fc98cb26b7ea24959eea9b043e96d9dfa0b635ee049d3c263f0be58d9b3960 README-Windows-x64.txt
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"schema": 1,
|
||||
"version": "0.1.3",
|
||||
"date": "2026-11-05",
|
||||
"notes": "Squid 0.1.3\n\n- 软件更新仅在发现新版本时显示版本变化与更新说明。\n- 左侧导航精简为「电脑概览、日常清理、应用卸载」。\n- 关闭主窗口后常驻托盘;托盘菜单提供「日常清理、应用卸载、深度清理」及退出。\n- macOS 与 Windows 同步发布 0.1.3。",
|
||||
"artifacts": {
|
||||
"macos": {
|
||||
"file": "Squid-0.1.3-macOS-universal.dmg",
|
||||
"sha256": "d44c41f88496652384380ceca1bff24656acb815f78fc32a57a35f29dce5c6d7",
|
||||
"size": 10688482
|
||||
},
|
||||
"windows": {
|
||||
"file": "Squid-Setup-0.1.3-win-x64.exe",
|
||||
"sha256": "64619e91347b64c3fa3e1ac69b1148667e06c920e756a473b370a4abaf82de2b",
|
||||
"size": 3343118
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
#!/bin/bash
|
||||
# Build the universal macOS DMG and copy it to the versioned release name.
|
||||
#
|
||||
# scripts/build-macos-release.sh [--skip-build]
|
||||
#
|
||||
# Produces artifacts/Squid-<version>-macOS-universal.dmg.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if [ "$(uname -s)" != "Darwin" ]; then
|
||||
echo "macOS release must be built on macOS." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export PATH="$HOME/.cargo/bin:$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:$PATH"
|
||||
export RUSTUP_TOOLCHAIN=stable-aarch64-apple-darwin
|
||||
|
||||
if [ -z "${SQUID_UPDATE_PUBKEY:-}" ] && [ -n "${SQUID_RELEASE_KEY:-}" ]; then
|
||||
SQUID_UPDATE_PUBKEY=$(python3 scripts/release-key.py pubkey "${SQUID_RELEASE_KEY%.ed25519}.pub")
|
||||
export SQUID_UPDATE_PUBKEY
|
||||
fi
|
||||
|
||||
SKIP_BUILD=0
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--skip-build) SKIP_BUILD=1 ;;
|
||||
*) echo "usage: $0 [--skip-build]" >&2; exit 2 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
|
||||
BUNDLE_DIR="src-tauri/target/universal-apple-darwin/release/bundle"
|
||||
APP="$BUNDLE_DIR/macos/Squid.app"
|
||||
OUTPUT="artifacts/Squid-$VERSION-macOS-universal.dmg"
|
||||
|
||||
rustup target add x86_64-apple-darwin aarch64-apple-darwin
|
||||
|
||||
if [ "$SKIP_BUILD" != "1" ]; then
|
||||
if [ -n "${SQUID_UPDATE_PUBKEY:-}" ]; then
|
||||
echo "== release key baked in: ${SQUID_UPDATE_PUBKEY:0:12}… =="
|
||||
else
|
||||
echo "== no release key: this build will report the feed as unsigned =="
|
||||
fi
|
||||
pnpm tauri build --target universal-apple-darwin --bundles app,dmg
|
||||
fi
|
||||
|
||||
test -d "$APP"
|
||||
DMG=$(find "$BUNDLE_DIR/dmg" -maxdepth 1 -type f -name '*.dmg' -print -quit)
|
||||
test -n "$DMG"
|
||||
|
||||
codesign --verify --deep --strict "$APP"
|
||||
hdiutil verify "$DMG" >/dev/null
|
||||
mkdir -p artifacts
|
||||
cp -f "$DMG" "$OUTPUT"
|
||||
hdiutil verify "$OUTPUT" >/dev/null
|
||||
|
||||
echo "== macOS release =="
|
||||
ls -lh "$OUTPUT"
|
||||
|
|
@ -0,0 +1,178 @@
|
|||
#!/bin/bash
|
||||
# Build the Windows x64 installer and refresh artifacts/SHA256SUMS.txt.
|
||||
#
|
||||
# scripts/build-windows-release.sh [--skip-build]
|
||||
#
|
||||
# On macOS this cross-compiles with cargo-xwin. On Windows (Git Bash/MSYS2) it
|
||||
# uses the native MSVC toolchain. Both paths feed the same NSIS installer.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
ROOT="$PWD"
|
||||
VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
|
||||
TARGET=x86_64-pc-windows-msvc
|
||||
INSTALLER="artifacts/Squid-Setup-$VERSION-win-x64.exe"
|
||||
NOTES="artifacts/README-Windows-x64.txt"
|
||||
HOST=$(uname -s)
|
||||
|
||||
if [ "$HOST" = "Darwin" ]; then
|
||||
export PATH="$HOME/.cargo/bin:$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin:/opt/homebrew/opt/llvm/bin:$PATH"
|
||||
export RUSTUP_TOOLCHAIN=stable-aarch64-apple-darwin
|
||||
export RUSTC="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin/rustc"
|
||||
fi
|
||||
|
||||
SKIP_BUILD=0
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--skip-build) SKIP_BUILD=1 ;;
|
||||
*) echo "usage: $0 [--skip-build]" >&2; exit 2 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
if [ -z "${SQUID_UPDATE_PUBKEY:-}" ] && [ -n "${SQUID_RELEASE_KEY:-}" ]; then
|
||||
SQUID_UPDATE_PUBKEY=$(python3 scripts/release-key.py pubkey "${SQUID_RELEASE_KEY%.ed25519}.pub")
|
||||
export SQUID_UPDATE_PUBKEY
|
||||
fi
|
||||
if [ -n "${SQUID_UPDATE_PUBKEY:-}" ]; then
|
||||
echo "== release key baked in: ${SQUID_UPDATE_PUBKEY:0:12}… =="
|
||||
else
|
||||
echo "== no release key: this build will report the feed as unsigned =="
|
||||
fi
|
||||
|
||||
if [ "$SKIP_BUILD" != "1" ]; then
|
||||
echo "== frontend (Windows target: chrome105) =="
|
||||
TAURI_ENV_PLATFORM=windows pnpm build
|
||||
|
||||
echo "== rust build ($TARGET) =="
|
||||
CROSS_LOG=$(mktemp /tmp/squid-win-build.XXXXXX)
|
||||
if [ "$HOST" = "Darwin" ]; then
|
||||
if ! (
|
||||
cd src-tauri
|
||||
cargo xwin build --target "$TARGET" --release \
|
||||
--features tauri/custom-protocol >"$CROSS_LOG" 2>&1
|
||||
); then
|
||||
sed -n '1,240p' "$CROSS_LOG"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
if ! (
|
||||
cd src-tauri
|
||||
cargo build --target "$TARGET" --release \
|
||||
--features tauri/custom-protocol >"$CROSS_LOG" 2>&1
|
||||
); then
|
||||
sed -n '1,240p' "$CROSS_LOG"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
grep -Ev "^warning:|^\s+\||^\s+=|LNK4099|failed to load|^$|^\s+-->|^note:" \
|
||||
"$CROSS_LOG" || true
|
||||
fi
|
||||
|
||||
EXE="src-tauri/target/$TARGET/release/squid-desktop.exe"
|
||||
test -f "$EXE"
|
||||
|
||||
echo "== PE machine check (x64) =="
|
||||
python3 - "$EXE" <<'PY'
|
||||
import pathlib, struct, sys
|
||||
exe = pathlib.Path(sys.argv[1]).read_bytes()
|
||||
machine = struct.unpack_from("<H", exe, struct.unpack_from("<I", exe, 0x3C)[0] + 4)[0]
|
||||
if machine != 0x8664:
|
||||
sys.exit(f"{sys.argv[1]} is PE machine 0x{machine:04x}, expected 0x8664")
|
||||
print("pe machine ok: 0x8664")
|
||||
PY
|
||||
|
||||
echo "== verify the frontend is embedded =="
|
||||
python3 - "$EXE" <<'PY'
|
||||
import pathlib, sys
|
||||
exe = pathlib.Path(sys.argv[1]).read_bytes()
|
||||
assets = pathlib.Path("dist/assets")
|
||||
missing = [p.name for p in assets.iterdir() if p.name.encode() not in exe]
|
||||
if b"index.html" not in exe:
|
||||
missing.append("index.html")
|
||||
asset_text = "".join(
|
||||
p.read_text(encoding="utf-8")
|
||||
for p in assets.iterdir()
|
||||
if p.suffix in {".js", ".css", ".html"}
|
||||
)
|
||||
for marker in ("智能扫描", "扫描完成", "自动检查更新"):
|
||||
if marker not in asset_text:
|
||||
missing.append(marker)
|
||||
if missing:
|
||||
sys.exit(f"frontend not embedded, missing: {missing}")
|
||||
print(f"embedded ok: {len(exe):,} byte exe carries the current dist/assets")
|
||||
PY
|
||||
|
||||
echo "== windows notes (x64) =="
|
||||
STAGE=$(mktemp -d /tmp/squid-windows-release.XXXXXX)
|
||||
python3 - "$STAGE" "$VERSION" <<'PY'
|
||||
import pathlib, sys
|
||||
stage = pathlib.Path(sys.argv[1])
|
||||
version = sys.argv[2]
|
||||
text = f"""Squid {version} - Windows x64
|
||||
|
||||
系统要求
|
||||
--------
|
||||
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
|
||||
- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid
|
||||
启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime:
|
||||
https://developer.microsoft.com/microsoft-edge/webview2/
|
||||
- 安装与运行都不需要管理员权限。安装位置为
|
||||
%LOCALAPPDATA%\\Programs\\Squid。
|
||||
|
||||
安装
|
||||
----
|
||||
1. 运行 Squid-Setup-{version}-win-x64.exe。
|
||||
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
|
||||
3. 卸载请在 Windows“设置 > 应用”中移除 Squid。
|
||||
|
||||
更新
|
||||
----
|
||||
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
|
||||
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
|
||||
还会验证清单的 Ed25519 签名。
|
||||
|
||||
校验
|
||||
----
|
||||
PowerShell:
|
||||
Get-FileHash .\\Squid-Setup-{version}-win-x64.exe -Algorithm SHA256
|
||||
"""
|
||||
(stage / "README-Windows.txt").write_bytes(text.replace("\n", "\r\n").encode("utf-8"))
|
||||
PY
|
||||
|
||||
echo "== NSIS installer (x64) =="
|
||||
mkdir -p artifacts
|
||||
SIZE_KB=$(( ($(stat -f%z "$EXE" 2>/dev/null || stat -c%s "$EXE") + 1023) / 1024 ))
|
||||
makensis -V2 \
|
||||
-DSQUID_EXE="$ROOT/$EXE" \
|
||||
-DLICENSE_FILE="$ROOT/LICENSE" \
|
||||
-DREADME_FILE="$STAGE/README-Windows.txt" \
|
||||
-DICONS_DIR="$ROOT/src-tauri/icons" \
|
||||
-DOUT_FILE="$ROOT/$INSTALLER" \
|
||||
-DVERSION="$VERSION" \
|
||||
-DEST_SIZE_KB="$SIZE_KB" \
|
||||
scripts/windows-installer.nsi
|
||||
mv "$STAGE/README-Windows.txt" "$NOTES"
|
||||
rm -rf "$STAGE"
|
||||
|
||||
echo "== checksums =="
|
||||
python3 - "$VERSION" <<'PY'
|
||||
import hashlib, pathlib, sys
|
||||
version = sys.argv[1]
|
||||
artifacts = pathlib.Path("artifacts")
|
||||
preferred = [
|
||||
f"Squid-{version}-macOS-universal.dmg",
|
||||
f"Squid-Setup-{version}-win-x64.exe",
|
||||
"README-Windows-x64.txt",
|
||||
]
|
||||
names = [name for name in preferred if (artifacts / name).is_file()]
|
||||
lines = [
|
||||
f"{hashlib.sha256((artifacts / name).read_bytes()).hexdigest()} {name}"
|
||||
for name in names
|
||||
]
|
||||
(artifacts / "SHA256SUMS.txt").write_text("".join(line + "\n" for line in lines), encoding="utf-8")
|
||||
print("\n".join(lines))
|
||||
PY
|
||||
|
||||
echo "== result =="
|
||||
ls -lh artifacts/
|
||||
|
|
@ -0,0 +1,153 @@
|
|||
#!/bin/bash
|
||||
# Publish installers to the orphan git branch that is Squid's update channel.
|
||||
#
|
||||
# scripts/publish-release.sh [--notes FILE] [--key FILE] [--dry-run]
|
||||
# [--no-push] [--branch NAME]
|
||||
#
|
||||
# The branch contains `squid-update.json`, the exact installers it names, and
|
||||
# optionally `squid-update.sig` over the manifest's bytes. Rebuilding the branch
|
||||
# from scratch on every run prevents installers from accumulating in history.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
BRANCH="${SQUID_RELEASE_BRANCH:-releases}"
|
||||
MANIFEST="squid-update.json"
|
||||
SIGNATURE="squid-update.sig"
|
||||
NOTES_FILE=""
|
||||
KEY_FILE="${SQUID_RELEASE_KEY:-}"
|
||||
DRY_RUN=0
|
||||
NO_PUSH=0
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--notes) NOTES_FILE="$2"; shift 2 ;;
|
||||
--dry-run) DRY_RUN=1; shift ;;
|
||||
--no-push) NO_PUSH=1; shift ;;
|
||||
--branch) BRANCH="$2"; shift 2 ;;
|
||||
--key) KEY_FILE="$2"; shift 2 ;;
|
||||
*) echo "unknown argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
|
||||
PLAN=$(mktemp /tmp/squid-release-plan.XXXXXX)
|
||||
INDEX_FILE=$(mktemp /tmp/squid-release-index.XXXXXX)
|
||||
MANIFEST_PATH=$(mktemp /tmp/squid-manifest.XXXXXX)
|
||||
SIGNATURE_PATH=$(mktemp /tmp/squid-signature.XXXXXX)
|
||||
trap 'rm -f "$PLAN" "$INDEX_FILE" "$MANIFEST_PATH" "$SIGNATURE_PATH"' EXIT
|
||||
|
||||
python3 - "$VERSION" "$MANIFEST" "$NOTES_FILE" > "$PLAN" <<'PY'
|
||||
import datetime, hashlib, json, pathlib, re, sys
|
||||
|
||||
version, manifest_name, notes_file = sys.argv[1:4]
|
||||
artifacts = pathlib.Path("artifacts")
|
||||
if not artifacts.is_dir():
|
||||
sys.exit("artifacts/ is missing; build a release first.")
|
||||
notes = pathlib.Path(notes_file).read_text(encoding="utf-8").strip() if notes_file else ""
|
||||
|
||||
patterns = [
|
||||
("macos", rf"^Squid-{re.escape(version)}-macOS-universal\.dmg$"),
|
||||
("windows", rf"^Squid-Setup-{re.escape(version)}-win-x64\.exe$"),
|
||||
]
|
||||
candidates = sorted(p.name for p in artifacts.iterdir() if p.is_file())
|
||||
|
||||
def digest(name):
|
||||
path = artifacts / name
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest(), path.stat().st_size
|
||||
|
||||
manifest = {
|
||||
"schema": 1,
|
||||
"version": version,
|
||||
"date": datetime.date.today().isoformat(),
|
||||
"notes": notes,
|
||||
"artifacts": {},
|
||||
}
|
||||
chosen = []
|
||||
for platform, pattern in patterns:
|
||||
match = next((name for name in candidates if re.search(pattern, name)), None)
|
||||
if not match:
|
||||
sys.exit(
|
||||
f"missing installer for {platform} at version {version}; expected "
|
||||
f"Squid-{version}-macOS-universal.dmg and "
|
||||
f"Squid-Setup-{version}-win-x64.exe"
|
||||
)
|
||||
digest_value, size = digest(match)
|
||||
manifest["artifacts"][platform] = {
|
||||
"file": match,
|
||||
"sha256": digest_value,
|
||||
"size": size,
|
||||
}
|
||||
chosen.append(match)
|
||||
|
||||
unexpected = [
|
||||
name
|
||||
for name in candidates
|
||||
if re.search(r"\.(dmg|exe|msi|pkg|zip|AppImage|deb)$", name, re.IGNORECASE)
|
||||
and name not in chosen
|
||||
]
|
||||
if unexpected:
|
||||
sys.exit("only versioned release installers may be published; remove: " + ", ".join(unexpected))
|
||||
|
||||
sys.stdout.write(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n")
|
||||
sys.stdout.write("\0")
|
||||
for name in candidates:
|
||||
if name in {manifest_name, "squid-update.sig"} or name.startswith("."):
|
||||
continue
|
||||
digest_value, size = digest(name)
|
||||
sys.stdout.write(f"{name}\t{digest_value}\t{size}\0")
|
||||
PY
|
||||
|
||||
MANIFEST_JSON=$(python3 -c "import sys;print(sys.stdin.read().split('\0')[0],end='')" < "$PLAN")
|
||||
echo "== manifest for $VERSION =="
|
||||
printf '%s\n' "$MANIFEST_JSON"
|
||||
printf '%s\n' "$MANIFEST_JSON" > "$MANIFEST_PATH"
|
||||
|
||||
if [ -n "$KEY_FILE" ]; then
|
||||
python3 scripts/release-key.py sign "$KEY_FILE" "$MANIFEST_PATH" > "$SIGNATURE_PATH"
|
||||
PUBLIC_FILE="${KEY_FILE%.ed25519}.pub"
|
||||
if [ "$PUBLIC_FILE" != "$KEY_FILE" ] && [ -f "$PUBLIC_FILE" ]; then
|
||||
python3 scripts/release-key.py verify "$PUBLIC_FILE" "$MANIFEST_PATH" "$SIGNATURE_PATH"
|
||||
fi
|
||||
echo "== manifest signed with $KEY_FILE =="
|
||||
fi
|
||||
|
||||
echo "== building the $BRANCH tree =="
|
||||
export GIT_INDEX_FILE="$INDEX_FILE"
|
||||
git read-tree --empty
|
||||
git update-index --add --cacheinfo "100644,$(git hash-object -w "$MANIFEST_PATH"),$MANIFEST"
|
||||
if [ -s "$SIGNATURE_PATH" ]; then
|
||||
git update-index --add --cacheinfo "100644,$(git hash-object -w "$SIGNATURE_PATH"),$SIGNATURE"
|
||||
fi
|
||||
while IFS=$'\t' read -r -d '' name digest_value size; do
|
||||
[ -n "$name" ] || continue
|
||||
git update-index --add --cacheinfo "100644,$(git hash-object -w "artifacts/$name"),$name"
|
||||
printf ' %-42s %10s B %s…\n' "$name" "$size" "${digest_value:0:16}"
|
||||
done < <(python3 -c "
|
||||
import sys
|
||||
for entry in sys.stdin.read().split('\0')[1:]:
|
||||
if entry.strip():
|
||||
sys.stdout.write(entry + '\0')
|
||||
" < "$PLAN")
|
||||
TREE=$(git write-tree)
|
||||
COMMIT=$(git commit-tree "$TREE" -m "release $VERSION")
|
||||
unset GIT_INDEX_FILE
|
||||
|
||||
if [ "$DRY_RUN" = 1 ]; then
|
||||
echo "== dry run: $COMMIT would become $BRANCH =="
|
||||
git ls-tree -rl "$COMMIT" | while read -r mode type hash size name; do
|
||||
printf ' %12s B %s\n' "$size" "$name"
|
||||
done
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git update-ref "refs/heads/$BRANCH" "$COMMIT"
|
||||
echo "committed $VERSION as $(git rev-parse --short "$BRANCH")"
|
||||
|
||||
if [ "$NO_PUSH" = 1 ]; then
|
||||
echo "--no-push: committed locally on $BRANCH"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "== pushing $BRANCH =="
|
||||
git push --force origin "$BRANCH"
|
||||
echo "published $VERSION"
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Ed25519 signing for Squid's git-backed update channel.
|
||||
|
||||
scripts/release-key.py keygen KEY_FILE
|
||||
scripts/release-key.py pubkey KEY_FILE
|
||||
scripts/release-key.py sign KEY_FILE FILE
|
||||
scripts/release-key.py verify PUBKEY FILE SIG_FILE
|
||||
|
||||
The signature covers the manifest file's exact bytes, so verification does not
|
||||
depend on JSON canonicalisation. Keep the private key outside this repository.
|
||||
"""
|
||||
import base64
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
try:
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
||||
Ed25519PrivateKey,
|
||||
Ed25519PublicKey,
|
||||
)
|
||||
except ImportError:
|
||||
sys.exit("needs cryptography: python3 -m pip install cryptography")
|
||||
|
||||
USAGE = __doc__
|
||||
|
||||
|
||||
def public_hex(path):
|
||||
if path.suffix == ".pub":
|
||||
key = Ed25519PublicKey.from_public_bytes(path.read_bytes())
|
||||
else:
|
||||
key = Ed25519PrivateKey.from_private_bytes(path.read_bytes()).public_key()
|
||||
return key.public_bytes(
|
||||
serialization.Encoding.Raw, serialization.PublicFormat.Raw
|
||||
).hex()
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) < 2:
|
||||
sys.exit(USAGE)
|
||||
command, key_file = argv[0], pathlib.Path(argv[1])
|
||||
|
||||
if command == "keygen":
|
||||
if key_file.exists():
|
||||
sys.exit(f"{key_file} exists; refusing to overwrite a release key")
|
||||
key = Ed25519PrivateKey.generate()
|
||||
key_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
key_file.write_bytes(
|
||||
key.private_bytes(
|
||||
serialization.Encoding.Raw,
|
||||
serialization.PrivateFormat.Raw,
|
||||
serialization.NoEncryption(),
|
||||
)
|
||||
)
|
||||
key_file.chmod(0o600)
|
||||
public = key_file.with_suffix(".pub")
|
||||
public.write_bytes(
|
||||
key.public_key().public_bytes(
|
||||
serialization.Encoding.Raw, serialization.PublicFormat.Raw
|
||||
)
|
||||
)
|
||||
print(f"key: {key_file} (keep this private, never commit it)")
|
||||
print(f"pubkey: {public}")
|
||||
print(f"build with SQUID_UPDATE_PUBKEY={public_hex(public)}")
|
||||
return 0
|
||||
|
||||
if command == "pubkey":
|
||||
print(public_hex(key_file))
|
||||
return 0
|
||||
|
||||
if command == "sign":
|
||||
if len(argv) < 3:
|
||||
sys.exit(USAGE)
|
||||
key = Ed25519PrivateKey.from_private_bytes(key_file.read_bytes())
|
||||
signature = key.sign(pathlib.Path(argv[2]).read_bytes())
|
||||
sys.stdout.write(base64.b64encode(signature).decode() + "\n")
|
||||
return 0
|
||||
|
||||
if command == "verify":
|
||||
if len(argv) < 4:
|
||||
sys.exit(USAGE)
|
||||
signature = base64.b64decode(pathlib.Path(argv[3]).read_text().strip())
|
||||
Ed25519PublicKey.from_public_bytes(key_file.read_bytes()).verify(
|
||||
signature, pathlib.Path(argv[2]).read_bytes()
|
||||
)
|
||||
print("signature ok")
|
||||
return 0
|
||||
|
||||
sys.exit(f"unknown command: {command}\n\n{USAGE}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
|
|
@ -0,0 +1,186 @@
|
|||
; Squid - Windows installer (NSIS 3, per-user, no administrator rights).
|
||||
;
|
||||
; makensis -DSQUID_EXE=<path> -DLICENSE_FILE=<path> -DREADME_FILE=<path> \
|
||||
; -DICONS_DIR=<path> -DOUT_FILE=<path> -DVERSION=0.1.0 \
|
||||
; -DEST_SIZE_KB=<kb> scripts/windows-installer.nsi
|
||||
;
|
||||
; The x64 package also runs on Windows 11 ARM64 through the system's x64
|
||||
; compatibility layer. Install scope is per-user: Squid writes to HKCU and its
|
||||
; own LocalAppData folder only.
|
||||
|
||||
!include "MUI2.nsh"
|
||||
!include "LogicLib.nsh"
|
||||
!include "WinVer.nsh"
|
||||
!include "x64.nsh"
|
||||
|
||||
!ifndef VERSION
|
||||
!error "VERSION is required (for example -DVERSION=0.1.0)"
|
||||
!endif
|
||||
!ifndef SQUID_EXE
|
||||
!error "SQUID_EXE is required"
|
||||
!endif
|
||||
!ifndef OUT_FILE
|
||||
!define OUT_FILE "Squid-Setup.exe"
|
||||
!endif
|
||||
!ifndef EST_SIZE_KB
|
||||
!define EST_SIZE_KB "40000"
|
||||
!endif
|
||||
|
||||
!define APP_NAME "Squid"
|
||||
!define APP_ID "app.nex.squid"
|
||||
!define APP_VERSION "${VERSION}"
|
||||
!define PUBLISHER "Squid Contributors"
|
||||
!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${APP_ID}"
|
||||
!define WEBVIEW_KEY "SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"
|
||||
|
||||
Unicode true
|
||||
Name "${APP_NAME}"
|
||||
OutFile "${OUT_FILE}"
|
||||
InstallDir "$LOCALAPPDATA\Programs\${APP_NAME}"
|
||||
InstallDirRegKey HKCU "Software\${APP_NAME}" "InstallDirectory"
|
||||
RequestExecutionLevel user
|
||||
SetCompressor /SOLID lzma
|
||||
|
||||
!define /date BUILD_YEAR "%Y"
|
||||
VIProductVersion "${APP_VERSION}.0"
|
||||
VIAddVersionKey ProductName "${APP_NAME}"
|
||||
VIAddVersionKey ProductVersion "${APP_VERSION}"
|
||||
VIAddVersionKey CompanyName "${PUBLISHER}"
|
||||
VIAddVersionKey LegalCopyright "Copyright ${BUILD_YEAR} ${PUBLISHER}"
|
||||
VIAddVersionKey FileDescription "${APP_NAME} installer"
|
||||
VIAddVersionKey FileVersion "${APP_VERSION}.0"
|
||||
VIAddVersionKey OriginalFilename "Squid-Setup-${VERSION}-win-x64.exe"
|
||||
|
||||
!define MUI_ICON "${ICONS_DIR}\icon.ico"
|
||||
!define MUI_UNICON "${ICONS_DIR}\icon.ico"
|
||||
!define MUI_ABORTWARNING
|
||||
!define MUI_FINISHPAGE_RUN "$INSTDIR\squid-desktop.exe"
|
||||
!define MUI_FINISHPAGE_RUN_TEXT "$(run_squid)"
|
||||
!define MUI_FINISHPAGE_SHOWREADME
|
||||
!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(read_me)"
|
||||
!define MUI_FINISHPAGE_SHOWREADME_NOTCHECKED
|
||||
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION show_readme
|
||||
|
||||
!insertmacro MUI_PAGE_WELCOME
|
||||
!insertmacro MUI_PAGE_DIRECTORY
|
||||
!insertmacro MUI_PAGE_INSTFILES
|
||||
!insertmacro MUI_PAGE_FINISH
|
||||
!insertmacro MUI_UNPAGE_CONFIRM
|
||||
!insertmacro MUI_UNPAGE_INSTFILES
|
||||
|
||||
!insertmacro MUI_LANGUAGE "English"
|
||||
!insertmacro MUI_LANGUAGE "SimpChinese"
|
||||
|
||||
LangString run_squid 1033 "Launch Squid when the installer closes."
|
||||
LangString run_squid 2052 "安装完成后启动 Squid。"
|
||||
LangString read_me 1033 "Open the Windows notes."
|
||||
LangString read_me 2052 "打开 Windows 使用说明。"
|
||||
LangString close_squid 1033 "${APP_NAME} is running and must close before it can be updated.$\r$\n$\r$\nClick OK to close it now, or Cancel to keep things as they are."
|
||||
LangString close_squid 2052 "${APP_NAME} 正在运行,需要先退出才能更新。$\r$\n$\r$\n点击“确定”立即退出,点击“取消”保持现状。"
|
||||
LangString webview_missing 1033 "${APP_NAME} uses Microsoft Edge WebView2, which this installer did not find.$\r$\n$\r$\nIf Squid opens a blank window, install the WebView2 Evergreen Runtime from Microsoft and launch Squid again.$\r$\n$\r$\nhttps://developer.microsoft.com/microsoft-edge/webview2/"
|
||||
LangString webview_missing 2052 "${APP_NAME} 的界面依赖 Microsoft Edge WebView2,安装程序没有检测到它。$\r$\n$\r$\n如果 Squid 启动后窗口空白,请从微软官网安装 WebView2 Evergreen Runtime,然后重新启动 Squid。$\r$\n$\r$\nhttps://developer.microsoft.com/microsoft-edge/webview2/"
|
||||
|
||||
Var ReadmePath
|
||||
|
||||
Function .onInit
|
||||
SetShellVarContext current
|
||||
${IfNot} ${AtLeastWin10}
|
||||
MessageBox MB_OK|MB_ICONSTOP "${APP_NAME} needs Windows 10 or later."
|
||||
Abort
|
||||
${EndIf}
|
||||
|
||||
${IfNot} ${IsNativeAMD64}
|
||||
${IfNot} ${IsNativeARM64}
|
||||
MessageBox MB_OK|MB_ICONSTOP "This package requires 64-bit Windows (x64 or ARM64)."
|
||||
Abort
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
|
||||
${If} ${FileExists} "$INSTDIR\squid-desktop.exe"
|
||||
FindWindow $0 "" "${APP_NAME}"
|
||||
${If} $0 != 0
|
||||
${IfNot} ${Silent}
|
||||
MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "$(close_squid)" IDOK +2
|
||||
Abort
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
${EndIf}
|
||||
|
||||
nsExec::Exec 'taskkill /IM squid-desktop.exe /F'
|
||||
Pop $0
|
||||
FunctionEnd
|
||||
|
||||
Function un.onInit
|
||||
SetShellVarContext current
|
||||
nsExec::Exec 'taskkill /IM squid-desktop.exe /F'
|
||||
Pop $0
|
||||
FunctionEnd
|
||||
|
||||
Section "Install"
|
||||
SetOutPath "$INSTDIR"
|
||||
File "${SQUID_EXE}"
|
||||
!ifdef LICENSE_FILE
|
||||
File /oname=LICENSE.txt "${LICENSE_FILE}"
|
||||
!endif
|
||||
!ifdef README_FILE
|
||||
File /oname=README-Windows.txt "${README_FILE}"
|
||||
!endif
|
||||
|
||||
WriteUninstaller "$INSTDIR\Uninstall.exe"
|
||||
StrCpy $ReadmePath "$INSTDIR\README-Windows.txt"
|
||||
|
||||
WriteRegStr HKCU "Software\${APP_NAME}" "InstallDirectory" "$INSTDIR"
|
||||
|
||||
CreateDirectory "$SMPROGRAMS\${APP_NAME}"
|
||||
CreateShortCut "$SMPROGRAMS\${APP_NAME}\${APP_NAME}.lnk" "$INSTDIR\squid-desktop.exe"
|
||||
CreateShortCut "$SMPROGRAMS\${APP_NAME}\Uninstall.lnk" "$INSTDIR\Uninstall.exe"
|
||||
CreateShortCut "$DESKTOP\${APP_NAME}.lnk" "$INSTDIR\squid-desktop.exe"
|
||||
|
||||
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "${APP_NAME}"
|
||||
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${APP_VERSION}"
|
||||
WriteRegStr HKCU "${UNINSTALL_KEY}" "Publisher" "${PUBLISHER}"
|
||||
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\squid-desktop.exe"
|
||||
WriteRegStr HKCU "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR"
|
||||
WriteRegStr HKCU "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\Uninstall.exe"'
|
||||
WriteRegStr HKCU "${UNINSTALL_KEY}" "QuietUninstallString" '"$INSTDIR\Uninstall.exe" /S'
|
||||
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1
|
||||
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1
|
||||
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "EstimatedSize" ${EST_SIZE_KB}
|
||||
SectionEnd
|
||||
|
||||
Section "PostInstall"
|
||||
ClearErrors
|
||||
ReadRegStr $0 HKLM "${WEBVIEW_KEY}" "pv"
|
||||
${If} $0 == ""
|
||||
ReadRegStr $0 HKCU "${WEBVIEW_KEY}" "pv"
|
||||
${EndIf}
|
||||
${If} $0 == ""
|
||||
MessageBox MB_OK|MB_ICONINFORMATION "$(webview_missing)"
|
||||
${EndIf}
|
||||
SectionEnd
|
||||
|
||||
Function show_readme
|
||||
${If} ${FileExists} "$ReadmePath"
|
||||
Exec 'notepad.exe "$ReadmePath"'
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
Section "Uninstall"
|
||||
nsExec::Exec 'taskkill /IM squid-desktop.exe /F'
|
||||
Pop $0
|
||||
|
||||
Delete "$INSTDIR\squid-desktop.exe"
|
||||
Delete "$INSTDIR\LICENSE.txt"
|
||||
Delete "$INSTDIR\README-Windows.txt"
|
||||
Delete "$INSTDIR\Uninstall.exe"
|
||||
RMDir "$INSTDIR"
|
||||
|
||||
Delete "$SMPROGRAMS\${APP_NAME}\${APP_NAME}.lnk"
|
||||
Delete "$SMPROGRAMS\${APP_NAME}\Uninstall.lnk"
|
||||
RMDir "$SMPROGRAMS\${APP_NAME}"
|
||||
Delete "$DESKTOP\${APP_NAME}.lnk"
|
||||
|
||||
DeleteRegKey HKCU "${UNINSTALL_KEY}"
|
||||
DeleteRegValue HKCU "Software\${APP_NAME}" "InstallDirectory"
|
||||
DeleteRegKey /ifempty HKCU "Software\${APP_NAME}"
|
||||
SectionEnd
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
[package]
|
||||
name = "squid-desktop"
|
||||
version = "0.1.3"
|
||||
description = "Squid — a CleanMyMac-inspired cleaner, uninstaller and system monitor."
|
||||
authors = ["squid contributors"]
|
||||
edition = "2021"
|
||||
rust-version = "1.80"
|
||||
license = "GPL-3.0-only"
|
||||
default-run = "squid-desktop"
|
||||
|
||||
[lib]
|
||||
name = "squid_desktop_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[[bin]]
|
||||
name = "squid-desktop"
|
||||
path = "src/main.rs"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
squid-core = { path = "../crates/squid-core" }
|
||||
squid-engine = { path = "../crates/squid-engine" }
|
||||
squid-platform = { path = "../crates/squid-platform" }
|
||||
squid-stats = { path = "../crates/squid-stats" }
|
||||
tauri = { version = "2.11", features = ["tray-icon", "image-png", "macos-private-api"] }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-single-instance = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
chrono = { version = "0.4", features = ["clock"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
base64 = "0.22"
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
ed25519-dalek = { version = "3.0.0", default-features = false, features = ["alloc", "fast"] }
|
||||
globset = "0.4"
|
||||
|
||||
[profile.dev]
|
||||
debug = 1
|
||||
|
||||
[profile.dev.package."*"]
|
||||
debug = false
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSDocumentsFolderUsageDescription</key>
|
||||
<string>Squid analyzes the folder you choose and removes only the items you approve.</string>
|
||||
<key>NSDownloadsFolderUsageDescription</key>
|
||||
<string>Squid analyzes your Downloads folder only when you choose it.</string>
|
||||
<key>NSDesktopFolderUsageDescription</key>
|
||||
<string>Squid analyzes your Desktop folder only when you choose it.</string>
|
||||
<key>NSPicturesFolderUsageDescription</key>
|
||||
<string>Squid measures picture folder sizes only when you choose that folder.</string>
|
||||
<key>NSRemovableVolumesUsageDescription</key>
|
||||
<string>Squid can analyze removable volumes you select.</string>
|
||||
<key>NSNetworkVolumesUsageDescription</key>
|
||||
<string>Squid can analyze network volumes you select.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
//! Build-time wiring for the git-backed update channel.
|
||||
//!
|
||||
//! The feed lives in this repository's `releases` branch. The manifest URL is
|
||||
//! derived from the `origin` remote, matching the mechanism used by nex_shift.
|
||||
//! `SQUID_UPDATE_URL` and `SQUID_UPDATE_PUBKEY` are the two explicit overrides.
|
||||
|
||||
use std::{path::Path, process::Command};
|
||||
|
||||
const RELEASE_BRANCH: &str = "releases";
|
||||
const MANIFEST: &str = "squid-update.json";
|
||||
const PUBKEY_ENV: &str = "SQUID_UPDATE_PUBKEY";
|
||||
|
||||
fn git(args: &[&str]) -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(Path::new(env!("CARGO_MANIFEST_DIR")).parent()?)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let text = String::from_utf8(output.stdout).ok()?;
|
||||
let text = text.trim().to_string();
|
||||
(!text.is_empty()).then_some(text)
|
||||
}
|
||||
|
||||
fn parse_remote(url: &str) -> Option<(String, String)> {
|
||||
let url = url.trim().trim_end_matches('/').trim_end_matches(".git");
|
||||
let (host, path) = if let Some(rest) = url.strip_prefix("ssh://") {
|
||||
rest.split_once('/')?
|
||||
} else if let Some(rest) = url.find("://").map(|index| &url[index + 3..]) {
|
||||
rest.split_once('/')?
|
||||
} else if let Some((host, path)) = url.split_once(':') {
|
||||
(host.strip_prefix("git@")?, path)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
(!host.is_empty() && !path.is_empty()).then(|| (format!("https://{host}"), path.to_string()))
|
||||
}
|
||||
|
||||
fn raw_directory(host: &str, path: &str) -> String {
|
||||
let domain = host.replace("https://", "");
|
||||
let segment = if domain.ends_with("github.com") {
|
||||
format!("raw/{RELEASE_BRANCH}")
|
||||
} else if domain.contains("gitlab") {
|
||||
format!("-/raw/{RELEASE_BRANCH}")
|
||||
} else {
|
||||
format!("raw/branch/{RELEASE_BRANCH}")
|
||||
};
|
||||
format!("{host}/{path}/{segment}")
|
||||
}
|
||||
|
||||
fn manifest_url() -> Option<String> {
|
||||
if let Ok(url) = std::env::var("SQUID_UPDATE_URL") {
|
||||
if !url.trim().is_empty() {
|
||||
return Some(url.trim().to_string());
|
||||
}
|
||||
}
|
||||
let (host, path) = parse_remote(&git(&["remote", "get-url", "origin"])?)?;
|
||||
Some(format!("{}/{}", raw_directory(&host, &path), MANIFEST))
|
||||
}
|
||||
|
||||
fn public_key() -> Result<String, String> {
|
||||
let raw = match std::env::var(PUBKEY_ENV) {
|
||||
Ok(value) => value,
|
||||
Err(_) => return Ok(String::new()),
|
||||
};
|
||||
let value: String = raw
|
||||
.trim()
|
||||
.chars()
|
||||
.filter(|character| !character.is_whitespace() && *character != ':')
|
||||
.collect::<String>()
|
||||
.to_ascii_lowercase();
|
||||
if value.len() != 64 || !value.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(format!("{PUBKEY_ENV} must be 64 hex characters (32 bytes)"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=../dist");
|
||||
println!("cargo:rerun-if-env-changed=SQUID_UPDATE_URL");
|
||||
println!("cargo:rerun-if-env-changed={PUBKEY_ENV}");
|
||||
println!("cargo:rerun-if-changed=../.git/config");
|
||||
println!(
|
||||
"cargo:rustc-env=SQUID_UPDATE_URL={}",
|
||||
manifest_url().unwrap_or_default()
|
||||
);
|
||||
match public_key() {
|
||||
Ok(key) => println!("cargo:rustc-env=SQUID_UPDATE_PUBKEY={key}"),
|
||||
Err(error) => panic!("{error}"),
|
||||
}
|
||||
tauri_build::build()
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Default permissions for the Squid main window.",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-start-dragging",
|
||||
"dialog:default",
|
||||
"opener:default"
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
<svg width="1024" height="1024" viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="110" y1="80" x2="902" y2="944" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#FFB25C"/>
|
||||
<stop offset="0.52" stop-color="#FF6B35"/>
|
||||
<stop offset="1" stop-color="#C66BFF"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="body" x1="356" y1="200" x2="678" y2="704" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="white"/>
|
||||
<stop offset="1" stop-color="#FFF6EE"/>
|
||||
</linearGradient>
|
||||
<filter id="shadow" x="248" y="248" width="528" height="540" filterUnits="userSpaceOnUse">
|
||||
<feDropShadow dx="0" dy="22" stdDeviation="28" flood-color="#7A3018" flood-opacity="0.28"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<rect x="40" y="40" width="944" height="944" rx="228" fill="url(#bg)"/>
|
||||
<path d="M141 327C236 125 462 50 668 107C872 163 977 359 947 570C915 792 725 941 494 936C266 932 78 771 64 555C59 474 85 394 141 327Z" fill="url(#body)" fill-opacity="0.15"/>
|
||||
<g filter="url(#shadow)">
|
||||
<path d="M512 206C608 206 682 286 682 386V499C682 599 608 679 512 679C416 679 342 599 342 499V386C342 286 416 206 512 206Z" fill="url(#body)"/>
|
||||
<path d="M386 353C430 323 479 313 512 313C545 313 594 323 638 353" stroke="#D94F1F" stroke-width="28" stroke-linecap="round" opacity="0.9"/>
|
||||
<circle cx="443" cy="445" r="28" fill="#7A3018"/>
|
||||
<circle cx="581" cy="445" r="28" fill="#7A3018"/>
|
||||
<circle cx="434" cy="436" r="8" fill="white"/>
|
||||
<circle cx="572" cy="436" r="8" fill="white"/>
|
||||
<path d="M456 532C479 553 545 553 568 532" stroke="#D94F1F" stroke-width="22" stroke-linecap="round"/>
|
||||
<path d="M393 624C350 665 333 720 342 786" stroke="#FFF6EE" stroke-width="54" stroke-linecap="round"/>
|
||||
<path d="M456 652C438 714 447 770 478 820" stroke="#FFF6EE" stroke-width="48" stroke-linecap="round"/>
|
||||
<path d="M568 652C586 714 577 770 546 820" stroke="#FFF6EE" stroke-width="48" stroke-linecap="round"/>
|
||||
<path d="M631 624C674 665 691 720 682 786" stroke="#FFF6EE" stroke-width="54" stroke-linecap="round"/>
|
||||
<circle cx="342" cy="813" r="32" fill="#FFF6EE"/>
|
||||
<circle cx="478" cy="841" r="28" fill="#FFF6EE"/>
|
||||
<circle cx="546" cy="841" r="28" fill="#FFF6EE"/>
|
||||
<circle cx="682" cy="813" r="32" fill="#FFF6EE"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.3 KiB |
|
After Width: | Height: | Size: 8.9 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 1.7 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 7.3 KiB |
|
After Width: | Height: | Size: 9.9 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 5.5 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
|
@ -0,0 +1,5 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 5.7 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 5.1 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 7.3 KiB |
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
|
@ -0,0 +1,4 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#FFFFFF</color>
|
||||
</resources>
|
||||
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 939 B |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 5.4 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 4.9 KiB |
|
After Width: | Height: | Size: 4.9 KiB |
|
After Width: | Height: | Size: 8.2 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 8.2 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 4.6 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
|
@ -0,0 +1,989 @@
|
|||
//! Tauri command surface for the desktop application.
|
||||
//!
|
||||
//! The UI never invents a deletion target. Scans are held in this process and
|
||||
//! a delete command can only select indices from the scan that produced them.
|
||||
//! The engine still re-validates every path against the same safety policy and
|
||||
//! whitelist used by the CLI and TUI.
|
||||
|
||||
use squid_core::ledger::{self, Session};
|
||||
use squid_core::paths;
|
||||
use squid_core::progress::{CancelToken, Event, Progress};
|
||||
use squid_core::{
|
||||
AppInfo, Bytes, Category, CleanupItem, DeleteMode, ItemKind, LockReason, ScanReport, Settings,
|
||||
UninstallPlan,
|
||||
};
|
||||
use squid_engine::analyze::{self, FileEntry, Node};
|
||||
use squid_engine::delete::{self, DeleteJob, DeleteOutcome};
|
||||
use squid_engine::{clean, purge, uninstall, Engine};
|
||||
use squid_platform::PlatformId;
|
||||
use squid_stats::{ProcessSample, Sampler, SystemSnapshot};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::{Duration, Instant};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct AppState {
|
||||
jobs: Mutex<HashMap<String, CancelToken>>,
|
||||
scans: Mutex<HashMap<String, ScanReport>>,
|
||||
plans: Mutex<HashMap<String, UninstallPlan>>,
|
||||
apps: Mutex<Vec<AppInfo>>,
|
||||
sampler: Mutex<Sampler>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
fn lock<T>(value: &Mutex<T>) -> Result<MutexGuard<'_, T>, String> {
|
||||
value
|
||||
.lock()
|
||||
.map_err(|_| "The application state is unavailable; restart Squid.".to_string())
|
||||
}
|
||||
|
||||
fn begin(&self, job_id: &str) -> Result<CancelToken, String> {
|
||||
if job_id.trim().is_empty() {
|
||||
return Err("A job identifier is required.".into());
|
||||
}
|
||||
let token = CancelToken::new();
|
||||
let mut jobs = Self::lock(&self.jobs)?;
|
||||
jobs.insert(job_id.to_string(), token.clone());
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
fn finish(&self, job_id: &str) {
|
||||
if let Ok(mut jobs) = self.jobs.lock() {
|
||||
jobs.remove(job_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ProgressView {
|
||||
job_id: String,
|
||||
kind: String,
|
||||
event: String,
|
||||
phase: Option<String>,
|
||||
detail: Option<String>,
|
||||
done: Option<u64>,
|
||||
total: Option<u64>,
|
||||
subject: Option<String>,
|
||||
freed: Option<u64>,
|
||||
}
|
||||
|
||||
struct ProgressReporter {
|
||||
stop: Arc<AtomicBool>,
|
||||
handle: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl ProgressReporter {
|
||||
fn start(app: AppHandle, job_id: String, kind: &'static str, progress: Progress) -> Self {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let stopped = stop.clone();
|
||||
let handle = thread::spawn(move || {
|
||||
while !stopped.load(Ordering::Relaxed) {
|
||||
if let Some(event) = progress.recv(Duration::from_millis(80)) {
|
||||
emit_progress(&app, &job_id, kind, event);
|
||||
}
|
||||
}
|
||||
for event in progress.drain() {
|
||||
emit_progress(&app, &job_id, kind, event);
|
||||
}
|
||||
});
|
||||
Self {
|
||||
stop,
|
||||
handle: Some(handle),
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(mut self) {
|
||||
self.stop.store(true, Ordering::Relaxed);
|
||||
if let Some(handle) = self.handle.take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ProgressReporter {
|
||||
fn drop(&mut self) {
|
||||
self.stop.store(true, Ordering::Relaxed);
|
||||
if let Some(handle) = self.handle.take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_progress(app: &AppHandle, job_id: &str, kind: &str, event: Event) {
|
||||
let payload = match event {
|
||||
Event::Phase { phase, detail } => ProgressView {
|
||||
job_id: job_id.into(),
|
||||
kind: kind.into(),
|
||||
event: "phase".into(),
|
||||
phase: Some(phase.into()),
|
||||
detail: Some(detail),
|
||||
done: None,
|
||||
total: None,
|
||||
subject: None,
|
||||
freed: None,
|
||||
},
|
||||
Event::Tick {
|
||||
done,
|
||||
total,
|
||||
subject,
|
||||
} => ProgressView {
|
||||
job_id: job_id.into(),
|
||||
kind: kind.into(),
|
||||
event: "tick".into(),
|
||||
phase: None,
|
||||
detail: None,
|
||||
done: Some(done),
|
||||
total,
|
||||
subject: subject.map(|path| paths::pretty(&path)),
|
||||
freed: None,
|
||||
},
|
||||
Event::Note(note) => ProgressView {
|
||||
job_id: job_id.into(),
|
||||
kind: kind.into(),
|
||||
event: "note".into(),
|
||||
phase: None,
|
||||
detail: Some(note),
|
||||
done: None,
|
||||
total: None,
|
||||
subject: None,
|
||||
freed: None,
|
||||
},
|
||||
Event::Warning(warning) => ProgressView {
|
||||
job_id: job_id.into(),
|
||||
kind: kind.into(),
|
||||
event: "warning".into(),
|
||||
phase: None,
|
||||
detail: Some(warning),
|
||||
done: None,
|
||||
total: None,
|
||||
subject: None,
|
||||
freed: None,
|
||||
},
|
||||
Event::Deleted { path, freed } => ProgressView {
|
||||
job_id: job_id.into(),
|
||||
kind: kind.into(),
|
||||
event: "deleted".into(),
|
||||
phase: None,
|
||||
detail: Some(paths::pretty(&path)),
|
||||
done: None,
|
||||
total: None,
|
||||
subject: None,
|
||||
freed: Some(freed.as_u64()),
|
||||
},
|
||||
Event::Bucket {
|
||||
category,
|
||||
total,
|
||||
count,
|
||||
} => ProgressView {
|
||||
job_id: job_id.into(),
|
||||
kind: kind.into(),
|
||||
event: "bucket".into(),
|
||||
phase: None,
|
||||
detail: Some(format!("{}:{}:{}", category.id(), count, total.as_u64())),
|
||||
done: None,
|
||||
total: None,
|
||||
subject: None,
|
||||
freed: None,
|
||||
},
|
||||
Event::Done(_) => return,
|
||||
};
|
||||
let _ = app.emit("squid://progress", payload);
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CleanupItemView {
|
||||
path: String,
|
||||
display_path: String,
|
||||
kind: ItemKind,
|
||||
size: u64,
|
||||
allocated: u64,
|
||||
on_disk: u64,
|
||||
category: Category,
|
||||
label: String,
|
||||
rule_id: String,
|
||||
selected: bool,
|
||||
lock: Option<LockReason>,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
impl From<&CleanupItem> for CleanupItemView {
|
||||
fn from(item: &CleanupItem) -> Self {
|
||||
Self {
|
||||
path: item.path.to_string_lossy().to_string(),
|
||||
display_path: item.display_path(),
|
||||
kind: item.kind,
|
||||
size: item.size.as_u64(),
|
||||
allocated: item.allocated.as_u64(),
|
||||
on_disk: item.on_disk().as_u64(),
|
||||
category: item.category,
|
||||
label: item.label.clone(),
|
||||
rule_id: item.rule_id.clone(),
|
||||
selected: item.selected,
|
||||
lock: item.lock,
|
||||
note: item.note.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScanView {
|
||||
scan_id: String,
|
||||
items: Vec<CleanupItemView>,
|
||||
total: u64,
|
||||
total_selected: u64,
|
||||
selected_count: usize,
|
||||
unreadable: u32,
|
||||
elapsed_ms: u64,
|
||||
}
|
||||
|
||||
fn scan_view(scan_id: String, report: &ScanReport, elapsed_ms: u64) -> ScanView {
|
||||
let selected_total = report
|
||||
.items
|
||||
.iter()
|
||||
.filter(|item| item.selected && item.lock.is_none())
|
||||
.map(|item| item.on_disk().as_u64())
|
||||
.sum();
|
||||
ScanView {
|
||||
scan_id,
|
||||
items: report.items.iter().map(CleanupItemView::from).collect(),
|
||||
total: report.total_all().as_u64(),
|
||||
total_selected: selected_total,
|
||||
selected_count: report
|
||||
.items
|
||||
.iter()
|
||||
.filter(|item| item.selected && item.lock.is_none())
|
||||
.count(),
|
||||
unreadable: report.unreadable,
|
||||
elapsed_ms,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SkippedView {
|
||||
path: String,
|
||||
reason: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeleteResultView {
|
||||
freed: u64,
|
||||
freed_allocated: u64,
|
||||
removed: usize,
|
||||
failed: usize,
|
||||
errors: Vec<String>,
|
||||
mode: Option<DeleteMode>,
|
||||
session_id: Option<String>,
|
||||
skipped: Vec<SkippedView>,
|
||||
}
|
||||
|
||||
impl DeleteResultView {
|
||||
fn from_outcome(outcome: DeleteOutcome) -> Self {
|
||||
Self {
|
||||
freed: outcome.summary.freed.as_u64(),
|
||||
freed_allocated: outcome.summary.freed_allocated.as_u64(),
|
||||
removed: outcome.summary.removed,
|
||||
failed: outcome.summary.failed,
|
||||
errors: outcome.summary.errors,
|
||||
mode: outcome.summary.mode,
|
||||
session_id: outcome.summary.session_id,
|
||||
skipped: outcome
|
||||
.skipped
|
||||
.into_iter()
|
||||
.map(|(path, reason)| SkippedView {
|
||||
path: paths::pretty(&path),
|
||||
reason,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SettingsView {
|
||||
delete_mode: DeleteMode,
|
||||
whitelist: Vec<String>,
|
||||
purge_roots: Vec<String>,
|
||||
purge_min_age_days: u64,
|
||||
show_allocated: bool,
|
||||
language: Option<String>,
|
||||
history_keep: usize,
|
||||
setup_reviewed: bool,
|
||||
errors: Vec<String>,
|
||||
}
|
||||
|
||||
impl SettingsView {
|
||||
fn from_settings(settings: &Settings, errors: Vec<String>) -> Self {
|
||||
Self {
|
||||
delete_mode: settings.delete_mode,
|
||||
whitelist: settings.whitelist.clone(),
|
||||
purge_roots: settings.purge_roots.clone(),
|
||||
purge_min_age_days: settings.purge_min_age_days,
|
||||
show_allocated: settings.show_allocated,
|
||||
language: settings.language.clone(),
|
||||
history_keep: settings.history_keep,
|
||||
setup_reviewed: settings.desktop_setup_reviewed,
|
||||
errors,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BootstrapView {
|
||||
version: String,
|
||||
platform: String,
|
||||
os_name: String,
|
||||
os_version: String,
|
||||
hardware: String,
|
||||
arch: String,
|
||||
device: String,
|
||||
language: String,
|
||||
bin_noun: String,
|
||||
config_path: String,
|
||||
history_path: String,
|
||||
update_feed_url: String,
|
||||
update_check_enabled: bool,
|
||||
settings: SettingsView,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn bootstrap() -> BootstrapView {
|
||||
let (settings, errors) = Settings::load();
|
||||
let engine = Engine::new();
|
||||
let locale = squid_core::Locale::detect(&settings);
|
||||
let prefs = crate::update::load_prefs();
|
||||
BootstrapView {
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
platform: PlatformId::current().as_str().into(),
|
||||
os_name: engine.platform().display_name(),
|
||||
os_version: engine.platform().os_version(),
|
||||
hardware: engine.platform().hardware_model(),
|
||||
arch: std::env::consts::ARCH.into(),
|
||||
device: match engine.platform().device() {
|
||||
squid_platform::Device::Mac => "mac".into(),
|
||||
squid_platform::Device::Pc => "pc".into(),
|
||||
squid_platform::Device::Machine => "machine".into(),
|
||||
},
|
||||
language: locale.code().into(),
|
||||
bin_noun: match engine.platform().bin_noun() {
|
||||
squid_platform::BinNoun::Trash => "trash".into(),
|
||||
squid_platform::BinNoun::RecycleBin => "recycle-bin".into(),
|
||||
},
|
||||
config_path: Settings::path().to_string_lossy().to_string(),
|
||||
history_path: ledger::history_dir().to_string_lossy().to_string(),
|
||||
update_feed_url: crate::update::manifest_url(),
|
||||
update_check_enabled: prefs.update_check_enabled,
|
||||
settings: SettingsView::from_settings(&settings, errors),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn cancel_job(app: AppHandle, job_id: String) -> bool {
|
||||
let state = app.state::<AppState>();
|
||||
let Ok(jobs) = AppState::lock(&state.jobs) else {
|
||||
return false;
|
||||
};
|
||||
let Some(token) = jobs.get(&job_id) else {
|
||||
return false;
|
||||
};
|
||||
token.cancel();
|
||||
true
|
||||
}
|
||||
|
||||
fn parse_categories(values: &[String]) -> Result<Vec<Category>, String> {
|
||||
let mut categories = Vec::new();
|
||||
for value in values {
|
||||
let category =
|
||||
Category::parse(value).ok_or_else(|| format!("Unknown cleanup category: {value}"))?;
|
||||
if !categories.contains(&category) {
|
||||
categories.push(category);
|
||||
}
|
||||
}
|
||||
Ok(categories)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cleanup_scan(
|
||||
app: AppHandle,
|
||||
job_id: String,
|
||||
categories: Vec<String>,
|
||||
min_age_days: Option<u64>,
|
||||
orphans: bool,
|
||||
) -> Result<ScanView, String> {
|
||||
let token = app.state::<AppState>().begin(&job_id)?;
|
||||
let categories = parse_categories(&categories)?;
|
||||
let progress = Progress::new();
|
||||
let reporter =
|
||||
ProgressReporter::start(app.clone(), job_id.clone(), "cleanup", progress.clone());
|
||||
let started = Instant::now();
|
||||
let task = tauri::async_runtime::spawn_blocking(move || {
|
||||
let engine = Engine::new();
|
||||
let options = clean::CleanOptions {
|
||||
categories,
|
||||
skip_admin_rules: true,
|
||||
min_age_days,
|
||||
orphans,
|
||||
fast: false,
|
||||
};
|
||||
let report = clean::scan(&engine, &options, &progress, &token)?;
|
||||
clean::publish_buckets(&report, &progress);
|
||||
Ok::<ScanReport, squid_core::SquidError>(clean::sort_for_display(report))
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Cleanup scan failed: {error}"))?;
|
||||
reporter.finish();
|
||||
app.state::<AppState>().finish(&job_id);
|
||||
let report = task.map_err(|error| error.to_string())?;
|
||||
let view = scan_view(
|
||||
job_id.clone(),
|
||||
&report,
|
||||
started.elapsed().as_millis() as u64,
|
||||
);
|
||||
app.state::<AppState>()
|
||||
.scans
|
||||
.lock()
|
||||
.map_err(|_| "The scan cache is unavailable.".to_string())?
|
||||
.insert(job_id, report);
|
||||
Ok(view)
|
||||
}
|
||||
|
||||
fn select_indices(report: &mut ScanReport, selected: &[usize]) -> Result<(), String> {
|
||||
let selected: HashSet<usize> = selected.iter().copied().collect();
|
||||
if let Some(index) = selected.iter().find(|index| **index >= report.items.len()) {
|
||||
return Err(format!("Selected item {index} is not in this scan."));
|
||||
}
|
||||
for (index, item) in report.items.iter_mut().enumerate() {
|
||||
item.selected = selected.contains(&index) && item.lock.is_none();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cleanup_delete(
|
||||
app: AppHandle,
|
||||
job_id: String,
|
||||
scan_id: String,
|
||||
selected: Vec<usize>,
|
||||
mode: DeleteMode,
|
||||
) -> Result<DeleteResultView, String> {
|
||||
let token = app.state::<AppState>().begin(&job_id)?;
|
||||
let mut report = app
|
||||
.state::<AppState>()
|
||||
.scans
|
||||
.lock()
|
||||
.map_err(|_| "The scan cache is unavailable.".to_string())?
|
||||
.get(&scan_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| "This scan has expired. Run it again.".to_string())?;
|
||||
select_indices(&mut report, &selected)?;
|
||||
let items = report.items;
|
||||
let progress = Progress::new();
|
||||
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "delete", progress.clone());
|
||||
let task = tauri::async_runtime::spawn_blocking(move || {
|
||||
let engine = Engine::new();
|
||||
let job = DeleteJob::new(items, mode, "Squid · Cleanup");
|
||||
delete::execute(&engine, &job, &progress, &token)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Cleanup failed: {error}"))?;
|
||||
reporter.finish();
|
||||
app.state::<AppState>().finish(&job_id);
|
||||
let outcome = task.map_err(|error| error.to_string())?;
|
||||
if let Ok(mut scans) = app.state::<AppState>().scans.lock() {
|
||||
scans.remove(&scan_id);
|
||||
}
|
||||
Ok(DeleteResultView::from_outcome(outcome))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn purge_scan(
|
||||
app: AppHandle,
|
||||
job_id: String,
|
||||
roots: Vec<String>,
|
||||
min_age_days: Option<u64>,
|
||||
force: bool,
|
||||
) -> Result<ScanView, String> {
|
||||
let token = app.state::<AppState>().begin(&job_id)?;
|
||||
let progress = Progress::new();
|
||||
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "purge", progress.clone());
|
||||
let started = Instant::now();
|
||||
let task = tauri::async_runtime::spawn_blocking(move || {
|
||||
let engine = Engine::new();
|
||||
let options = purge::PurgeOptions {
|
||||
roots: roots.into_iter().map(|root| paths::expand(&root)).collect(),
|
||||
min_age_days,
|
||||
force,
|
||||
max_depth: None,
|
||||
};
|
||||
let mut report = purge::scan(&engine, &options, &progress, &token)?;
|
||||
report.items.sort_by(|a, b| {
|
||||
b.on_disk()
|
||||
.cmp(&a.on_disk())
|
||||
.then_with(|| a.path.cmp(&b.path))
|
||||
});
|
||||
Ok::<ScanReport, squid_core::SquidError>(report)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Deep clean scan failed: {error}"))?;
|
||||
reporter.finish();
|
||||
app.state::<AppState>().finish(&job_id);
|
||||
let report = task.map_err(|error| error.to_string())?;
|
||||
let view = scan_view(
|
||||
job_id.clone(),
|
||||
&report,
|
||||
started.elapsed().as_millis() as u64,
|
||||
);
|
||||
app.state::<AppState>()
|
||||
.scans
|
||||
.lock()
|
||||
.map_err(|_| "The scan cache is unavailable.".to_string())?
|
||||
.insert(job_id, report);
|
||||
Ok(view)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn purge_delete(
|
||||
app: AppHandle,
|
||||
job_id: String,
|
||||
scan_id: String,
|
||||
selected: Vec<usize>,
|
||||
mode: DeleteMode,
|
||||
) -> Result<DeleteResultView, String> {
|
||||
let token = app.state::<AppState>().begin(&job_id)?;
|
||||
let mut report = app
|
||||
.state::<AppState>()
|
||||
.scans
|
||||
.lock()
|
||||
.map_err(|_| "The scan cache is unavailable.".to_string())?
|
||||
.get(&scan_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| "This scan has expired. Run it again.".to_string())?;
|
||||
select_indices(&mut report, &selected)?;
|
||||
let items = report.items;
|
||||
let progress = Progress::new();
|
||||
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "delete", progress.clone());
|
||||
let task = tauri::async_runtime::spawn_blocking(move || {
|
||||
let engine = Engine::new();
|
||||
let job = DeleteJob::new(items, mode, "Squid · Deep Clean");
|
||||
delete::execute(&engine, &job, &progress, &token)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Deep clean failed: {error}"))?;
|
||||
reporter.finish();
|
||||
app.state::<AppState>().finish(&job_id);
|
||||
let outcome = task.map_err(|error| error.to_string())?;
|
||||
if let Ok(mut scans) = app.state::<AppState>().scans.lock() {
|
||||
scans.remove(&scan_id);
|
||||
}
|
||||
Ok(DeleteResultView::from_outcome(outcome))
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AppsView {
|
||||
apps: Vec<AppInfo>,
|
||||
total: u64,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn apps_scan(app: AppHandle, job_id: String) -> Result<AppsView, String> {
|
||||
let token = app.state::<AppState>().begin(&job_id)?;
|
||||
let progress = Progress::new();
|
||||
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "apps", progress.clone());
|
||||
let task = tauri::async_runtime::spawn_blocking(move || {
|
||||
let engine = Engine::new();
|
||||
uninstall::scan_apps(&engine, true, &progress, &token)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Application scan failed: {error}"))?;
|
||||
reporter.finish();
|
||||
app.state::<AppState>().finish(&job_id);
|
||||
let apps = task.map_err(|error| error.to_string())?;
|
||||
let total = apps.iter().map(|app| app.size.as_u64()).sum();
|
||||
if let Ok(mut cache) = app.state::<AppState>().apps.lock() {
|
||||
*cache = apps.clone();
|
||||
}
|
||||
Ok(AppsView { apps, total })
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PlanView {
|
||||
plan_id: String,
|
||||
app: AppInfo,
|
||||
items: Vec<CleanupItemView>,
|
||||
warnings: Vec<String>,
|
||||
total: u64,
|
||||
selected_count: usize,
|
||||
selected_total: u64,
|
||||
}
|
||||
|
||||
fn plan_view(plan_id: String, plan: &UninstallPlan) -> PlanView {
|
||||
PlanView {
|
||||
plan_id,
|
||||
app: plan.app.clone(),
|
||||
items: plan.items.iter().map(CleanupItemView::from).collect(),
|
||||
warnings: plan.warnings.clone(),
|
||||
total: plan.total().as_u64(),
|
||||
selected_count: plan
|
||||
.items
|
||||
.iter()
|
||||
.filter(|item| item.selected && item.lock.is_none())
|
||||
.count(),
|
||||
selected_total: plan
|
||||
.items
|
||||
.iter()
|
||||
.filter(|item| item.selected && item.lock.is_none())
|
||||
.map(|item| item.on_disk().as_u64())
|
||||
.sum(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn app_plan(app: AppHandle, job_id: String, app_key: String) -> Result<PlanView, String> {
|
||||
let chosen = app
|
||||
.state::<AppState>()
|
||||
.apps
|
||||
.lock()
|
||||
.map_err(|_| "The application inventory is unavailable.".to_string())?
|
||||
.iter()
|
||||
.find(|candidate| candidate.key() == app_key)
|
||||
.cloned()
|
||||
.ok_or_else(|| "That application is no longer in the inventory.".to_string())?;
|
||||
let token = app.state::<AppState>().begin(&job_id)?;
|
||||
let progress = Progress::new();
|
||||
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "plan", progress.clone());
|
||||
let task = tauri::async_runtime::spawn_blocking(move || {
|
||||
let engine = Engine::new();
|
||||
uninstall::build_plan(&engine, &chosen, &progress, &token)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Removal plan failed: {error}"))?;
|
||||
reporter.finish();
|
||||
app.state::<AppState>().finish(&job_id);
|
||||
let plan = task.map_err(|error| error.to_string())?;
|
||||
let view = plan_view(job_id.clone(), &plan);
|
||||
app.state::<AppState>()
|
||||
.plans
|
||||
.lock()
|
||||
.map_err(|_| "The removal plan cache is unavailable.".to_string())?
|
||||
.insert(job_id, plan);
|
||||
Ok(view)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn app_uninstall(
|
||||
app: AppHandle,
|
||||
job_id: String,
|
||||
plan_id: String,
|
||||
selected: Vec<usize>,
|
||||
mode: DeleteMode,
|
||||
) -> Result<DeleteResultView, String> {
|
||||
let token = app.state::<AppState>().begin(&job_id)?;
|
||||
let mut plan = app
|
||||
.state::<AppState>()
|
||||
.plans
|
||||
.lock()
|
||||
.map_err(|_| "The removal plan cache is unavailable.".to_string())?
|
||||
.get(&plan_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| "This removal plan has expired. Build it again.".to_string())?;
|
||||
let chosen: HashSet<usize> = selected.into_iter().collect();
|
||||
if let Some(index) = chosen.iter().find(|index| **index >= plan.items.len()) {
|
||||
return Err(format!("Selected item {index} is not in this plan."));
|
||||
}
|
||||
for (index, item) in plan.items.iter_mut().enumerate() {
|
||||
item.selected = chosen.contains(&index) && item.lock.is_none();
|
||||
}
|
||||
let progress = Progress::new();
|
||||
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "delete", progress.clone());
|
||||
let task = tauri::async_runtime::spawn_blocking(move || {
|
||||
let engine = Engine::new();
|
||||
uninstall::remove_plan(&engine, &plan, mode, &progress, &token)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Uninstall failed: {error}"))?;
|
||||
reporter.finish();
|
||||
app.state::<AppState>().finish(&job_id);
|
||||
let outcome = task.map_err(|error| error.to_string())?;
|
||||
if let Ok(mut plans) = app.state::<AppState>().plans.lock() {
|
||||
plans.remove(&plan_id);
|
||||
}
|
||||
Ok(DeleteResultView::from_outcome(outcome))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn storage_explore(
|
||||
app: AppHandle,
|
||||
job_id: String,
|
||||
path: Option<String>,
|
||||
depth: Option<usize>,
|
||||
top: Option<usize>,
|
||||
) -> Result<Node, String> {
|
||||
let token = app.state::<AppState>().begin(&job_id)?;
|
||||
let progress = Progress::new();
|
||||
let reporter =
|
||||
ProgressReporter::start(app.clone(), job_id.clone(), "storage", progress.clone());
|
||||
let root = path
|
||||
.filter(|path| !path.trim().is_empty())
|
||||
.map(|path| paths::expand(&path))
|
||||
.unwrap_or_else(paths::home_dir);
|
||||
if !root.is_dir() {
|
||||
app.state::<AppState>().finish(&job_id);
|
||||
reporter.finish();
|
||||
return Err(format!("{} is not a folder.", root.display()));
|
||||
}
|
||||
let task = tauri::async_runtime::spawn_blocking(move || {
|
||||
analyze::explore(
|
||||
&root,
|
||||
depth.unwrap_or(1).clamp(1, 3),
|
||||
top.unwrap_or(16),
|
||||
&token,
|
||||
&progress,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Storage analysis failed: {error}"))?;
|
||||
reporter.finish();
|
||||
app.state::<AppState>().finish(&job_id);
|
||||
task.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn storage_largest_files(
|
||||
app: AppHandle,
|
||||
job_id: String,
|
||||
path: String,
|
||||
limit: Option<usize>,
|
||||
) -> Result<Vec<FileEntry>, String> {
|
||||
let token = app.state::<AppState>().begin(&job_id)?;
|
||||
let progress = Progress::new();
|
||||
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "files", progress.clone());
|
||||
let root = paths::expand(&path);
|
||||
let task = tauri::async_runtime::spawn_blocking(move || {
|
||||
analyze::largest_files(
|
||||
&root,
|
||||
limit.unwrap_or(40).clamp(1, 200),
|
||||
Bytes(1_000_000),
|
||||
&token,
|
||||
&progress,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Large-file scan failed: {error}"))?;
|
||||
reporter.finish();
|
||||
app.state::<AppState>().finish(&job_id);
|
||||
task.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn system_snapshot(app: AppHandle) -> Result<SystemSnapshot, String> {
|
||||
let state = app.state::<AppState>();
|
||||
let mut sampler = AppState::lock(&state.sampler)?;
|
||||
Ok(sampler.refresh())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn stop_process(app: AppHandle, process: ProcessSample) -> Result<(), String> {
|
||||
let state = app.state::<AppState>();
|
||||
let mut sampler = AppState::lock(&state.sampler)?;
|
||||
sampler.stop(&process).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn history_list(limit: Option<usize>) -> Vec<Session> {
|
||||
ledger::load_sessions(limit.unwrap_or(60).clamp(1, 500))
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UndoResultView {
|
||||
restored: usize,
|
||||
skipped: usize,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn history_undo(session_id: String) -> Result<UndoResultView, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let (restored, skipped) =
|
||||
delete::restore_session(&session_id).map_err(|e| e.to_string())?;
|
||||
Ok(UndoResultView { restored, skipped })
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[derive(Clone, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SettingsPatch {
|
||||
delete_mode: Option<DeleteMode>,
|
||||
language: Option<String>,
|
||||
show_allocated: Option<bool>,
|
||||
purge_min_age_days: Option<u64>,
|
||||
history_keep: Option<usize>,
|
||||
setup_reviewed: Option<bool>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn settings_save(patch: SettingsPatch) -> Result<SettingsView, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let (mut settings, mut errors) = Settings::load();
|
||||
if let Some(mode) = patch.delete_mode {
|
||||
settings.delete_mode = mode;
|
||||
}
|
||||
if let Some(language) = patch.language {
|
||||
let trimmed = language.trim();
|
||||
settings.language = (!trimmed.is_empty()).then(|| trimmed.to_string());
|
||||
}
|
||||
if let Some(show) = patch.show_allocated {
|
||||
settings.show_allocated = show;
|
||||
}
|
||||
if let Some(days) = patch.purge_min_age_days {
|
||||
settings.purge_min_age_days = days.min(3650);
|
||||
}
|
||||
if let Some(keep) = patch.history_keep {
|
||||
settings.history_keep = keep.clamp(5, 500);
|
||||
}
|
||||
if let Some(reviewed) = patch.setup_reviewed {
|
||||
settings.desktop_setup_reviewed = reviewed;
|
||||
}
|
||||
settings
|
||||
.save()
|
||||
.map_err(|error| format!("Could not save settings: {error}"))?;
|
||||
errors.retain(|error| !error.contains("config.toml"));
|
||||
Ok(SettingsView::from_settings(&settings, errors))
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
fn escape_glob(text: &str) -> String {
|
||||
let mut escaped = String::with_capacity(text.len());
|
||||
for character in text.chars() {
|
||||
if matches!(character, '*' | '?' | '[' | ']' | '{' | '}' | '!') {
|
||||
escaped.push('\\');
|
||||
}
|
||||
escaped.push(character);
|
||||
}
|
||||
escaped
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn whitelist_add(path: String) -> Result<SettingsView, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let (mut settings, errors) = Settings::load();
|
||||
let expanded = paths::expand(&path);
|
||||
if expanded.as_os_str().is_empty() {
|
||||
return Err("Choose a path to protect.".into());
|
||||
}
|
||||
settings.add_whitelist(escape_glob(&paths::pretty(&expanded)));
|
||||
settings
|
||||
.save()
|
||||
.map_err(|error| format!("Could not save settings: {error}"))?;
|
||||
Ok(SettingsView::from_settings(&settings, errors))
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn whitelist_remove(pattern: String) -> Result<SettingsView, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let (mut settings, errors) = Settings::load();
|
||||
settings.remove_whitelist(&pattern);
|
||||
settings
|
||||
.save()
|
||||
.map_err(|error| format!("Could not save settings: {error}"))?;
|
||||
Ok(SettingsView::from_settings(&settings, errors))
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn reveal_path(app: AppHandle, path: String) -> Result<(), String> {
|
||||
let target = PathBuf::from(path);
|
||||
if !target.exists() {
|
||||
return Err(format!("{} no longer exists.", target.display()));
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
crate::process::command("/usr/bin/open")
|
||||
.arg("-R")
|
||||
.arg(&target)
|
||||
.status()
|
||||
.map_err(|error| error.to_string())?;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
crate::process::command("explorer.exe")
|
||||
.arg(format!("/select,{}", target.display()))
|
||||
.status()
|
||||
.map_err(|error| error.to_string())?;
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
{
|
||||
crate::process::command("xdg-open")
|
||||
.arg(target.parent().unwrap_or(Path::new("/")))
|
||||
.status()
|
||||
.map_err(|error| error.to_string())?;
|
||||
}
|
||||
let _ = app;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn open_trash() -> Result<(), String> {
|
||||
let platform = squid_platform::current();
|
||||
platform.reveal_trash();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_selected_index_can_never_select_a_locked_item() {
|
||||
let mut report = ScanReport::default();
|
||||
report.items.push(CleanupItem::new(
|
||||
PathBuf::from("/tmp/keep"),
|
||||
ItemKind::File,
|
||||
Category::Logs,
|
||||
"keep",
|
||||
));
|
||||
report.items.push(
|
||||
CleanupItem::new(
|
||||
PathBuf::from("/tmp/locked"),
|
||||
ItemKind::File,
|
||||
Category::Logs,
|
||||
"locked",
|
||||
)
|
||||
.locked(LockReason::Protected),
|
||||
);
|
||||
select_indices(&mut report, &[0, 1]).unwrap();
|
||||
assert!(report.items[0].selected);
|
||||
assert!(!report.items[1].selected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_out_of_range_selection_is_refused() {
|
||||
let mut report = ScanReport::default();
|
||||
assert!(select_indices(&mut report, &[0]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitelist_paths_are_taken_literally() {
|
||||
assert_eq!(escape_glob("~/Caches/[demo]*"), "~/Caches/\\[demo\\]\\*");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
mod app;
|
||||
mod permissions;
|
||||
mod process;
|
||||
mod update;
|
||||
|
||||
use tauri::{
|
||||
menu::{Menu, MenuItem, PredefinedMenuItem},
|
||||
tray::TrayIconBuilder,
|
||||
AppHandle, Emitter, Manager, WindowEvent,
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use tauri::RunEvent;
|
||||
|
||||
fn show_main_window(app: &AppHandle) {
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.unminimize();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
}
|
||||
|
||||
fn navigate_to(app: &AppHandle, page: &'static str) {
|
||||
show_main_window(app);
|
||||
let _ = app.emit("squid://navigate", page);
|
||||
}
|
||||
|
||||
fn create_tray(app: &AppHandle) -> tauri::Result<()> {
|
||||
let open = MenuItem::with_id(app, "open", "打开 Squid", true, None::<&str>)?;
|
||||
let cleanup = MenuItem::with_id(app, "cleanup", "日常清理", true, None::<&str>)?;
|
||||
let apps = MenuItem::with_id(app, "applications", "应用卸载", true, None::<&str>)?;
|
||||
let purge = MenuItem::with_id(app, "purge", "深度清理", true, None::<&str>)?;
|
||||
let quit = MenuItem::with_id(app, "quit", "退出 Squid", true, None::<&str>)?;
|
||||
let first_separator = PredefinedMenuItem::separator(app)?;
|
||||
let last_separator = PredefinedMenuItem::separator(app)?;
|
||||
let menu = Menu::with_items(
|
||||
app,
|
||||
&[
|
||||
&open,
|
||||
&first_separator,
|
||||
&cleanup,
|
||||
&apps,
|
||||
&purge,
|
||||
&last_separator,
|
||||
&quit,
|
||||
],
|
||||
)?;
|
||||
let icon = app
|
||||
.default_window_icon()
|
||||
.cloned()
|
||||
.ok_or_else(|| tauri::Error::AssetNotFound("default window icon".into()))?;
|
||||
|
||||
TrayIconBuilder::with_id("squid-tray")
|
||||
.icon(icon)
|
||||
.tooltip("Squid")
|
||||
.menu(&menu)
|
||||
.show_menu_on_left_click(true)
|
||||
.on_menu_event(|app, event| match event.id.as_ref() {
|
||||
"open" => show_main_window(app),
|
||||
"cleanup" => navigate_to(app, "cleanup"),
|
||||
"applications" => navigate_to(app, "applications"),
|
||||
"purge" => navigate_to(app, "purge"),
|
||||
"quit" => app.exit(0),
|
||||
_ => {}
|
||||
})
|
||||
.build(app)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
let app = tauri::Builder::default()
|
||||
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
|
||||
show_main_window(app);
|
||||
}))
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.on_window_event(|window, event| {
|
||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||
api.prevent_close();
|
||||
let _ = window.hide();
|
||||
}
|
||||
})
|
||||
.manage(app::AppState::default())
|
||||
.manage(update::UpdateState::default())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
app::bootstrap,
|
||||
app::cancel_job,
|
||||
app::cleanup_scan,
|
||||
app::cleanup_delete,
|
||||
app::purge_scan,
|
||||
app::purge_delete,
|
||||
app::apps_scan,
|
||||
app::app_plan,
|
||||
app::app_uninstall,
|
||||
app::storage_explore,
|
||||
app::storage_largest_files,
|
||||
app::system_snapshot,
|
||||
app::stop_process,
|
||||
app::history_list,
|
||||
app::history_undo,
|
||||
app::settings_save,
|
||||
app::whitelist_add,
|
||||
app::whitelist_remove,
|
||||
app::reveal_path,
|
||||
app::open_trash,
|
||||
permissions::permission_status,
|
||||
permissions::open_full_disk_access_settings,
|
||||
update::update_check,
|
||||
update::update_status,
|
||||
update::update_download,
|
||||
update::update_install,
|
||||
update::update_clear,
|
||||
update::set_update_check_enabled,
|
||||
])
|
||||
.setup(|app| {
|
||||
create_tray(app.handle())?;
|
||||
update::spawn_startup_check(app.handle());
|
||||
Ok(())
|
||||
})
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while running Squid");
|
||||
|
||||
app.run(|app_handle, event| {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let RunEvent::Reopen {
|
||||
has_visible_windows: false,
|
||||
..
|
||||
} = event
|
||||
{
|
||||
show_main_window(app_handle);
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let _ = (app_handle, event);
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
squid_desktop_lib::run();
|
||||
}
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
//! Optional macOS privacy access used by the guided first-run check and Settings.
|
||||
//!
|
||||
//! macOS has no public API that reports Full Disk Access. The app probes a small
|
||||
//! set of TCC-protected locations that a system-care tool normally reads. The probe
|
||||
//! only opens a file or lists a directory; it never reads their contents.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PermissionStatus {
|
||||
/// `granted`, `denied`, `unknown`, or `not-required`.
|
||||
pub full_disk_access: String,
|
||||
}
|
||||
|
||||
impl PermissionStatus {
|
||||
fn new(state: &str) -> Self {
|
||||
Self {
|
||||
full_disk_access: state.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn permission_status() -> PermissionStatus {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
PermissionStatus::new(full_disk_access_state())
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
PermissionStatus::new("not-required")
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn open_full_disk_access_settings() -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let status = crate::process::command("/usr/bin/open")
|
||||
.arg("x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles")
|
||||
.status()
|
||||
.map_err(|error| format!("Could not open Full Disk Access settings: {error}"))?;
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
Err("Could not open Full Disk Access settings.".into())
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
Err("Full Disk Access is macOS-specific.".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn full_disk_access_state() -> &'static str {
|
||||
let home = squid_core::paths::home_dir();
|
||||
let probes = [
|
||||
home.join("Library/Application Support/com.apple.TCC/TCC.db"),
|
||||
home.join("Library/Safari"),
|
||||
home.join("Library/Mail"),
|
||||
home.join("Library/Messages"),
|
||||
];
|
||||
|
||||
let mut readable = false;
|
||||
let mut denied = false;
|
||||
for path in probes {
|
||||
match probe(&path) {
|
||||
Probe::Readable => readable = true,
|
||||
Probe::Denied => denied = true,
|
||||
Probe::Missing | Probe::Unknown => {}
|
||||
}
|
||||
}
|
||||
if readable {
|
||||
"granted"
|
||||
} else if denied {
|
||||
"denied"
|
||||
} else {
|
||||
"unknown"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
enum Probe {
|
||||
Readable,
|
||||
Denied,
|
||||
Missing,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn probe(path: &std::path::Path) -> Probe {
|
||||
use std::io::ErrorKind;
|
||||
|
||||
let metadata = match std::fs::metadata(path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => return Probe::Missing,
|
||||
Err(error) if error.kind() == ErrorKind::PermissionDenied => return Probe::Denied,
|
||||
Err(_) => return Probe::Unknown,
|
||||
};
|
||||
let result = if metadata.is_dir() {
|
||||
std::fs::read_dir(path).map(|_| ())
|
||||
} else {
|
||||
std::fs::File::open(path).map(|_| ())
|
||||
};
|
||||
match result {
|
||||
Ok(()) => Probe::Readable,
|
||||
Err(error) if error.kind() == ErrorKind::PermissionDenied => Probe::Denied,
|
||||
Err(_) => Probe::Unknown,
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
//! Child-process helpers for a GUI app.
|
||||
//!
|
||||
//! Every helper is spawned without a console window on Windows. The updater
|
||||
//! also relies on the same hidden spawn path so a background download never
|
||||
//! flashes a terminal over the main window.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
#[cfg(target_os = "windows")]
|
||||
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
|
||||
|
||||
pub fn hidden(command: &mut Command) -> &mut Command {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let _ = command;
|
||||
command
|
||||
}
|
||||
|
||||
pub fn command(program: impl AsRef<OsStr>) -> Command {
|
||||
let mut command = Command::new(program);
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
hidden(&mut command);
|
||||
command
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Squid",
|
||||
"version": "0.1.3",
|
||||
"identifier": "app.nex.squid",
|
||||
"mainBinaryName": "squid-desktop",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
"devUrl": "http://localhost:1420",
|
||||
"beforeBuildCommand": "pnpm build",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"app": {
|
||||
"macOSPrivateApi": true,
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "Squid",
|
||||
"url": "index.html",
|
||||
"width": 1220,
|
||||
"height": 800,
|
||||
"minWidth": 1000,
|
||||
"minHeight": 680,
|
||||
"center": true,
|
||||
"visible": true,
|
||||
"titleBarStyle": "Overlay",
|
||||
"hiddenTitle": true,
|
||||
"acceptFirstMouse": true
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": ["app", "dmg", "nsis"],
|
||||
"category": "Utility",
|
||||
"shortDescription": "Clean, uninstall, purge and monitor your Mac or PC.",
|
||||
"longDescription": "Squid is a cross-platform system care app for macOS and Windows. It scans caches and system junk, removes applications with their leftovers, finds project build artefacts, maps disk usage and monitors live system health.",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"macOS": {
|
||||
"minimumSystemVersion": "12.0",
|
||||
"infoPlist": "Info.plist",
|
||||
"signingIdentity": "-",
|
||||
"hardenedRuntime": false
|
||||
},
|
||||
"windows": {
|
||||
"nsis": {
|
||||
"installMode": "currentUser",
|
||||
"displayLanguageSelector": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,419 @@
|
|||
import {
|
||||
AppWindow,
|
||||
ChevronDown,
|
||||
Eraser,
|
||||
History,
|
||||
LayoutDashboard,
|
||||
RefreshCw,
|
||||
Settings,
|
||||
ShieldCheck,
|
||||
Sparkles,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useState, type ReactNode } from "react";
|
||||
import { useAppsWorkspace } from "./hooks/useAppsWorkspace";
|
||||
import { useScanWorkspace } from "./hooks/useScanWorkspace";
|
||||
import { useSystemSnapshot } from "./hooks/useSystemSnapshot";
|
||||
import { useUpdateFlow } from "./hooks/useUpdateFlow";
|
||||
import { detectLanguage, I18nProvider, useI18n } from "./i18n";
|
||||
import { api } from "./lib/api";
|
||||
import { messageFrom } from "./lib/format";
|
||||
import type {
|
||||
Bootstrap,
|
||||
DeleteMode,
|
||||
Language,
|
||||
PageId,
|
||||
SettingsView,
|
||||
} from "./types";
|
||||
import { useToast } from "./components/ui";
|
||||
import { SetupPanel } from "./components/SetupPanel";
|
||||
import appIconUrl from "../src-tauri/icons/128x128.png";
|
||||
import { ApplicationsPage } from "./pages/ApplicationsPage";
|
||||
import { CleanupPage } from "./pages/CleanupPage";
|
||||
import { HistoryPage } from "./pages/HistoryPage";
|
||||
import { OverviewPage } from "./pages/OverviewPage";
|
||||
import { PurgePage } from "./pages/PurgePage";
|
||||
import { SettingsPage } from "./pages/SettingsPage";
|
||||
import { StoragePage } from "./pages/StoragePage";
|
||||
import { SystemPage } from "./pages/SystemPage";
|
||||
|
||||
const NAV_ITEMS: {
|
||||
id: PageId;
|
||||
labelEn: string;
|
||||
labelZh: string;
|
||||
icon: typeof LayoutDashboard;
|
||||
}[] = [
|
||||
{
|
||||
id: "overview",
|
||||
labelEn: "Computer overview",
|
||||
labelZh: "电脑概览",
|
||||
icon: LayoutDashboard,
|
||||
},
|
||||
{
|
||||
id: "cleanup",
|
||||
labelEn: "Daily cleanup",
|
||||
labelZh: "日常清理",
|
||||
icon: Eraser,
|
||||
},
|
||||
{
|
||||
id: "applications",
|
||||
labelEn: "Uninstall apps",
|
||||
labelZh: "应用卸载",
|
||||
icon: AppWindow,
|
||||
},
|
||||
];
|
||||
|
||||
const PAGE_TITLES: Record<PageId, [string, string]> = {
|
||||
overview: ["Computer overview", "电脑概览"],
|
||||
cleanup: ["Daily cleanup", "日常清理"],
|
||||
applications: ["Uninstall apps", "应用卸载"],
|
||||
purge: ["Deep Clean", "深度清理"],
|
||||
storage: ["Storage", "存储空间"],
|
||||
system: ["System", "系统状态"],
|
||||
history: ["History", "历史记录"],
|
||||
settings: ["Settings", "设置"],
|
||||
};
|
||||
|
||||
function BrandMark({ small = false }: { small?: boolean }) {
|
||||
return (
|
||||
<img
|
||||
className={`brand-mark ${small ? "is-small" : ""}`}
|
||||
src={appIconUrl}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function LoadingScreen() {
|
||||
return (
|
||||
<div className="app-loading">
|
||||
<div className="loading-orb">
|
||||
<BrandMark />
|
||||
</div>
|
||||
<strong>Squid</strong>
|
||||
<span>Preparing your computer care workspace…</span>
|
||||
<div className="loading-track">
|
||||
<i />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BootstrapError({ message }: { message: string }) {
|
||||
return (
|
||||
<div className="app-loading is-error">
|
||||
<div className="loading-orb">
|
||||
<BrandMark />
|
||||
</div>
|
||||
<strong>Squid could not start</strong>
|
||||
<span>{message}</span>
|
||||
<button onClick={() => window.location.reload()}>
|
||||
<RefreshCw size={14} />
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const { push } = useToast();
|
||||
const [bootstrap, setBootstrap] = useState<Bootstrap | null>(null);
|
||||
const [bootError, setBootError] = useState<string | null>(null);
|
||||
const [page, setPage] = useState<PageId>("overview");
|
||||
const [lang, setLang] = useState<Language>(detectLanguage);
|
||||
const [settings, setSettings] = useState<SettingsView | null>(null);
|
||||
const [autoCheck, setAutoCheck] = useState(true);
|
||||
const [setupOpen, setSetupOpen] = useState(false);
|
||||
const cleanup = useScanWorkspace("cleanup");
|
||||
const purge = useScanWorkspace("purge");
|
||||
const apps = useAppsWorkspace();
|
||||
const systemActive = page === "overview" || page === "system";
|
||||
const system = useSystemSnapshot(systemActive);
|
||||
const update = useUpdateFlow(bootstrap?.updateFeedUrl ?? "", autoCheck);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void api
|
||||
.bootstrap()
|
||||
.then((next) => {
|
||||
if (cancelled) return;
|
||||
setBootstrap(next);
|
||||
setSettings(next.settings);
|
||||
setLang(next.language);
|
||||
setAutoCheck(next.updateCheckEnabled);
|
||||
setSetupOpen(!next.settings.setupReviewed);
|
||||
document.documentElement.lang = next.language === "zh" ? "zh-CN" : "en";
|
||||
})
|
||||
.catch((reason) => {
|
||||
if (!cancelled) setBootError(messageFrom(reason));
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let unlisten: (() => void) | null = null;
|
||||
void api
|
||||
.onNavigate((next) => {
|
||||
if (!cancelled) setPage(next);
|
||||
})
|
||||
.then((stop) => {
|
||||
if (cancelled) stop();
|
||||
else unlisten = stop;
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unlisten?.();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const order: PageId[] = [
|
||||
"overview",
|
||||
"cleanup",
|
||||
"applications",
|
||||
"purge",
|
||||
"storage",
|
||||
"system",
|
||||
"history",
|
||||
"settings",
|
||||
];
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return;
|
||||
const index = Number(event.key) - 1;
|
||||
if (!Number.isInteger(index) || index < 0 || index >= order.length) return;
|
||||
event.preventDefault();
|
||||
setPage(order[index]);
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, []);
|
||||
|
||||
const changeLanguage = useCallback(
|
||||
async (nextLanguage: Language) => {
|
||||
setLang(nextLanguage);
|
||||
document.documentElement.lang = nextLanguage === "zh" ? "zh-CN" : "en";
|
||||
try {
|
||||
const next = await api.settingsSave({ language: nextLanguage });
|
||||
setSettings(next);
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
}
|
||||
},
|
||||
[push],
|
||||
);
|
||||
|
||||
const changeAutoCheck = useCallback(
|
||||
(enabled: boolean) => {
|
||||
setAutoCheck(enabled);
|
||||
void api
|
||||
.setUpdateCheckEnabled(enabled)
|
||||
.catch((reason) => {
|
||||
setAutoCheck(!enabled);
|
||||
push(messageFrom(reason), "danger");
|
||||
});
|
||||
},
|
||||
[push],
|
||||
);
|
||||
|
||||
const finishSetup = useCallback(async () => {
|
||||
setSetupOpen(false);
|
||||
try {
|
||||
const next = await api.settingsSave({ setupReviewed: true });
|
||||
setSettings(next);
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
}
|
||||
}, [push]);
|
||||
|
||||
if (bootError) return <BootstrapError message={bootError} />;
|
||||
if (!bootstrap || !settings) return <LoadingScreen />;
|
||||
|
||||
const deleteMode: DeleteMode = settings.deleteMode;
|
||||
const activeUpdate =
|
||||
update.status?.state === "available" || update.status?.state === "ready"
|
||||
? update.status
|
||||
: null;
|
||||
|
||||
return (
|
||||
<I18nProvider lang={lang} setLang={setLang}>
|
||||
<AppChrome
|
||||
bootstrap={bootstrap}
|
||||
page={page}
|
||||
setPage={setPage}
|
||||
updateVersion={activeUpdate?.availableVersion ?? null}
|
||||
>
|
||||
{page === "overview" ? (
|
||||
<OverviewPage
|
||||
bootstrap={bootstrap}
|
||||
snapshot={system.snapshot}
|
||||
cleanup={cleanup}
|
||||
onNavigate={setPage}
|
||||
/>
|
||||
) : null}
|
||||
{page === "cleanup" ? (
|
||||
<CleanupPage
|
||||
workspace={cleanup}
|
||||
deleteMode={deleteMode}
|
||||
onHistory={() => setPage("history")}
|
||||
/>
|
||||
) : null}
|
||||
{page === "applications" ? (
|
||||
<ApplicationsPage workspace={apps} onHistory={() => setPage("history")} />
|
||||
) : null}
|
||||
{page === "purge" ? (
|
||||
<PurgePage
|
||||
workspace={purge}
|
||||
bootstrap={bootstrap}
|
||||
deleteMode={deleteMode}
|
||||
onHistory={() => setPage("history")}
|
||||
/>
|
||||
) : null}
|
||||
{page === "storage" ? <StoragePage bootstrap={bootstrap} /> : null}
|
||||
{page === "system" ? (
|
||||
<SystemPage
|
||||
snapshot={system.snapshot}
|
||||
error={system.error}
|
||||
loading={system.loading}
|
||||
refresh={system.refresh}
|
||||
/>
|
||||
) : null}
|
||||
{page === "history" ? <HistoryPage /> : null}
|
||||
{page === "settings" ? (
|
||||
<SettingsPage
|
||||
bootstrap={bootstrap}
|
||||
settings={settings}
|
||||
flow={update}
|
||||
autoCheck={autoCheck}
|
||||
onSettingsChange={setSettings}
|
||||
onLanguageChange={changeLanguage}
|
||||
onAutoCheckChange={changeAutoCheck}
|
||||
/>
|
||||
) : null}
|
||||
</AppChrome>
|
||||
{setupOpen ? <SetupPanel onDone={() => void finishSetup()} /> : null}
|
||||
</I18nProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function AppChrome({
|
||||
bootstrap,
|
||||
page,
|
||||
setPage,
|
||||
updateVersion,
|
||||
children,
|
||||
}: {
|
||||
bootstrap: Bootstrap;
|
||||
page: PageId;
|
||||
setPage: (page: PageId) => void;
|
||||
updateVersion: string | null;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { t, lang } = useI18n();
|
||||
const title = PAGE_TITLES[page][lang === "zh" ? 1 : 0];
|
||||
|
||||
return (
|
||||
<div
|
||||
className="app"
|
||||
data-platform={bootstrap.platform}
|
||||
data-page={page}
|
||||
>
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-drag" data-tauri-drag-region />
|
||||
<div className="sidebar-brand">
|
||||
<BrandMark />
|
||||
<div>
|
||||
<strong>Squid</strong>
|
||||
<span>{t("Give your computer a bath", "给你的电脑洗个澡")}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="sidebar-nav" aria-label={t("Main navigation", "主导航")}>
|
||||
{NAV_ITEMS.map((item) => {
|
||||
const Icon = item.icon;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
className={`nav-item ${page === item.id ? "is-active" : ""}`}
|
||||
onClick={() => setPage(item.id)}
|
||||
aria-current={page === item.id ? "page" : undefined}
|
||||
>
|
||||
<Icon size={18} />
|
||||
<span>{lang === "zh" ? item.labelZh : item.labelEn}</span>
|
||||
{item.id === "cleanup" && page !== "cleanup" ? (
|
||||
<i className="nav-dot" />
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-bottom">
|
||||
{updateVersion ? (
|
||||
<button
|
||||
className="sidebar-update"
|
||||
onClick={() => {
|
||||
setPage("settings");
|
||||
}}
|
||||
>
|
||||
<span>
|
||||
<Sparkles size={15} />
|
||||
</span>
|
||||
<div>
|
||||
<strong>{t("Update available", "有可用更新")}</strong>
|
||||
<small>Squid {updateVersion}</small>
|
||||
</div>
|
||||
<ChevronDown size={14} />
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
className={`nav-item ${page === "history" ? "is-active" : ""}`}
|
||||
onClick={() => setPage("history")}
|
||||
>
|
||||
<History size={18} />
|
||||
<span>{t("History", "历史记录")}</span>
|
||||
</button>
|
||||
<button
|
||||
className={`nav-item ${page === "settings" ? "is-active" : ""}`}
|
||||
onClick={() => setPage("settings")}
|
||||
>
|
||||
<Settings size={18} />
|
||||
<span>{t("Settings", "设置")}</span>
|
||||
{updateVersion ? <i className="nav-dot" /> : null}
|
||||
</button>
|
||||
<div className="sidebar-meta">
|
||||
<span>Squid {bootstrap.version}</span>
|
||||
<span>{bootstrap.platform === "windows" ? "Windows" : bootstrap.osName}</span>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main className="main">
|
||||
<header className="topbar" data-tauri-drag-region>
|
||||
<div className="topbar-title" data-tauri-drag-region>
|
||||
<span>{title}</span>
|
||||
<i />
|
||||
<small>{bootstrap.hardware}</small>
|
||||
</div>
|
||||
<div className="topbar-actions">
|
||||
<span className="privacy-pill">
|
||||
<ShieldCheck size={13} />
|
||||
{t("Local & private", "本地与私密")}
|
||||
</span>
|
||||
{updateVersion ? (
|
||||
<button className="topbar-update" onClick={() => setPage("settings")}>
|
||||
<Sparkles size={13} />
|
||||
{t("Update", "更新")} {updateVersion}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</header>
|
||||
<div className="page-scroll" key={page}>
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,406 @@
|
|||
import {
|
||||
ArrowUpRight,
|
||||
FolderOpen,
|
||||
LockKeyhole,
|
||||
RotateCcw,
|
||||
ShieldCheck,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { formatBytes, formatCount, shortPath } from "../lib/format";
|
||||
import type { Category, CleanupItem, DeleteMode, ScanResult } from "../types";
|
||||
import type { ScanWorkspace } from "../hooks/useScanWorkspace";
|
||||
import {
|
||||
Button,
|
||||
CATEGORY_META,
|
||||
CATEGORY_ORDER,
|
||||
CategoryCard,
|
||||
Checkbox,
|
||||
ConfirmDialog,
|
||||
InlineError,
|
||||
ProgressCard,
|
||||
ResultSummary,
|
||||
SectionTitle,
|
||||
categoryLabel,
|
||||
lockLabel,
|
||||
useToast,
|
||||
} from "./ui";
|
||||
|
||||
type CategoryGroup = { total: number; count: number; items: number[]; selected: number };
|
||||
|
||||
function grouped(result: ScanResult) {
|
||||
const groups = new Map<Category, CategoryGroup>();
|
||||
result.items.forEach((item, index) => {
|
||||
const group = groups.get(item.category) ?? {
|
||||
total: 0,
|
||||
count: 0,
|
||||
items: [],
|
||||
selected: 0,
|
||||
};
|
||||
group.total += item.onDisk;
|
||||
group.count += 1;
|
||||
group.items.push(index);
|
||||
group.selected += 1;
|
||||
groups.set(item.category, group);
|
||||
});
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function CategorySummary({
|
||||
result,
|
||||
selected,
|
||||
onToggle,
|
||||
onInspect,
|
||||
}: {
|
||||
result: ScanResult;
|
||||
selected: Set<number>;
|
||||
onToggle: (category: Category) => void;
|
||||
onInspect: (category: Category) => void;
|
||||
}) {
|
||||
const groups = useMemo(() => grouped(result), [result]);
|
||||
return (
|
||||
<div className="category-grid">
|
||||
{CATEGORY_ORDER.filter((category) => groups.has(category)).map((category) => {
|
||||
const group = groups.get(category)!;
|
||||
const indexes = group.items.filter((index) => !result.items[index].lock);
|
||||
const allSelected = indexes.length > 0 && indexes.every((index) => selected.has(index));
|
||||
return (
|
||||
<CategoryCard
|
||||
key={category}
|
||||
category={category}
|
||||
total={group.total}
|
||||
count={group.count}
|
||||
selected={allSelected}
|
||||
disabled={indexes.length === 0}
|
||||
onToggle={() => onToggle(category)}
|
||||
onInspect={() => onInspect(category)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ItemRow({
|
||||
item,
|
||||
checked,
|
||||
onToggle,
|
||||
}: {
|
||||
item: CleanupItem;
|
||||
checked: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const { lang, t } = useI18n();
|
||||
const Icon = CATEGORY_META[item.category].icon;
|
||||
return (
|
||||
<div
|
||||
className={`cleanup-row ${item.lock ? "is-locked" : ""} ${
|
||||
checked ? "is-selected" : ""
|
||||
}`}
|
||||
onClick={item.lock ? undefined : onToggle}
|
||||
>
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
disabled={Boolean(item.lock)}
|
||||
onChange={onToggle}
|
||||
label={item.label}
|
||||
/>
|
||||
<span className={`row-icon tone-${CATEGORY_META[item.category].tone}`}>
|
||||
<Icon size={17} />
|
||||
</span>
|
||||
<span className="cleanup-row-copy">
|
||||
<span className="cleanup-row-title">
|
||||
<strong>{item.label}</strong>
|
||||
<span className="row-category">{categoryLabel(item.category, lang)}</span>
|
||||
</span>
|
||||
<span className="cleanup-row-path" title={item.displayPath}>
|
||||
{shortPath(item.displayPath, 90)}
|
||||
</span>
|
||||
{item.lock || item.note ? (
|
||||
<span className={`cleanup-row-note ${item.lock ? "is-locked" : ""}`}>
|
||||
{item.lock ? <LockKeyhole size={12} /> : null}
|
||||
{item.lock ? lockLabel(item.lock, t) : item.note}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="cleanup-row-size">{formatBytes(item.onDisk)}</span>
|
||||
<button
|
||||
className="row-reveal"
|
||||
title={t("Show in Finder", "在访达中显示")}
|
||||
aria-label={t("Show in Finder", "Show in Finder")}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
void api.revealPath(item.path).catch(() => undefined);
|
||||
}}
|
||||
>
|
||||
<ArrowUpRight size={15} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CleanupInventory({
|
||||
workspace,
|
||||
defaultMode,
|
||||
onHistory,
|
||||
}: {
|
||||
workspace: ScanWorkspace;
|
||||
defaultMode: DeleteMode;
|
||||
onHistory: () => void;
|
||||
}) {
|
||||
const { t, lang, bin } = useI18n();
|
||||
const { push } = useToast();
|
||||
const [focus, setFocus] = useState<Category | null>(null);
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [mode, setMode] = useState<DeleteMode>(defaultMode);
|
||||
|
||||
useEffect(() => setMode(defaultMode), [defaultMode]);
|
||||
|
||||
const result = workspace.result;
|
||||
const groups = useMemo(
|
||||
() => (result ? grouped(result) : new Map<Category, CategoryGroup>()),
|
||||
[result],
|
||||
);
|
||||
const visibleItems = useMemo(() => {
|
||||
if (!result) return [];
|
||||
return result.items
|
||||
.map((item, index) => ({ item, index }))
|
||||
.filter(({ item }) => !focus || item.category === focus);
|
||||
}, [focus, result]);
|
||||
const removables = result?.items.filter((item) => !item.lock).length ?? 0;
|
||||
|
||||
if (workspace.scanning) {
|
||||
return (
|
||||
<ProgressCard
|
||||
progress={workspace.progress}
|
||||
title={t("Scanning your computer safely…", "正在安全扫描您的电脑…")}
|
||||
onCancel={() => void workspace.cancel()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (workspace.summary) {
|
||||
return (
|
||||
<ResultSummary
|
||||
removed={workspace.summary.removed}
|
||||
freed={workspace.summary.freedAllocated || workspace.summary.freed}
|
||||
failed={workspace.summary.failed}
|
||||
mode={workspace.summary.mode}
|
||||
onAgain={() => void workspace.runScan()}
|
||||
onHistory={onHistory}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (!result) return null;
|
||||
|
||||
const confirm = async () => {
|
||||
const summary = await workspace.clean(mode);
|
||||
setConfirming(false);
|
||||
if (summary) {
|
||||
push(
|
||||
t(
|
||||
`${formatBytes(summary.freedAllocated || summary.freed)} cleaned`,
|
||||
`已清理 ${formatBytes(summary.freedAllocated || summary.freed)}`,
|
||||
),
|
||||
"success",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="scan-result-hero">
|
||||
<div>
|
||||
<span className="result-kicker">
|
||||
<ShieldCheck size={14} />
|
||||
{t("Scan complete", "扫描完成")}
|
||||
</span>
|
||||
<h2>
|
||||
{formatBytes(workspace.selectedTotal)}
|
||||
<small>{t(" ready to clean", " 可安全清理")}</small>
|
||||
</h2>
|
||||
<p>
|
||||
{t(
|
||||
`${formatCount(workspace.selectedCount)} of ${formatCount(
|
||||
removables,
|
||||
)} available items selected`,
|
||||
`已选择 ${formatCount(workspace.selectedCount)} / ${formatCount(
|
||||
removables,
|
||||
)} 个可清理项目`,
|
||||
)}
|
||||
{result.unreadable > 0
|
||||
? t(
|
||||
` · ${formatCount(result.unreadable)} could not be read`,
|
||||
` · ${formatCount(result.unreadable)} 项无法读取`,
|
||||
)
|
||||
: ""}
|
||||
</p>
|
||||
</div>
|
||||
<div className="scan-result-actions">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={workspace.clearSelection}
|
||||
disabled={workspace.selectedCount === 0}
|
||||
>
|
||||
{t("Deselect all", "取消全选")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={<Trash2 size={16} />}
|
||||
disabled={workspace.selectedCount === 0}
|
||||
onClick={() => setConfirming(true)}
|
||||
>
|
||||
{t("Review & clean", "检查并清理")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{workspace.error ? (
|
||||
<InlineError message={workspace.error} onDismiss={workspace.clearError} />
|
||||
) : null}
|
||||
|
||||
<div className="category-grid">
|
||||
{CATEGORY_ORDER.filter((category) => groups.has(category)).map((category) => {
|
||||
const group = groups.get(category);
|
||||
if (!group) return null;
|
||||
const indexes = group.items.filter((index) => !result.items[index].lock);
|
||||
const allSelected =
|
||||
indexes.length > 0 && indexes.every((index) => workspace.selected.has(index));
|
||||
return (
|
||||
<CategoryCard
|
||||
key={category}
|
||||
category={category}
|
||||
total={group.total}
|
||||
count={group.count}
|
||||
selected={allSelected}
|
||||
focused={focus === category}
|
||||
disabled={indexes.length === 0}
|
||||
onToggle={() => workspace.toggleCategory(category)}
|
||||
onInspect={() => setFocus(focus === category ? null : category)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<section className="cleanup-list-panel">
|
||||
<SectionTitle
|
||||
title={
|
||||
focus
|
||||
? categoryLabel(focus, lang)
|
||||
: t("Everything found in this scan", "本次扫描的全部项目")
|
||||
}
|
||||
subtitle={t(
|
||||
"Only checked items are touched. Protected items stay locked.",
|
||||
"只会处理已勾选的项目,受保护项目始终保持锁定。",
|
||||
)}
|
||||
action={
|
||||
focus ? (
|
||||
<Button variant="ghost" size="sm" onClick={() => setFocus(null)}>
|
||||
{t("Show all", "显示全部")}
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="ghost" size="sm" onClick={workspace.selectAll}>
|
||||
{workspace.selectedCount === removables
|
||||
? t("Deselect all", "取消全选")
|
||||
: t("Select all", "全部选择")}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
<div className="cleanup-rows">
|
||||
{visibleItems.map(({ item, index }) => (
|
||||
<ItemRow
|
||||
key={`${item.path}-${index}`}
|
||||
item={item}
|
||||
checked={workspace.selected.has(index)}
|
||||
onToggle={() => workspace.toggleItem(index)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="floating-action">
|
||||
<div>
|
||||
<span>{t("Selected for cleanup", "已选择清理")}</span>
|
||||
<strong>{formatBytes(workspace.selectedTotal)}</strong>
|
||||
</div>
|
||||
<div className="floating-actions">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<FolderOpen size={15} />}
|
||||
onClick={() => void api.openTrash().catch(() => undefined)}
|
||||
>
|
||||
{bin}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={<Trash2 size={15} />}
|
||||
disabled={workspace.selectedCount === 0}
|
||||
onClick={() => setConfirming(true)}
|
||||
>
|
||||
{t("Clean now", "立即清理")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirming}
|
||||
title={t("Ready to make room?", "准备释放空间?")}
|
||||
message={
|
||||
<span>
|
||||
{t(
|
||||
`${formatCount(workspace.selectedCount)} items · ${formatBytes(
|
||||
workspace.selectedTotal,
|
||||
)}`,
|
||||
`${formatCount(workspace.selectedCount)} 项 · ${formatBytes(
|
||||
workspace.selectedTotal,
|
||||
)}`,
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
note={
|
||||
mode === "trash"
|
||||
? t(
|
||||
`Items will move to the ${bin}. You can restore them from History.`,
|
||||
`文件将移入${bin},之后可从历史记录中还原。`,
|
||||
)
|
||||
: t(
|
||||
"Permanent removal cannot be undone. Squid re-checks every path before deleting it.",
|
||||
"永久删除无法撤销。Squid 会在删除前重新检查每一个路径。",
|
||||
)
|
||||
}
|
||||
confirmLabel={
|
||||
mode === "trash"
|
||||
? t(`Move to ${bin}`, `移入${bin}`)
|
||||
: t("Remove permanently", "永久删除")
|
||||
}
|
||||
cancelLabel={t("Keep files", "保留文件")}
|
||||
onConfirm={() => void confirm()}
|
||||
onClose={() => setConfirming(false)}
|
||||
busy={workspace.deleting}
|
||||
icon={<RotateCcw size={23} />}
|
||||
>
|
||||
<div className="mode-picker">
|
||||
<button
|
||||
className={mode === "trash" ? "is-active" : ""}
|
||||
onClick={() => setMode("trash")}
|
||||
>
|
||||
<FolderOpen size={17} />
|
||||
<span>{bin}</span>
|
||||
</button>
|
||||
<button
|
||||
className={mode === "permanent" ? "is-active" : ""}
|
||||
onClick={() => setMode("permanent")}
|
||||
>
|
||||
<Trash2 size={17} />
|
||||
<span>{t("Permanent", "永久")}</span>
|
||||
</button>
|
||||
</div>
|
||||
</ConfirmDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,169 @@
|
|||
import {
|
||||
Check,
|
||||
LoaderCircle,
|
||||
LockKeyhole,
|
||||
RefreshCw,
|
||||
ShieldCheck,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import type { PermissionStatus } from "../types";
|
||||
import { Button } from "./ui";
|
||||
|
||||
type State = "checking" | "granted" | "denied" | "unknown" | "not-required" | "error";
|
||||
|
||||
const SYSTEM_SETTINGS_COPY = {
|
||||
en: "System Settings › Privacy & Security › Full Disk Access",
|
||||
zh: "系统设置 › 隐私与安全性 › 完全磁盘访问权限",
|
||||
};
|
||||
|
||||
export function SetupPanel({ onDone }: { onDone: () => void }) {
|
||||
const { t, lang } = useI18n();
|
||||
const [state, setState] = useState<State>("checking");
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setState("checking");
|
||||
try {
|
||||
const status: PermissionStatus = await api.permissionStatus();
|
||||
setState(status.fullDiskAccess);
|
||||
} catch {
|
||||
setState("error");
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
const onFocus = () => void refresh();
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") onDone();
|
||||
};
|
||||
window.addEventListener("focus", onFocus);
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
window.removeEventListener("focus", onFocus);
|
||||
window.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, [onDone, refresh]);
|
||||
|
||||
const checking = state === "checking";
|
||||
const ready = state === "granted" || state === "not-required";
|
||||
const needsAttention = state === "denied" || state === "unknown" || state === "error";
|
||||
const stateLabel = checking
|
||||
? t("Checking…", "检查中…")
|
||||
: ready
|
||||
? t("Ready", "已就绪")
|
||||
: state === "denied"
|
||||
? t("Needs you", "需要你处理")
|
||||
: t("Not confirmed", "未确认");
|
||||
const detail = checking
|
||||
? t("Reading this Mac's privacy state…", "正在读取这台 Mac 的隐私权限状态…")
|
||||
: state === "granted"
|
||||
? t(
|
||||
"Squid can include protected app caches and leftovers in its scans.",
|
||||
"Squid 可以扫描受保护的 App 缓存与卸载残留。",
|
||||
)
|
||||
: state === "not-required"
|
||||
? t(
|
||||
"Windows needs no extra privacy permission for Squid.",
|
||||
"Windows 上使用 Squid 不需要额外隐私权限。",
|
||||
)
|
||||
: state === "denied"
|
||||
? t(
|
||||
"Optional. Without it Squid still works, but skips protected app data.",
|
||||
"这是可选项。未授权时 Squid 仍可正常工作,只会跳过受保护的 App 数据。",
|
||||
)
|
||||
: t(
|
||||
"Open System Settings to review access, then come back and recheck.",
|
||||
"请到系统设置中确认权限,然后返回重新检查。",
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="setup-scrim"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="setup-title"
|
||||
>
|
||||
<div className="setup-card">
|
||||
<header className="setup-head">
|
||||
<span className="setup-brand">
|
||||
<ShieldCheck size={22} />
|
||||
</span>
|
||||
<div>
|
||||
<div className="setup-eyebrow">NEX · SQUID</div>
|
||||
<h2 id="setup-title">{t("Before you start", "开始之前")}</h2>
|
||||
<p>
|
||||
{t(
|
||||
"Squid runs entirely on this computer. One optional macOS permission improves scan coverage.",
|
||||
"Squid 完全在这台电脑上运行。macOS 上有一项可选权限可以提升扫描覆盖范围。",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className={`setup-check is-${checking ? "checking" : ready ? "ok" : "problem"}`}>
|
||||
<span className="setup-check-icon">
|
||||
<LockKeyhole size={18} />
|
||||
</span>
|
||||
<div className="setup-check-copy">
|
||||
<strong>
|
||||
{t("Full Disk Access", "完全磁盘访问权限")}
|
||||
<span className="setup-check-state">
|
||||
{ready ? <Check size={13} /> : needsAttention ? <X size={13} /> : null}
|
||||
{stateLabel}
|
||||
</span>
|
||||
</strong>
|
||||
<small>{detail}</small>
|
||||
{state === "denied" || state === "unknown" || state === "error" ? (
|
||||
<code>{SYSTEM_SETTINGS_COPY[lang]}</code>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="setup-note">
|
||||
{t(
|
||||
"You can skip this now. Permissions and the same check remain available in Settings at any time.",
|
||||
"现在可以跳过;之后随时都能在设置中检查权限或重新授权。",
|
||||
)}
|
||||
</p>
|
||||
|
||||
<footer className="setup-foot">
|
||||
<div className="setup-actions-secondary">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<RefreshCw size={13} className={checking ? "spin" : ""} />}
|
||||
onClick={() => void refresh()}
|
||||
disabled={checking}
|
||||
>
|
||||
{t("Recheck", "重新检查")}
|
||||
</Button>
|
||||
{needsAttention ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => void api.openFullDiskAccessSettings()}
|
||||
>
|
||||
{t("Open Settings", "打开系统设置")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="setup-actions-primary">
|
||||
<Button variant="ghost" onClick={onDone}>
|
||||
{t("Not now", "暂不设置")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={onDone}
|
||||
icon={checking ? <LoaderCircle size={14} className="spin" /> : <Check size={14} />}
|
||||
>
|
||||
{t("Start using Squid", "开始使用 Squid")}
|
||||
</Button>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,214 @@
|
|||
import {
|
||||
Check,
|
||||
Download,
|
||||
LoaderCircle,
|
||||
Monitor,
|
||||
RefreshCw,
|
||||
Sparkles,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { formatBytes } from "../lib/format";
|
||||
import type { UpdateFlow } from "../hooks/useUpdateFlow";
|
||||
import type { Bootstrap } from "../types";
|
||||
import { Button, Toggle } from "./ui";
|
||||
|
||||
function architectureLabel(arch: string): string {
|
||||
if (arch === "aarch64") return "ARM64";
|
||||
if (arch === "x86_64") return "x64";
|
||||
return arch;
|
||||
}
|
||||
|
||||
export function UpdatePanel({
|
||||
flow,
|
||||
autoCheck,
|
||||
onAutoCheckChange,
|
||||
bootstrap,
|
||||
}: {
|
||||
flow: UpdateFlow;
|
||||
autoCheck: boolean;
|
||||
onAutoCheckChange: (enabled: boolean) => void;
|
||||
bootstrap: Bootstrap;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const status = flow.status;
|
||||
const verified = status?.state === "ready";
|
||||
const available = status?.state === "available" || verified;
|
||||
const updateStateLabel = verified
|
||||
? t("Downloaded and verified", "已下载并校验")
|
||||
: t("Update available", "发现新版本");
|
||||
const statusError =
|
||||
status?.message &&
|
||||
(status.state === "error" || status.state === "unavailable")
|
||||
? status.message
|
||||
: null;
|
||||
|
||||
return (
|
||||
<section className="settings-section update-section">
|
||||
<div className="settings-section-head">
|
||||
<div>
|
||||
<h2>
|
||||
<Sparkles size={18} />
|
||||
{t("Software updates", "软件更新")}
|
||||
</h2>
|
||||
<p>
|
||||
{t(
|
||||
"Check for a new version, then download and verify it before installing.",
|
||||
"发现新版本后,下载并自动校验,确认无误再安装。",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
icon={<RefreshCw size={14} className={flow.checking ? "spin" : ""} />}
|
||||
onClick={() => void flow.check()}
|
||||
disabled={flow.checking || flow.downloading || !bootstrap.updateFeedUrl}
|
||||
>
|
||||
{flow.checking ? t("Checking…", "检查中…") : t("Check now", "立即检查")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="update-system-panel">
|
||||
<span className="update-system-icon">
|
||||
<Monitor size={16} />
|
||||
</span>
|
||||
<div className="update-system-copy">
|
||||
<small>{t("Current system", "当前系统")}</small>
|
||||
<strong>
|
||||
{bootstrap.osName} {bootstrap.osVersion}
|
||||
</strong>
|
||||
</div>
|
||||
<div className="update-system-facts">
|
||||
<span>{architectureLabel(bootstrap.arch)}</span>
|
||||
<span className="is-app">Squid {bootstrap.version}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{available && status ? (
|
||||
<div className="update-status">
|
||||
<div className="update-status-copy">
|
||||
<span className={`update-state is-${status.state}`}>
|
||||
{updateStateLabel}
|
||||
</span>
|
||||
<span className="update-version-line">
|
||||
<strong>Squid {status.currentVersion}</strong>
|
||||
<span aria-hidden="true">→</span>
|
||||
<b>{status.availableVersion}</b>
|
||||
</span>
|
||||
</div>
|
||||
{status.date ? <time>{status.date}</time> : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{available && status?.notes ? (
|
||||
<p className="update-notes">{status.notes}</p>
|
||||
) : null}
|
||||
|
||||
{flow.percent !== null ? (
|
||||
<div className="update-progress">
|
||||
<div className="update-progress-head">
|
||||
<span>
|
||||
{flow.progress?.state === "verifying"
|
||||
? t("Verifying download…", "正在校验下载…")
|
||||
: t("Downloading update…", "正在下载更新…")}
|
||||
</span>
|
||||
<b>{flow.percent}%</b>
|
||||
</div>
|
||||
<div
|
||||
className="progress-track"
|
||||
role="progressbar"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={flow.percent}
|
||||
>
|
||||
<span style={{ width: `${flow.percent}%` }} />
|
||||
</div>
|
||||
<small>
|
||||
{flow.progress
|
||||
? `${formatBytes(flow.progress.downloaded)} / ${formatBytes(
|
||||
flow.progress.total,
|
||||
)}`
|
||||
: ""}
|
||||
</small>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{statusError ? (
|
||||
<div className="update-message is-error" role="alert">
|
||||
{statusError}
|
||||
</div>
|
||||
) : null}
|
||||
{flow.installError ? (
|
||||
<div className="update-message is-error" role="alert">
|
||||
{flow.installError}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="update-actions">
|
||||
{available && !verified ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={
|
||||
flow.downloading ? (
|
||||
<LoaderCircle size={15} className="spin" />
|
||||
) : (
|
||||
<Download size={15} />
|
||||
)
|
||||
}
|
||||
onClick={() => void flow.download()}
|
||||
disabled={flow.downloading}
|
||||
>
|
||||
{flow.downloading
|
||||
? t("Downloading…", "下载中…")
|
||||
: t("Download and verify", "下载并校验")}
|
||||
</Button>
|
||||
) : null}
|
||||
{verified ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={
|
||||
flow.installing ? (
|
||||
<LoaderCircle size={15} className="spin" />
|
||||
) : (
|
||||
<Check size={15} />
|
||||
)
|
||||
}
|
||||
onClick={() => void flow.install()}
|
||||
disabled={flow.installing}
|
||||
>
|
||||
{flow.installing
|
||||
? t("Restarting…", "正在重启…")
|
||||
: t("Install and restart", "安装并重启")}
|
||||
</Button>
|
||||
) : null}
|
||||
{verified && !flow.installing ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<X size={14} />}
|
||||
onClick={() => void flow.clear()}
|
||||
>
|
||||
{t("Discard", "放弃")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="settings-row">
|
||||
<div>
|
||||
<strong>{t("Check for updates daily", "每天自动检查更新")}</strong>
|
||||
<span>
|
||||
{t(
|
||||
"Checks at most once a day when Squid starts.",
|
||||
"启动 Squid 时每天最多检查一次。",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<Toggle
|
||||
checked={autoCheck}
|
||||
onChange={onAutoCheckChange}
|
||||
label={t("Check for updates automatically", "自动检查更新")}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,824 @@
|
|||
import {
|
||||
AlertTriangle,
|
||||
AppWindow,
|
||||
Boxes,
|
||||
Check,
|
||||
ChevronDown,
|
||||
Code2,
|
||||
FileWarning,
|
||||
Globe2,
|
||||
Languages,
|
||||
LoaderCircle,
|
||||
PackageOpen,
|
||||
Puzzle,
|
||||
Trash2,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type CSSProperties,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { formatBytes, formatCount, percent, shortPath } from "../lib/format";
|
||||
import type { Category, JobProgress, LockReason } from "../types";
|
||||
|
||||
export interface CategoryMeta {
|
||||
en: string;
|
||||
zh: string;
|
||||
blurbEn: string;
|
||||
blurbZh: string;
|
||||
icon: typeof Boxes;
|
||||
tone: string;
|
||||
}
|
||||
|
||||
export const CATEGORY_META: Record<Category, CategoryMeta> = {
|
||||
"system-junk": {
|
||||
en: "System junk",
|
||||
zh: "系统垃圾",
|
||||
blurbEn: "Temporary files and system scratch data",
|
||||
blurbZh: "临时文件与系统缓存",
|
||||
icon: Trash2,
|
||||
tone: "blue",
|
||||
},
|
||||
"app-caches": {
|
||||
en: "App caches",
|
||||
zh: "应用缓存",
|
||||
blurbEn: "Caches apps can rebuild",
|
||||
blurbZh: "应用可自动重建的缓存",
|
||||
icon: AppWindow,
|
||||
tone: "cyan",
|
||||
},
|
||||
"browser-caches": {
|
||||
en: "Browser caches",
|
||||
zh: "浏览器缓存",
|
||||
blurbEn: "Web content and offline data",
|
||||
blurbZh: "网页内容与离线数据",
|
||||
icon: Globe2,
|
||||
tone: "violet",
|
||||
},
|
||||
logs: {
|
||||
en: "Logs & reports",
|
||||
zh: "日志与报告",
|
||||
blurbEn: "Rotated logs and crash reports",
|
||||
blurbZh: "旧日志与崩溃报告",
|
||||
icon: FileWarning,
|
||||
tone: "orange",
|
||||
},
|
||||
developer: {
|
||||
en: "Developer files",
|
||||
zh: "开发文件",
|
||||
blurbEn: "Simulators, archives and tool caches",
|
||||
blurbZh: "模拟器、归档与工具缓存",
|
||||
icon: Code2,
|
||||
tone: "indigo",
|
||||
},
|
||||
"project-artifacts": {
|
||||
en: "Build artefacts",
|
||||
zh: "构建产物",
|
||||
blurbEn: "Regenerable project build folders",
|
||||
blurbZh: "可重新生成的构建目录",
|
||||
icon: PackageOpen,
|
||||
tone: "teal",
|
||||
},
|
||||
trash: {
|
||||
en: "Trash",
|
||||
zh: "废纸篓",
|
||||
blurbEn: "Files waiting to be emptied",
|
||||
blurbZh: "等待清空的文件",
|
||||
icon: Trash2,
|
||||
tone: "slate",
|
||||
},
|
||||
"language-packs": {
|
||||
en: "Language packs",
|
||||
zh: "语言包",
|
||||
blurbEn: "Unused voice and localisation data",
|
||||
blurbZh: "未使用的语音与本地化数据",
|
||||
icon: Languages,
|
||||
tone: "pink",
|
||||
},
|
||||
leftovers: {
|
||||
en: "Leftovers",
|
||||
zh: "卸载残留",
|
||||
blurbEn: "Data left by removed applications",
|
||||
blurbZh: "已删除应用留下的数据",
|
||||
icon: Puzzle,
|
||||
tone: "amber",
|
||||
},
|
||||
};
|
||||
|
||||
export const CATEGORY_ORDER = Object.keys(CATEGORY_META) as Category[];
|
||||
|
||||
export function categoryLabel(category: Category, language: "zh" | "en"): string {
|
||||
return language === "zh" ? CATEGORY_META[category].zh : CATEGORY_META[category].en;
|
||||
}
|
||||
|
||||
export function lockLabel(
|
||||
lock: LockReason | null,
|
||||
t: (en: string, zh: string) => string,
|
||||
): string {
|
||||
if (!lock) return "";
|
||||
switch (lock) {
|
||||
case "app-running":
|
||||
return t("App is running", "应用正在运行");
|
||||
case "shared-with-other-install":
|
||||
return t("Shared with another install", "与其他安装共用");
|
||||
case "whitelisted":
|
||||
return t("Protected by you", "已加入保护名单");
|
||||
case "not-owned":
|
||||
return t("Needs administrator rights", "需要管理员权限");
|
||||
case "protected":
|
||||
return t("Protected by the safety policy", "受安全策略保护");
|
||||
}
|
||||
}
|
||||
|
||||
export function PageHeader({
|
||||
eyebrow,
|
||||
title,
|
||||
description,
|
||||
actions,
|
||||
}: {
|
||||
eyebrow?: string;
|
||||
title: string;
|
||||
description: string;
|
||||
actions?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<header className="page-header">
|
||||
<div>
|
||||
{eyebrow ? <div className="page-eyebrow">{eyebrow}</div> : null}
|
||||
<h1>{title}</h1>
|
||||
<p>{description}</p>
|
||||
</div>
|
||||
{actions ? <div className="page-header-actions">{actions}</div> : null}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
export function Button({
|
||||
children,
|
||||
variant = "secondary",
|
||||
size = "md",
|
||||
icon,
|
||||
className = "",
|
||||
...props
|
||||
}: React.ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
variant?: "primary" | "secondary" | "ghost" | "danger";
|
||||
size?: "sm" | "md" | "lg";
|
||||
icon?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<button className={`button is-${variant} is-${size} ${className}`} {...props}>
|
||||
{icon ? <span className="button-icon">{icon}</span> : null}
|
||||
<span>{children}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function IconButton({
|
||||
label,
|
||||
children,
|
||||
className = "",
|
||||
...props
|
||||
}: React.ButtonHTMLAttributes<HTMLButtonElement> & { label: string }) {
|
||||
return (
|
||||
<button className={`icon-button ${className}`} aria-label={label} title={label} {...props}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function Toggle({
|
||||
checked,
|
||||
onChange,
|
||||
disabled,
|
||||
label,
|
||||
}: {
|
||||
checked: boolean;
|
||||
onChange: (next: boolean) => void;
|
||||
disabled?: boolean;
|
||||
label: string;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={checked}
|
||||
aria-label={label}
|
||||
className={`toggle ${checked ? "is-on" : ""}`}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(!checked)}
|
||||
>
|
||||
<span />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function Checkbox({
|
||||
checked,
|
||||
indeterminate = false,
|
||||
disabled = false,
|
||||
onChange,
|
||||
label,
|
||||
}: {
|
||||
checked: boolean;
|
||||
indeterminate?: boolean;
|
||||
disabled?: boolean;
|
||||
onChange: () => void;
|
||||
label: string;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={indeterminate ? "mixed" : checked}
|
||||
aria-label={label}
|
||||
disabled={disabled}
|
||||
className={`checkbox ${checked ? "is-checked" : ""} ${
|
||||
indeterminate ? "is-mixed" : ""
|
||||
}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onChange();
|
||||
}}
|
||||
>
|
||||
{checked ? <Check size={13} strokeWidth={3} /> : null}
|
||||
{!checked && indeterminate ? <span /> : null}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProgressCard({
|
||||
progress,
|
||||
title,
|
||||
onCancel,
|
||||
compact = false,
|
||||
}: {
|
||||
progress: JobProgress | null;
|
||||
title: string;
|
||||
onCancel?: () => void;
|
||||
compact?: boolean;
|
||||
}) {
|
||||
const { t, lang } = useI18n();
|
||||
const phase = useMemo(() => {
|
||||
if (!progress?.phase) return title;
|
||||
const labels: Record<string, [string, string]> = {
|
||||
match: ["Finding candidates", "正在查找可清理项目"],
|
||||
measure: ["Measuring sizes", "正在计算大小"],
|
||||
purge: ["Searching for build artefacts", "正在查找构建产物"],
|
||||
verify: ["Checking Git and file ages", "正在核对 Git 与文件年龄"],
|
||||
delete: ["Removing approved items", "正在删除已确认项目"],
|
||||
apps: ["Reading installed applications", "正在读取已安装应用"],
|
||||
plan: ["Finding application leftovers", "正在查找应用残留"],
|
||||
storage: ["Measuring folders", "正在测量文件夹"],
|
||||
files: ["Finding the largest files", "正在查找大文件"],
|
||||
orphans: ["Finding unused leftovers", "正在查找孤立残留"],
|
||||
};
|
||||
const pair = labels[progress.phase];
|
||||
return pair ? (lang === "zh" ? pair[1] : pair[0]) : title;
|
||||
}, [lang, progress?.phase, t, title]);
|
||||
const denominator = progress?.total ?? 0;
|
||||
const done = progress?.done ?? 0;
|
||||
const ratio =
|
||||
denominator > 0 ? Math.min(100, Math.max(0, (done / denominator) * 100)) : null;
|
||||
const detail = progress?.detail || progress?.subject || "";
|
||||
|
||||
return (
|
||||
<section className={`progress-card ${compact ? "is-compact" : ""}`}>
|
||||
<div className="progress-orbit" aria-hidden="true">
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<LoaderCircle size={24} className="spin" />
|
||||
</div>
|
||||
<div className="progress-copy">
|
||||
<div className="progress-title-row">
|
||||
<strong>{phase}</strong>
|
||||
{denominator > 0 ? (
|
||||
<span className="progress-count">
|
||||
{formatCount(done)} / {formatCount(denominator)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div
|
||||
className={`progress-track ${ratio === null ? "is-indeterminate" : ""}`}
|
||||
role="progressbar"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={ratio ?? undefined}
|
||||
>
|
||||
<span style={{ width: ratio === null ? undefined : `${ratio}%` }} />
|
||||
</div>
|
||||
<div className="progress-detail" title={detail}>
|
||||
{detail || t("Working safely in the background…", "正在后台安全处理…")}
|
||||
</div>
|
||||
</div>
|
||||
{onCancel ? (
|
||||
<Button variant="ghost" size="sm" onClick={onCancel}>
|
||||
{t("Cancel", "取消")}
|
||||
</Button>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function InlineError({
|
||||
message,
|
||||
onDismiss,
|
||||
}: {
|
||||
message: string;
|
||||
onDismiss?: () => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
return (
|
||||
<div className="inline-error" role="alert">
|
||||
<AlertTriangle size={17} />
|
||||
<span>{message}</span>
|
||||
{onDismiss ? (
|
||||
<IconButton label={t("Dismiss", "关闭")} onClick={onDismiss}>
|
||||
<X size={14} />
|
||||
</IconButton>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Modal({
|
||||
open,
|
||||
onClose,
|
||||
title,
|
||||
subtitle,
|
||||
children,
|
||||
footer,
|
||||
size = "md",
|
||||
tone = "default",
|
||||
dismissible = true,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
title: ReactNode;
|
||||
subtitle?: ReactNode;
|
||||
children: ReactNode;
|
||||
footer?: ReactNode;
|
||||
size?: "sm" | "md" | "lg" | "drawer";
|
||||
tone?: "default" | "danger" | "success";
|
||||
dismissible?: boolean;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const panel = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape" && dismissible) onClose();
|
||||
};
|
||||
document.addEventListener("keydown", onKey);
|
||||
const timer = window.setTimeout(() => {
|
||||
panel.current?.querySelector<HTMLElement>(
|
||||
"button:not([disabled]), input:not([disabled]), select:not([disabled])",
|
||||
)?.focus();
|
||||
}, 30);
|
||||
return () => {
|
||||
document.removeEventListener("keydown", onKey);
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
}, [dismissible, onClose, open]);
|
||||
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div
|
||||
className="modal-backdrop"
|
||||
role="presentation"
|
||||
onMouseDown={(event) => {
|
||||
if (event.target === event.currentTarget && dismissible) onClose();
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={panel}
|
||||
className={`modal-panel is-${size} is-${tone}`}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={typeof title === "string" ? title : undefined}
|
||||
>
|
||||
<header className="modal-head">
|
||||
<div>
|
||||
<h2>{title}</h2>
|
||||
{subtitle ? <p>{subtitle}</p> : null}
|
||||
</div>
|
||||
{dismissible ? (
|
||||
<IconButton label={t("Close", "关闭")} onClick={onClose}>
|
||||
<X size={17} />
|
||||
</IconButton>
|
||||
) : null}
|
||||
</header>
|
||||
<div className="modal-body">{children}</div>
|
||||
{footer ? <footer className="modal-footer">{footer}</footer> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ConfirmDialog({
|
||||
open,
|
||||
title,
|
||||
message,
|
||||
note,
|
||||
confirmLabel,
|
||||
cancelLabel,
|
||||
tone = "danger",
|
||||
icon,
|
||||
onConfirm,
|
||||
onClose,
|
||||
busy = false,
|
||||
children,
|
||||
}: {
|
||||
open: boolean;
|
||||
title: string;
|
||||
message: ReactNode;
|
||||
note?: ReactNode;
|
||||
confirmLabel: string;
|
||||
cancelLabel: string;
|
||||
tone?: "danger" | "default";
|
||||
icon?: ReactNode;
|
||||
onConfirm: () => void;
|
||||
onClose: () => void;
|
||||
busy?: boolean;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={title}
|
||||
size="sm"
|
||||
dismissible={!busy}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" onClick={onClose} disabled={busy}>
|
||||
{cancelLabel}
|
||||
</Button>
|
||||
<Button
|
||||
variant={tone === "danger" ? "danger" : "primary"}
|
||||
onClick={onConfirm}
|
||||
disabled={busy}
|
||||
icon={busy ? <LoaderCircle size={15} className="spin" /> : icon}
|
||||
>
|
||||
{confirmLabel}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className={`confirm-content is-${tone}`}>
|
||||
<div className="confirm-icon">{icon ?? <AlertTriangle size={24} />}</div>
|
||||
<div>
|
||||
<div className="confirm-message">{message}</div>
|
||||
{note ? <div className="confirm-note">{note}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
{children ? <div className="confirm-extra">{children}</div> : null}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function Gauge({
|
||||
value,
|
||||
size = 160,
|
||||
stroke = 12,
|
||||
tone = "blue",
|
||||
children,
|
||||
label,
|
||||
}: {
|
||||
value: number;
|
||||
size?: number;
|
||||
stroke?: number;
|
||||
tone?: "blue" | "green" | "orange" | "violet" | "red";
|
||||
children?: ReactNode;
|
||||
label?: string;
|
||||
}) {
|
||||
const normalized = Math.max(0, Math.min(100, value));
|
||||
const radius = (size - stroke) / 2;
|
||||
const circumference = Math.PI * 2 * radius;
|
||||
return (
|
||||
<div
|
||||
className={`gauge tone-${tone}`}
|
||||
style={{ width: size, height: size } as CSSProperties}
|
||||
role="img"
|
||||
aria-label={label ?? `${Math.round(normalized)}%`}
|
||||
>
|
||||
<svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
|
||||
<circle
|
||||
className="gauge-track"
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
fill="none"
|
||||
strokeWidth={stroke}
|
||||
/>
|
||||
<circle
|
||||
className="gauge-value"
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
fill="none"
|
||||
strokeWidth={stroke}
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={circumference}
|
||||
strokeDashoffset={circumference * (1 - normalized / 100)}
|
||||
transform={`rotate(-90 ${size / 2} ${size / 2})`}
|
||||
/>
|
||||
</svg>
|
||||
<div className="gauge-center">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function MetricBar({
|
||||
value,
|
||||
tone = "blue",
|
||||
}: {
|
||||
value: number;
|
||||
tone?: "blue" | "green" | "orange" | "violet" | "red";
|
||||
}) {
|
||||
return (
|
||||
<div className={`metric-bar tone-${tone}`}>
|
||||
<span style={{ width: `${Math.max(0, Math.min(100, value))}%` }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyState({
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
}: {
|
||||
icon: ReactNode;
|
||||
title: string;
|
||||
description: string;
|
||||
action?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<div className="empty-icon">{icon}</div>
|
||||
<h2>{title}</h2>
|
||||
<p>{description}</p>
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SectionTitle({
|
||||
title,
|
||||
subtitle,
|
||||
action,
|
||||
}: {
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
action?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="section-title">
|
||||
<div>
|
||||
<h2>{title}</h2>
|
||||
{subtitle ? <p>{subtitle}</p> : null}
|
||||
</div>
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CategoryCard({
|
||||
category,
|
||||
total,
|
||||
count,
|
||||
selected,
|
||||
disabled,
|
||||
onToggle,
|
||||
onInspect,
|
||||
focused = false,
|
||||
}: {
|
||||
category: Category;
|
||||
total: number;
|
||||
count: number;
|
||||
selected: boolean;
|
||||
disabled?: boolean;
|
||||
onToggle: () => void;
|
||||
onInspect: () => void;
|
||||
focused?: boolean;
|
||||
}) {
|
||||
const { lang, t } = useI18n();
|
||||
const meta = CATEGORY_META[category];
|
||||
const Icon = meta.icon;
|
||||
return (
|
||||
<article
|
||||
className={`category-card tone-${meta.tone} ${selected ? "is-selected" : ""} ${
|
||||
disabled ? "is-disabled" : ""
|
||||
} ${focused ? "is-focused" : ""}`}
|
||||
onClick={disabled ? undefined : onToggle}
|
||||
>
|
||||
<div className="category-card-top">
|
||||
<span className="category-icon">
|
||||
<Icon size={21} />
|
||||
</span>
|
||||
<Checkbox
|
||||
checked={selected}
|
||||
disabled={disabled}
|
||||
onChange={onToggle}
|
||||
label={categoryLabel(category, lang)}
|
||||
/>
|
||||
</div>
|
||||
<div className="category-copy">
|
||||
<strong>{categoryLabel(category, lang)}</strong>
|
||||
<span>{lang === "zh" ? meta.blurbZh : meta.blurbEn}</span>
|
||||
</div>
|
||||
<div className="category-card-foot">
|
||||
<span className="category-size">{formatBytes(total)}</span>
|
||||
<button
|
||||
className="text-button"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onInspect();
|
||||
}}
|
||||
>
|
||||
{t(`${formatCount(count)} items`, `${formatCount(count)} 项`)}
|
||||
<ChevronDown size={13} />
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
type ToastTone = "default" | "success" | "danger";
|
||||
interface ToastItem {
|
||||
id: number;
|
||||
message: string;
|
||||
tone: ToastTone;
|
||||
}
|
||||
|
||||
const ToastContext = createContext<{
|
||||
push: (message: string, tone?: ToastTone) => void;
|
||||
} | null>(null);
|
||||
|
||||
export function ToastProvider({ children }: { children: ReactNode }) {
|
||||
const [toasts, setToasts] = useState<ToastItem[]>([]);
|
||||
const sequence = useRef(0);
|
||||
|
||||
const remove = useCallback((id: number) => {
|
||||
setToasts((current) => current.filter((toast) => toast.id !== id));
|
||||
}, []);
|
||||
|
||||
const push = useCallback(
|
||||
(message: string, tone: ToastTone = "default") => {
|
||||
const id = ++sequence.current;
|
||||
setToasts((current) => [...current.slice(-3), { id, message, tone }]);
|
||||
window.setTimeout(() => remove(id), 4200);
|
||||
},
|
||||
[remove],
|
||||
);
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={{ push }}>
|
||||
{children}
|
||||
<div className="toast-stack" aria-live="polite">
|
||||
{toasts.map((toast) => (
|
||||
<div key={toast.id} className={`toast is-${toast.tone}`}>
|
||||
{toast.tone === "success" ? <Check size={16} /> : null}
|
||||
{toast.tone === "danger" ? <AlertTriangle size={16} /> : null}
|
||||
<span>{toast.message}</span>
|
||||
<button onClick={() => remove(toast.id)} aria-label="Dismiss">
|
||||
<X size={13} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useToast() {
|
||||
const value = useContext(ToastContext);
|
||||
if (!value) throw new Error("useToast must be used inside ToastProvider");
|
||||
return value;
|
||||
}
|
||||
|
||||
export function ResultSummary({
|
||||
removed,
|
||||
freed,
|
||||
failed,
|
||||
mode,
|
||||
onAgain,
|
||||
onHistory,
|
||||
}: {
|
||||
removed: number;
|
||||
freed: number;
|
||||
failed: number;
|
||||
mode: string | null;
|
||||
onAgain: () => void;
|
||||
onHistory: () => void;
|
||||
}) {
|
||||
const { t, lang, bin } = useI18n();
|
||||
return (
|
||||
<div className="result-summary">
|
||||
<div className="result-check" aria-hidden="true">
|
||||
<Check size={28} strokeWidth={2.6} />
|
||||
</div>
|
||||
<div className="result-copy">
|
||||
<span className="result-eyebrow">{t("Cleanup complete", "清理完成")}</span>
|
||||
<h2>
|
||||
{t(
|
||||
`${formatBytes(freed)} reclaimed`,
|
||||
`已释放 ${formatBytes(freed)}`,
|
||||
)}
|
||||
</h2>
|
||||
<p>
|
||||
{t(
|
||||
`${formatCount(removed)} items removed${
|
||||
failed > 0 ? ` · ${failed} could not be removed` : ""
|
||||
}.`,
|
||||
`已处理 ${formatCount(removed)} 项${
|
||||
failed > 0 ? ` · ${failed} 项未能删除` : ""
|
||||
}。`,
|
||||
)}
|
||||
{mode === "trash"
|
||||
? t(
|
||||
` Items are in the ${bin} and can still be restored from History.`,
|
||||
` 文件已移入${bin},可在历史记录中还原。`,
|
||||
)
|
||||
: ""}
|
||||
</p>
|
||||
</div>
|
||||
<div className="result-actions">
|
||||
<Button variant="ghost" onClick={onHistory}>
|
||||
{t("View history", "查看历史")}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onAgain}>
|
||||
{t("Scan again", "再次扫描")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PathRow({
|
||||
path,
|
||||
note,
|
||||
size,
|
||||
selected,
|
||||
disabled,
|
||||
onToggle,
|
||||
onReveal,
|
||||
}: {
|
||||
path: string;
|
||||
note?: string | null;
|
||||
size: number;
|
||||
selected: boolean;
|
||||
disabled: boolean;
|
||||
onToggle: () => void;
|
||||
onReveal: () => void;
|
||||
}) {
|
||||
const { t, lang } = useI18n();
|
||||
return (
|
||||
<div className={`path-row ${disabled ? "is-disabled" : ""}`}>
|
||||
<Checkbox
|
||||
checked={selected}
|
||||
disabled={disabled}
|
||||
onChange={onToggle}
|
||||
label={lang === "zh" ? "选择项目" : "Select item"}
|
||||
/>
|
||||
<div className="path-row-copy">
|
||||
<span className="path-row-path" title={path}>
|
||||
{shortPath(path, 78)}
|
||||
</span>
|
||||
{note ? (
|
||||
<span className="path-row-note">{note}</span>
|
||||
) : null}
|
||||
</div>
|
||||
<span className="path-row-size">{formatBytes(size)}</span>
|
||||
<IconButton label={t("Show in folder", "在文件夹中显示")} onClick={onReveal}>
|
||||
<ChevronDown size={15} className="reveal-arrow" />
|
||||
</IconButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function UsageBar({
|
||||
used,
|
||||
total,
|
||||
tone = "blue",
|
||||
}: {
|
||||
used: number;
|
||||
total: number;
|
||||
tone?: "blue" | "green" | "orange" | "violet" | "red";
|
||||
}) {
|
||||
return (
|
||||
<div className={`usage-bar tone-${tone}`}>
|
||||
<span style={{ width: `${percent(used, total)}%` }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,216 @@
|
|||
import { useCallback, useMemo, useState } from "react";
|
||||
import { api, subscribeJobProgress } from "../lib/api";
|
||||
import { isCancelled, messageFrom } from "../lib/format";
|
||||
import type {
|
||||
AppInfo,
|
||||
DeleteMode,
|
||||
DeleteResult,
|
||||
JobProgress,
|
||||
PlanResult,
|
||||
} from "../types";
|
||||
|
||||
function jobId(): string {
|
||||
return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
}
|
||||
|
||||
export interface AppsWorkspace {
|
||||
apps: AppInfo[];
|
||||
total: number;
|
||||
scanned: boolean;
|
||||
scanning: boolean;
|
||||
planning: boolean;
|
||||
deleting: boolean;
|
||||
progress: JobProgress | null;
|
||||
error: string | null;
|
||||
selectedApp: AppInfo | null;
|
||||
plan: PlanResult | null;
|
||||
planSelected: Set<number>;
|
||||
summary: DeleteResult | null;
|
||||
planSelectedTotal: number;
|
||||
scan: () => Promise<void>;
|
||||
chooseApp: (app: AppInfo | null) => void;
|
||||
buildPlan: (app: AppInfo) => Promise<void>;
|
||||
togglePlanItem: (index: number) => void;
|
||||
togglePlanAll: () => void;
|
||||
uninstall: (mode: DeleteMode) => Promise<DeleteResult | null>;
|
||||
cancel: () => Promise<void>;
|
||||
resetPlan: () => void;
|
||||
clearError: () => void;
|
||||
clearSummary: () => void;
|
||||
}
|
||||
|
||||
export function useAppsWorkspace(): AppsWorkspace {
|
||||
const [apps, setApps] = useState<AppInfo[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [scanned, setScanned] = useState(false);
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [planning, setPlanning] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [progress, setProgress] = useState<JobProgress | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedApp, setSelectedApp] = useState<AppInfo | null>(null);
|
||||
const [plan, setPlan] = useState<PlanResult | null>(null);
|
||||
const [planSelected, setPlanSelected] = useState<Set<number>>(new Set());
|
||||
const [summary, setSummary] = useState<DeleteResult | null>(null);
|
||||
const [activeJob, setActiveJob] = useState<string | null>(null);
|
||||
|
||||
const scan = useCallback(async () => {
|
||||
if (scanning || deleting) return;
|
||||
const id = jobId();
|
||||
setActiveJob(id);
|
||||
setScanning(true);
|
||||
setError(null);
|
||||
setSummary(null);
|
||||
const stop = await subscribeJobProgress(id, setProgress);
|
||||
try {
|
||||
const result = await api.appsScan(id);
|
||||
setApps(result.apps);
|
||||
setTotal(result.total);
|
||||
setScanned(true);
|
||||
} catch (reason) {
|
||||
if (!isCancelled(reason)) setError(messageFrom(reason));
|
||||
} finally {
|
||||
stop();
|
||||
setScanning(false);
|
||||
setProgress(null);
|
||||
setActiveJob(null);
|
||||
}
|
||||
}, [deleting, scanning]);
|
||||
|
||||
const chooseApp = useCallback((app: AppInfo | null) => {
|
||||
setSelectedApp(app);
|
||||
setPlan(null);
|
||||
setPlanSelected(new Set());
|
||||
}, []);
|
||||
|
||||
const buildPlan = useCallback(
|
||||
async (app: AppInfo) => {
|
||||
if (planning) return;
|
||||
const id = jobId();
|
||||
setActiveJob(id);
|
||||
setPlanning(true);
|
||||
setSelectedApp(app);
|
||||
setPlan(null);
|
||||
setError(null);
|
||||
const stop = await subscribeJobProgress(id, setProgress);
|
||||
try {
|
||||
const next = await api.appPlan(id, app.bundle_id || app.path);
|
||||
setPlan(next);
|
||||
setPlanSelected(
|
||||
new Set(
|
||||
next.items
|
||||
.map((item, index) => ({ item, index }))
|
||||
.filter(({ item }) => item.selected && !item.lock)
|
||||
.map(({ index }) => index),
|
||||
),
|
||||
);
|
||||
} catch (reason) {
|
||||
if (!isCancelled(reason)) setError(messageFrom(reason));
|
||||
} finally {
|
||||
stop();
|
||||
setPlanning(false);
|
||||
setProgress(null);
|
||||
setActiveJob(null);
|
||||
}
|
||||
},
|
||||
[planning],
|
||||
);
|
||||
|
||||
const togglePlanItem = useCallback((index: number) => {
|
||||
setPlanSelected((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(index)) next.delete(index);
|
||||
else next.add(index);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const togglePlanAll = useCallback(() => {
|
||||
if (!plan) return;
|
||||
setPlanSelected((current) => {
|
||||
const all = plan.items
|
||||
.map((item, index) => ({ item, index }))
|
||||
.filter(({ item }) => !item.lock)
|
||||
.map(({ index }) => index);
|
||||
if (all.length > 0 && all.every((index) => current.has(index))) return new Set();
|
||||
return new Set(all);
|
||||
});
|
||||
}, [plan]);
|
||||
|
||||
const planSelectedTotal = useMemo(() => {
|
||||
if (!plan) return 0;
|
||||
let total = 0;
|
||||
for (const index of planSelected) total += plan.items[index]?.onDisk ?? 0;
|
||||
return total;
|
||||
}, [plan, planSelected]);
|
||||
|
||||
const uninstall = useCallback(
|
||||
async (mode: DeleteMode) => {
|
||||
if (!plan || planSelected.size === 0 || deleting) return null;
|
||||
const id = jobId();
|
||||
setActiveJob(id);
|
||||
setDeleting(true);
|
||||
setError(null);
|
||||
const stop = await subscribeJobProgress(id, setProgress);
|
||||
try {
|
||||
const result = await api.appUninstall(id, plan.planId, [...planSelected], mode);
|
||||
setSummary(result);
|
||||
setApps((current) =>
|
||||
current.filter(
|
||||
(app) =>
|
||||
(app.bundle_id || app.path) !==
|
||||
(plan.app.bundle_id || plan.app.path),
|
||||
),
|
||||
);
|
||||
setPlan(null);
|
||||
setPlanSelected(new Set());
|
||||
setSelectedApp(null);
|
||||
return result;
|
||||
} catch (reason) {
|
||||
if (!isCancelled(reason)) setError(messageFrom(reason));
|
||||
return null;
|
||||
} finally {
|
||||
stop();
|
||||
setDeleting(false);
|
||||
setProgress(null);
|
||||
setActiveJob(null);
|
||||
}
|
||||
},
|
||||
[deleting, plan, planSelected],
|
||||
);
|
||||
|
||||
const cancel = useCallback(async () => {
|
||||
if (activeJob) await api.cancelJob(activeJob).catch(() => false);
|
||||
}, [activeJob]);
|
||||
|
||||
const resetPlan = useCallback(() => {
|
||||
setPlan(null);
|
||||
setPlanSelected(new Set());
|
||||
}, []);
|
||||
|
||||
return {
|
||||
apps,
|
||||
total,
|
||||
scanned,
|
||||
scanning,
|
||||
planning,
|
||||
deleting,
|
||||
progress,
|
||||
error,
|
||||
selectedApp,
|
||||
plan,
|
||||
planSelected,
|
||||
summary,
|
||||
planSelectedTotal,
|
||||
scan,
|
||||
chooseApp,
|
||||
buildPlan,
|
||||
togglePlanItem,
|
||||
togglePlanAll,
|
||||
uninstall,
|
||||
cancel,
|
||||
resetPlan,
|
||||
clearError: () => setError(null),
|
||||
clearSummary: () => setSummary(null),
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,226 @@
|
|||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { api, subscribeJobProgress } from "../lib/api";
|
||||
import { isCancelled, messageFrom } from "../lib/format";
|
||||
import type {
|
||||
Category,
|
||||
DeleteMode,
|
||||
DeleteResult,
|
||||
JobProgress,
|
||||
ScanResult,
|
||||
} from "../types";
|
||||
|
||||
function jobId(): string {
|
||||
return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
}
|
||||
|
||||
export type ScanKind = "cleanup" | "purge";
|
||||
|
||||
export interface ScanWorkspace {
|
||||
kind: ScanKind;
|
||||
result: ScanResult | null;
|
||||
selected: Set<number>;
|
||||
progress: JobProgress | null;
|
||||
scanning: boolean;
|
||||
deleting: boolean;
|
||||
error: string | null;
|
||||
summary: DeleteResult | null;
|
||||
currentJob: string | null;
|
||||
selectedTotal: number;
|
||||
selectedCount: number;
|
||||
runScan: (options?: {
|
||||
force?: boolean;
|
||||
minAgeDays?: number | null;
|
||||
roots?: string[];
|
||||
}) => Promise<void>;
|
||||
cancel: () => Promise<void>;
|
||||
toggleItem: (index: number) => void;
|
||||
toggleCategory: (category: Category) => void;
|
||||
selectAll: () => void;
|
||||
clearSelection: () => void;
|
||||
clean: (mode: DeleteMode) => Promise<DeleteResult | null>;
|
||||
clearError: () => void;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
|
||||
const [result, setResult] = useState<ScanResult | null>(null);
|
||||
const [selected, setSelected] = useState<Set<number>>(new Set());
|
||||
const [progress, setProgress] = useState<JobProgress | null>(null);
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [summary, setSummary] = useState<DeleteResult | null>(null);
|
||||
const [currentJob, setCurrentJob] = useState<string | null>(null);
|
||||
const activeJob = useRef<string | null>(null);
|
||||
|
||||
const runScan = useCallback(
|
||||
async (options?: {
|
||||
force?: boolean;
|
||||
minAgeDays?: number | null;
|
||||
roots?: string[];
|
||||
}) => {
|
||||
if (scanning || deleting) return;
|
||||
const id = jobId();
|
||||
activeJob.current = id;
|
||||
setCurrentJob(id);
|
||||
setScanning(true);
|
||||
setError(null);
|
||||
setSummary(null);
|
||||
setProgress(null);
|
||||
const stop = await subscribeJobProgress(id, setProgress);
|
||||
try {
|
||||
const next =
|
||||
kind === "cleanup"
|
||||
? await api.cleanupScan(id, [], options?.minAgeDays ?? null, false)
|
||||
: await api.purgeScan(
|
||||
id,
|
||||
options?.roots ?? [],
|
||||
options?.minAgeDays ?? null,
|
||||
options?.force ?? false,
|
||||
);
|
||||
if (activeJob.current !== id) return;
|
||||
setResult(next);
|
||||
setSelected(
|
||||
new Set(
|
||||
next.items
|
||||
.map((item, index) => ({ item, index }))
|
||||
.filter(({ item }) => item.selected && !item.lock)
|
||||
.map(({ index }) => index),
|
||||
),
|
||||
);
|
||||
} catch (reason) {
|
||||
if (!isCancelled(reason)) setError(messageFrom(reason));
|
||||
} finally {
|
||||
stop();
|
||||
if (activeJob.current === id) {
|
||||
setScanning(false);
|
||||
setProgress(null);
|
||||
setCurrentJob(null);
|
||||
}
|
||||
}
|
||||
},
|
||||
[deleting, kind, scanning],
|
||||
);
|
||||
|
||||
const cancel = useCallback(async () => {
|
||||
if (activeJob.current) await api.cancelJob(activeJob.current).catch(() => false);
|
||||
}, []);
|
||||
|
||||
const toggleItem = useCallback((index: number) => {
|
||||
setSelected((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(index)) next.delete(index);
|
||||
else next.add(index);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleCategory = useCallback(
|
||||
(category: Category) => {
|
||||
if (!result) return;
|
||||
const indexes = result.items
|
||||
.map((item, index) => ({ item, index }))
|
||||
.filter(({ item }) => item.category === category && !item.lock)
|
||||
.map(({ index }) => index);
|
||||
setSelected((current) => {
|
||||
const next = new Set(current);
|
||||
const allSelected = indexes.length > 0 && indexes.every((index) => next.has(index));
|
||||
for (const index of indexes) {
|
||||
if (allSelected) next.delete(index);
|
||||
else next.add(index);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[result],
|
||||
);
|
||||
|
||||
const selectAll = useCallback(() => {
|
||||
if (!result) return;
|
||||
setSelected((current) => {
|
||||
const all = result.items
|
||||
.map((item, index) => ({ item, index }))
|
||||
.filter(({ item }) => !item.lock)
|
||||
.map(({ index }) => index);
|
||||
if (all.length > 0 && all.every((index) => current.has(index))) return new Set();
|
||||
return new Set(all);
|
||||
});
|
||||
}, [result]);
|
||||
|
||||
const clearSelection = useCallback(() => setSelected(new Set()), []);
|
||||
|
||||
const selectedTotal = useMemo(() => {
|
||||
if (!result) return 0;
|
||||
let total = 0;
|
||||
for (const index of selected) total += result.items[index]?.onDisk ?? 0;
|
||||
return total;
|
||||
}, [result, selected]);
|
||||
|
||||
const selectedCount = selected.size;
|
||||
|
||||
const clean = useCallback(
|
||||
async (mode: DeleteMode) => {
|
||||
if (!result || selected.size === 0 || deleting) return null;
|
||||
const id = jobId();
|
||||
activeJob.current = id;
|
||||
setCurrentJob(id);
|
||||
setDeleting(true);
|
||||
setError(null);
|
||||
setProgress(null);
|
||||
const stop = await subscribeJobProgress(id, setProgress);
|
||||
try {
|
||||
const next =
|
||||
kind === "cleanup"
|
||||
? await api.cleanupDelete(id, result.scanId, [...selected], mode)
|
||||
: await api.purgeDelete(id, result.scanId, [...selected], mode);
|
||||
if (activeJob.current !== id) return null;
|
||||
setResult(null);
|
||||
setSelected(new Set());
|
||||
setSummary(next);
|
||||
return next;
|
||||
} catch (reason) {
|
||||
if (!isCancelled(reason)) setError(messageFrom(reason));
|
||||
return null;
|
||||
} finally {
|
||||
stop();
|
||||
if (activeJob.current === id) {
|
||||
setDeleting(false);
|
||||
setProgress(null);
|
||||
setCurrentJob(null);
|
||||
}
|
||||
}
|
||||
},
|
||||
[deleting, kind, result, selected],
|
||||
);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setResult(null);
|
||||
setSelected(new Set());
|
||||
setSummary(null);
|
||||
setError(null);
|
||||
setProgress(null);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
kind,
|
||||
result,
|
||||
selected,
|
||||
progress,
|
||||
scanning,
|
||||
deleting,
|
||||
error,
|
||||
summary,
|
||||
currentJob,
|
||||
selectedTotal,
|
||||
selectedCount,
|
||||
runScan,
|
||||
cancel,
|
||||
toggleItem,
|
||||
toggleCategory,
|
||||
selectAll,
|
||||
clearSelection,
|
||||
clean,
|
||||
clearError: () => setError(null),
|
||||
reset,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
import { useCallback, useRef, useState } from "react";
|
||||
import { api, subscribeJobProgress } from "../lib/api";
|
||||
import { isCancelled, messageFrom } from "../lib/format";
|
||||
import type { JobProgress, LargestFile, StorageNode } from "../types";
|
||||
|
||||
function jobId(): string {
|
||||
return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
}
|
||||
|
||||
export interface StorageWorkspace {
|
||||
node: StorageNode | null;
|
||||
files: LargestFile[];
|
||||
progress: JobProgress | null;
|
||||
exploring: boolean;
|
||||
scanningFiles: boolean;
|
||||
error: string | null;
|
||||
explore: (path?: string | null) => Promise<void>;
|
||||
largestFiles: (path: string) => Promise<void>;
|
||||
cancel: () => Promise<void>;
|
||||
clearError: () => void;
|
||||
clearFiles: () => void;
|
||||
}
|
||||
|
||||
export function useStorageWorkspace(): StorageWorkspace {
|
||||
const [node, setNode] = useState<StorageNode | null>(null);
|
||||
const [files, setFiles] = useState<LargestFile[]>([]);
|
||||
const [progress, setProgress] = useState<JobProgress | null>(null);
|
||||
const [exploring, setExploring] = useState(false);
|
||||
const [scanningFiles, setScanningFiles] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const activeJob = useRef<string | null>(null);
|
||||
|
||||
const explore = useCallback(async (path?: string | null) => {
|
||||
if (exploring || scanningFiles) return;
|
||||
const id = jobId();
|
||||
activeJob.current = id;
|
||||
setExploring(true);
|
||||
setError(null);
|
||||
setProgress(null);
|
||||
setFiles([]);
|
||||
const stop = await subscribeJobProgress(id, setProgress);
|
||||
try {
|
||||
const next = await api.storageExplore(id, path ?? null, 1, 16);
|
||||
if (activeJob.current !== id) return;
|
||||
setNode(next);
|
||||
} catch (reason) {
|
||||
if (!isCancelled(reason)) setError(messageFrom(reason));
|
||||
} finally {
|
||||
stop();
|
||||
if (activeJob.current === id) {
|
||||
setExploring(false);
|
||||
setProgress(null);
|
||||
activeJob.current = null;
|
||||
}
|
||||
}
|
||||
}, [exploring, scanningFiles]);
|
||||
|
||||
const largestFiles = useCallback(
|
||||
async (path: string) => {
|
||||
if (exploring || scanningFiles) return;
|
||||
const id = jobId();
|
||||
activeJob.current = id;
|
||||
setScanningFiles(true);
|
||||
setError(null);
|
||||
setProgress(null);
|
||||
setFiles([]);
|
||||
const stop = await subscribeJobProgress(id, setProgress);
|
||||
try {
|
||||
const next = await api.storageLargestFiles(id, path, 40);
|
||||
if (activeJob.current !== id) return;
|
||||
setFiles(next);
|
||||
} catch (reason) {
|
||||
if (!isCancelled(reason)) setError(messageFrom(reason));
|
||||
} finally {
|
||||
stop();
|
||||
if (activeJob.current === id) {
|
||||
setScanningFiles(false);
|
||||
setProgress(null);
|
||||
activeJob.current = null;
|
||||
}
|
||||
}
|
||||
},
|
||||
[exploring, scanningFiles],
|
||||
);
|
||||
|
||||
const cancel = useCallback(async () => {
|
||||
if (activeJob.current) await api.cancelJob(activeJob.current).catch(() => false);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
node,
|
||||
files,
|
||||
progress,
|
||||
exploring,
|
||||
scanningFiles,
|
||||
error,
|
||||
explore,
|
||||
largestFiles,
|
||||
cancel,
|
||||
clearError: () => setError(null),
|
||||
clearFiles: () => setFiles([]),
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { api } from "../lib/api";
|
||||
import { messageFrom } from "../lib/format";
|
||||
import type { SystemSnapshot } from "../types";
|
||||
|
||||
export function useSystemSnapshot(active: boolean, intervalMs = 1800) {
|
||||
const [snapshot, setSnapshot] = useState<SystemSnapshot | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const inFlight = useRef(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
setLoading(true);
|
||||
try {
|
||||
setSnapshot(await api.systemSnapshot());
|
||||
setError(null);
|
||||
} catch (reason) {
|
||||
setError(messageFrom(reason));
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
void refresh();
|
||||
const timer = window.setInterval(() => void refresh(), intervalMs);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [active, intervalMs, refresh]);
|
||||
|
||||
return { snapshot, error, loading, refresh };
|
||||
}
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { api } from "../lib/api";
|
||||
import { messageFrom } from "../lib/format";
|
||||
import type { UpdateProgress, UpdateStatus } from "../types";
|
||||
|
||||
export interface UpdateFlow {
|
||||
status: UpdateStatus | null;
|
||||
checking: boolean;
|
||||
downloading: boolean;
|
||||
installing: boolean;
|
||||
installError: string | null;
|
||||
progress: UpdateProgress | null;
|
||||
percent: number | null;
|
||||
check: () => Promise<void>;
|
||||
download: () => Promise<void>;
|
||||
install: () => Promise<void>;
|
||||
clear: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function useUpdateFlow(feedUrl: string, autoCheck = true): UpdateFlow {
|
||||
const [status, setStatus] = useState<UpdateStatus | null>(null);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [downloading, setDownloading] = useState(false);
|
||||
const [installing, setInstalling] = useState(false);
|
||||
const [installError, setInstallError] = useState<string | null>(null);
|
||||
const [progress, setProgress] = useState<UpdateProgress | null>(null);
|
||||
const [percent, setPercent] = useState<number | null>(null);
|
||||
const mounted = useRef(true);
|
||||
const statusRef = useRef<UpdateStatus | null>(null);
|
||||
|
||||
const publish = useCallback((next: UpdateStatus | null) => {
|
||||
statusRef.current = next;
|
||||
if (mounted.current) setStatus(next);
|
||||
}, []);
|
||||
|
||||
const check = useCallback(async () => {
|
||||
if (checking) return;
|
||||
setChecking(true);
|
||||
try {
|
||||
const outcome = await api.updateCheck();
|
||||
publish(outcome.status);
|
||||
} catch {
|
||||
publish(await api.updateStatus().catch(() => null));
|
||||
} finally {
|
||||
if (mounted.current) setChecking(false);
|
||||
}
|
||||
}, [checking, publish]);
|
||||
|
||||
const download = useCallback(async () => {
|
||||
if (downloading) return;
|
||||
setDownloading(true);
|
||||
setInstallError(null);
|
||||
setProgress(null);
|
||||
setPercent(null);
|
||||
try {
|
||||
const ready = await api.updateDownload();
|
||||
publish(ready);
|
||||
} catch (error) {
|
||||
if (mounted.current) setInstallError(messageFrom(error));
|
||||
publish(await api.updateStatus().catch(() => null));
|
||||
} finally {
|
||||
if (mounted.current) {
|
||||
setDownloading(false);
|
||||
setProgress(null);
|
||||
setPercent(null);
|
||||
}
|
||||
}
|
||||
}, [downloading, publish]);
|
||||
|
||||
const install = useCallback(async () => {
|
||||
if (installing || !statusRef.current?.path) return;
|
||||
setInstalling(true);
|
||||
try {
|
||||
await api.updateInstall();
|
||||
} catch (error) {
|
||||
if (mounted.current) {
|
||||
setInstallError(messageFrom(error));
|
||||
setInstalling(false);
|
||||
}
|
||||
}
|
||||
}, [installing]);
|
||||
|
||||
const clear = useCallback(async () => {
|
||||
setInstallError(null);
|
||||
await api.updateClear().catch(() => undefined);
|
||||
publish(null);
|
||||
}, [publish]);
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
void api
|
||||
.updateStatus()
|
||||
.then((last) => {
|
||||
if (last) publish(last);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
const unlisteners: (() => void)[] = [];
|
||||
void api
|
||||
.onUpdateProgress((next) => {
|
||||
if (!mounted.current) return;
|
||||
setProgress(next);
|
||||
setPercent(
|
||||
next.total > 0
|
||||
? Math.min(100, Math.round((next.downloaded / next.total) * 100))
|
||||
: null,
|
||||
);
|
||||
})
|
||||
.then((stop) => unlisteners.push(stop));
|
||||
void api
|
||||
.onUpdateStatus((next) => {
|
||||
if (!mounted.current) return;
|
||||
statusRef.current = next;
|
||||
setStatus(next);
|
||||
})
|
||||
.then((stop) => unlisteners.push(stop));
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
unlisteners.forEach((stop) => stop());
|
||||
};
|
||||
}, [publish]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!feedUrl || !autoCheck) return;
|
||||
// A startup check runs in Rust. This is a quiet fallback for builds whose
|
||||
// first check is due but whose event was emitted before the webview mounted.
|
||||
const timer = window.setTimeout(() => {
|
||||
if (!statusRef.current) void check();
|
||||
}, 1200);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [autoCheck, check, feedUrl]);
|
||||
|
||||
return {
|
||||
status,
|
||||
checking,
|
||||
downloading,
|
||||
installing,
|
||||
installError,
|
||||
progress,
|
||||
percent,
|
||||
check,
|
||||
download,
|
||||
install,
|
||||
clear,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import { createContext, useContext, type ReactNode } from "react";
|
||||
import type { Language } from "./types";
|
||||
|
||||
interface I18nValue {
|
||||
lang: Language;
|
||||
setLang: (language: Language) => void;
|
||||
t: (en: string, zh: string) => string;
|
||||
bin: string;
|
||||
binLower: string;
|
||||
currency: string;
|
||||
}
|
||||
|
||||
const I18nContext = createContext<I18nValue | null>(null);
|
||||
|
||||
export function I18nProvider({
|
||||
lang,
|
||||
setLang,
|
||||
children,
|
||||
}: {
|
||||
lang: Language;
|
||||
setLang: (language: Language) => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const value: I18nValue = {
|
||||
lang,
|
||||
setLang,
|
||||
t: (en, zh) => (lang === "zh" ? zh : en),
|
||||
bin: lang === "zh" ? "废纸篓" : "Trash",
|
||||
binLower: lang === "zh" ? "废纸篓" : "trash",
|
||||
currency: lang === "zh" ? "zh-CN" : "en-US",
|
||||
};
|
||||
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
|
||||
}
|
||||
|
||||
export function useI18n(): I18nValue {
|
||||
const value = useContext(I18nContext);
|
||||
if (!value) throw new Error("useI18n must be used inside I18nProvider");
|
||||
return value;
|
||||
}
|
||||
|
||||
export function detectLanguage(): Language {
|
||||
const candidate = navigator.language || "en";
|
||||
return candidate.toLowerCase().startsWith("zh") ? "zh" : "en";
|
||||
}
|
||||