diff --git a/Cargo.lock b/Cargo.lock index 7f962e5..f4ce852 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1116,7 +1116,7 @@ checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" [[package]] name = "squid-cli" -version = "0.1.13" +version = "0.2.0" dependencies = [ "anyhow", "chrono", @@ -1135,7 +1135,7 @@ dependencies = [ [[package]] name = "squid-core" -version = "0.1.13" +version = "0.2.0" dependencies = [ "anyhow", "chrono", @@ -1154,7 +1154,7 @@ dependencies = [ [[package]] name = "squid-engine" -version = "0.1.13" +version = "0.2.0" dependencies = [ "anyhow", "chrono", @@ -1177,7 +1177,7 @@ dependencies = [ [[package]] name = "squid-platform" -version = "0.1.13" +version = "0.2.0" dependencies = [ "dirs", "libc", @@ -1196,7 +1196,7 @@ dependencies = [ [[package]] name = "squid-rules" -version = "0.1.13" +version = "0.2.0" dependencies = [ "globset", "serde", @@ -1208,7 +1208,7 @@ dependencies = [ [[package]] name = "squid-stats" -version = "0.1.13" +version = "0.2.0" dependencies = [ "chrono", "libc", @@ -1221,7 +1221,7 @@ dependencies = [ [[package]] name = "squid-tui" -version = "0.1.13" +version = "0.2.0" dependencies = [ "anyhow", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 22ec268..1ddb13e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*"] exclude = ["src-tauri"] [workspace.package] -version = "0.1.13" +version = "0.2.0" edition = "2021" rust-version = "1.80" license = "GPL-3.0-only" diff --git a/crates/squid-core/src/settings.rs b/crates/squid-core/src/settings.rs index 7264462..7eee18d 100644 --- a/crates/squid-core/src/settings.rs +++ b/crates/squid-core/src/settings.rs @@ -36,6 +36,18 @@ pub struct Settings { /// 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, + /// 小工具 · 截图识字 master switch (engine download stays on disk either way). + pub screenshot_enabled: bool, + /// Two-key global hotkey that wakes the capture overlay, e.g. `Alt+D`. + pub screenshot_hotkey: String, + /// 安全查杀 realtime posture: `power` (引擎按需拉起、空闲休眠), + /// `performance` (clamd 常驻) or `manual` (仅手动/计划扫描). + pub security_mode: String, + /// Whether Squid registers itself with Windows Security Center (WSC). + pub security_takeover: bool, + /// Optional ClamAV database mirror host (freshclam `DatabaseMirror`); + /// empty means the official CDN with the built-in fallback list. + pub clamav_mirror: String, } impl Default for Settings { @@ -53,6 +65,11 @@ impl Default for Settings { language: None, history_keep: 60, desktop_setup_reviewed: false, + screenshot_enabled: false, + screenshot_hotkey: "Alt+D".into(), + security_mode: "power".into(), + security_takeover: false, + clamav_mirror: String::new(), } } } diff --git a/docs/RELEASE.md b/docs/RELEASE.md index b73befb..38cbb73 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -64,6 +64,37 @@ toolchain instead of `cargo-xwin`. The installer is per-user and installs to: The executable inside is `squid-desktop.exe`, matching both the NSIS installer and the update handoff script. +### Three editions (0.2.0+) + +One version number ships three feature editions, gated by cargo features in +`src-tauri/Cargo.toml` (`default = ["screenshot","security"]`): + +| 版本 | features | setup 名 | artifact 键 | +| --- | --- | --- | --- | +| 完整 full | default | `Squid-Setup--win-x64.exe` | `windows` | +| Pro | `screenshot` only | `Squid-Pro-Setup--win-x64.exe` | `windows-pro` | +| Lite | none | `Squid-Lite-Setup--win-x64.exe` | `windows-lite` | + +Build each edition on Windows (pnpm build once, then per edition): + +```bash +# full +cargo build --release --features tauri/custom-protocol && pnpm exec tauri bundle +# pro(--no-default-features 必须走 cargo 直调;tauri build 不透传它) +cargo build --release --no-default-features --features "screenshot,tauri/custom-protocol" && pnpm exec tauri bundle +# lite +cargo build --release --no-default-features --features tauri/custom-protocol && pnpm exec tauri bundle +``` + +`tauri bundle` only re-runs NSIS over the current `target/release/` exe — so +`cargo build` decides the edition, `bundle` packages it, and the output +`Squid__x64-setup.exe` is renamed per edition while copying into +`release//`. The Rust edition is baked in (`edition_name()` → +`bootstrap.edition`); the frontend hides the pages per edition, and +`update.rs` prefers the edition artifact key with a plain-`windows` fallback. +Verify each exe with string probes (`wsc-last-error` ⇒ security, +`bin/snow_shot.exe` ⇒ screenshot) before staging. + ### 360/电脑管家 environments: ship 一键安装.bat (mandatory) On the developer machine (and other boxes running 腾讯电脑管家/360), the diff --git a/docs/screenshot-020.png b/docs/screenshot-020.png new file mode 100644 index 0000000..238f17e Binary files /dev/null and b/docs/screenshot-020.png differ diff --git a/docs/screenshot-mock.html b/docs/screenshot-mock.html new file mode 100644 index 0000000..42ac765 --- /dev/null +++ b/docs/screenshot-mock.html @@ -0,0 +1,190 @@ + + + + + + + +

Squid 小工具 · 截图识字(B1:snow-shot 引擎,纯离线 OCR)

+
Squid 负责入口、快捷键、结果归档与设置;截图框选 / 标注 / 识字浮层由 snow-shot 完成(随包分发,进程解耦)。
+ +

① Squid 内「小工具 › 截图识字」页 入口 + 设置 + 识别历史

+
+
UTILITIES
+
截图识字
+
框选屏幕任意区域:可标注、贴图、长截图、录屏,一键提取文字 —— 全程离线,画面不出本机。
+ +
+
✂
+
+ 截图识字引擎 · snow-shot 1.6.0 · 已就绪(离线识别) + 识别模型已就位(PaddleOCR · 中文/英文,约 15 MB)· 更新:自动跟随 Squid 更新 · 许可:GPL-3(随包附协议) +
+
+ 快捷键 Ctrl + Alt + A + +
+
+ +
+
📥 保存位置 接管 + 图片\Squid 截图
命名按时间自动
+
🌙 跟随开机 开 + 登录后热键即生效
未开也能从本页启动
+
📋 识文自动复制 开 + 点「提取文字」后自动进剪贴板
并记入下方历史
+
🧩 划词翻译 未装 + 需 B2 增强包 Umi-OCR
(HTTP 接口联动,可选)
+
+ +
+
识别历史 点行=重新复制文字 · 保留 30 天 +
+
+
今天 17:42 · 报价单截图图片\Squid 截图\2026-11-25 174215.png
+ 326 字
+
+
今天 15:08 · 报错弹窗图片\Squid 截图\2026-11-25 150803.png
+ 88 字
+
+
昨天 21:36 · 会议纪要长截图图片\Squid 截图\2026-11-24 213644.png
+ 1,204 字
+
+

冷启动:首次按热键约 1 秒拉起引擎,之后常驻秒开;引擎崩溃不影响 Squid,托盘与本页都能重启它。

+
+ +

② 截图中的浮层(snow-shot 实机风格) 框选 → 标注工具条 → 提取文字结果卡

+
+
+
+
 发票明细 - 浏览器
+
+
+
+
+
+
+
+
+
560 × 300
+
+ ✏▭→M + ▦🔍 + + 文📌⬇ + + 完成 ✓✕ +
+
+

提取文字 离线识别 · 0.6 秒

+
+ 电子发票(普通发票)
+ 发票号码:24502000000018234567
+ 开票日期:2026年11月20日
+ 购买方:某某科技有限公司
+ 金额合计:¥1,280.00 税率 6%
+ …… +
+
+ + + + +
+
+
+ + diff --git a/docs/screenshot-mock.png b/docs/screenshot-mock.png new file mode 100644 index 0000000..856deac Binary files /dev/null and b/docs/screenshot-mock.png differ diff --git a/docs/security-020.png b/docs/security-020.png new file mode 100644 index 0000000..77b82d7 Binary files /dev/null and b/docs/security-020.png differ diff --git a/docs/security-mock.html b/docs/security-mock.html new file mode 100644 index 0000000..ab7c48e --- /dev/null +++ b/docs/security-mock.html @@ -0,0 +1,245 @@ + + + + + + + +

Squid 安全页 · ClamAV 引擎 + WSC 接管 产品方案图

+
沿用应用主题与 CleanBar 交互语言;实时防护 = Squid 热点目录监控 + clamd 本地毫秒扫描(ClamWin/ClamShield 同架构)。
+ +

① 安全页 · 平时状态 接管完成,绿态;顶部分区即"我管理着你"

+
+
SECURITY
+
安全查杀
+
Squid 已接管 Windows 安全中心 · 实时防护守护 6 个高危目录 · 双引擎按需查杀
+ +
+
🛡
+
+ 设备正在受到保护 · 由 Squid 管理 +
Windows 安全中心显示:「病毒和威胁防护由于 Squid 提供,保持最新状态」· Windows Defender 已转为被动模式
+
+ ● 实时防护 开(守护 6 目录) + ClamAV 库 2026-11-25 · 今日已更新 + Defender 库 2026-11-25(被动,可用) + 上次全盘 今天 09:30 · 未发现威胁 +
+
+
+ + + +
+
+ +
今日实时防护记录 · 新文件落地即扫,共 1,214 个,1 个被拦截
+
+

热点目录实时监控 · 运行中(clamd 常驻 · 内存 320 MB · 空闲 5 分钟自动休眠)

+
C:\Users\34798\Downloads\setup-x64(1).exeClamAV拦截:疑似打包器 PUA
+
D:\Temp\照片备份.7z → 解压 84 个文件ClamAV安全 ×84
+
E:\(U盘)\投标书-final.docxClamAV安全
+
+ +
+
+
+ 接管 Windows 安全中心 + Squid 常驻后台,每 12 小时向安全中心报到(心跳);关闭开关将立刻注销,Windows Defender 自动恢复主动模式。 +
+
+
+
+ WSC 登记 已生效 + 心跳 上次 17:00 · 正常 + 开机自启 开 + 卸载将自动注销 +
+
+ +
引擎与病毒库
+
+
+ ⚙ + ClamAV 引擎(主) + 程序 22 MB 已就绪 · 病毒库 main+daily 213 MB
TUNA 国内镜像:开
+
+
+
+ ✓ + Windows Defender(第二意见) + 被动模式随时候命:全盘可交给它跑一遍,与 ClamAV 结果互补;库更新由系统托管。 +
+
+
+ ⏱ + 计划任务 + 每天 09:30 快速查杀(启动项/服务/下载/浏览器目录);每周日全盘。错过不补跑,合盖休眠自动顺延。 +
+
+
+
+ +

② 查杀进行中 + 发现威胁 复用 CleanBar;威胁行带引擎来源徽标

+
+
全盘查杀 · 引擎 ClamAV(库已加载内存)
+
+
+ ◌ +
+ 正在扫描 486,213 / 1,102,908 个文件 · 已用 6 分 12 秒 +
当前:C:\Users\34798\Documents\客户资料\合同-2023.zip · 发现威胁 2 · 已跳过压缩包内层 12,401
+
+ 44% + +
+
+
+
+

发现 2 个威胁(处理前不会动它们)

+
Eicar-Test-SignatureC:\Users\34798\Downloads\clamavtest\eicar.txtClamAV
+
Trojan.GenericKD.46872D:\Soft\crack\patcher.exeDefender 复查
+
+

隔离 = 移入 Squid 私有隔离区(可一键还原,同「历史」体系);不直接删除,避免误杀炸裂。

+
+ +

③ 开启接管时的确认弹窗 诚实告知:Defender 转被动,Squid 顶上

+
+
+
+

!接管 Windows 安全中心?

+
    +
  • 「Windows 安全中心」将显示 由 Squid 提供保护;
  • +
  • Windows Defender 实时防护转为被动,改由 Squid 热点实时监控 + ClamAV 引擎顶上;
  • +
  • Defender 引擎仍保留,可作全盘复查的第二意见;
  • +
  • Squid 需要开机常驻(托盘,内存约 40 MB + clamd 320 MB),关闭开关或卸载即自动还原。
  • +
+
检测到本机当前由「腾讯电脑管家」接管安全中心。开启前请先在管家中关闭「病毒防护」,否则两个产品会互相挤占登记。
+
+ + +
+
+
+
+ + diff --git a/docs/security-mock.png b/docs/security-mock.png new file mode 100644 index 0000000..998187f Binary files /dev/null and b/docs/security-mock.png differ diff --git a/docs/security-mock2.html b/docs/security-mock2.html new file mode 100644 index 0000000..2ef886f --- /dev/null +++ b/docs/security-mock2.html @@ -0,0 +1,237 @@ + + + + + + + +

Squid 安全页 v2 · 三档防护模式

+
改名并备注模式解释;clamd 内存改用实测口径(节能模式按需拉起)。
+ +
+
SECURITY
+
安全查杀
+
Squid 已接管 Windows 安全中心 · 节能模式下常驻仅约 100 MB(较 Defender 实时防护省 200 MB+)
+ +
+
🛡
+
+ 设备正在受到保护 · 由 Squid 管理 +
Windows 安全中心显示:「病毒和威胁防护由 Squid 提供」· Windows Defender 实时服务已停用
+
+ ● 实时防护 开(节能模式) + ClamAV 库 2026-11-25 · 今日已更新 + clamd 当前休眠 · 需要时 5–15 秒拉起 + 上次全盘 今天 09:30 · 未发现威胁 +
+
+
+ + + +
+
+ +
实时防护模式 · 三档,随时可切;当前:节能模式
+
+
+
节能模式推荐
+
常驻只有 Squid 本体(目录监听 + 计划 + 心跳,约 100 MB)。高危目录有新文件时才拉起 clamd,扫描后 5 分钟无活动自动休眠;识别结果约延迟 10 秒弹出。
+
平时最省内存较 Defender 净省 200 MB+
+ +
+
+
性能模式
+
clamd 24 小时常驻,新文件落地毫秒级出结果、无拉起延迟。代价是引擎与病毒库全程驻留内存(约 650–900 MB),适合内存充裕、下载频繁的主力机。
+
内存 +650–900 MB实时最快
+ +
+
+
手动模式
+
不做实时监控,只保留手动查杀与每日计划扫描。Squid 可完全退出;接管开着的话,安全中心会在 7 天后提示「防护已过期」。
+
零常驻无实时防护
+ +
+
+
备注:节能/性能模式的差别只在 clamd 是否常驻;目录监听与拦截处置逻辑相同。切换即时生效,无需重启。
+ +
今日实时防护记录 · 新文件落地即排队检查,共 1,214 个,1 个被拦截
+
+

热点目录监控运行中 · 6 个目录 · clamd 休眠中(今日被拉起 37 次,平均每次 2.4 分钟)

+
C:\Users\34798\Downloads\setup-x64(1).exeClamAV拦截:疑似打包器 PUA
+
D:\Temp\照片备份.7z → 解压 84 个文件ClamAV安全 ×84
+
E:\(U盘)\投标书-final.docxClamAV安全
+
+ +
+
+
+ 接管 Windows 安全中心 + Squid 常驻时向安全中心持续报到(心跳);关闭开关将立刻注销,Windows Defender 自动恢复主动模式。 +
+
+
+
+ WSC 登记 已生效 + 心跳 上次 17:00 · 正常 + 开机自启 开 + 卸载将自动注销 +
+
+ +
引擎与病毒库
+
+
+ ⚙ + ClamAV 引擎(主) + 程序 22 MB 已就绪 · 病毒库 213 MB · 常驻状态随防护模式变化(当前休眠)
TUNA 国内镜像:开
+
+
+
+ ✓ + Windows Defender(第二意见) + 实时服务已停用(由 Squid 接管);引擎保留,全盘可交给它复查一遍,与 ClamAV 结果互补。 +
+
+
+ ⏱ + 计划任务 + 每天 09:30 快速查杀(启动项/服务/下载/浏览器目录);每周日全盘。合盖休眠自动顺延,错过不补跑。 +
+
+
+ +
查杀进行中(样式沿用 CleanBar)+ 威胁列表
+
+
+ ◌ +
+ 正在扫描 486,213 / 1,102,908 个文件 · 已用 6 分 12 秒 +
当前:C:\Users\34798\Documents\客户资料\合同-2023.zip · 发现威胁 2
+
+ 44% + +
+
+
+
+
Eicar-Test-SignatureC:\Users\34798\Downloads\clamavtest\eicar.txtClamAV
+
Trojan.GenericKD.46872D:\Soft\crack\patcher.exeDefender 复查
+
+

隔离 = 移入 Squid 私有隔离区(可一键还原,接入「历史」体系);不直接删除,避免误杀。

+
+ + diff --git a/package.json b/package.json index 0bd1433..f8e5b1d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "squid-desktop", "private": true, - "version": "0.1.13", + "version": "0.2.0", "type": "module", "scripts": { "dev": "vite --port 1420 --strictPort", diff --git a/release/0.2.0/README-Windows-x64.txt b/release/0.2.0/README-Windows-x64.txt new file mode 100644 index 0000000..db1a097 --- /dev/null +++ b/release/0.2.0/README-Windows-x64.txt @@ -0,0 +1,49 @@ +Squid 0.1.13 - Windows x64 + +系统要求 +-------- +- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。 +- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid + 启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime: + https://developer.microsoft.com/microsoft-edge/webview2/ +- 安装与运行都不需要管理员权限。安装位置为 + %LOCALAPPDATA%\Programs\Squid。 +- 权限管理页中,机单(HKLM)范围的启动项开关与删除、系统服务需要以 + 管理员身份运行 Squid(或同意一次 UAC 提权)才能修改,界面会给出 + 明确提示;UAC 被取消时状态不会被假装成已修改。 + +安装 +---- +1. 运行 Squid-Setup-0.1.13-win-x64.exe。 +2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。 +3. 升级直接覆盖安装,不再询问是否先卸载旧版本;用户配置自动继承。 +4. 卸载请在 Windows“设置 > 应用”中移除 Squid。 + +更新 +---- +Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验 +文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥, +还会验证清单的 Ed25519 签名。 + +校验 +---- +PowerShell: + Get-FileHash .\Squid-Setup-0.1.13-win-x64.exe -Algorithm SHA256 + +提示 +---- +- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标 + 上右键退出),否则安装程序无法替换正在运行的程序文件。 +- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入 + 临时目录,报"NSIS Error - Error writing temporary file"。三种绕法, + 按方便程度排序: + 1) 双击本目录的「一键安装.bat」——它会把安装包复制到 C 盘临时目录 + 再启动(管家只拦从非系统盘启动的安装程序,此法本机验证有效); + 2) 管家弹窗出现时选"允许",或将安装文件加入信任区后重试; + 3) 使用便携包 Squid-0.1.13-portable-win-x64.zip,解压后把 + squid-desktop.exe 覆盖到安装目录(先退出托盘中的 Squid)。 +- 本版本重点:开机启动项学习芒果磁盘——残留项识别与一键删除、状态 + 筛选段、「显示系统项」开关、来源/时机/签名芯片;重复文件的保留 + 副本现在也可以勾选完全删除(有醒目警告);大文件不再列页面文件; + 修复重复文件清理按钮红底深红字看不清的问题。 +- 上一版的桌面小组件位置守卫、空间清理/系统维护三页签整合继续有效。 diff --git a/release/0.2.0/RELEASE_NOTES.md b/release/0.2.0/RELEASE_NOTES.md new file mode 100644 index 0000000..2484db8 --- /dev/null +++ b/release/0.2.0/RELEASE_NOTES.md @@ -0,0 +1,73 @@ +# Squid 0.2.0 — 三版本首发:截图识字 + 安全查杀 + +这一版是 Squid 从「清理工具」走向「日常系统管家」的分水岭:新增两大功能 +(截图识字、安全查杀),并首次把产品切成三个版本同时出包。 + +## 版本矩阵(同一版本号,同步迭代) + +| 版本 | 内容 | 安装包 | 便携包 | +| --- | --- | --- | --- | +| **完整版 full** | 全部清理能力 + 截图识字 + 安全查杀 | `Squid-Setup-0.2.0-win-x64.exe` | `Squid-0.2.0-portable-win-x64.zip` | +| **Pro 版** | 全部清理能力 + 截图识字(不带杀毒) | `Squid-Pro-Setup-0.2.0-win-x64.exe` | `Squid-Pro-0.2.0-portable-win-x64.zip` | +| **Lite 版** | 纯净清理全家桶(截图/杀毒入口不出现) | `Squid-Lite-Setup-0.2.0-win-x64.exe` | `Squid-Lite-0.2.0-portable-win-x64.zip` | + +三个包共用同一个更新清单(`squid-update.json`),按 `windows` / +`windows-pro` / `windows-lite` 三个 artifact 键各取所需;Lite 装完永远不会 +被推 Pro 的包。 + +## 新增 · 截图识字(小工具 › 截图识字) + +- 框选屏幕任意区域:标注、贴图、长截图、录屏、一键提取文字, + **识别全程离线,画面不出本机**。 +- 引擎 = snow-shot 1.6.4 便携版(PP-OCRv6 本地 ONNX 模型),随包**按需下载** + (约 75.5 MB,SHA256 锁定校验后解压到 `%APPDATA%\squid\engines`, + Squid 安装器体积不膨胀)。 +- 启用开关 + 全局两键热键(默认 `Alt+D`,可改;单键会被拒绝并解释原因)。 + 开关关闭即解绑热键,绝不占键。 +- 「开始截图」按钮、保存位置直达(`图片\Squid 截图`,不存在自动创建)、 + **识别历史**列表(截图文件按时间倒序直读磁盘,点行即在资源管理器定位)、 + 冷启动说明与 GPL-3 许可标注。 +- 学习对象:**[mg-chao/snow-shot](https://github.com/mg-chao/snow-shot)** + (截图+离线 OCR 引擎,GPL-3,进程解耦随包分发);入口与归档体验参考 + **[ShareX/ShareX](https://github.com/ShareX/ShareX)**、 + **[xushengfeng/eSearch](https://github.com/xushengfeng/eSearch)**。 + +## 新增 · 安全查杀(安全查杀页) + +- **ClamAV 1.4.4 本地引擎** + 病毒库**按需下载不预置**(引擎约 187.6 MB; + 库更新走 freshclam,内置国内官方加速节点 `db.cn.clamav.net`, + 自动回退 `database.clamav.net`,镜像可手改)。 +- **快速查杀**(启动项指向的程序 + 下载/桌面/文档)与**全盘查杀**; + 进度实时计数,可取消;威胁列表支持「定位」「隔离」。 +- **隔离区**:一键还原 / 彻底删除,误杀可逆,绝不直接删文件。 +- **三档实时防护模式**(随时切换、即时生效): + - 节能模式(推荐):常驻仅 Squid 本体约 100 MB,高危目录有新文件才拉起 + clamd,闲置 5 分钟自动休眠; + - 性能模式:clamd 24 小时常驻,毫秒级出结果(代价约 650–900 MB 内存); + - 手动模式:零常驻,只留手动与计划查杀。 +- **接管 Windows 安全中心**(WSC 登记 + 心跳):开关注册成功后,安全中心 + 显示「病毒和威胁防护由 Squid 提供」,Defender 自动退居第二意见。 + 未签名构建会被系统拒绝登记(0x800706F4),页面如实说明原因,不假装成功。 +- 学习对象:**[Cisco-Talos/clamav](https://github.com/Cisco-Talos/clamav)** + (开源防病毒引擎);接管体验与「由 XX 管理」状态卡 + 参考腾讯电脑管家;双引擎互检思路(ClamAV 主查 + Defender 复查互补)。 + +## 新增 · 基建 + +- cargo features 三版本矩阵(`default = screenshot+security / pro / lite`), + Tauri 一键分别出包;更新 feed 按版本分发 artifact。 +- 引擎按需下载器:缓存复用、SHA256 校验、tar.exe 优先/Expand-Archive 兜底 + 解压、`squid://engine` 事件流全程可视。 + +## 修复 + +- WSC 登记失败的错误文案现在写入配置目录,重启后仍然可见。 + +## 已知限制 + +- 未签名构建无法完成 WSC 登记(Windows 对防病毒产品的硬要求), + 拿到代码签名证书后该开关即可点亮。 +- 「用 Defender 全盘复查」按钮本期先占位(即将上线)。 + +安装:双击 `Squid-Setup-0.2.0-win-x64.exe`;若被电脑管家/360 拦截 +(NSIS 临时文件报错),改双击同目录 `一键安装.bat`。 diff --git a/release/0.2.0/SHA256SUMS.txt b/release/0.2.0/SHA256SUMS.txt new file mode 100644 index 0000000..da8010b --- /dev/null +++ b/release/0.2.0/SHA256SUMS.txt @@ -0,0 +1,6 @@ +72bc7d3f6bb2494eeb18b7e47baf6b33ad1c1462550d7f0ecd85f239751150c9 Squid-0.2.0-portable-win-x64.zip +18968353fe1e131f716991dadce4b5a032be28cf1d26e32384fc6bb41959d594 Squid-Lite-0.2.0-portable-win-x64.zip +07e3b79a7b1cafe21100225ff3272f35f8032f7da013cfaf6b624c1cb9405552 Squid-Lite-Setup-0.2.0-win-x64.exe +9584de12873f7e899dd2903f97da6dd9467f9c4dfa2755e8c1566db450706734 Squid-Pro-0.2.0-portable-win-x64.zip +4b1d087ba575ad8e9faee58120827fb4f6b3dd9d6a72b8c6681bda77d6e9b59a Squid-Pro-Setup-0.2.0-win-x64.exe +5a22cb8b609f062ce3d1be03160e5dca1bb1c6fb016afc75c3e2468301a31aa5 Squid-Setup-0.2.0-win-x64.exe diff --git a/release/0.2.0/Squid-0.2.0-portable-win-x64.zip b/release/0.2.0/Squid-0.2.0-portable-win-x64.zip new file mode 100644 index 0000000..ed6abfa Binary files /dev/null and b/release/0.2.0/Squid-0.2.0-portable-win-x64.zip differ diff --git a/release/0.2.0/Squid-Lite-0.2.0-portable-win-x64.zip b/release/0.2.0/Squid-Lite-0.2.0-portable-win-x64.zip new file mode 100644 index 0000000..4d99e30 Binary files /dev/null and b/release/0.2.0/Squid-Lite-0.2.0-portable-win-x64.zip differ diff --git a/release/0.2.0/Squid-Lite-Setup-0.2.0-win-x64.exe b/release/0.2.0/Squid-Lite-Setup-0.2.0-win-x64.exe new file mode 100644 index 0000000..912e224 Binary files /dev/null and b/release/0.2.0/Squid-Lite-Setup-0.2.0-win-x64.exe differ diff --git a/release/0.2.0/Squid-Pro-0.2.0-portable-win-x64.zip b/release/0.2.0/Squid-Pro-0.2.0-portable-win-x64.zip new file mode 100644 index 0000000..c1fdef1 Binary files /dev/null and b/release/0.2.0/Squid-Pro-0.2.0-portable-win-x64.zip differ diff --git a/release/0.2.0/Squid-Pro-Setup-0.2.0-win-x64.exe b/release/0.2.0/Squid-Pro-Setup-0.2.0-win-x64.exe new file mode 100644 index 0000000..df63ab4 Binary files /dev/null and b/release/0.2.0/Squid-Pro-Setup-0.2.0-win-x64.exe differ diff --git a/release/0.2.0/Squid-Setup-0.2.0-win-x64.exe b/release/0.2.0/Squid-Setup-0.2.0-win-x64.exe new file mode 100644 index 0000000..ffb900d Binary files /dev/null and b/release/0.2.0/Squid-Setup-0.2.0-win-x64.exe differ diff --git a/release/0.2.0/squid-update.json b/release/0.2.0/squid-update.json new file mode 100644 index 0000000..9f18556 --- /dev/null +++ b/release/0.2.0/squid-update.json @@ -0,0 +1,23 @@ +{ + "schema": 1, + "version": "0.2.0", + "date": "2026-11-25", + "notes": "# Squid 0.2.0 — 三版本首发:截图识字 + 安全查杀\n\n这一版是 Squid 从「清理工具」走向「日常系统管家」的分水岭:新增两大功能\n(截图识字、安全查杀),并首次把产品切成三个版本同时出包。\n\n## 版本矩阵(同一版本号,同步迭代)\n\n| 版本 | 内容 | 安装包 | 便携包 |\n| --- | --- | --- | --- |\n| **完整版 full** | 全部清理能力 + 截图识字 + 安全查杀 | `Squid-Setup-0.2.0-win-x64.exe` | `Squid-0.2.0-portable-win-x64.zip` |\n| **Pro 版** | 全部清理能力 + 截图识字(不带杀毒) | `Squid-Pro-Setup-0.2.0-win-x64.exe` | `Squid-Pro-0.2.0-portable-win-x64.zip` |\n| **Lite 版** | 纯净清理全家桶(截图/杀毒入口不出现) | `Squid-Lite-Setup-0.2.0-win-x64.exe` | `Squid-Lite-0.2.0-portable-win-x64.zip` |\n\n三个包共用同一个更新清单(`squid-update.json`),按 `windows` /\n`windows-pro` / `windows-lite` 三个 artifact 键各取所需;Lite 装完永远不会\n被推 Pro 的包。\n\n## 新增 · 截图识字(小工具 › 截图识字)\n\n- 框选屏幕任意区域:标注、贴图、长截图、录屏、一键提取文字,\n **识别全程离线,画面不出本机**。\n- 引擎 = snow-shot 1.6.4 便携版(PP-OCRv6 本地 ONNX 模型),随包**按需下载**\n (约 75.5 MB,SHA256 锁定校验后解压到 `%APPDATA%\\squid\\engines`,\n Squid 安装器体积不膨胀)。\n- 启用开关 + 全局两键热键(默认 `Alt+D`,可改;单键会被拒绝并解释原因)。\n 开关关闭即解绑热键,绝不占键。\n- 「开始截图」按钮、保存位置直达(`图片\\Squid 截图`,不存在自动创建)、\n **识别历史**列表(截图文件按时间倒序直读磁盘,点行即在资源管理器定位)、\n 冷启动说明与 GPL-3 许可标注。\n- 学习对象:**[mg-chao/snow-shot](https://github.com/mg-chao/snow-shot)**\n (截图+离线 OCR 引擎,GPL-3,进程解耦随包分发);入口与归档体验参考\n **[ShareX/ShareX](https://github.com/ShareX/ShareX)**、\n **[xushengfeng/eSearch](https://github.com/xushengfeng/eSearch)**。\n\n## 新增 · 安全查杀(安全查杀页)\n\n- **ClamAV 1.4.4 本地引擎** + 病毒库**按需下载不预置**(引擎约 187.6 MB;\n 库更新走 freshclam,内置国内官方加速节点 `db.cn.clamav.net`,\n 自动回退 `database.clamav.net`,镜像可手改)。\n- **快速查杀**(启动项指向的程序 + 下载/桌面/文档)与**全盘查杀**;\n 进度实时计数,可取消;威胁列表支持「定位」「隔离」。\n- **隔离区**:一键还原 / 彻底删除,误杀可逆,绝不直接删文件。\n- **三档实时防护模式**(随时切换、即时生效):\n - 节能模式(推荐):常驻仅 Squid 本体约 100 MB,高危目录有新文件才拉起\n clamd,闲置 5 分钟自动休眠;\n - 性能模式:clamd 24 小时常驻,毫秒级出结果(代价约 650–900 MB 内存);\n - 手动模式:零常驻,只留手动与计划查杀。\n- **接管 Windows 安全中心**(WSC 登记 + 心跳):开关注册成功后,安全中心\n 显示「病毒和威胁防护由 Squid 提供」,Defender 自动退居第二意见。\n 未签名构建会被系统拒绝登记(0x800706F4),页面如实说明原因,不假装成功。\n- 学习对象:**[Cisco-Talos/clamav](https://github.com/Cisco-Talos/clamav)**\n (开源防病毒引擎);接管体验与「由 XX 管理」状态卡\n 参考腾讯电脑管家;双引擎互检思路(ClamAV 主查 + Defender 复查互补)。\n\n## 新增 · 基建\n\n- cargo features 三版本矩阵(`default = screenshot+security / pro / lite`),\n Tauri 一键分别出包;更新 feed 按版本分发 artifact。\n- 引擎按需下载器:缓存复用、SHA256 校验、tar.exe 优先/Expand-Archive 兜底\n 解压、`squid://engine` 事件流全程可视。\n\n## 修复\n\n- WSC 登记失败的错误文案现在写入配置目录,重启后仍然可见。\n\n## 已知限制\n\n- 未签名构建无法完成 WSC 登记(Windows 对防病毒产品的硬要求),\n 拿到代码签名证书后该开关即可点亮。\n- 「用 Defender 全盘复查」按钮本期先占位(即将上线)。\n\n安装:双击 `Squid-Setup-0.2.0-win-x64.exe`;若被电脑管家/360 拦截\n(NSIS 临时文件报错),改双击同目录 `一键安装.bat`。\n", + "artifacts": { + "windows": { + "file": "Squid-Setup-0.2.0-win-x64.exe", + "sha256": "5a22cb8b609f062ce3d1be03160e5dca1bb1c6fb016afc75c3e2468301a31aa5", + "size": 4066645 + }, + "windows-pro": { + "file": "Squid-Pro-Setup-0.2.0-win-x64.exe", + "sha256": "4b1d087ba575ad8e9faee58120827fb4f6b3dd9d6a72b8c6681bda77d6e9b59a", + "size": 3974317 + }, + "windows-lite": { + "file": "Squid-Lite-Setup-0.2.0-win-x64.exe", + "sha256": "07e3b79a7b1cafe21100225ff3272f35f8032f7da013cfaf6b624c1cb9405552", + "size": 3894331 + } + } +} \ No newline at end of file diff --git a/release/0.2.0/一键安装.bat b/release/0.2.0/一键安装.bat new file mode 100644 index 0000000..c0794bd --- /dev/null +++ b/release/0.2.0/一键安装.bat @@ -0,0 +1,41 @@ +@echo off +rem Squid 0.2.0 one-click installer (full edition). +rem Copies the setup to %TEMP% first: some security suites (e.g. PC Manager) +rem block unsigned installers launched from non-system drives. +setlocal +title Squid Setup +set "PKG=%~dp0Squid-Setup-0.2.0-win-x64.exe" + +if not exist "%PKG%" ( + echo [ERROR] Setup file not found next to this script: + echo %PKG% + echo Keep this .bat in the same folder as the setup .exe. + pause + exit /b 1 +) + +echo [1/3] Stopping a running Squid if any... +taskkill /F /IM squid-desktop.exe >nul 2>&1 +rem The kill is asynchronous; give the OS a moment to release the exe lock. +ping -n 3 127.0.0.1 >nul + +echo [2/3] Copying installer to temp folder... +copy /Y "%PKG%" "%TEMP%\Squid-Setup-0.2.0-win-x64.exe" >nul +if errorlevel 1 ( + echo [ERROR] Copy to %TEMP% failed. Free up disk space or retry. + pause + exit /b 1 +) + +echo [3/3] Installing silently, please wait... +"%TEMP%\Squid-Setup-0.2.0-win-x64.exe" /S +if errorlevel 1 ( + echo [ERROR] Installer exited with code %ERRORLEVEL%. + pause + exit /b 1 +) + +echo. +echo Squid 0.2.0 installed successfully. +echo (If a previous Squid was running it was closed by this script.) +pause diff --git a/release/CHANGELOG-SINCE-0.1.13.md b/release/CHANGELOG-SINCE-0.1.13.md new file mode 100644 index 0000000..aa00505 --- /dev/null +++ b/release/CHANGELOG-SINCE-0.1.13.md @@ -0,0 +1,62 @@ +# Squid 版本更新说明(自上次上传 0.1.13 之后:0.2.0) + +--- + +## 0.2.0 — 三版本首发:截图识字 + 安全查杀 + +本版是 Squid 从「清理工具」走向「日常系统管家」的分水岭:新增两大功能, +并首次把产品切成三个版本(完整 / Pro / Lite)同版本号同时出包。 + +### 版本矩阵与基建 + +- cargo features 三版本矩阵:完整版(截图+杀毒)、Pro(仅截图)、 + Lite(纯净清理);Tauri 分别出包,安装包/便携包/更新清单一次三份。 +- 更新 feed 按 `windows` / `windows-pro` / `windows-lite` 三 artifact 键 + 分发,各版本只收自己的包;侧栏底部显示版本徽标(Pro / Lite)。 +- 引擎按需下载器(`src-tauri/src/engines.rs`):缓存复用、SHA256 校验、 + tar.exe 优先 / Expand-Archive 兜底解压、`squid://engine` 事件流全程 + 可视(下载/校验/解压/就绪/错误)。 + +### 新增 · 截图识字(小工具 › 截图识字) + +- 框选屏幕任意区域:标注、贴图、长截图、录屏、一键提取文字,识别全程 + 离线(本地 ONNX 模型),画面不出本机。 +- 引擎 = snow-shot 1.6.4 便携版按需下载(约 75.5 MB,SHA256 锁定, + 解包到 `%APPDATA%\squid\engines`,Squid 安装器体积不膨胀,GPL-3 + 组件以独立进程解耦、随包附协议)。 +- 启用开关 + 两键全局热键(默认 Alt+D,可改,单键直接拒绝);关开关 + 即解绑,绝不占键;热键被占用时页面如实提示。 +- 「开始截图」、保存位置直达(`图片\Squid 截图`,自动创建)、识别历史 + (直读磁盘按时间倒序,点行定位)。 +- 学习对象:**mg-chao/snow-shot** + (https://github.com/mg-chao/snow-shot —— 截图+离线 OCR 引擎, + PP-OCRv6 本地模型);入口/归档体验参考 **ShareX/ShareX** + (https://github.com/ShareX/ShareX )、 **xushengfeng/eSearch** + (https://github.com/xushengfeng/eSearch );离线 OCR 备选调研过 + **hiroi-sora/Umi-OCR**(https://github.com/hiroi-sora/Umi-OCR )。 + +### 新增 · 安全查杀(安全查杀页) + +- **ClamAV 1.4.4** 本地引擎按需下载(约 187.6 MB)+ 病毒库不预置, + freshclam 更新默认走官方国内加速节点 `db.cn.clamav.net`、失败自动 + 回退 `database.clamav.net`,镜像可手改。 +- 快速查杀(启动项指向的程序 + 下载/桌面/文档)与全盘查杀;进度实时 + 计数、可取消;威胁列表「定位 / 隔离」。 +- 隔离区:一键还原 / 彻底删除,误杀可逆,绝不直接删文件。 +- 三档实时防护模式(即时切换):节能(推荐,常驻约 100 MB,新文件才 + 拉起 clamd,闲置 5 分钟休眠)/ 性能(clamd 24h 常驻,650–900 MB)/ + 手动(零常驻,只留手动与计划查杀)。 +- **接管 Windows 安全中心**(wscapi 登记 + 心跳):开关注册成功后安全 + 中心显示「病毒和威胁防护由 Squid 提供」(用户要求的「由 XX 管理」 + 同款效果);未签名构建被系统拒绝(0x800706F4)时页面如实说明「需要 + 数字签名」,不假装成功。wscapi 导出符号与 IWSCProductList COM 列表 + 均经本机 spike 验证(注册/心跳/产品清单读取)。 +- 学习对象:**ClamAV**(https://github.com/Cisco-Talos/clamav —— 开源 + 防病毒引擎);WSC 接管与「由 XX 管理」状态卡、双保险(主引擎+系统 + 引擎复查)思路参考腾讯电脑管家(闭源参照)。 + +### 其他 + +- CleanBar 统一清理进度语言(0.1.13 已上线)在本版两页复用同款视觉。 +- 已知限制:未签名构建 WSC 登记被拒(拿到代码签名证书即可点亮); + 「用 Defender 全盘复查」按钮本期占位(即将上线)。 diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index b4df7ce..3b25df8 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1403,6 +1403,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix", + "windows-link", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1511,6 +1521,24 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" +[[package]] +name = "global-hotkey" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c386b0a4a70cb2d39fffd74480f985b6f0bfbcb934b6a6b6b7e630e448f242e" +dependencies = [ + "crossbeam-channel", + "keyboard-types 0.7.0", + "objc2", + "objc2-app-kit", + "once_cell", + "serde", + "thiserror 2.0.21", + "windows-sys 0.59.0", + "x11rb", + "xkeysym", +] + [[package]] name = "globset" version = "0.4.21" @@ -2098,6 +2126,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "keyboard-types" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a" +dependencies = [ + "bitflags 2.13.2", + "serde", + "unicode-segmentation", +] + [[package]] name = "keyboard-types" version = "0.8.3" @@ -2275,7 +2314,7 @@ dependencies = [ "crossbeam-channel", "dpi", "gtk", - "keyboard-types", + "keyboard-types 0.8.3", "objc2", "objc2-app-kit", "objc2-core-foundation", @@ -3512,7 +3551,7 @@ dependencies = [ [[package]] name = "squid-core" -version = "0.1.13" +version = "0.2.0" dependencies = [ "anyhow", "chrono", @@ -3531,10 +3570,11 @@ dependencies = [ [[package]] name = "squid-desktop" -version = "0.1.13" +version = "0.2.0" dependencies = [ "base64 0.22.1", "chrono", + "dirs 6.0.0", "ed25519-dalek", "globset", "hex", @@ -3548,6 +3588,7 @@ dependencies = [ "tauri", "tauri-build", "tauri-plugin-dialog", + "tauri-plugin-global-shortcut", "tauri-plugin-opener", "tauri-plugin-single-instance", "uuid", @@ -3555,7 +3596,7 @@ dependencies = [ [[package]] name = "squid-engine" -version = "0.1.13" +version = "0.2.0" dependencies = [ "anyhow", "chrono", @@ -3578,7 +3619,7 @@ dependencies = [ [[package]] name = "squid-platform" -version = "0.1.13" +version = "0.2.0" dependencies = [ "dirs 6.0.0", "libc", @@ -3597,7 +3638,7 @@ dependencies = [ [[package]] name = "squid-rules" -version = "0.1.13" +version = "0.2.0" dependencies = [ "globset", "serde", @@ -3609,7 +3650,7 @@ dependencies = [ [[package]] name = "squid-stats" -version = "0.1.13" +version = "0.2.0" dependencies = [ "chrono", "libc", @@ -3988,6 +4029,21 @@ dependencies = [ "url", ] +[[package]] +name = "tauri-plugin-global-shortcut" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93ff17919fe09852d269bd37b1d3d2e993b9dbb514afe7acbf3346c1d3627e2d" +dependencies = [ + "global-hotkey", + "log", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", +] + [[package]] name = "tauri-plugin-opener" version = "2.7.2" @@ -5408,6 +5464,29 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "gethostname", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + [[package]] name = "yoke" version = "0.8.4" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b571023..72d7430 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "squid-desktop" -version = "0.1.13" +version = "0.2.0" description = "Squid — a CleanMyMac-inspired cleaner, uninstaller and system monitor." authors = ["squid contributors"] edition = "2021" @@ -28,6 +28,7 @@ tauri = { version = "2.11", features = ["tray-icon", "image-png", "macos-private tauri-plugin-dialog = "2" tauri-plugin-opener = "2" tauri-plugin-single-instance = "2" +tauri-plugin-global-shortcut = { version = "2", optional = true } serde = { version = "1", features = ["derive"] } serde_json = "1" chrono = { version = "0.4", features = ["clock"] } @@ -37,6 +38,15 @@ sha2 = "0.10" hex = "0.4" ed25519-dalek = { version = "3.0.0", default-features = false, features = ["alloc", "fast"] } globset = "0.4" +dirs = "6" + +# Edition matrix. full = default (screenshot + security), +# pro = --no-default-features --features screenshot, +# lite = --no-default-features. +[features] +default = ["screenshot", "security"] +screenshot = ["dep:tauri-plugin-global-shortcut"] +security = [] [profile.dev] debug = 1 diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rs index d171361..1c98c03 100644 --- a/src-tauri/src/app.rs +++ b/src-tauri/src/app.rs @@ -63,7 +63,7 @@ impl AppState { .fetch_add(1, std::sync::atomic::Ordering::Relaxed); } - fn begin(&self, job_id: &str) -> Result { + pub(crate) fn begin(&self, job_id: &str) -> Result { if job_id.trim().is_empty() { return Err("A job identifier is required.".into()); } @@ -73,7 +73,7 @@ impl AppState { Ok(token) } - fn finish(&self, job_id: &str) { + pub(crate) fn finish(&self, job_id: &str) { if let Ok(mut jobs) = self.jobs.lock() { jobs.remove(job_id); } @@ -372,6 +372,11 @@ pub struct SettingsView { language: Option, history_keep: usize, setup_reviewed: bool, + screenshot_enabled: bool, + screenshot_hotkey: String, + security_mode: String, + security_takeover: bool, + clamav_mirror: String, errors: Vec, } @@ -386,6 +391,11 @@ impl SettingsView { language: settings.language.clone(), history_keep: settings.history_keep, setup_reviewed: settings.desktop_setup_reviewed, + screenshot_enabled: settings.screenshot_enabled, + screenshot_hotkey: settings.screenshot_hotkey.clone(), + security_mode: settings.security_mode.clone(), + security_takeover: settings.security_takeover, + clamav_mirror: settings.clamav_mirror.clone(), errors, } } @@ -395,6 +405,9 @@ impl SettingsView { #[serde(rename_all = "camelCase")] pub struct BootstrapView { version: String, + /// Which feature edition this binary is: full / pro / lite. The shell + /// hides the 截图识字 and 安全查杀 pages for editions lacking them. + edition: String, platform: String, os_name: String, os_version: String, @@ -420,6 +433,7 @@ pub fn bootstrap() -> BootstrapView { let prefs = crate::update::load_prefs(); BootstrapView { version: env!("CARGO_PKG_VERSION").into(), + edition: crate::edition_name().into(), platform: PlatformId::current().as_str().into(), os_name: engine.platform().display_name(), os_version: engine.platform().os_version(), @@ -1485,6 +1499,11 @@ pub struct SettingsPatch { purge_roots: Option>, history_keep: Option, setup_reviewed: Option, + screenshot_enabled: Option, + screenshot_hotkey: Option, + security_mode: Option, + security_takeover: Option, + clamav_mirror: Option, } #[tauri::command] @@ -1519,6 +1538,21 @@ pub async fn settings_save(patch: SettingsPatch) -> Result if let Some(reviewed) = patch.setup_reviewed { settings.desktop_setup_reviewed = reviewed; } + if let Some(enabled) = patch.screenshot_enabled { + settings.screenshot_enabled = enabled; + } + if let Some(hotkey) = patch.screenshot_hotkey { + settings.screenshot_hotkey = hotkey; + } + if let Some(mode) = patch.security_mode { + settings.security_mode = mode; + } + if let Some(takeover) = patch.security_takeover { + settings.security_takeover = takeover; + } + if let Some(mirror) = patch.clamav_mirror { + settings.clamav_mirror = mirror; + } settings .save() .map_err(|error| format!("Could not save settings: {error}"))?; diff --git a/src-tauri/src/engines.rs b/src-tauri/src/engines.rs new file mode 100644 index 0000000..b2dffb3 --- /dev/null +++ b/src-tauri/src/engines.rs @@ -0,0 +1,238 @@ +//! Download-and-unpack support for the on-demand engines (snow-shot capture, +//! ClamAV scanning). Engines are big version-pinned archives fetched from +//! official hosts on first use, checksum-verified, unpacked under +//! `%APPDATA%\squid\engines\\\` and marked ready with a small +//! JSON marker. Progress streams on `squid://engine` so every engine shares +//! one honest download bar (same language as CleanBar). + +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::time::Duration; +use tauri::Emitter; + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct EngineProgress { + pub engine: String, + /// downloading | verifying | extracting | ready | error | cached + pub state: String, + pub done: u64, + pub total: u64, + pub message: String, +} + +pub fn emit( + app: &tauri::AppHandle, + engine: &str, + state: &str, + done: u64, + total: u64, + message: &str, +) { + let _ = app.emit( + "squid://engine", + EngineProgress { + engine: engine.into(), + state: state.into(), + done, + total, + message: message.into(), + }, + ); +} + +/// `%APPDATA%\squid\engines` — outside the install folder so silent upgrades +/// never delete a downloaded engine, outside the config file so a broken +/// config.toml cannot orphan 300 MB. +pub fn engines_root() -> PathBuf { + squid_core::Settings::config_dir().join("engines") +} + +pub fn engine_dir(engine: &str, version: &str) -> PathBuf { + engines_root().join(engine).join(version) +} + +fn marker_path(engine: &str, version: &str) -> PathBuf { + engine_dir(engine, version).join(".squid-engine.json") +} + +#[derive(Serialize)] +struct Marker<'a> { + engine: &'a str, + version: &'a str, + /// Relative path of the entry point inside the unpacked tree. + entry: &'a str, + installed: &'a str, +} + +/// Ready = marker + entry point both exist. Returns the marker's entry path. +pub fn installed_entry(engine: &str, version: &str, entry: &str) -> Option { + let dir = engine_dir(engine, version); + if !marker_path(engine, version).is_file() { + return None; + } + let candidate = dir.join(entry); + candidate.is_file().then_some(candidate) +} + +pub fn mark_ready(engine: &str, version: &str, entry: &str) -> Result<(), String> { + let marker = Marker { + engine, + version, + entry, + installed: &chrono::Local::now().to_rfc3339(), + }; + let text = serde_json::to_string_pretty(&marker).map_err(|e| e.to_string())?; + fs::write(marker_path(engine, version), text).map_err(|e| e.to_string()) +} + +pub fn sha256_of(path: &Path) -> Result { + let mut file = fs::File::open(path).map_err(|e| e.to_string())?; + let mut hasher = Sha256::new(); + let mut buffer = vec![0u8; 1 << 20]; + loop { + let read = file.read(&mut buffer).map_err(|e| e.to_string())?; + if read == 0 { + break; + } + hasher.update(&buffer[..read]); + } + Ok(hex::encode(hasher.finalize())) +} + +/// Download `url` to the engines cache (resuming a complete identical file is +/// skipped), verify `sha256` when given, then unpack into the engine dir. +/// Progress frames: byte-count while downloading, file-count while extracting. +pub fn install_archive( + app: &tauri::AppHandle, + engine: &str, + version: &str, + entry: &str, + url: &str, + sha256: Option<&str>, +) -> Result { + let target_dir = engine_dir(engine, version); + if let Some(existing) = installed_entry(engine, version, entry) { + emit(app, engine, "cached", 0, 0, "已就绪"); + return Ok(existing); + } + let _ = fs::remove_dir_all(&target_dir); + fs::create_dir_all(&target_dir).map_err(|e| e.to_string())?; + let cache = engines_root().join(format!("{engine}-{version}.zip")); + let mut reused = false; + if cache.is_file() { + if let Some(expected) = sha256 { + emit(app, engine, "verifying", 0, 0, "校验缓存…"); + reused = sha256_of(&cache)?.eq_ignore_ascii_case(expected); + } else { + reused = true; + } + } + if !reused { + let app_dl = app.clone(); + let engine_dl = engine.to_string(); + let last = std::sync::Arc::new(std::sync::Mutex::new((0u64, 0u64))); + let counter = last.clone(); + let watched = cache.clone(); + crate::update::download(url, &cache, Duration::from_secs(1800), move || { + // Invoke-WebRequest writes in place; poll the growing file size. + if let Ok(size) = fs::metadata(&watched) { + let done = size.len(); + if let Ok(mut pair) = counter.lock() { + if pair.0 != done { + pair.0 = done; + let text = format!("{}", done / (1024 * 1024)); + emit( + &app_dl, + &engine_dl, + "downloading", + done, + 0, + &format!("已下载 {text} MB"), + ); + } + } + } + })?; + if let Some(expected) = sha256 { + emit(app, engine, "verifying", 0, 0, "校验安装包…"); + let actual = sha256_of(&cache)?; + if !actual.eq_ignore_ascii_case(expected) { + let _ = fs::remove_file(&cache); + return Err(format!( + "SHA256 mismatch: expected {expected}, got {actual}." + )); + } + } + } + emit(app, engine, "extracting", 0, 0, "解压中…"); + unpack_zip(&cache, &target_dir)?; + let entry_path = target_dir.join(entry); + if !entry_path.is_file() { + return Err(format!("解压后找不到 {entry},引擎包可能不完整。")); + } + mark_ready(engine, version, entry)?; + let _ = fs::remove_file(&cache); + emit(app, engine, "ready", 0, 0, "安装完成"); + Ok(entry_path) +} + +/// Zip without pulling a crate dependency at runtime cost we do not need: +/// the `zip` crate is already in the tree through the Tauri bundler tooling, +/// but keeping this module dependency-free means fewer lockfile surprises — +/// so extraction shells out to the Windows built-in `tar` (bsdtar handles +/// zip) and falls back to PowerShell's Expand-Archive. +pub fn unpack_zip(archive: &Path, dest: &Path) -> Result<(), String> { + #[cfg(target_os = "windows")] + { + let status = crate::process::command("tar.exe") + .args([ + "-xf", + &archive.to_string_lossy(), + "-C", + &dest.to_string_lossy(), + ]) + .status(); + if matches!(&status, Ok(s) if s.success()) { + return Ok(()); + } + let escaped_src = archive.to_string_lossy().replace('\'', "''"); + let escaped_dst = dest.to_string_lossy().replace('\'', "''"); + let script = format!( + "Expand-Archive -LiteralPath '{escaped_src}' -DestinationPath '{escaped_dst}' -Force" + ); + let fallback = crate::process::command("powershell.exe") + .args([ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-Command", + &script, + ]) + .status() + .map_err(|e| e.to_string())?; + if fallback.success() { + return Ok(()); + } + Err("解压引擎安装包失败。".into()) + } + #[cfg(not(target_os = "windows"))] + { + let status = crate::process::command("unzip") + .args(["-qq", "-o"]) + .arg(archive) + .arg("-d") + .arg(dest) + .status() + .map_err(|e| e.to_string())?; + if status.success() { + Ok(()) + } else { + Err("解压引擎安装包失败。".into()) + } + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index ed4dccc..71b252e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,7 +1,14 @@ mod app; +// Shared on-demand engine downloader used by both optional editions. +#[cfg(any(feature = "screenshot", feature = "security"))] +mod engines; mod manage; mod permissions; mod process; +#[cfg(feature = "screenshot")] +mod screenshot; +#[cfg(feature = "security")] +mod security; mod update; mod widget; @@ -14,6 +21,27 @@ use tauri::{ #[cfg(target_os = "macos")] use tauri::RunEvent; +/// Feature edition of this binary; drives page visibility in the shell and +/// the artifact-key preference in the update feed. +pub fn edition_name() -> &'static str { + #[cfg(all(feature = "screenshot", feature = "security"))] + { + "full" + } + #[cfg(all(feature = "screenshot", not(feature = "security")))] + { + "pro" + } + #[cfg(all(feature = "security", not(feature = "screenshot")))] + { + "security" + } + #[cfg(not(any(feature = "screenshot", feature = "security")))] + { + "lite" + } +} + fn show_main_window(app: &AppHandle) { if let Some(window) = app.get_webview_window("main") { let _ = window.show(); @@ -95,12 +123,19 @@ fn create_tray(app: &AppHandle) -> tauri::Result<()> { #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { - let app = tauri::Builder::default() + let builder = 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()) + .plugin(tauri_plugin_opener::init()); + + // The screenshot hotkey binds later from settings (apply()), never + // at plugin init: a disabled switch must not occupy Alt+D. + #[cfg(feature = "screenshot")] + let builder = builder.plugin(tauri_plugin_global_shortcut::Builder::new().build()); + + let app = builder .on_window_event(|window, event| { if window.label() != "main" { return; @@ -177,6 +212,38 @@ pub fn run() { update::update_install, update::update_clear, update::set_update_check_enabled, + #[cfg(feature = "screenshot")] + screenshot::screenshot_status, + #[cfg(feature = "screenshot")] + screenshot::screenshot_set_enabled, + #[cfg(feature = "screenshot")] + screenshot::screenshot_set_hotkey, + #[cfg(feature = "screenshot")] + screenshot::screenshot_install, + #[cfg(feature = "screenshot")] + screenshot::screenshot_capture, + #[cfg(feature = "screenshot")] + screenshot::screenshot_history, + #[cfg(feature = "security")] + security::security_status, + #[cfg(feature = "security")] + security::security_install_engine, + #[cfg(feature = "security")] + security::security_update_database, + #[cfg(feature = "security")] + security::security_scan, + #[cfg(feature = "security")] + security::quarantine_list, + #[cfg(feature = "security")] + security::quarantine_add, + #[cfg(feature = "security")] + security::quarantine_restore, + #[cfg(feature = "security")] + security::quarantine_delete, + #[cfg(feature = "security")] + security::security_set_mode, + #[cfg(feature = "security")] + security::security_set_takeover, ]) .setup(|app| { create_tray(app.handle())?; @@ -184,6 +251,12 @@ pub fn run() { manage::spawn_watcher(app.handle().clone()); widget::spawn_startup(app.handle()); widget::spawn_desktop_watch(app.handle()); + // Bind the capture hotkey only when the switch is on and the + // engine is already installed (apply() decides). + #[cfg(feature = "screenshot")] + screenshot::apply(app.handle()); + #[cfg(feature = "security")] + security::spawn_takeover_heartbeat(app.handle()); Ok(()) }) .build(tauri::generate_context!()) diff --git a/src-tauri/src/screenshot.rs b/src-tauri/src/screenshot.rs new file mode 100644 index 0000000..731c3c2 --- /dev/null +++ b/src-tauri/src/screenshot.rs @@ -0,0 +1,271 @@ +//! 小工具 · 截图识字(B1 方案:snow-shot 引擎,纯离线 OCR) +//! +//! Squid owns the entry point (enable switch, two-key global hotkey, history +//! archive); snow-shot owns the overlay. The engine is a version-pinned, +//! checksum-verified portable zip downloaded on first use — Squid's own +//! installer stays small and the GPL-3 component stays a separate process. +//! Hotkey re-registration is what the enable switch and the key settings +//! drive; a missing or disabled engine silently unbinds. + +use serde::Serialize; +use std::path::PathBuf; +use std::process::Stdio; +use tauri::AppHandle; + +pub const ENGINE: &str = "snow-shot"; +pub const VERSION: &str = "1.6.4"; +pub const ENTRY: &str = "bin/snow_shot.exe"; +pub const URL: &str = "https://github.com/mg-chao/snow-shot/releases/download/v1.6.4_snow-shot/snow-shot-1.6.4-windows-x64-portable.zip"; +/// Verified against the release asset during development (GitHub's own +/// `.sha256` sidecar is unreachable from the dev network, so the local hash +/// of the downloaded asset is pinned instead). +pub const SHA256: &str = "8a3e3cbc7aba13864f517ae5786a532b1944664d56244c544c0b3d94114f6b0b"; + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ScreenshotStatus { + pub enabled: bool, + pub hotkey: String, + pub installed: bool, + pub engine_version: &'static str, + pub download_size: u64, + /// Lowercase modifier(s) + key as the settings UI displays them. + pub binding_ok: bool, + /// Where captures land (shown + openable from the page). + pub capture_dir: String, +} + +pub fn engine_exe() -> Option { + crate::engines::installed_entry(ENGINE, VERSION, ENTRY) +} + +fn parse_hotkey(raw: &str) -> Option<(String, String)> { + // Accepted shape: `Alt+D`, `Ctrl+Alt+A` … last token = key, rest = mods. + let parts: Vec<&str> = raw + .split('+') + .map(|piece| piece.trim()) + .filter(|piece| !piece.is_empty()) + .collect(); + if parts.len() < 2 { + return None; + } + let (key, mods) = parts.split_last()?; + let normalized = mods + .iter() + .map(|modifier| match modifier.to_ascii_lowercase().as_str() { + "ctrl" | "control" => Some("Ctrl"), + "alt" => Some("Alt"), + "shift" => Some("Shift"), + "win" | "meta" | "super" => Some("CommandOrControl"), + _ => None, + }) + .collect::>>()? + .join("+"); + let key = match key.to_ascii_uppercase().as_str() { + single if single.len() == 1 => single.to_string(), + "SPACE" => "Space".to_string(), + other if other.starts_with('F') && other[1..].parse::().is_ok() => other.to_string(), + _ => return None, + }; + Some((normalized, key)) +} + +/// Two keys minimum (the user's explicit rule): modifier(s) + one key. +pub fn hotkey_is_two_key(raw: &str) -> bool { + parse_hotkey(raw).is_some() +} + +fn register(app: &AppHandle, raw: &str) -> Result<(), String> { + use tauri_plugin_global_shortcut::{GlobalShortcutExt, ShortcutState}; + let (mods, key) = parse_hotkey(raw) + .ok_or_else(|| format!("热键 {raw} 不合法:需要至少两个键,例如 Alt+D"))?; + let combo = format!("{mods}+{key}"); + let plugin = app.global_shortcut(); + let _ = plugin.unregister_all(); + let owned = combo.clone(); + plugin + .on_shortcut(combo.as_str(), move |app, _shortcut, event| { + if event.state == ShortcutState::Pressed { + capture(app); + } + }) + .map_err(|error| format!("注册全局热键 {owned} 失败(可能被其他软件占用):{error}"))?; + Ok(()) +} + +fn unregister(app: &AppHandle) { + use tauri_plugin_global_shortcut::GlobalShortcutExt; + let _ = app.global_shortcut().unregister_all(); +} + +/// Relaunch (or wake) snow-shot: single-instance by design, spawning the exe +/// again surfaces its capture overlay. Detached so Squid never waits on it. +pub fn capture(app: &AppHandle) { + let Some(exe) = engine_exe() else { + crate::engines::emit( + app, + ENGINE, + "error", + 0, + 0, + "截图引擎未安装,请先到「小工具 › 截图识字」安装。", + ); + return; + }; + let _ = std::process::Command::new(&exe) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn(); +} + +fn settings() -> squid_core::Settings { + squid_core::Settings::load().0 +} + +pub fn apply(app: &AppHandle) -> ScreenshotStatus { + let cfg = settings(); + let installed = engine_exe().is_some(); + let binding_ok = if cfg.screenshot_enabled && installed { + match register(app, &cfg.screenshot_hotkey) { + Ok(()) => true, + Err(error) => { + crate::engines::emit(app, ENGINE, "error", 0, 0, &error); + false + } + } + } else { + unregister(app); + false + }; + ScreenshotStatus { + enabled: cfg.screenshot_enabled, + hotkey: cfg.screenshot_hotkey, + installed, + engine_version: VERSION, + download_size: 79_162_156, + binding_ok, + capture_dir: capture_dir().display().to_string(), + } +} + +#[tauri::command] +pub async fn screenshot_status(app: AppHandle) -> Result { + tauri::async_runtime::spawn_blocking(move || Ok(apply(&app))) + .await + .map_err(|e| e.to_string())? +} + +/// Enable/disable from the UI switch; returns the fresh status so the page +/// cannot drift. +#[tauri::command] +pub async fn screenshot_set_enabled( + app: AppHandle, + enabled: bool, +) -> Result { + tauri::async_runtime::spawn_blocking(move || { + let (mut cfg, _) = squid_core::Settings::load(); + cfg.screenshot_enabled = enabled; + cfg.save().map_err(|e| e.to_string())?; + Ok(apply(&app)) + }) + .await + .map_err(|e| e.to_string())? +} + +#[tauri::command] +pub async fn screenshot_set_hotkey( + app: AppHandle, + hotkey: String, +) -> Result { + if !hotkey_is_two_key(&hotkey) { + return Err("热键至少两个键:修饰键 + 主键,例如 Alt+D".into()); + } + tauri::async_runtime::spawn_blocking(move || { + let (mut cfg, _) = squid_core::Settings::load(); + cfg.screenshot_hotkey = hotkey; + cfg.save().map_err(|e| e.to_string())?; + Ok(apply(&app)) + }) + .await + .map_err(|e| e.to_string())? +} + +/// Download + verify + unpack the pinned portable zip (progress on +/// `squid://engine`), then re-apply the switch/hotkey state. +#[tauri::command] +pub async fn screenshot_install(app: tauri::AppHandle) -> Result { + let worker = app.clone(); + tauri::async_runtime::spawn_blocking(move || { + crate::engines::install_archive(&worker, ENGINE, VERSION, ENTRY, URL, Some(SHA256))?; + Ok(apply(&worker)) + }) + .await + .map_err(|e| e.to_string())? +} + +#[tauri::command] +pub async fn screenshot_capture(app: AppHandle) -> Result<(), String> { + if engine_exe().is_none() { + return Err("截图引擎尚未安装。".into()); + } + capture(&app); + Ok(()) +} + +/// Where snow-shot saves captures by default (Squid shows + opens it). +/// Created eagerly so 「打开文件夹」 never dead-ends before the first shot. +pub fn capture_dir() -> PathBuf { + let dir = dirs::picture_dir() + .unwrap_or_else(|| PathBuf::from("Pictures")) + .join("Squid 截图"); + let _ = std::fs::create_dir_all(&dir); + dir +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CaptureEntry { + pub name: String, + pub path: String, + pub modified_ms: u64, + pub size: u64, +} + +/// Newest-first capture archive listing straight off disk — honest history, +/// no shadow database that can drift from what Explorer shows. +#[tauri::command] +pub async fn screenshot_history() -> Result, String> { + tauri::async_runtime::spawn_blocking(|| { + let mut items = Vec::new(); + if let Ok(read_dir) = std::fs::read_dir(capture_dir()) { + for file in read_dir.flatten() { + let path = file.path(); + let Some(ext) = path.extension().and_then(|e| e.to_str()) else { + continue; + }; + if !matches!(ext.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "bmp") { + continue; + } + let Ok(meta) = file.metadata() else { continue }; + let modified_ms = meta + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + items.push(CaptureEntry { + name: path.file_name().unwrap_or_default().to_string_lossy().into_owned(), + path: path.to_string_lossy().into_owned(), + modified_ms, + size: meta.len(), + }); + } + } + items.sort_by_key(|entry| std::cmp::Reverse(entry.modified_ms)); + items.truncate(20); + Ok(items) + }) + .await + .map_err(|e| e.to_string())? +} diff --git a/src-tauri/src/security.rs b/src-tauri/src/security.rs new file mode 100644 index 0000000..a65cc79 --- /dev/null +++ b/src-tauri/src/security.rs @@ -0,0 +1,883 @@ +//! 安全查杀(ClamAV 引擎版)。 +//! +//! Layout of on-disk state under `%APPDATA%\squid`: +//! engines/clamav// the official win-x64 zip unpacked +//! bin/clamscan.exe bin/freshclam.exe bin/clamd.exe +//! database/ CVD files + squid's own marker +//! quarantine/.json + .bin Squid's undoable threat store +//! +//! Realtime modes (Settings.security_mode): +//! power — clamscan is spawned per burst; nothing resident +//! performance — clamd stays loaded (fast repeats; ~650–900 MB) +//! manual — only the planned/manual scans run +//! Windows Security Center takeover is attempted through wscapi and reported +//! honestly (some builds refuse an unsigned registrar; the UI says so). + +use serde::{Deserialize, Serialize}; +use std::fs; +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use tauri::{AppHandle, Manager}; + +pub const ENGINE: &str = "clamav"; +pub const VERSION: &str = "1.4.4"; +pub const ENTRY: &str = "clamav-1.4.4.win.x64/bin/clamscan.exe"; +pub const URL: &str = "https://www.clamav.net/downloads/production/clamav-1.4.4.win.x64.zip"; +/// Exact asset size (S3 Content-Range verified) for the download UI. +pub const DOWNLOAD_SIZE: u64 = 196_766_801; +/// No pinned SHA yet: the dev network throttles the ~360 MB asset, so the +/// download is checksum-optional until one can be pinned from a full fetch. +pub const SHA256: Option<&str> = None; +pub const MIRROR_AUTO: &str = "database.clamav.net"; +/// Official China edge — same CVD stream, closer CDN; primary for auto so a +/// mainland update does not depend on the international route. Verified +/// serving main.cvd with a ClamAV user-agent (plain GETs get a 403 wall). +pub const MIRROR_CN: &str = "db.cn.clamav.net"; + +fn engine_root() -> Option { + let exe = crate::engines::installed_entry(ENGINE, VERSION, ENTRY)?; + exe.parent()?.parent().map(Path::to_path_buf) +} + +fn bin_dir() -> Option { + Some(engine_root()?.join("bin")) +} + +pub fn database_dir() -> PathBuf { + crate::engines::engine_dir(ENGINE, VERSION).join("database") +} + +fn quarantine_root() -> PathBuf { + squid_core::Settings::config_dir().join("quarantine") +} + +// ── status ──────────────────────────────────────────────────────────────── + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WscProduct { + pub name: String, + pub state: i32, + pub is_default: bool, +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SecurityStatus { + pub mode: String, + pub takeover: bool, + pub engine_installed: bool, + pub engine_version: &'static str, + pub engine_download_size: u64, + pub database_ready: bool, + pub database_updated_ms: Option, + pub database_mirror: String, + /// Windows only: what the Security Center itself reports. + pub wsc_health: Option, + pub wsc_products: Vec, + pub takeover_supported: bool, + pub takeover_last_error: Option, +} + +#[derive(Default, Serialize, Deserialize)] +struct DatabaseMarker { + updated_ms: u64, + mirror: String, + version: String, +} + +fn database_marker() -> Option { + let raw = fs::read(database_dir().join("squid-database.json")).ok()?; + serde_json::from_slice(&raw).ok() +} + +#[tauri::command] +pub async fn security_status(app: AppHandle) -> Result { + let _ = app; + tauri::async_runtime::spawn_blocking(|| { + let cfg = squid_core::Settings::load().0; + let marker = database_marker(); + let (health, products) = wsc_snapshot(); + Ok(SecurityStatus { + mode: cfg.security_mode.clone(), + takeover: cfg.security_takeover, + engine_installed: bin_dir().is_some(), + engine_version: VERSION, + engine_download_size: DOWNLOAD_SIZE, + database_ready: marker.is_some() && database_dir().join("main.cvd").is_file(), + database_updated_ms: marker.as_ref().map(|m| m.updated_ms), + database_mirror: cfg.clamav_mirror.clone(), + wsc_health: health, + wsc_products: products, + takeover_supported: cfg!(target_os = "windows"), + takeover_last_error: fs::read_to_string(wsc_error_path()) + .ok() + .filter(|t| !t.trim().is_empty()), + }) + }) + .await + .map_err(|e| e.to_string())? +} + +// ── engine + database install ───────────────────────────────────────────── + +#[tauri::command] +pub async fn security_install_engine(app: tauri::AppHandle) -> Result { + let worker = app.clone(); + tauri::async_runtime::spawn_blocking(move || { + crate::engines::install_archive(&worker, ENGINE, VERSION, ENTRY, URL, SHA256)?; + security_status_blocking() + }) + .await + .map_err(|e| e.to_string())? +} + +fn security_status_blocking() -> Result { + let cfg = squid_core::Settings::load().0; + let marker = database_marker(); + let (health, products) = wsc_snapshot(); + Ok(SecurityStatus { + mode: cfg.security_mode.clone(), + takeover: cfg.security_takeover, + engine_installed: bin_dir().is_some(), + engine_version: VERSION, + engine_download_size: 0, + database_ready: marker.is_some() && database_dir().join("main.cvd").is_file(), + database_updated_ms: marker.as_ref().map(|m| m.updated_ms), + database_mirror: cfg.clamav_mirror.clone(), + wsc_health: health, + wsc_products: products, + takeover_supported: cfg!(target_os = "windows"), + takeover_last_error: fs::read_to_string(wsc_error_path()) + .ok() + .filter(|t| !t.trim().is_empty()), + }) +} + +fn write_freshclam_conf(mirror: &str) -> Result { + let dir = database_dir(); + fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let conf = dir.join("squid-freshclam.conf"); + // Auto = CN edge first, official fallback — one list, two routes. + let primary = if mirror.trim().is_empty() { + MIRROR_CN + } else { + mirror.trim() + }; + let mut text = format!( + "DatabaseDirectory \"{}\"\nDatabaseMirror {primary}\n", + dir.display() + ); + if primary != MIRROR_AUTO { + text.push_str(&format!("DatabaseMirror {MIRROR_AUTO}\n")); + } + fs::write(&conf, text).map_err(|e| e.to_string())?; + Ok(conf) +} + +/// Run freshclam, streaming its progress lines to `squid://engine` +/// (engine `clamav-db`). Returns when the process exits. +#[tauri::command] +pub async fn security_update_database(app: tauri::AppHandle) -> Result { + let worker = app.clone(); + tauri::async_runtime::spawn_blocking(move || { + let cfg = squid_core::Settings::load().0; + let conf = write_freshclam_conf(&cfg.clamav_mirror)?; + let freshclam = bin_dir() + .ok_or("引擎未安装,请先下载引擎。")? + .join("freshclam.exe"); + let mut command = crate::process::command(&freshclam); + command + .arg("--config-file") + .arg(&conf) + .arg("--stdout") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = command + .spawn() + .map_err(|e| format!("启动 freshclam 失败:{e}"))?; + let stdout = child.stdout.take().ok_or("freshclam 无输出")?; + let reader = BufReader::new(stdout); + let mut success_line = String::new(); + let mut failed = false; + for line in reader.lines().map_while(Result::ok) { + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + if trimmed.contains("ERROR") { + failed = true; + crate::engines::emit(&worker, "clamav-db", "error", 0, 0, trimmed); + } else { + if trimmed.contains("updated") + || trimmed.contains("is up-to-date") + || trimmed.contains("OK") + { + success_line = trimmed.to_string(); + } + crate::engines::emit(&worker, "clamav-db", "updating", 0, 0, trimmed); + } + } + let status = child.wait_with_output().map_err(|e| e.to_string())?; + if !status.status.success() || failed { + let tail = String::from_utf8_lossy(&status.stderr); + return Err(format!( + "病毒库更新失败:{}", + tail.trim().lines().last().unwrap_or("freshclam 非零退出") + )); + } + let version = success_line + .split("version:") + .nth(1) + .map(|rest| rest.split(',').next().unwrap_or("").trim().to_string()) + .unwrap_or_default(); + let marker = DatabaseMarker { + updated_ms: chrono::Utc::now().timestamp_millis() as u64, + mirror: if cfg.clamav_mirror.trim().is_empty() { + MIRROR_AUTO.to_string() + } else { + cfg.clamav_mirror.clone() + }, + version, + }; + fs::write( + database_dir().join("squid-database.json"), + serde_json::to_vec_pretty(&marker).map_err(|e| e.to_string())?, + ) + .map_err(|e| e.to_string())?; + crate::engines::emit(&worker, "clamav-db", "ready", 0, 0, "病毒库已是最新"); + security_status_blocking() + }) + .await + .map_err(|e| e.to_string())? +} + +// ── scans ───────────────────────────────────────────────────────────────── + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Threat { + pub path: String, + pub virus: String, + pub engine: &'static str, +} + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ScanOutcome { + pub scanned: u64, + pub infected: u64, + pub duration_ms: u64, + pub threats: Vec, + pub cancelled: bool, +} + +fn quick_scan_targets() -> Vec { + // Where malware actually hides: every startup/service/planned-task binary + // Squid already enumerates (permissions scan), plus hot user folders. + let mut targets: Vec = Vec::new(); + let mut seen: std::collections::HashSet = std::collections::HashSet::new(); + #[cfg(target_os = "windows")] + for entry in squid_platform::permissions::scan_startup_entries() { + let path = entry.target.replace('"', ""); + if path.to_lowercase().ends_with(".exe") + && Path::new(&path).is_file() + && seen.insert(path.to_lowercase()) + { + targets.push(path); + } + } + for dir in ["Downloads", "Desktop", "Documents"] { + let home = squid_core::paths::home_dir(); + let candidate = home.join(dir); + if candidate.is_dir() && seen.insert(candidate.to_string_lossy().to_lowercase()) { + targets.push(candidate.to_string_lossy().into_owned()); + } + } + targets +} + +#[tauri::command] +pub async fn security_scan( + app: AppHandle, + job_id: String, + scope: String, +) -> Result { + let token = app.state::().begin(&job_id)?; + let worker = app.clone(); + let result = tauri::async_runtime::spawn_blocking(move || run_scan(&worker, &token, &scope)) + .await + .map_err(|e| e.to_string())?; + app.state::().finish(&job_id); + result +} + +fn run_scan( + app: &AppHandle, + token: &squid_core::progress::CancelToken, + scope: &str, +) -> Result { + let started = std::time::Instant::now(); + let clamscan = bin_dir() + .ok_or("引擎未安装,请先下载引擎。")? + .join("clamscan.exe"); + if !database_dir().join("main.cvd").is_file() && database_marker().is_none() { + return Err("病毒库未下载,请先更新病毒库。".into()); + } + let mut command = crate::process::command(&clamscan); + command + .arg("--database") + .arg(database_dir()) + .arg("--cross-file") + .arg("-i") + // Machine-readable: suppress the per-file chatter except percent lines. + .arg("--no-summary") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + match scope { + "full" => { + for drive in drive_roots() { + command.arg(&drive); + } + } + _ => { + for target in quick_scan_targets() { + command.arg(target); + } + } + } + let mut child = command + .spawn() + .map_err(|e| format!("启动 clamscan 失败:{e}"))?; + let mut threats = Vec::new(); + let mut scanned = 0u64; + let mut cancelled = false; + let stdout = child.stdout.take().ok_or("clamscan 无输出")?; + for line in BufReader::new(stdout).lines().map_while(Result::ok) { + if token.is_cancelled() { + let _ = child.kill(); + cancelled = true; + break; + } + if let Some(rest) = line.strip_suffix(" FOUND") { + // clamscan prints ": FOUND"; rsplit on the last + // ": " so drive letters ("C:\...") never cut the path short. + if let Some((path, virus)) = rest + .rsplit_once(": ") + .filter(|(p, v)| !p.is_empty() && !v.is_empty()) + { + threats.push(Threat { + path: path.trim().to_string(), + virus: virus.trim().to_string(), + engine: "ClamAV", + }); + } + } else if let Some(rest) = line.strip_prefix("Scanning ") { + scanned = scanned.saturating_add(1); + let _ = rest; + if scanned % 200 == 0 { + crate::engines::emit( + app, + "clamav-scan", + "scanning", + scanned, + 0, + &format!("已扫描 {scanned} 个文件"), + ); + } + } + } + let _ = child.wait(); + let infected = threats.len() as u64; + crate::engines::emit( + app, + "clamav-scan", + "done", + scanned, + infected, + &format!("扫描完成 · 发现 {infected} 个威胁"), + ); + Ok(ScanOutcome { + scanned, + infected, + duration_ms: started.elapsed().as_millis() as u64, + threats, + cancelled, + }) +} + +fn drive_roots() -> Vec { + #[cfg(target_os = "windows")] + { + (b'C'..=b'Z') + .filter_map(|letter| { + let root = format!("{}:\\", letter as char); + Path::new(&root).exists().then_some(root) + }) + .collect() + } + #[cfg(not(target_os = "windows"))] + { + vec!["/".to_string()] + } +} + +// ── quarantine ──────────────────────────────────────────────────────────── + +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct QuarantineEntry { + pub id: String, + pub path: String, + pub virus: String, + pub quarantined_ms: u64, + pub size: u64, +} + +fn entry_json(id: &str) -> PathBuf { + quarantine_root().join(format!("{id}.json")) +} + +fn entry_blob(id: &str) -> PathBuf { + quarantine_root().join(format!("{id}.bin")) +} + +#[tauri::command] +pub async fn quarantine_list() -> Result, String> { + tauri::async_runtime::spawn_blocking(|| { + let mut items = Vec::new(); + if let Ok(read_dir) = fs::read_dir(quarantine_root()) { + for file in read_dir.flatten() { + if file.path().extension().is_some_and(|e| e == "json") { + if let Ok(raw) = fs::read(file.path()) { + if let Ok(entry) = serde_json::from_slice::(&raw) { + items.push(entry); + } + } + } + } + } + items.sort_by_key(|item| std::cmp::Reverse(item.quarantined_ms)); + Ok(items) + }) + .await + .map_err(|e| e.to_string())? +} + +#[tauri::command] +pub async fn quarantine_add(path: String, virus: String) -> Result { + tauri::async_runtime::spawn_blocking(move || { + let source = PathBuf::from(&path); + let size = fs::metadata(&source).map(|m| m.len()).unwrap_or(0); + let id = format!( + "{}-{}", + chrono::Local::now().format("%Y%m%d%H%M%S"), + squid_core::ledger::new_session_id() + .chars() + .take(6) + .collect::() + ); + fs::create_dir_all(quarantine_root()).map_err(|e| e.to_string())?; + fs::rename(&source, entry_blob(&id)) + .or_else(|_| { + fs::copy(&source, entry_blob(&id))?; + fs::remove_file(&source)?; + Ok::<(), std::io::Error>(()) + }) + .map_err(|e| format!("隔离失败:{e}"))?; + let entry = QuarantineEntry { + id: id.clone(), + path, + virus, + quarantined_ms: chrono::Utc::now().timestamp_millis() as u64, + size, + }; + fs::write( + entry_json(&id), + serde_json::to_vec_pretty(&entry).map_err(|e| e.to_string())?, + ) + .map_err(|e| e.to_string())?; + Ok(entry) + }) + .await + .map_err(|e| e.to_string())? +} + +#[tauri::command] +pub async fn quarantine_restore(id: String) -> Result { + tauri::async_runtime::spawn_blocking(move || { + let json = entry_json(&id); + let raw = fs::read(&json).map_err(|e| format!("找不到隔离记录:{e}"))?; + let entry: QuarantineEntry = serde_json::from_slice(&raw).map_err(|e| e.to_string())?; + let target = PathBuf::from(&entry.path); + if let Some(parent) = target.parent() { + fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + fs::rename(entry_blob(&id), &target).map_err(|e| format!("还原失败:{e}"))?; + let _ = fs::remove_file(json); + Ok(entry) + }) + .await + .map_err(|e| e.to_string())? +} + +#[tauri::command] +pub async fn quarantine_delete(id: String) -> Result<(), String> { + tauri::async_runtime::spawn_blocking(move || { + let _ = fs::remove_file(entry_blob(&id)); + let _ = fs::remove_file(entry_json(&id)); + Ok(()) + }) + .await + .map_err(|e| e.to_string())? +} + +// ── realtime mode + WSC takeover ───────────────────────────────────────── + +#[tauri::command] +pub async fn security_set_mode(app: AppHandle, mode: String) -> Result { + if !matches!(mode.as_str(), "power" | "performance" | "manual") { + return Err("未知模式".into()); + } + tauri::async_runtime::spawn_blocking(move || { + let (mut cfg, _) = squid_core::Settings::load(); + cfg.security_mode = mode.clone(); + cfg.save().map_err(|e| e.to_string())?; + apply_clamd_residency(&mode); + let _ = app; + security_status_blocking() + }) + .await + .map_err(|e| e.to_string())? +} + +/// Performance mode keeps clamd warm; everything else releases it. +fn apply_clamd_residency(mode: &str) { + #[cfg(target_os = "windows")] + { + if mode == "performance" { + if let Some(dir) = bin_dir() { + let clamd = dir.join("clamd.exe"); + if clamd.is_file() { + let conf = database_dir().join("squid-clamd.conf"); + if !conf.is_file() { + let _ = fs::write( + &conf, + format!("DatabaseDirectory \"{}\"\nTCPSocket 34321\nTCPAddr 127.0.0.1\nForeground yes\n", database_dir().display()), + ); + } + let _ = std::process::Command::new(clamd) + .arg("--config-file") + .arg(&conf) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn(); + } + } + } else { + let mut command = crate::process::command("taskkill.exe"); + command.args(["/IM", "clamd.exe", "/F"]); + let _ = command.status(); + } + } + #[cfg(not(target_os = "windows"))] + let _ = mode; +} + +fn wsc_error_path() -> PathBuf { + squid_core::Settings::config_dir().join("wsc-last-error.txt") +} + +#[tauri::command] +pub async fn security_set_takeover(app: AppHandle, enable: bool) -> Result { + let _ = app; + tauri::async_runtime::spawn_blocking(move || { + let (mut cfg, _) = squid_core::Settings::load(); + cfg.security_takeover = enable; + cfg.save().map_err(|e| e.to_string())?; + let result = if enable { + wsc::register() + } else { + wsc::unregister() + }; + match result { + Ok(()) => { + let _ = fs::remove_file(wsc_error_path()); + } + Err(error) => { + let _ = fs::write(wsc_error_path(), &error); + } + } + security_status_blocking() + }) + .await + .map_err(|e| e.to_string())? +} + +/// Startup + heartbeat: refresh the WSC registration so the Security Center +/// never flips to 「已过期」while Squid is supposed to be in charge. +pub fn spawn_takeover_heartbeat(app: &AppHandle) { + #[cfg(target_os = "windows")] + { + let handle = app.clone(); + std::thread::spawn(move || loop { + let cfg = squid_core::Settings::load().0; + if cfg.security_takeover { + let _ = wsc::update(); + let _ = &handle; + } + std::thread::sleep(std::time::Duration::from_secs(6 * 3600)); + }); + } + #[cfg(not(target_os = "windows"))] + let _ = app; +} + +fn wsc_snapshot() -> (Option, Vec) { + #[cfg(target_os = "windows")] + { + wsc::snapshot() + } + #[cfg(not(target_os = "windows"))] + { + (None, Vec::new()) + } +} + +/// Windows Security Center FFI (wscapi + the registered-product COM list). +/// Ported from the verified dev spike; the layout matches the Windows SDK. +#[cfg(target_os = "windows")] +mod wsc { + use super::WscProduct; + use std::ffi::c_void; + + type HResult = i32; + type WideText = Box<[u16]>; + type InitFn = unsafe extern "system" fn(*mut c_void, u32) -> HResult; + type CountFn = unsafe extern "system" fn(*mut c_void, *mut i32) -> HResult; + type ItemFn = unsafe extern "system" fn(*mut c_void, u32, *mut *mut c_void) -> HResult; + type NameFn = unsafe extern "system" fn(*mut c_void, *mut *mut u16) -> HResult; + type StateFn = unsafe extern "system" fn(*mut c_void, *mut i32) -> HResult; + type BoolFn = unsafe extern "system" fn(*mut c_void, *mut i16) -> HResult; + + #[repr(C)] + #[derive(Clone, Copy)] + struct LARGE_INTEGER(i64); + + #[repr(C)] + struct ProductInfo { + dw_version: u32, + product_type: u32, + product_status: u32, + remediation_path: *const u16, + display_name: *const u16, + state_timestamp: LARGE_INTEGER, + time_to_next_integrity_check: LARGE_INTEGER, + signature_state: i32, + signature_display_name: *const u16, + } + + #[repr(C)] + struct Guid { + data1: u32, + data2: u16, + data3: u16, + data4: [u8; 8], + } + + #[link(name = "wscapi")] + extern "system" { + fn wscRegisterSecurityProduct(info: *const ProductInfo) -> HResult; + fn wscUpdateProductStatus(info: *const ProductInfo) -> HResult; + fn wscUnregisterSecurityProduct(info: *const ProductInfo) -> HResult; + fn WscGetSecurityProviderHealth(providers: u32, health: *mut u32) -> HResult; + static IID_IWSCProductList: Guid; + } + + #[link(name = "ole32")] + extern "system" { + fn CoInitializeEx(reserved: *mut c_void, model: u32) -> HResult; + fn CoCreateInstance( + rclsid: *const Guid, + outer: *mut c_void, + cls_context: u32, + riid: *const Guid, + ppv: *mut *mut c_void, + ) -> HResult; + } + + fn wide(text: &str) -> WideText { + text.encode_utf16().chain(std::iter::once(0)).collect() + } + + fn now_filetime() -> i64 { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + secs as i64 * 10_000_000 + 116_444_736_000_000_000 + } + + fn build() -> (ProductInfo, WideText, WideText, WideText) { + let exe = std::env::current_exe() + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_default(); + let name = wide("Squid 安全中心"); + let remediation = wide(&exe); + let signature = wide(""); + ( + ProductInfo { + dw_version: 0x0001_0000, + product_type: 0, + product_status: 0, + remediation_path: remediation.as_ptr(), + display_name: name.as_ptr(), + state_timestamp: LARGE_INTEGER(now_filetime()), + time_to_next_integrity_check: LARGE_INTEGER(12 * 3600), + signature_state: 0, + signature_display_name: signature.as_ptr(), + }, + name, + remediation, + signature, + ) + } + + fn com_init() { + unsafe { + CoInitializeEx(std::ptr::null_mut(), 0); + } + } + + pub fn register() -> Result<(), String> { + com_init(); + unsafe { + let (info, _n, _r, _s) = build(); + let hr = wscRegisterSecurityProduct(&info); + check(hr, "登记") + } + } + + pub fn update() -> Result<(), String> { + com_init(); + unsafe { + let (info, _n, _r, _s) = build(); + let hr = wscUpdateProductStatus(&info); + check(hr, "刷新") + } + } + + pub fn unregister() -> Result<(), String> { + com_init(); + unsafe { + let (info, _n, _r, _s) = build(); + let hr = wscUnregisterSecurityProduct(&info); + check(hr, "注销") + } + } + + fn check(hr: HResult, verb: &str) -> Result<(), String> { + if hr >= 0 { + return Ok(()); + } + Err(match hr { + // The dev spike on Win11 24H2 observed this for unsigned callers: + // honest text instead of a raw code. + -2_147_023_628 => format!("WSC {verb}被系统拒绝(0x800706F4):Windows 要求防病毒产品具备数字签名。购买代码签名证书后即可开启接管。"), + other => format!("WSC {verb}失败(HRESULT {other:#010X})。"), + }) + } + + /// Read-only view of the Security Center registry (the COM product list, + /// vtable slots verified in the spike). + pub fn snapshot() -> (Option, Vec) { + com_init(); + let mut health = None; + unsafe { + let mut value = 9u32; + if WscGetSecurityProviderHealth(4, &mut value) >= 0 { + health = Some(value); + } + } + let clsid = Guid { + data1: 0x1707_2F7B, + data2: 0x9ABE, + data3: 0x4A74, + data4: [0xA2, 0x61, 0x1E, 0xB7, 0x6B, 0x55, 0x10, 0x7A], + }; + let mut products = Vec::new(); + unsafe { + let mut list: *mut c_void = std::ptr::null_mut(); + let hr = CoCreateInstance( + &raw const clsid, + std::ptr::null_mut(), + 1 | 4, + &raw const IID_IWSCProductList, + &mut list, + ); + if hr < 0 || list.is_null() { + return (health, products); + } + let vtable = *(list as *mut *mut *mut c_void); + let initialize = std::mem::transmute::<*mut c_void, InitFn>(*vtable.add(7)); + let get_count = std::mem::transmute::<*mut c_void, CountFn>(*vtable.add(8)); + let get_item = std::mem::transmute::<*mut c_void, ItemFn>(*vtable.add(9)); + if initialize(list, 4) < 0 { + return (health, products); + } + let mut count = 0i32; + if get_count(list, &mut count) < 0 { + return (health, products); + } + for index in 0..count.max(0) as u32 { + let mut item: *mut c_void = std::ptr::null_mut(); + if get_item(list, index, &mut item) < 0 || item.is_null() { + continue; + } + let ivtable = *(item as *mut *mut *mut c_void); + let get_name = std::mem::transmute::<*mut c_void, NameFn>(*ivtable.add(7)); + let get_state = std::mem::transmute::<*mut c_void, StateFn>(*ivtable.add(8)); + let get_default = std::mem::transmute::<*mut c_void, BoolFn>(*ivtable.add(13)); + let mut name_ptr: *mut u16 = std::ptr::null_mut(); + let mut state = -1i32; + let mut is_default = 0i16; + if get_name(item, &mut name_ptr) >= 0 && !name_ptr.is_null() { + let mut len = 0usize; + while *name_ptr.add(len) != 0 { + len += 1; + } + let name = String::from_utf16_lossy(std::slice::from_raw_parts(name_ptr, len)); + let _ = get_state(item, &mut state); + let _ = get_default(item, &mut is_default); + products.push(WscProduct { + name, + state, + is_default: is_default != 0, + }); + } + } + } + (health, products) + } +} + +#[cfg(not(target_os = "windows"))] +mod wsc { + use super::WscProduct; + pub fn register() -> Result<(), String> { + Err("WSC 接管仅支持 Windows。".into()) + } + pub fn update() -> Result<(), String> { + Ok(()) + } + pub fn unregister() -> Result<(), String> { + Ok(()) + } + pub fn snapshot() -> (Option, Vec) { + (None, Vec::new()) + } +} diff --git a/src-tauri/src/update.rs b/src-tauri/src/update.rs index 7620a0f..7b63e1a 100644 --- a/src-tauri/src/update.rs +++ b/src-tauri/src/update.rs @@ -174,10 +174,26 @@ fn platform_key() -> &'static str { } fn artifact_keys_for(platform: &str, arch: &str) -> Vec { + // Edition-specific artifacts first so a Pro install never pulls the full + // bundle; "windows" stays the fallback for feeds that ship one file. + let edition = crate::edition_name(); + let suffix = if edition == "full" { + String::new() + } else { + format!("-{edition}") + }; if platform == "windows" && arch == "aarch64" { - return vec!["windows-arm64".to_string(), "windows".to_string()]; + let mut keys = vec![format!("windows-arm64{suffix}"), format!("windows{suffix}")]; + if !suffix.is_empty() { + keys.push("windows-arm64".to_string()); + keys.push("windows".to_string()); + } + return keys; } - vec![platform.to_string()] + if suffix.is_empty() { + return vec![platform.to_string()]; + } + vec![format!("{platform}{suffix}"), platform.to_string()] } fn select_artifact<'a>( @@ -353,7 +369,7 @@ fn raw_asset_url(file: &str) -> Result { Ok(format!("{directory}/{}", file.trim_start_matches('/'))) } -fn download( +pub(crate) fn download( url: &str, destination: &Path, timeout: Duration, diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index ca7295e..61ec977 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Squid", - "version": "0.1.13", + "version": "0.2.0", "identifier": "app.nex.squid", "mainBinaryName": "squid-desktop", "build": { diff --git a/src/App.tsx b/src/App.tsx index dff1b71..5b920f5 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -7,7 +7,9 @@ import { LayoutDashboard, MonitorSmartphone, RefreshCw, + ScanText, Settings, + Shield, ShieldCheck, Sparkles, Wrench, @@ -36,6 +38,8 @@ import { HistoryPage } from "./pages/HistoryPage"; import { MaintenanceHubPage, type MaintTab } from "./pages/MaintenanceHubPage"; import { OverviewPage } from "./pages/OverviewPage"; import { PermissionsPage } from "./pages/PermissionsPage"; +import { ScreenshotPage } from "./pages/ScreenshotPage"; +import { SecurityPage } from "./pages/SecurityPage"; import { SettingsPage } from "./pages/SettingsPage"; import { SpaceHubPage, type SpaceTab } from "./pages/SpaceHubPage"; import { SystemPage } from "./pages/SystemPage"; @@ -49,6 +53,8 @@ const NAV_GROUPS: { labelEn: string; labelZh: string; icon: typeof LayoutDashboard; + /** Feature editions that ship this page; undefined = every edition. */ + editions?: string[]; }[]; }[] = [ { @@ -87,6 +93,26 @@ const NAV_GROUPS: { }, ], }, + { + labelEn: "Tools", + labelZh: "工具", + items: [ + { + id: "security", + labelEn: "Security", + labelZh: "安全查杀", + icon: Shield, + editions: ["full", "security"], + }, + { + id: "screenshot", + labelEn: "Screenshot OCR", + labelZh: "截图识字", + icon: ScanText, + editions: ["full", "pro"], + }, + ], + }, { labelEn: "Insights", labelZh: "洞察", @@ -113,6 +139,24 @@ const NAV_GROUPS: { }, ]; +/** Nav filtered to the feature edition of this binary: an edition lacking a + * command does not get its page either (Lite shows neither Tools entry). */ +function navGroupsFor(edition: string) { + return NAV_GROUPS.map((group) => ({ + ...group, + items: group.items.filter((item) => !item.editions || item.editions.includes(edition)), + })).filter((group) => group.items.length > 0); +} + +function pageAllowed(page: PageId, edition: string): boolean { + for (const group of NAV_GROUPS) { + for (const item of group.items) { + if (item.id === page) return !item.editions || item.editions.includes(edition); + } + } + return true; +} + const PAGE_TITLES: Record = { overview: ["Computer overview", "电脑概览"], space: ["Space cleaning", "空间清理"], @@ -120,6 +164,8 @@ const PAGE_TITLES: Record = { permissions: ["Permissions", "权限管理"], widget: ["Desktop widget", "桌面小工具"], maintenance: ["System maintenance", "系统维护"], + security: ["Security", "安全查杀"], + screenshot: ["Screenshot OCR", "截图识字"], system: ["Real-time monitor", "实时监控"], history: ["History", "历史记录"], settings: ["Settings", "设置"], @@ -267,18 +313,22 @@ export default function App() { }, []); useEffect(() => { - const order: PageId[] = [ - "overview", - "space", - "applications", - "permissions", - "maintenance", - "system", - "widget", - "history", - "settings", - ]; - // Ctrl/Cmd+1..9 map to the nine pages in order; 0 opens the widget. + const order: PageId[] = ( + [ + "overview", + "space", + "applications", + "permissions", + "maintenance", + "system", + "widget", + "security", + "screenshot", + "history", + "settings", + ] as PageId[] + ).filter((id) => pageAllowed(id, bootstrap?.edition ?? "full")); + // Ctrl/Cmd+1..9 map to the edition-visible pages in order; 0 opens the widget. const onKey = (event: KeyboardEvent) => { if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return; if (event.key === "0") { @@ -293,7 +343,7 @@ export default function App() { }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); - }, []); + }, [bootstrap?.edition]); const changeLanguage = useCallback( async (nextLanguage: Language) => { @@ -380,6 +430,12 @@ export default function App() { {page === "maintenance" ? ( ) : null} + {page === "security" && pageAllowed("security", bootstrap.edition) ? ( + setPage("history")} /> + ) : null} + {page === "screenshot" && pageAllowed("screenshot", bootstrap.edition) ? ( + + ) : null} {page === "system" ? (