diff --git a/CHANGELOG.md b/CHANGELOG.md index 012067d..aacc8f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,16 @@ Squid 的重要变更记录在这里。版本号使用语义化版本,日期 - 版权署名改为 mula.liu,许可证明确为 GPL-3.0-only。 - GitHub 作为源码镜像,不承载 `releases` 分支;新增 `scripts/sync-github.sh` 同步脚本。 +## [0.1.13] - 2026-11-25 + +- 合并 dev 分支的空间清理、系统维护、权限管理与桌面小工具改造,左侧导航按功能合并为“维护 / 安全 / 洞察 / 桌面”四组。 +- 空间清理升级为“垃圾清理 / 重复文件 / 大文件”三页签,切换页签保留扫描结果与勾选状态。 +- 系统维护升级为“一键修复 / 隐私清理 / 系统优化”三页签。 +- 权限管理新增开机启动项分组、残留识别、系统项隐藏、右键菜单分组与进阶启动项。 +- 重复文件支持“本组一份不剩”,删除仍走回收站并可撤销。 +- 保留并接入安全扫描、隔离区与白名单机制;安全入口位于“安全”分组。 +- 概览页采用新的三列指标布局,所有页面一级标题下不再重复二级描述。 + ## [0.1.11] - 2026-11-22 - 设置页的“常规”和“清理”分区改为整行布局,删除方式仍并排显示,版面更清晰。 diff --git a/Cargo.lock b/Cargo.lock index f843721..5c2ef7f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -43,9 +43,9 @@ dependencies = [ [[package]] name = "annotate-snippets" -version = "0.12.17" +version = "0.12.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a5b0a5ab8561c603f16c3b78c24a386b1f70e7fc1b1b1e8c15738828e4a176" +checksum = "0258346f92c78dbc5b336b9a5b27c64447aa10643bc64e651db2edb145361564" dependencies = [ "anstyle", "memchr", @@ -119,9 +119,9 @@ dependencies = [ [[package]] name = "ar_archive_writer" -version = "0.5.3" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" dependencies = [ "object", ] @@ -211,15 +211,6 @@ dependencies = [ "system-deps 6.2.2", ] -[[package]] -name = "atomic" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" -dependencies = [ - "bytemuck", -] - [[package]] name = "autocfg" version = "1.5.1" @@ -343,9 +334,9 @@ dependencies = [ [[package]] name = "bstr" -version = "1.13.1" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214" dependencies = [ "memchr", "regex-automata", @@ -367,12 +358,6 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" -[[package]] -name = "bytemuck" -version = "1.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" - [[package]] name = "cairo-rs" version = "0.18.5" @@ -429,12 +414,12 @@ dependencies = [ [[package]] name = "cfg-expr" -version = "0.20.10" +version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f" +checksum = "8d4ba6e40bd1184518716a6e1a781bf9160e286d219ccdb8ab2612e74cfe4789" dependencies = [ "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.12.16", ] [[package]] @@ -538,9 +523,9 @@ dependencies = [ [[package]] name = "const-oid" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" [[package]] name = "convert_case" @@ -598,27 +583,27 @@ dependencies = [ [[package]] name = "cranelift-assembler-x64" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10c7459262c93a3c408bda96acaaa3d92868f166b33d445b20921f8378325038" +checksum = "da23f7367f4f5d003249eb1067760b3e6f5df82ad61829d40db22fdf8d41fd22" dependencies = [ "cranelift-assembler-x64-meta", ] [[package]] name = "cranelift-assembler-x64-meta" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97a25bfba0da265ef1f98728358e9bb3ab7489913e7bd759c743108892288934" +checksum = "a8dbd10a21204ce6ae3786f8369860ec4e10a24913e987d5abe4c3cc0c7195d6" dependencies = [ "cranelift-srcgen", ] [[package]] name = "cranelift-bforest" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a9ad33269057337a70db66950f426fbdce436a66fe8071f55851a13a2e40cd" +checksum = "4439be9aa2867bcef9effa83a265f550763a37b2cf4ad560c7bc41cbda947a48" dependencies = [ "cranelift-entity", "wasmtime-internal-core", @@ -626,9 +611,9 @@ dependencies = [ [[package]] name = "cranelift-bitset" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d322e6584efe3b229b1164b49edf55aec561553426f7fe3e228a45e80a15a190" +checksum = "9913a7776903ccf6a3172633f59a0d6da2b428ec631c4b999a4b7401efdca1a7" dependencies = [ "serde", "serde_derive", @@ -637,9 +622,9 @@ dependencies = [ [[package]] name = "cranelift-codegen" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a7b9f73f97da69d6edc9adbfeec068cdb2649f0221be41abd3909267cb1cd53" +checksum = "ffc88c2b684ca7df2ed79fa42b38a983e4d3632ee9d57bc2a389f69fc7ff9348" dependencies = [ "bumpalo", "cranelift-assembler-x64", @@ -662,15 +647,15 @@ dependencies = [ "serde_derive", "sha2 0.10.9", "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", "wasmtime-internal-core", ] [[package]] name = "cranelift-codegen-meta" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7015ef10993d7129e0bce933874b60dab8187239aca4ceca352987d9907d528" +checksum = "df667a6e48506af68c087cebee157bfe69e04d78df83e243025ce6473a538fcd" dependencies = [ "cranelift-assembler-x64-meta", "cranelift-codegen-shared", @@ -681,24 +666,24 @@ dependencies = [ [[package]] name = "cranelift-codegen-shared" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37916b08a7b17e063bae743cb746da542df7df283ced961aae213620dc11e27a" +checksum = "ed3fdd2cd7bcd83a9263a978ea1d66477742a1a92095fa08f8752cb9a79ece11" [[package]] name = "cranelift-control" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8154d189f2cc2a84a95a8129773799ddcf2f4609f667047db30715db4be6aa0a" +checksum = "8e1ecc088bd88f5a271f55b1544a8ec60b9d7373f61efe267d54bd2481adf5a3" dependencies = [ "arbitrary", ] [[package]] name = "cranelift-entity" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccbd0c43e96db753f44a84e44f680f9423ed0a475b81f301ba7c44b5db52c37b" +checksum = "2e9e591820d13f0671f879602ff29b241ea8b1dd54a386acbcbf4c3787f41af0" dependencies = [ "cranelift-bitset", "serde", @@ -708,45 +693,45 @@ dependencies = [ [[package]] name = "cranelift-frontend" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b28ae2961cdda7a6814431b40e87bee46e57b7f92294467b32f447108e14674" +checksum = "b00cf9b20096b09b3499d19f82cca658c13c6988ecbc54881caf12a2f01b2f8c" dependencies = [ "cranelift-codegen", "hashbrown 0.17.1", "log", "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", ] [[package]] name = "cranelift-isle" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41eef45b50970e024d673e3fc4a0703e4fee75ca31d63b26566eb0f142300179" +checksum = "4c9fc3f2d35b0b5879107b4c83246e3dfb93bf678e0c68f74f7bd9b7001f7a06" [[package]] name = "cranelift-native" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "649c7b9ad93d5d92287fee74608cacfb139602116293a46e2f25e6ea5402f05c" +checksum = "3c41c07ce15db19296c5ee3bed3019ec95bf2d773fbb28e73bdcb7fbc6ef9196" dependencies = [ "cranelift-codegen", "libc", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", ] [[package]] name = "cranelift-srcgen" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da04416d8e400ad7ae6d9722db72bfbddfbf36d0ff528ec422c4cc336621a172" +checksum = "7ed086d4ea76eb20e03b689abcc9a34bacaec54b1fc3e04269004acbed4587f0" [[package]] name = "crc32fast" -version = "1.5.4" +version = "1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" dependencies = [ "cfg-if", ] @@ -836,9 +821,9 @@ dependencies = [ [[package]] name = "crypto-bigint" -version = "0.7.10" +version = "0.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" dependencies = [ "cpubits", "ctutils", @@ -1235,7 +1220,7 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ff9f725b347b91d04340444fcbce0770886e4a6513e5f8e9e73a9e344efe73b" dependencies = [ - "gio 0.22.10", + "gio 0.22.11", "gtk", "log", "objc2", @@ -1257,6 +1242,16 @@ dependencies = [ "winapi", ] +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -1529,16 +1524,16 @@ dependencies = [ [[package]] name = "gio" -version = "0.22.10" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4620fbafdf19dba814473e19f18e75290cb3338662f6ae35f0402affd3b2b699" +checksum = "536990682bab3b8bf68a78d298ccae69702a114290b096edf2bec6eb2e4013b3" dependencies = [ "futures-channel", "futures-core", "futures-io", "futures-util", - "gio-sys 0.22.9", - "glib 0.22.10", + "gio-sys 0.22.11", + "glib 0.22.11", "libc", "pin-project-lite", "smallvec", @@ -1559,11 +1554,11 @@ dependencies = [ [[package]] name = "gio-sys" -version = "0.22.9" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5" +checksum = "b9c253490f9a475047f109bf6ccb68c407e9d186b7bfab01849188f4e669e669" dependencies = [ - "glib-sys 0.22.9", + "glib-sys 0.22.11", "gobject-sys 0.22.9", "libc", "system-deps 9.0.1", @@ -1595,9 +1590,9 @@ dependencies = [ [[package]] name = "glib" -version = "0.22.10" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694" +checksum = "c9c4cbf1972a07741ae5ce9b23a582a90efc69745fc713f8b037b8d962f604da" dependencies = [ "bitflags 2.13.2", "futures-channel", @@ -1605,8 +1600,8 @@ dependencies = [ "futures-executor", "futures-task", "futures-util", - "glib-macros 0.22.9", - "glib-sys 0.22.9", + "glib-macros 0.22.11", + "glib-sys 0.22.11", "gobject-sys 0.22.9", "libc", "memchr", @@ -1629,9 +1624,9 @@ dependencies = [ [[package]] name = "glib-macros" -version = "0.22.9" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9" +checksum = "d4014e54e2049108c93cf278b64e89f490849402e09b455a25dfa2098cc35093" dependencies = [ "heck 0.5.0", "proc-macro2", @@ -1651,9 +1646,9 @@ dependencies = [ [[package]] name = "glib-sys" -version = "0.22.9" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295" +checksum = "8b01e8b94529c2698b98f765b887f1e001b76195c1e25d1139aa9336019e745d" dependencies = [ "libc", "system-deps 9.0.1", @@ -1700,7 +1695,7 @@ version = "0.22.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834" dependencies = [ - "glib-sys 0.22.9", + "glib-sys 0.22.11", "libc", "system-deps 9.0.1", ] @@ -1969,9 +1964,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "js-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -2001,12 +1996,6 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" -[[package]] -name = "leb128" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" - [[package]] name = "leb128fmt" version = "0.1.0" @@ -2057,9 +2046,9 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litrs" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" +checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" [[package]] name = "lock_api" @@ -2123,7 +2112,7 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3d0581a75c45969c63afd2bb87b1d8b25cfcc556c7a918cf9bb13b0fe8d2381" dependencies = [ - "nix 0.31.3", + "nix 0.31.4", "windows-sys 0.61.2", ] @@ -2243,9 +2232,9 @@ dependencies = [ [[package]] name = "nix" -version = "0.31.3" +version = "0.31.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7" dependencies = [ "bitflags 2.13.2", "cfg-if", @@ -2677,9 +2666,9 @@ dependencies = [ [[package]] name = "pest" -version = "2.9.5" +version = "2.9.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8db75153506001cb36ed924f08cadc862eb3f8c4d0d534139f29074769d7660" +checksum = "44cf434b793f79ab490e99ae3b2f9acce4ef02cdac3eee541a69de78c1aadd7c" dependencies = [ "memchr", "pest_stack_guard", @@ -2688,9 +2677,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.9.5" +version = "2.9.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20aa17e11fb35664b67d5214a0afac57a360d231b6ec53d6eba0700b27d933b4" +checksum = "082f5f21b49230a02b9ee78a8a39d5771fd0ed6dc4d88ecc9fd583cb781e5751" dependencies = [ "pest", "pest_generator", @@ -2698,9 +2687,9 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.9.5" +version = "2.9.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626ec5afccf44ccbfeb2b232316510bb55b4bf34d891afcb0fb07d2b17d7fe9d" +checksum = "5e4725db179c5bc5ea719d3312ce518f4b70d368139d630f4c9309d9117a3ac1" dependencies = [ "pest", "pest_meta", @@ -2711,9 +2700,9 @@ dependencies = [ [[package]] name = "pest_meta" -version = "2.9.5" +version = "2.9.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3f45b6caa65c1b08186832745159c2529994146340a7bf44168095469720f5d" +checksum = "8363b5d48f0960fc3db68b1c8aa0bdc1a370d465a8c74287172ed5093a4cf293" dependencies = [ "pest", ] @@ -2846,9 +2835,9 @@ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] name = "postcard" -version = "1.1.3" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +checksum = "5431b3dcfdf6d1985c87d11f267a171c0dec0a8cd544c6727b747d36365f1fca" dependencies = [ "cobs", "embedded-io 0.4.0", @@ -2974,9 +2963,9 @@ dependencies = [ [[package]] name = "pulley-interpreter" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e6d73adcf2f76b98d3de7a31831b6d6436fd2b6518e0ad4f7cc722a12ad4133" +checksum = "1f153f8d747fe1a04a7323d84963bd99a609f41391357da9d35f1965fb2c58b7" dependencies = [ "cranelift-bitset", "log", @@ -2986,9 +2975,9 @@ dependencies = [ [[package]] name = "pulley-macros" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bde547f939ab9aa321a54c6694aef2e1e27741c2523c0627ff306677b3cbcff" +checksum = "90dd329c9c89b9d4cea5803db3399f34f122e93d43549058caf46f5a7d4406ec" dependencies = [ "proc-macro2", "quote", @@ -3194,9 +3183,9 @@ dependencies = [ [[package]] name = "regalloc2" -version = "0.15.2" +version = "0.15.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "757712e8e61590d6d4f5d563483755538b5aa13467837a3b41cd9832509a7f85" +checksum = "34f923657880712029496c2e68bb40bef163806b2011adde559b28bbcedc82ea" dependencies = [ "allocator-api2", "bumpalo", @@ -3209,9 +3198,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" dependencies = [ "aho-corasick", "memchr", @@ -3221,9 +3210,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.18" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" dependencies = [ "aho-corasick", "memchr", @@ -3232,9 +3221,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.11" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" [[package]] name = "rfc6979" @@ -3270,9 +3259,9 @@ dependencies = [ [[package]] name = "rsa" -version = "0.10.0-rc.21" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47cf9537fc2210e5db7a35a1cdda9d8d451b9df6fba234ec1cf0cd746c120c35" +checksum = "23e77fd77e0dea28b3011fd62d15445b7de7959333b0276d930e03be0f755699" dependencies = [ "const-oid", "crypto-bigint", @@ -3594,7 +3583,7 @@ dependencies = [ [[package]] name = "squid-cli" -version = "0.1.11" +version = "0.1.13" dependencies = [ "anyhow", "chrono", @@ -3614,7 +3603,7 @@ dependencies = [ [[package]] name = "squid-core" -version = "0.1.11" +version = "0.1.13" dependencies = [ "anyhow", "chrono", @@ -3633,27 +3622,30 @@ dependencies = [ [[package]] name = "squid-engine" -version = "0.1.11" +version = "0.1.13" dependencies = [ "anyhow", "chrono", "crossbeam-channel", "dirs", + "filetime", "globset", "libc", "rayon", "serde", "serde_json", + "sha2 0.10.9", "squid-core", "squid-platform", "squid-rules", "squid-stats", "walkdir", + "winreg", ] [[package]] name = "squid-guard" -version = "0.1.11" +version = "0.1.13" dependencies = [ "chrono", "hex", @@ -3669,7 +3661,7 @@ dependencies = [ [[package]] name = "squid-platform" -version = "0.1.11" +version = "0.1.13" dependencies = [ "dirs", "file_icon_provider", @@ -3689,7 +3681,7 @@ dependencies = [ [[package]] name = "squid-rules" -version = "0.1.11" +version = "0.1.13" dependencies = [ "globset", "serde", @@ -3701,7 +3693,7 @@ dependencies = [ [[package]] name = "squid-stats" -version = "0.1.11" +version = "0.1.13" dependencies = [ "chrono", "libc", @@ -3714,7 +3706,7 @@ dependencies = [ [[package]] name = "squid-tui" -version = "0.1.11" +version = "0.1.13" dependencies = [ "anyhow", "chrono", @@ -3865,10 +3857,10 @@ version = "9.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d" dependencies = [ - "cfg-expr 0.20.10", + "cfg-expr 0.17.2", "heck 0.5.0", "pkg-config", - "toml 1.2.1+spec-1.1.0", + "toml 1.2.3+spec-1.1.0", "version-compare", ] @@ -3886,9 +3878,9 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" [[package]] name = "target-lexicon" -version = "0.13.5" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" [[package]] name = "termcolor" @@ -4077,9 +4069,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.2.1+spec-1.1.0" +version = "1.2.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073" dependencies = [ "indexmap", "serde_core", @@ -4134,9 +4126,9 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.1.5+spec-1.1.0" +version = "1.1.7+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" dependencies = [ "winnow 1.0.5", ] @@ -4155,9 +4147,9 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "ucd-trie" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" +checksum = "8f20bdbfc9915686faa18fb5bbe8b4552778505defbf9f12289beefbc44092a6" [[package]] name = "unicode-ident" @@ -4202,11 +4194,10 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.29.0" +version = "1.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" dependencies = [ - "atomic", "getrandom 0.4.3", "js-sys", "wasm-bindgen", @@ -4251,14 +4242,13 @@ dependencies = [ [[package]] name = "walrus" -version = "0.27.3" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5691aeb3546554822fe2c13d63149c26a027cd07d900a72c7c7f37f4321bfaea" +checksum = "04f034ddbc5b46d705409d64c617d01b9ed8c6c9ccac0ab6483e907d525bbf37" dependencies = [ "anyhow", "gimli 0.32.3", "id-arena", - "leb128", "log", "walrus-macro", "wasm-encoder 0.245.1", @@ -4294,12 +4284,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -4307,9 +4296,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4317,9 +4306,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", @@ -4330,9 +4319,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] @@ -4396,9 +4385,9 @@ dependencies = [ [[package]] name = "wasmtime" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2afcadb2e7d0417cb8f3f322c66eff49338b288f22290c0ca0bd3e9570732aa" +checksum = "8f47e5ae0d077a8415d626b028a1701fd4d4b3ed4d57e21a0b5daefe99ae81f1" dependencies = [ "addr2line", "async-trait", @@ -4418,7 +4407,7 @@ dependencies = [ "serde", "serde_derive", "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", "wasmparser 0.254.2", "wasmtime-environ", "wasmtime-internal-core", @@ -4433,9 +4422,9 @@ dependencies = [ [[package]] name = "wasmtime-environ" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2de252f4aedfff6c2054ea5bea2454878a931c56e2553c6356b581e5e30a7e4e" +checksum = "956c03e93a68f39d8fb93b5b72885e327b38249272b14cac7a968804f5bad49f" dependencies = [ "anyhow", "cpp_demangle", @@ -4454,7 +4443,7 @@ dependencies = [ "serde_derive", "sha2 0.10.9", "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", "wasm-encoder 0.254.2", "wasmparser 0.254.2", "wasmprinter", @@ -4464,15 +4453,15 @@ dependencies = [ [[package]] name = "wasmtime-internal-component-util" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ad52499e6246d30bf8bf509506bd637248eee17c8dd623e0c7dbe43e7a1036" +checksum = "59133f8e0df9cb35ed819c3aad45ca3c5984267ec0a38e9c463d2bfadea01988" [[package]] name = "wasmtime-internal-core" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8838d7debfc98a69342d260a990ea6f64adf498184915fccfdbd6718bb40a9b" +checksum = "1463b7c70e14ab1db19709f29f298affc1f0ea50ea59b519d8aec8a6f5a56453" dependencies = [ "hashbrown 0.17.1", "libm", @@ -4481,9 +4470,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-cranelift" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "478c09af53c545d96227b349d35c70fc78e99816923f41428ffff00974bcd145" +checksum = "1a70ad5c0cf92e3b3f0dc2d15d140b83083170fa31fae5dcdd836cabf66873cb" dependencies = [ "cranelift-codegen", "cranelift-control", @@ -4496,7 +4485,7 @@ dependencies = [ "object", "pulley-interpreter", "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", "thiserror 2.0.21", "wasmparser 0.254.2", "wasmtime-environ", @@ -4507,9 +4496,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-fiber" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96dce7a8ea302c0f1eb4154eb1756525c90c595bbabbc590abad64d4c5ff8bbb" +checksum = "cce8b2932cdefb95f711d05e11e5959efad509481f3987917a5ab9b12e784291" dependencies = [ "cc", "libc", @@ -4521,9 +4510,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-jit-debug" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "895f3231b24ce0c12c8a7bb129a9f6ddc6772ec78e59748e53af743dcdd733d1" +checksum = "4e380afb5a32fdb509c2eecd8ab55e8203db6487770738ef96c216fef5ff76aa" dependencies = [ "cc", "wasmtime-internal-versioned-export-macros", @@ -4531,9 +4520,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-jit-icache-coherence" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b60a0c1f735da6b862679b763f8bab653caa477ccc603a25752488b795fec5" +checksum = "6e944d8cec74d9e20db5a874cbc82e1174bf78d1dc092dbf6d79048ff41abfdf" dependencies = [ "libc", "wasmtime-internal-core", @@ -4542,9 +4531,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-unwinder" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97b2c29c8f458bdf1b948058bfbb8141aad0f7abcf0f7cb3479866f4316bf3c" +checksum = "9ef8cc822d036e5366d9e458cc918f75e08d2faa24115c75ac5f791b45f1c36d" dependencies = [ "cranelift-codegen", "log", @@ -4554,9 +4543,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-versioned-export-macros" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32766b38d56927eca9a65858ea8c7b1803424db82562aafd69727aa970057561" +checksum = "fb0a732411dc5a84d071df6f8d773cb84338e4c4cb2dbd21bcc4ccd70754df30" dependencies = [ "proc-macro2", "quote", @@ -5112,9 +5101,9 @@ dependencies = [ [[package]] name = "yara-x" -version = "1.23.0" +version = "1.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8a5ff1e1bb43734cc68f3ddc94646c9740c8c559d38fae559f0c79076f801db" +checksum = "46490aa1d13df1247f106e9620f4221fc8a13b351a9aeef5a34a9b0eaafd78cb" dependencies = [ "annotate-snippets", "anyhow", @@ -5171,9 +5160,9 @@ dependencies = [ [[package]] name = "yara-x-macros" -version = "1.23.0" +version = "1.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc0df20854de457fdeaa3207e6fa08e439d22c63628e37e5608ae4113ebd8a2a" +checksum = "5d9568f7c8c3ce9a14a8ef472612bb86668cad05854155173de85b53c2c7189b" dependencies = [ "darling", "proc-macro2", @@ -5183,9 +5172,9 @@ dependencies = [ [[package]] name = "yara-x-parser" -version = "1.23.0" +version = "1.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "336c1ef292d1d554526b10908198b71920f64dd58e56f39c8689b298fe858a1d" +checksum = "a7b6d18b9aeceb80d3516efc6658589d4311ee07bc4d29f1d740c28201b37109" dependencies = [ "ascii_tree", "bitflags 2.13.2", @@ -5201,9 +5190,9 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.9.1" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" [[package]] name = "zlib-rs" diff --git a/Cargo.toml b/Cargo.toml index d8c37db..1118483 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*"] exclude = ["src-tauri"] [workspace.package] -version = "0.1.11" +version = "0.1.13" edition = "2021" rust-version = "1.95" license = "GPL-3.0-only" @@ -35,6 +35,8 @@ dirs = "6" libc = "0.2" plist = "1" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } +sha2 = "0.10" +filetime = "0.2" sysinfo = { version = "0.34", default-features = false, features = ["system", "network", "disk", "user"] } crossterm = "0.28" ratatui = "0.30" diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 2612938..8180fbf 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,9 +1,11 @@ -Squid 0.1.11 +Squid 0.1.13 -- 设置页的“常规”和“清理”分区改为整行布局,删除方式仍并排显示,版面更清晰。 -- 所有应用页移除一级标题下的二级描述,并收紧标题间距,减少重复信息。 -- 安全页新增白名单机制:可按发布者、应用目录或提示类型信任正常软件。 -- 已信任内容不再出现在默认列表和托盘计数中,可在安全页“已信任”筛选和“设置 → 安全”中查看、撤销。 -- 已确认威胁永远不会被白名单静默,目录信任也会拒绝系统目录、下载目录等过宽范围。 +- 左侧导航按功能合并为“维护 / 安全 / 洞察 / 桌面”四组,常用入口更集中。 +- 空间清理整合“垃圾清理 / 重复文件 / 大文件”三页签,切换时保留扫描结果与勾选。 +- 系统维护整合“一键修复 / 隐私清理 / 系统优化”三页签。 +- 权限管理升级开机启动项:状态筛选、残留识别、系统项隐藏、按软件分组。 +- 右键菜单扩展按软件分组,重复文件支持“本组一份不剩”,删除均走回收站。 +- 保留安全扫描、隔离区与白名单机制,可在“安全扫描”页和设置的安全分区管理。 +- 所有页面一级标题下不再显示二级描述,标题末尾不再带句号。 macOS 与 Windows 安装包均为未签名构建。macOS 首次打开请在访达中右键选择“打开”;Windows SmartScreen 提示时选择“更多信息” > “仍要运行”。 diff --git a/crates/squid-cli/src/guard.rs b/crates/squid-cli/src/guard.rs index 5bcc37d..043cfde 100644 --- a/crates/squid-cli/src/guard.rs +++ b/crates/squid-cli/src/guard.rs @@ -619,7 +619,10 @@ fn with_progress( freed.human() ), ), - Event::Bucket { .. } | Event::Done(_) => {} + Event::Bucket { .. } + | Event::Metered { .. } + | Event::Group { .. } + | Event::Done(_) => {} } } if stop_now { diff --git a/crates/squid-cli/src/main.rs b/crates/squid-cli/src/main.rs index 9a21c1e..011887f 100644 --- a/crates/squid-cli/src/main.rs +++ b/crates/squid-cli/src/main.rs @@ -66,6 +66,8 @@ enum Command { Uninstall(UninstallArgs), /// Deep clean: node_modules, build folders, disk images, stale archives Purge(PurgeArgs), + /// Find byte-identical duplicate files (three-stage hash funnel) + Dupes(DupesArgs), /// Open the interface: disk map, system meters, cleanup, history State, /// One-shot system snapshot (scripts, dotfiles, cron) @@ -145,6 +147,18 @@ struct PurgeArgs { min_age: Option, } +#[derive(Args, Debug)] +struct DupesArgs { + /// Where to look; defaults to your user folders on every drive + paths: Vec, + /// Size floor in bytes (default 1 MiB) + #[arg(long)] + min_size: Option, + /// How many groups to print + #[arg(long, default_value_t = 20)] + top: usize, +} + #[derive(Args, Debug)] struct StatusArgs { /// How many processes to list @@ -378,6 +392,7 @@ fn run() -> Result { Some(Command::Clean(args)) => cmd_clean(args, cli.json), Some(Command::Uninstall(args)) => cmd_uninstall(args, cli.json), Some(Command::Purge(args)) => cmd_purge(args, cli.json), + Some(Command::Dupes(args)) => cmd_dupes(args, cli.json), Some(Command::Status(args)) => cmd_status(args, cli.json), Some(Command::Analyze(args)) => cmd_analyze(args, cli.json), Some(Command::History(args)) => cmd_history(args, cli.json), @@ -599,7 +614,10 @@ fn with_progress( ), ); } - Event::Bucket { .. } | Event::Done(_) => {} + Event::Bucket { .. } + | Event::Metered { .. } + | Event::Group { .. } + | Event::Done(_) => {} } } if stop_now { @@ -1147,6 +1165,75 @@ fn cmd_purge(args: PurgeArgs, json: bool) -> Result { // ---------------------------------------------------------------------- status +fn cmd_dupes(args: DupesArgs, json: bool) -> Result { + use squid_engine::duplicates; + let roots: Vec = if args.paths.is_empty() { + duplicates::default_roots() + } else { + args.paths.iter().map(|path| paths::expand(path)).collect() + }; + heading("Duplicate files"); + let report = with_progress("dupes", move |_engine, progress, cancel| { + duplicates::scan( + &roots, + args.min_size.unwrap_or(duplicates::DEFAULT_MIN_SIZE), + progress, + cancel, + ) + })?; + if json { + println!("{}", serde_json::to_string_pretty(&report)?); + return Ok(0); + } + shout( + "90", + &format!( + " funnel: {} walked → {} same-size → {} confirmed files in {} groups", + squid_core::bytes::format_thousands(report.walked), + squid_core::bytes::format_thousands(report.same_size), + squid_core::bytes::format_thousands(report.confirmed_files), + squid_core::bytes::format_thousands(report.confirmed_groups), + ), + ); + for group in report.groups.iter().take(args.top) { + let waste = group.size * (group.copies.len() as u64 - 1); + shout( + "36", + &format!( + " {} {} copies · {} each (wastes {})", + bullet(), + group.copies[0] + .path + .rsplit(['\\', '/']) + .next() + .unwrap_or("?"), + squid_core::Bytes(group.size).human(), + squid_core::Bytes(waste).human(), + ), + ); + for copy in &group.copies { + shout("90", &format!(" · {}", copy.path)); + } + } + if report.groups.len() > args.top { + shout( + "90", + &format!( + " … {} more groups (--top N to see them)", + report.groups.len() - args.top + ), + ); + } + shout( + "90", + &format!( + " total waste {}\n nothing deleted — the app offers these with recycle-bin undo", + squid_core::Bytes(report.wasted).human_long(), + ), + ); + Ok(0) +} + fn cmd_status(args: StatusArgs, json: bool) -> Result { let mut sampler = squid_stats::Sampler::new(); let _ = sampler.prime(); diff --git a/crates/squid-core/src/fs.rs b/crates/squid-core/src/fs.rs index d790c0e..4dcc08d 100644 --- a/crates/squid-core/src/fs.rs +++ b/crates/squid-core/src/fs.rs @@ -30,6 +30,8 @@ pub struct SizeInfo { pub files: u64, pub dirs: u64, pub unreadable: u32, + /// Newest last-modified seen while walking (unix seconds). `0` = unknown. + pub newest_write: u64, } impl SizeInfo { @@ -56,6 +58,7 @@ impl SizeInfo { self.files += other.files; self.dirs += other.dirs; self.unreadable += other.unreadable; + self.newest_write = self.newest_write.max(other.newest_write); } /// "12,431 files" style annotation for detail rows. @@ -207,6 +210,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo { if meta.file_type().is_symlink() { info.files += 1; info.logical += Bytes(meta.len()); + info.newest_write = mtime_secs(&meta); return info; } match kind { @@ -214,6 +218,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo { info.files += 1; info.logical += Bytes(meta.len()); info.allocated += Bytes(allocated_bytes(path, &meta)); + info.newest_write = mtime_secs(&meta); return info; } ItemKind::Path | ItemKind::Contents => {} @@ -222,6 +227,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo { info.files += 1; info.logical += Bytes(meta.len()); info.allocated += Bytes(allocated_bytes(path, &meta)); + info.newest_write = mtime_secs(&meta); return info; } @@ -251,6 +257,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo { info.files += 1; info.logical += Bytes(meta.len()); info.allocated += Bytes(allocated_bytes(entry.path(), &meta)); + info.newest_write = info.newest_write.max(mtime_secs(&meta)); } Err(_) => info.unreadable += 1, } @@ -261,6 +268,14 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo { info } +/// Last-modified as unix seconds; 0 when the platform withholds it. +fn mtime_secs(meta: &Metadata) -> u64 { + meta.modified() + .ok() + .and_then(|when| when.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |age| age.as_secs()) +} + /// Measure many paths in parallel. `progress` receives completed units. /// `Path` for folders (and anything that should be removed recursively), /// `File` for plain files and symlinks. @@ -280,7 +295,7 @@ pub fn kind_of(path: &Path) -> crate::model::ItemKind { pub fn measure_all( targets: &[(PathBuf, ItemKind)], cancel: &CancelToken, - on_unit: impl Fn(usize, &SizeInfo) + Send + Sync, + on_unit: impl Fn(usize, usize, &SizeInfo) + Send + Sync, ) -> Vec { let pool = rayon::ThreadPoolBuilder::new() .num_threads(measure_threads()) @@ -297,14 +312,18 @@ pub fn measure_all( let results: Vec = pool.install(|| { targets .par_iter() - .map(|(path, kind)| { + .enumerate() + .map(|(index, (path, kind))| { if cancel.is_cancelled() { cancelled.store(true, Ordering::Relaxed); return SizeInfo::default(); } let info = measure(path, *kind); - let idx = done.fetch_add(1, Ordering::Relaxed) as usize; - emit(idx, &info); + let completed = done.fetch_add(1, Ordering::Relaxed) as usize + 1; + // (target index, completed count): index identifies the unit — + // callbacks arrive in completion order under rayon — while the + // count drives monotonic progress bars. + emit(index, completed, &info); info }) .collect() @@ -369,6 +388,7 @@ pub fn remove_item_with( files: 0, dirs: 0, unreadable: 0, + newest_write: 0, }; Ok(freed.on_disk().max(Bytes::ZERO)) } diff --git a/crates/squid-core/src/model.rs b/crates/squid-core/src/model.rs index f699faa..70dcd29 100644 --- a/crates/squid-core/src/model.rs +++ b/crates/squid-core/src/model.rs @@ -20,10 +20,16 @@ pub enum Category { LanguagePacks, Leftovers, UpdateInstallers, + /// Duplicate-file scan results (its own page, streamed group by group). + Duplicates, + /// AI tool caches and local model files (Ollama, HuggingFace, …). + AiTools, + /// Privacy traces: browser history, recent items, clipboard, activity. + Privacy, } impl Category { - pub const ALL: [Category; 10] = [ + pub const ALL: [Category; 13] = [ Category::SystemJunk, Category::AppCaches, Category::BrowserCaches, @@ -34,6 +40,9 @@ impl Category { Category::LanguagePacks, Category::Leftovers, Category::UpdateInstallers, + Category::Duplicates, + Category::AiTools, + Category::Privacy, ]; pub fn id(self) -> &'static str { @@ -48,6 +57,9 @@ impl Category { Category::LanguagePacks => "languages", Category::Leftovers => "leftovers", Category::UpdateInstallers => "update-installers", + Category::Duplicates => "duplicates", + Category::AiTools => "ai", + Category::Privacy => "privacy", } } @@ -63,6 +75,9 @@ impl Category { Category::LanguagePacks => "Unneeded Languages", Category::Leftovers => "Uninstaller Leftovers", Category::UpdateInstallers => "Update Installers", + Category::Duplicates => "Duplicate Files", + Category::AiTools => "AI Tools & Models", + Category::Privacy => "Privacy Traces", } } @@ -81,6 +96,9 @@ impl Category { Category::LanguagePacks => "Speech and localization data for languages you do not use", Category::Leftovers => "Data belonging to apps that are no longer installed", Category::UpdateInstallers => "Installer packages apps keep after a successful update", + Category::Duplicates => "Byte-identical files confirmed by a three-stage hash funnel", + Category::AiTools => "Local model weights and caches that re-download when needed", + Category::Privacy => "History and traces that disappear without a recycle bin", } } @@ -109,6 +127,9 @@ impl Category { "update-installer" | "update-installers" | "upgrades" | "upgrade-packages" => { Category::UpdateInstallers } + "duplicate" | "duplicates" | "duplicate-files" => Category::Duplicates, + "ai" | "ai-tools" | "ai-models" | "models" => Category::AiTools, + "privacy" | "privacy-traces" | "private" => Category::Privacy, _ => return None, }; Some(alias) @@ -165,6 +186,21 @@ pub struct CleanupItem { /// stale or hand-edited item can never escape its sandbox. #[serde(default)] pub anchors: Vec, + /// Seconds since the *most recent* last-write inside the item (Mole's + /// decision aid: 1.2 GB alone is not actionable, "untouched for 3 months" + /// is — and a low value flags a live, working directory). Unknown until + /// measurement; `None` for unreadable paths. + #[serde(default)] + pub last_write_secs: Option, + /// File count from measurement — lets the UI say "12 files · 5 folders". + #[serde(default)] + pub file_count: u64, + /// Machine-readable judgement tokens (Mole's evidence chain, made + /// visible): `lock:`, `record:`, `record-missing`, + /// `modified:`, `git:ignored|untracked|none|tracked`, `age:`, + /// `busy`. The UI renders each token as a ✓/! line in a detail panel. + #[serde(default)] + pub evidence: Vec, } impl CleanupItem { @@ -187,6 +223,9 @@ impl CleanupItem { lock: lock_default(kind), note: None, anchors: Vec::new(), + last_write_secs: None, + file_count: 0, + evidence: Vec::new(), } } @@ -380,10 +419,23 @@ pub struct AppInfo { pub has_sibling_install: bool, pub publisher: Option, pub installed_ms: Option, - /// Raw `DisplayIcon` registry value (Windows): a path, optionally with an + /// Raw `DisplayIcon` registry value (Windows): a path, optionally with a /// `,index` suffix — the icon Explorer shows for this app. #[serde(default)] pub display_icon: Option, + /// The uninstaller command recorded by the app itself, when present. + #[serde(default)] + pub uninstall_string: Option, + /// Windows: the exact registry key holding this entry + /// (`HKCU|HKLM` + subkey), so an orphaned record can be removed after + /// its files are gone. + #[serde(default)] + pub reg_key: Option, + /// Install is broken: neither the install folder nor the uninstaller + /// target exists any more (or MSI reports the product absent while the + /// registry record remains). 「安装不完整」 — offer leftover cleanup. + #[serde(default)] + pub dead: bool, } impl AppInfo { diff --git a/crates/squid-core/src/progress.rs b/crates/squid-core/src/progress.rs index 29cd704..433f8ac 100644 --- a/crates/squid-core/src/progress.rs +++ b/crates/squid-core/src/progress.rs @@ -30,6 +30,19 @@ pub enum Event { total: Bytes, count: usize, }, + /// Cumulative measurement counters, streamed while sizes are computed + /// (Mole's "Scanning: 128,431 files · 38.2 GB" live status line). + Metered { + files: u64, + bytes: Bytes, + }, + /// A finished work unit streamed as soon as it is confirmed, shaped by + /// the producing engine (duplicate groups land while the scan still + /// runs — MangoDisk's lesson that results beat progress bars). + Group { + kind: &'static str, + payload: serde_json::Value, + }, Deleted { path: PathBuf, freed: Bytes, diff --git a/crates/squid-core/src/safety.rs b/crates/squid-core/src/safety.rs index 769d28a..cac5229 100644 --- a/crates/squid-core/src/safety.rs +++ b/crates/squid-core/src/safety.rs @@ -186,6 +186,13 @@ pub struct SafetyPolicy { /// Roots whose contents a non-admin run may still reach — on Unix /// `/Applications`, on Windows `%ProgramData%` and `%PUBLIC%`. pub outside_home_ok: Vec, + /// Accept *any* existing volume as an allowed anchor, not just system + /// paths. The duplicate-file scan runs over whole drives by design — the + /// files are the user's own, they were confirmed byte-identical, and + /// deletion still goes through the recycle bin + undo path. Everything + /// else about the policy (hard-deny roots, protected folders, symlink + /// refusal) keeps its full teeth. + pub all_volumes_ok: bool, } impl Default for SafetyPolicy { @@ -208,6 +215,7 @@ impl Default for SafetyPolicy { allow_system_paths: true, follow_symlinks: false, outside_home_ok: outside_home_ok(), + all_volumes_ok: false, } } } @@ -234,6 +242,33 @@ impl SafetyPolicy { self } + /// Let an unprivileged run reach files on any existing volume (the + /// duplicate-file scan); see [`SafetyPolicy::all_volumes_ok`]. + pub fn with_all_volumes(mut self) -> Self { + self.all_volumes_ok = true; + self + } + + /// True when `norm` sits on a drive/volume that exists right now. The + /// scan-anchors-are-volumes rule keeps its teeth in the other checks: + /// hard-deny roots, deny-exact folders and reserved names all run first. + fn on_existing_volume(&self, norm: &Path) -> bool { + #[cfg(windows)] + { + match norm.components().next() { + Some(std::path::Component::Prefix(prefix)) => { + PathBuf::from(prefix.as_os_str()).exists() + } + _ => false, + } + } + #[cfg(not(windows))] + { + let _ = norm; + true + } + } + fn is_exact_denied(&self, path: &Path) -> bool { self.deny_exact.iter().any(|deny| { // Trailing glob star entries deny the directory itself only. @@ -304,6 +339,7 @@ impl SafetyPolicy { } if !self.allow_system_paths + && !(self.all_volumes_ok && self.on_existing_volume(&norm)) && !paths::is_within(&paths::home_dir(), &norm) && !self .outside_home_ok diff --git a/crates/squid-core/src/settings.rs b/crates/squid-core/src/settings.rs index b9d7128..7a371a9 100644 --- a/crates/squid-core/src/settings.rs +++ b/crates/squid-core/src/settings.rs @@ -223,23 +223,9 @@ impl Default for Settings { delete_mode: DeleteMode::Trash, whitelist: Vec::new(), disabled_rules: Vec::new(), - purge_roots: vec![ - "~/code".into(), - "~/Code".into(), - "~/dev".into(), - "~/Dev".into(), - "~/develop".into(), - "~/projects".into(), - "~/Projects".into(), - "~/repos".into(), - "~/Repos".into(), - "~/src".into(), - "~/work".into(), - "~/Work".into(), - "~/Desktop".into(), - "~/Documents".into(), - "~/.codex/worktrees".into(), - ], + // Auto-discovery (purge::resolve_roots) owns the default story; + // this list is now only for hand-edited extra folders. + purge_roots: Vec::new(), purge_min_age_days: 7, purge_max_entries: 200_000, show_allocated: true, @@ -341,6 +327,13 @@ impl Settings { .collect() } + /// One raw whitelist line as a matcher — the shape the audit layer + /// needs when it must answer about a single pattern, not the list. + pub fn whitelist_matcher_for(raw: &str) -> Option { + let expanded = paths::expand(raw).to_string_lossy().into_owned(); + Glob::new(&expanded).ok().map(|g| g.compile_matcher()) + } + pub fn is_whitelisted(&self, path: &Path, matchers: &[GlobMatcher]) -> bool { if self.whitelist.is_empty() { return false; diff --git a/crates/squid-engine/Cargo.toml b/crates/squid-engine/Cargo.toml index d551d18..2f762fc 100644 --- a/crates/squid-engine/Cargo.toml +++ b/crates/squid-engine/Cargo.toml @@ -19,5 +19,10 @@ walkdir.workspace = true globset.workspace = true crossbeam-channel.workspace = true chrono.workspace = true +sha2.workspace = true +filetime.workspace = true dirs.workspace = true libc.workspace = true + +[target.'cfg(windows)'.dependencies] +winreg = "0.52" diff --git a/crates/squid-engine/src/ai.rs b/crates/squid-engine/src/ai.rs new file mode 100644 index 0000000..598ab5b --- /dev/null +++ b/crates/squid-engine/src/ai.rs @@ -0,0 +1,493 @@ +//! AI 工具与模型(AI tools & models)— the MangoDisk-inspired category for +//! the local-AI crowd: Ollama weights, HuggingFace caches, and the desktop +//! AI apps' own caches and update payloads. +//! +//! The discipline that separates this from every other rule: **a model is +//! the user's downloaded property, not a cache.** 16 GB of llama.cpp weights +//! "regenerate" as a three-hour download on a bad day. So model rows are +//! never pre-selected, carry their last-seen timestamp, and live beside the +//! genuinely disposable caches (chat-app Electron caches, update payloads) +//! that follow normal cache rules. +//! +//! Last-used honesty: Ollama records no access times we can trust, so the +//! newest mtime among a model's manifest and blobs is shown as 最近使用时间 +//! — the moment the model was pulled or re-patched. That is displayed, never +//! used to auto-delete. + +use squid_core::{Bytes, Category, CleanupItem, ItemKind}; +use std::path::{Path, PathBuf}; + +/// mtime of a file in ms since epoch, created() as backup. +fn mtime_ms(path: &Path) -> Option { + let meta = std::fs::metadata(path).ok()?; + meta.modified() + .or_else(|_| meta.created()) + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_millis() as u64) +} + +fn dir_size(path: &Path) -> (u64, Option) { + let mut total = 0u64; + let mut newest: Option = None; + for entry in walkdir::WalkDir::new(path) + .follow_links(false) + .max_depth(6) + .into_iter() + .filter_entry(|e| !e.file_type().is_symlink()) + .flatten() + { + if !entry.file_type().is_file() { + continue; + } + let Ok(meta) = entry.metadata() else { continue }; + total += meta.len(); + if let Some(ms) = mtime_ms(entry.path()) { + newest = Some(newest.map_or(ms, |cur: u64| cur.max(ms))); + } + } + (total, newest) +} + +fn age_days(ms: u64) -> Option { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .ok()? + .as_millis() as u64; + Some((now.saturating_sub(ms)) as f64 / 86_400_000.0) +} + +fn age_note(ms: Option) -> Option { + let days = ms.and_then(age_days)?; + if days < 1.0 { + Some("今天或昨天用过".into()) + } else if days < 30.0 { + Some(format!("约 {} 天前用过", days as u64)) + } else if days < 365.0 { + Some(format!( + "约 {} 个月没用过", + (days / 30.0).round().max(1.0) as u64 + )) + } else { + Some(format!( + "约 {} 年没用过", + (days / 365.0).round().max(1.0) as u64 + )) + } +} + +/// A model row: name, size, last seen. `selected=false` is the contract — +/// the user decides, never the scanner. +fn model_item( + root: PathBuf, + label: String, + size_bytes: u64, + last_ms: Option, + rule: &str, +) -> CleanupItem { + let mut item = CleanupItem::new(root, ItemKind::Path, Category::AiTools, label) + .with_rule(rule) + .with_note(age_note(last_ms).unwrap_or_default()); + item.size = Bytes(size_bytes); + item.allocated = Bytes(size_bytes); + item.selected = false; + if let Some(ms) = last_ms { + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + item.last_write_secs = Some(now_ms.saturating_sub(ms) / 1000); + } + item.evidence = vec![ + "record:manifest".into(), + format!("age:{}", age_note(last_ms).unwrap_or_default()), + ]; + item +} + +/// Ollama, sized honestly. A model is its manifest plus the blobs **no other +/// model also uses** — shared layers stay on disk until every model that +/// references them is gone, so a row's size never overstates what deleting +/// it frees. One model therefore becomes a small cluster of File items +/// (manifest + exclusive blobs) sharing a per-model rule id, which the 空间 +/// 清理 page renders as one 清理点 named 「Ollama · 模型名」. +fn note_digest(value: &serde_json::Value, out: &mut Vec<(String, u64)>) { + if let Some(digest) = value.get("digest").and_then(|d| d.as_str()) { + let size = value.get("size").and_then(|s| s.as_u64()).unwrap_or(0); + out.push((digest.to_string(), size)); + } +} + +fn ollama_models(home: &Path) -> Vec { + let models_root = home.join(".ollama").join("models"); + let manifests = models_root.join("manifests"); + if !manifests.is_dir() { + return Vec::new(); + } + // Pass 1: read every manifest, map digest → how many models use it. + type Manifest = (PathBuf, String, Vec<(String, u64)>); + let mut files: Vec = Vec::new(); + let mut refs: std::collections::HashMap = Default::default(); + let mut stack = vec![manifests]; + while let Some(dir) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + stack.push(path); + continue; + } + let Some(family) = path.parent().map(|p| { + p.file_name() + .map(|f| f.to_string_lossy().into_owned()) + .unwrap_or_default() + }) else { + continue; + }; + let Some(tag) = path.file_name().map(|t| t.to_string_lossy().into_owned()) else { + continue; + }; + let name = if family == "library" || family.is_empty() { + tag.clone() + } else { + format!("{family}/{tag}") + }; + let Ok(text) = std::fs::read_to_string(&path) else { + continue; + }; + let Ok(json) = serde_json::from_str::(&text) else { + continue; + }; + let mut digests: Vec<(String, u64)> = Vec::new(); + if let Some(config) = json.get("config") { + note_digest(config, &mut digests); + } + if let Some(layers) = json.get("layers").and_then(|l| l.as_array()) { + for layer in layers { + note_digest(layer, &mut digests); + } + } + for (digest, _) in &digests { + *refs.entry(digest.clone()).or_insert(0) += 1; + } + files.push((path, name, digests)); + } + } + // Pass 2: one cluster of items per model, exclusive bytes only. + let mut rows = Vec::new(); + for (manifest, name, digests) in files { + let slug: String = name + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect(); + let rule = format!("ai-ollama-{slug}"); + let mut size = 0u64; + let mut newest = mtime_ms(&manifest); + let mut shared_skipped = 0usize; + let mut blob_items: Vec<(PathBuf, u64, u64)> = Vec::new(); + for (digest, declared) in &digests { + if refs.get(digest).copied().unwrap_or(0) > 1 { + shared_skipped += 1; + continue; // another model still needs this layer + } + let blob = models_root.join("blobs").join(digest.replace(':', "-")); + let Ok(meta) = std::fs::metadata(&blob) else { + continue; + }; + let bytes = meta.len().max(*declared); + let ms = mtime_ms(&blob).unwrap_or(0); + size += bytes; + newest = Some(newest.map_or(ms, |cur: u64| cur.max(ms))); + blob_items.push((blob, bytes, ms)); + } + // A model whose layers are all shared frees nothing today, but the + // row still means 「从 ollama list 移除」 — keep it, sized honestly. + let age = age_note(newest); + let mut shared_note = String::new(); + if shared_skipped > 0 { + shared_note = format!(";另有 {shared_skipped} 个共享层被其它模型使用,不计算在内"); + } + let label = format!("Ollama · {name}"); + // The manifest is the anchor row and carries the cluster label. Every + // row — manifest and blobs alike — carries **its own** size: the 清理点 + // row sums its members, so charging the total to the manifest on top + // of the blobs would double-count the model. + let manifest_bytes = std::fs::metadata(&manifest).map(|m| m.len()).unwrap_or(0); + let mut item = model_item(manifest, label.clone(), manifest_bytes, newest, &rule); + item.kind = ItemKind::File; // the manifest file itself + item.note = Some(format!( + "{};整个模型可释放 {},删除后 `ollama pull` 可原样恢复{shared_note}", + age.clone().unwrap_or_else(|| "从未记录使用时间".into()), + Bytes(size + manifest_bytes) + )); + rows.push(item); + for (blob, bytes, ms) in blob_items { + let mut part = CleanupItem::new(blob, ItemKind::File, Category::AiTools, label.clone()) + .with_rule(&rule); + part.size = Bytes(bytes); + part.allocated = Bytes(bytes); + part.selected = false; + if let Some(ms) = Some(ms).filter(|m| *m > 0) { + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + part.last_write_secs = Some(now_ms.saturating_sub(ms) / 1000); + } + part.evidence = vec!["record:blob".into()]; + rows.push(part); + } + } + rows +} + +/// HuggingFace hub cache: one row per repo directory (models--org--name). +fn huggingface_cache(home: &Path) -> Vec { + let hub = home.join(".cache").join("huggingface").join("hub"); + let Ok(entries) = std::fs::read_dir(&hub) else { + return Vec::new(); + }; + let mut rows = Vec::new(); + for entry in entries.flatten() { + let path = entry.path(); + if !path.is_dir() { + continue; + } + let name = entry.file_name().to_string_lossy().into_owned(); + let pretty = name + .strip_prefix("models--") + .unwrap_or(&name) + .replace("--", "/"); + let (size, newest) = dir_size(&path); + if size == 0 { + continue; + } + let mut item = model_item( + path, + format!("HuggingFace · {pretty}"), + size, + newest, + "ai-huggingface", + ); + item.note = Some(format!( + "{};重新使用时会自动重新下载(可能占用流量)", + age_note(newest).unwrap_or_else(|| "从未记录使用时间".into()) + )); + rows.push(item); + } + rows +} + +/// The genuinely disposable side: Electron caches, logs, update payloads the +/// desktop AI apps keep. These follow normal cache semantics (pre-selected). +fn tool_caches() -> Vec { + let mut rows = Vec::new(); + let mut add = |label: &str, path: PathBuf, note: &str| { + if !path.is_dir() { + return; + } + let (size, _) = dir_size(&path); + if size == 0 { + return; + } + let mut item = CleanupItem::new(path, ItemKind::Contents, Category::AiTools, label) + .with_rule("ai-cache") + .with_note(note); + item.size = Bytes(size); + item.allocated = Bytes(size); + rows.push(item); + }; + let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) else { + return rows; + }; + let Some(roaming) = std::env::var_os("APPDATA").map(PathBuf::from) else { + return rows; + }; + add( + "Codex 桌面缓存", + local.join("Codex").join("Cache"), + "登录与界面缓存,重新打开自动重建", + ); + add( + "Codex 更新包", + local.join("Codex").join("Packages"), + "升级完成后不再需要", + ); + add( + "Claude 桌面缓存", + roaming.join("Claude").join("Cache"), + "重新打开自动重建", + ); + add( + "Claude 日志", + roaming.join("Claude").join("logs"), + "旧日志可安全清空", + ); + add( + "ChatGPT 桌面缓存", + roaming.join("ChatGPT").join("WebCache"), + "重新打开自动重建", + ); + add( + "ChatGPT 更新包", + roaming.join("ChatGPT").join("Update"), + "升级完成后不再需要", + ); + rows +} + +/// One entry point, same shape as `updates::collect`. +pub fn collect(_engine: &crate::Engine, cancel: &squid_core::CancelToken) -> Vec { + let mut rows = Vec::new(); + if cancel.is_cancelled() { + return rows; + } + let home = squid_core::paths::home_dir(); + rows.extend(ollama_models(&home)); + if cancel.is_cancelled() { + return rows; + } + rows.extend(huggingface_cache(&home)); + rows.extend(tool_caches()); + rows +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fixture() -> Option { + let root = std::env::temp_dir().join(format!( + "squid-ai-{}-{}", + std::process::id(), + squid_core::ledger::new_session_id() + )); + std::fs::create_dir_all(&root).ok()?; + Some(root) + } + + #[test] + fn ollama_models_are_listed_never_selected_with_sizes() { + let Some(root) = fixture() else { return }; + let manifests = root.join(".ollama/models/manifests/registry.ollama.ai/library/qwen3"); + let blobs = root.join(".ollama/models/blobs"); + std::fs::create_dir_all(&manifests).unwrap(); + std::fs::create_dir_all(&blobs).unwrap(); + std::fs::write( + manifests.join("8b"), + r#"{"layers":[{"digest":"sha256:aaa","size":2048}]}"#, + ) + .unwrap(); + std::fs::write(blobs.join("sha256-aaa"), vec![1u8; 2048]).unwrap(); + let rows = ollama_models(&root); + // Cluster: manifest File + exclusive blob File, one rule id each row. + assert_eq!(rows.len(), 2, "{rows:?}"); + assert!(rows.iter().all(|r| r.rule_id == "ai-ollama-qwen3-8b")); + assert_eq!(rows[0].label, "Ollama · qwen3/8b"); + // Each row carries its own size; the cluster total rides in the note. + let total = rows.iter().map(|r| r.size.as_u64()).sum::(); + assert!(total >= 2048, "manifest + exclusive blob, no double count"); + assert!(rows[0] + .note + .as_deref() + .is_some_and(|n| n.contains("可释放"))); + assert!(rows.iter().all(|r| !r.selected), "models never pre-checked"); + assert!(rows[0] + .note + .as_deref() + .is_some_and(|n| n.contains("可原样恢复"))); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn shared_blobs_are_not_billed_to_either_model() { + let Some(root) = fixture() else { return }; + let library = root.join(".ollama/models/manifests/registry.ollama.ai/library"); + std::fs::create_dir_all(library.join("a")).unwrap(); + std::fs::create_dir_all(library.join("b")).unwrap(); + std::fs::create_dir_all(root.join(".ollama/models/blobs")).unwrap(); + std::fs::write( + library.join("a").join("latest"), + r#"{"layers":[{"digest":"sha256:shared","size":5000},{"digest":"sha256:own-a","size":100}]}"#, + ) + .unwrap(); + std::fs::write( + library.join("b").join("latest"), + r#"{"layers":[{"digest":"sha256:shared","size":5000}]}"#, + ) + .unwrap(); + std::fs::write( + root.join(".ollama/models/blobs/sha256-shared"), + vec![0u8; 5000], + ) + .unwrap(); + std::fs::write( + root.join(".ollama/models/blobs/sha256-own-a"), + vec![0u8; 100], + ) + .unwrap(); + let rows = ollama_models(&root); + let model_a: Vec<_> = rows + .iter() + .filter(|r| r.rule_id == "ai-ollama-a-latest") + .collect(); + let model_b: Vec<_> = rows + .iter() + .filter(|r| r.rule_id == "ai-ollama-b-latest") + .collect(); + // A: manifest (its own JSON bytes) + own blob sized 100; the shared + // 5 GB belongs to nobody yet, so it is billed to neither row. + assert_eq!(model_a.len(), 2, "{model_a:?}"); + assert_eq!(model_a[1].size.as_u64(), 100); + assert!( + model_a[0].size.as_u64() < 200, + "manifest carries its own bytes" + ); + assert!(model_a[0] + .note + .as_deref() + .is_some_and(|n| n.contains("共享层"))); + // B: only the manifest survives (its own JSON bytes, not the shared + // 5 GB), and its note says the layers are held by other models. + assert_eq!(model_b.len(), 1, "{model_b:?}"); + assert!(model_b[0].size.as_u64() < 200, "manifest bytes only"); + assert!(model_b[0] + .note + .as_deref() + .is_some_and(|n| n.contains("共享层"))); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn library_prefix_is_stripped_from_official_models() { + let Some(root) = fixture() else { return }; + let manifests = root.join(".ollama/models/manifests/registry.ollama.ai/library/llama3"); + std::fs::create_dir_all(&manifests).unwrap(); + std::fs::create_dir_all(root.join(".ollama/models/blobs")).unwrap(); + std::fs::write( + manifests.join("latest"), + r#"{"layers":[{"digest":"sha256:bbb","size":10}]}"#, + ) + .unwrap(); + std::fs::write(root.join(".ollama/models/blobs/sha256-bbb"), vec![0u8; 10]).unwrap(); + let rows = ollama_models(&root); + assert_eq!(rows[0].label, "Ollama · llama3/latest"); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn huggingface_repos_get_one_row_each() { + let Some(root) = fixture() else { return }; + let hub = root.join(".cache/huggingface/hub/models--bert--base"); + std::fs::create_dir_all(hub.join("snapshots/x")).unwrap(); + std::fs::write(hub.join("snapshots/x/model.bin"), vec![7u8; 4096]).unwrap(); + let rows = huggingface_cache(&root); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].label, "HuggingFace · bert/base"); + assert_eq!(rows[0].size.as_u64(), 4096); + assert!(!rows[0].selected); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/crates/squid-engine/src/analyze.rs b/crates/squid-engine/src/analyze.rs index 8ed0daa..f8fd9cc 100644 --- a/crates/squid-engine/src/analyze.rs +++ b/crates/squid-engine/src/analyze.rs @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize}; use squid_core::fs; -use squid_core::progress::{CancelToken, Progress}; +use squid_core::progress::{CancelToken, Event, Progress}; use squid_core::Bytes; use std::path::{Path, PathBuf}; @@ -16,6 +16,7 @@ use std::path::{Path, PathBuf}; const CHILD_CAP: usize = 512; #[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct Node { pub path: PathBuf, pub logical: Bytes, @@ -196,9 +197,9 @@ pub fn expand( }) .collect(); progress.tick(0, Some(targets.len() as u64), None); - let sizes = fs::measure_all(&targets, cancel, |index, _info| { + let sizes = fs::measure_all(&targets, cancel, |index, completed, _info| { progress.tick( - index as u64 + 1, + completed as u64, Some(targets.len() as u64), targets.get(index).map(|(path, _)| path.clone()), ); @@ -307,6 +308,146 @@ pub fn largest_files( Ok(found) } +/// Type buckets the large-file page filters on (extension → class). +/// Anything not listed lands in the catch-all "other". +pub fn file_class(path: &Path) -> &'static str { + let ext = path + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); + match ext.as_str() { + "mp4" | "mkv" | "avi" | "mov" | "wmv" | "flv" | "webm" | "ts" | "m2ts" => "video", + "zip" | "rar" | "7z" | "tar" | "gz" | "bz2" | "xz" | "zst" => "archive", + "exe" | "msi" | "msp" | "appx" | "msix" | "dmg" | "pkg" | "deb" | "rpm" | "appimage" => { + "installer" + } + "iso" | "img" | "vhd" | "vhdx" | "vmdk" | "qcow2" | "wim" | "esd" => "image", + _ => "other", + } +} + +/// Large files across several roots with a byte threshold and optional +/// type-class filter. Streams `Metered` (folders walked / bytes found); +/// returns every hit at or above `min_bytes` — the UI counts them all, +/// "共 214 个" honesty beats a capped top-list. +pub fn large_files( + roots: &[PathBuf], + min_bytes: u64, + class: Option<&str>, + cancel: &CancelToken, + progress: &Progress, +) -> squid_core::Result> { + let mut found: Vec = Vec::new(); + let mut stack: Vec<(PathBuf, usize)> = roots + .iter() + .filter(|root| root.is_dir()) + .map(|root| (root.clone(), 0usize)) + .collect(); + let mut visited = 0usize; + let mut emitted = 0u64; + progress.phase("bigfiles", "scanning for large files"); + while let Some((dir, depth)) = stack.pop() { + cancel.check()?; + visited += 1; + if visited % 256 == 0 { + progress.publish(Event::Metered { + files: visited as u64, + bytes: Bytes(emitted), + }); + } + if depth > 24 { + continue; + } + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + let Ok(meta) = entry.metadata() else { + continue; + }; + if meta.is_dir() { + if !is_mountpoint(&path) && !skip_infra(&entry.file_name().to_string_lossy()) { + stack.push((path, depth + 1)); + } + continue; + } + if !meta.is_file() || meta.len() < min_bytes { + continue; + } + // The page files are system-managed and permanently locked: + // listing them only teaches users that deleting C:\pagefile.sys + // fails. hiberfil.sys stays — it has a real, actionable switch. + if is_pagefile(&path) { + continue; + } + if let Some(wanted) = class { + if file_class(&path) != wanted { + continue; + } + } + emitted += meta.len(); + let modified_ms = meta + .modified() + .or_else(|_| meta.created()) + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_millis() as u64); + found.push(FileEntry { + path, + logical: Bytes(meta.len()), + allocated: Bytes(allocated_of(&meta)), + modified_ms, + }); + } + } + found.sort_by_key(|entry| std::cmp::Reverse(entry.size())); + progress.publish(Event::Metered { + files: visited as u64, + bytes: Bytes(emitted), + }); + Ok(found) +} + +/// The virtual-memory page files. They sit at a volume root, are held open by +/// the kernel and cannot be deleted from Explorer, so a large-file sweep must +/// not offer them. `hiberfil.sys` deliberately stays: turning hibernation off +/// is a real, actionable way to free that space. +fn is_pagefile(path: &Path) -> bool { + // Only the volume-root copies are the system's; a photo named + // pagefile.sys inside a folder stays listed. `C:\pagefile.sys` has + // parent `C:\`, whose own parent is none. + let at_root = path + .parent() + .and_then(|parent| parent.parent()) + .map_or(true, |grand| grand.as_os_str().is_empty()); + if !at_root { + return false; + } + path.file_name() + .map(|name| { + let name = name.to_string_lossy(); + name.eq_ignore_ascii_case("pagefile.sys") || name.eq_ignore_ascii_case("swapfile.sys") + }) + .unwrap_or(false) +} + +/// System churn a large-file sweep should not crawl through. +fn skip_infra(name: &str) -> bool { + const SKIP: &[&str] = &[ + "$recycle.bin", + "system volume information", + "windows", + "program files", + "program files (x86)", + "node_modules", + ".git", + ]; + let lower = name.to_lowercase(); + SKIP.iter().any(|wanted| lower == *wanted) +} + #[cfg(unix)] fn allocated_of(meta: &std::fs::Metadata) -> u64 { use std::os::unix::fs::MetadataExt; @@ -442,4 +583,19 @@ mod tests { assert!(!node.complete); let _ = std::fs::remove_dir_all(&root); } + + #[cfg(windows)] + #[test] + fn page_files_hide_only_at_the_volume_root() { + // Paths are matched lexically; nothing has to exist on disk. + assert!(is_pagefile(std::path::Path::new(r"C:\pagefile.sys"))); + assert!(is_pagefile(std::path::Path::new(r"C:\swapfile.sys"))); + assert!(is_pagefile(std::path::Path::new(r"D:\PAGEFILE.SYS"))); + // hiberfil stays listed — it has an actionable switch (关闭休眠). + assert!(!is_pagefile(std::path::Path::new(r"C:\hiberfil.sys"))); + // A file that merely carries the name inside a folder is still shown. + assert!(!is_pagefile(std::path::Path::new( + r"C:\Users\me\pagefile.sys" + ))); + } } diff --git a/crates/squid-engine/src/assets.rs b/crates/squid-engine/src/assets.rs new file mode 100644 index 0000000..2abab57 --- /dev/null +++ b/crates/squid-engine/src/assets.rs @@ -0,0 +1,190 @@ +//! User-asset recognition — the Mole `app_protection` lesson for Windows. +//! +//! Some directories look exactly like caches but hold the user's own work: +//! chat files inside an IM data folder, PWA offline documents in a browser +//! profile's IndexedDB,输入法词库. A broad rule (or an eager user) must never +//! sweep them away, so they are pinned here: the scan lists them as locked, +//! visibly-explained rows, and the delete layer refuses them even when a +//! stale report still claims they are removable. + +use squid_core::{Category, CleanupItem, ItemKind}; +use std::path::Path; + +/// Lower-cased path fragment → human reason. Matching is on the *normalised* +/// (lower-case, `/`→`\`) path so one table covers every drive letter and user. +const ASSET_MARKERS: &[(&str, &str)] = &[ + ( + "\\appdata\\roaming\\texact\\", + "腾讯 QQ 数据目录(聊天记录与文件)", + ), + ( + "\\appdata\\roaming\\tencent\\", + "腾讯通用数据目录(聊天文件与配置)", + ), + ( + "\\documents\\weixin files\\filestorage", + "微信聊天文件与下载文档", + ), + ( + "\\appdata\\roaming\\weixin\\filestorage", + "微信聊天文件与下载文档", + ), + ("\\appdata\\roaming\\txdnd\\", "腾讯游戏数据目录"), + ("\\sogouexplorer\\", "搜狗输入法词库与用户习惯"), + ( + "\\appdata\\roaming\\sogouinput\\", + "搜狗输入法词库与用户习惯", + ), +]; + +/// Browser profile storage that holds PWA / offline web app documents — +/// Mole's `PROTECTED_SW_DOMAINS` equivalent. An `IndexedDB` folder inside a +/// Chromium-family browser profile is user work data (Figma / 剪映网页版 save +/// there), unlike `Cache` which is pure rebuildable bytes. +const CHROMIUM_PROFILE_MARKERS: &[&str] = &[ + "\\microsoft\\edge\\user data\\", + "\\google\\chrome\\user data\\", + "\\chromium\\application\\user data\\", +]; + +fn normalise(path: &Path) -> String { + path.to_string_lossy().to_lowercase().replace('/', "\\") +} + +/// Why this path is untouchable user property, if it is. The note lands in +/// the UI lock chip's explanation, mirroring 电脑管家's "创建者" honesty. +pub fn asset_reason(path: &Path) -> Option<&'static str> { + let lower = normalise(path); + // Deeper profile sub-paths (…\IndexedDB\foo) stay protected too: match + // the marker as a path prefix at a separator boundary. + if lower.contains("\\indexeddb") + && CHROMIUM_PROFILE_MARKERS + .iter() + .any(|marker| lower.starts_with(marker) || lower.contains(marker)) + { + return Some("可能含离线应用数据(Figma / 剪映网页版等工作文件)"); + } + ASSET_MARKERS + .iter() + .find(|(marker, _)| segment_match(&lower, marker)) + .map(|(_, reason)| *reason) +} + +/// True when `marker` appears inside `lower` at path segment boundaries. +/// Markers ending with a separator carry their own trailing boundary, so +/// `TencentGame\cache` must not match `\tencent\`. +fn segment_match(lower: &str, marker: &str) -> bool { + if marker.ends_with('\\') { + return lower.contains(marker); + } + lower.match_indices(marker).any(|(index, _)| { + // A marker that opens with `\` carries its own left boundary; a bare + // marker needs a separator (or drive colon) before it. + let before_ok = index == 0 + || marker.starts_with('\\') + || matches!(lower.as_bytes()[index - 1], b'\\' | b':'); + let after = index + marker.len(); + let after_ok = lower.len() == after || lower.as_bytes().get(after) == Some(&b'\\'); + before_ok && after_ok + }) +} + +/// Asset rows to surface in the 空间清理 list — existence checked, one row +/// per top-level asset. Rows anchor at their own parent: they are display +/// only (locked), and anchoring at the folder itself would make +/// `block_reason` deny the row's own deletion check. +pub fn known_asset_rows() -> Vec { + const SPECS: [(&str, &str); 6] = [ + ( + r"AppData\Roaming\Tencent", + "腾讯(QQ/微信旧版)数据目录(聊天记录与文件)", + ), + ( + r"Documents\WeChat Files", + "微信聊天文件与下载文档(旧版目录)", + ), + ( + r"Documents\Weixin Files\FileStorage", + "微信聊天文件与下载文档", + ), + (r"AppData\Roaming\SogouInput", "搜狗输入法词库与用户习惯"), + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\IndexedDB", + "可能含离线应用数据(Figma / 剪映网页版等工作文件)", + ), + ( + r"AppData\Local\Google\Chrome\User Data\Default\IndexedDB", + "可能含离线应用数据(Figma / 剪映网页版等工作文件)", + ), + ]; + let Ok(home) = std::env::var("USERPROFILE") else { + return Vec::new(); + }; + let home = Path::new(&home); + let mut rows = Vec::new(); + for (tail, reason) in SPECS { + let path = home.join(tail); + if !path.is_dir() { + continue; + } + let label = format!("🔒 {}", asset_label(&path)); + let parent = path + .parent() + .map(|dir| dir.to_path_buf()) + .unwrap_or_else(|| path.clone()); + let item = CleanupItem::new(path, ItemKind::Path, Category::AppCaches, label) + .with_rule("user-assets") + .with_anchors(std::iter::once(parent)) + .locked(squid_core::LockReason::Protected) + .with_note(reason); + rows.push(item); + } + rows +} + +fn asset_label(path: &Path) -> String { + let text = squid_core::paths::pretty(path); + text.rsplit(['\\', '/']) + .next() + .filter(|leaf| !leaf.is_empty()) + .unwrap_or(&text) + .to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + + #[test] + fn im_data_dirs_refuse_deletion_with_a_reason() { + let path = PathBuf::from(r"C:\Users\me\AppData\Roaming\Tencent\WeChat\111\msg"); + let reason = asset_reason(&path).expect("QQ tree must be protected"); + assert!(reason.contains("聊天")); + } + + #[test] + fn wechat_file_storage_is_protected_but_cache_paths_are_not() { + let storage = PathBuf::from(r"D:\Users\me\Documents\Weixin Files\FileStorage\File\2026-01"); + assert!(asset_reason(&storage).is_some()); + let edge_cache = + PathBuf::from(r"C:\Users\me\AppData\Local\Microsoft\Edge\User Data\Default\Cache"); + assert!(asset_reason(&edge_cache).is_none()); + } + + #[test] + fn profile_indexeddb_counts_as_offline_app_data() { + let pwa = PathBuf::from( + r"C:\Users\me\AppData\Local\Microsoft\Edge\User Data\Default\IndexedDB\figma_0.indexeddb.leveldb", + ); + let reason = asset_reason(&pwa).expect("PWA data must be protected"); + assert!(reason.contains("离线应用")); + } + + #[test] + fn markers_match_only_at_segment_boundaries() { + // A folder that merely *starts* with the marker text is not the asset. + let sneaky = PathBuf::from(r"C:\Users\me\AppData\Roaming\TencentGame\cache"); + assert!(asset_reason(&sneaky).is_none()); + } +} diff --git a/crates/squid-engine/src/clean.rs b/crates/squid-engine/src/clean.rs index caba765..657ccd1 100644 --- a/crates/squid-engine/src/clean.rs +++ b/crates/squid-engine/src/clean.rs @@ -172,6 +172,42 @@ pub fn scan( } } + // AI 工具与模型 (E1): local model weights (never pre-checked) plus the + // genuinely disposable Electron/update caches the desktop AI apps keep. + // Always on unless the caller filtered categories down to something else. + let ai_wanted = + options.categories.is_empty() || options.categories.contains(&Category::AiTools); + if ai_wanted { + progress.phase("ai", "collecting local AI models and caches"); + for item in crate::ai::collect(engine, cancel) { + if seen.contains_key(&item.path) { + continue; + } + let mut item = item; + if engine.is_whitelisted(&item.path) { + item = item.locked(LockReason::Whitelisted); + } else if let Some(reason) = engine.block_reason(&item) { + item = item.locked(LockReason::Protected).with_note(reason); + } + seen.insert(item.path.clone(), report.items.len()); + report.items.push(item); + } + } + + // User-asset rows (B4): pinned directories shown as locked, explained + // rows so "why can't I clean my WeChat files?" never becomes a mystery. + let assets_wanted = + options.categories.is_empty() || options.categories.contains(&Category::AppCaches); + if assets_wanted { + for item in crate::assets::known_asset_rows() { + if seen.contains_key(&item.path) { + continue; + } + seen.insert(item.path.clone(), report.items.len()); + report.items.push(item); + } + } + if !options.fast { measure(engine, &mut report, progress, cancel)?; } @@ -201,7 +237,7 @@ fn prepared_rules(engine: &Engine, options: &CleanOptions) -> Vec rules.into_iter().map(PreparedRule::new).collect() } -fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option { +pub fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option { if rule.skip_if_running.is_empty() { return None; } @@ -334,15 +370,42 @@ fn measure( .iter() .map(|item| (item.path.clone(), item.kind)) .collect(); - progress.tick(0, Some(targets.len() as u64), None); + let total = targets.len() as u64; + progress.tick(0, Some(total), None); - let results: Vec = measure_all(&targets, cancel, |index, _info| { - progress.tick( - index as u64 + 1, - Some(targets.len() as u64), - targets.get(index).map(|(path, _)| path.clone()), - ); - }); + // Cumulative counters for the live status line; the callback runs on + // rayon worker threads, hence the mutex. Emissions are throttled to + // ~10/s so the IPC stays a whisper while the walk screams. + let meter = std::sync::Mutex::new((0u64, 0u64, std::time::Instant::now())); + let results: Vec = + measure_all(&targets, cancel, |index, completed, info| { + let emit_line = { + let mut guard = meter + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + guard.0 += info.files; + guard.1 += info.on_disk().as_u64(); + if completed as u64 == total + || guard.2.elapsed() >= std::time::Duration::from_millis(90) + { + guard.2 = std::time::Instant::now(); + Some((guard.0, guard.1)) + } else { + None + } + }; + if let Some((files, bytes)) = emit_line { + progress.publish(Event::Metered { + files, + bytes: Bytes(bytes), + }); + } + progress.tick( + completed as u64, + Some(total), + targets.get(index).map(|(path, _)| path.clone()), + ); + }); if results.len() != report.items.len() { return Err(SquidError::Other( "measurement returned an unexpected number of results".into(), @@ -351,6 +414,17 @@ fn measure( for (item, info) in report.items.iter_mut().zip(results) { item.size = info.logical; item.allocated = info.allocated; + item.file_count = info.files; + // "Untouched for X" is the actionable half of a size figure; derived + // from the newest last-write seen during the walk we just did. + item.last_write_secs = if info.newest_write == 0 { + None + } else { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |since| since.as_secs()); + Some(now.saturating_sub(info.newest_write)) + }; if info.unreadable > 0 && item.note.is_none() { item.note = Some(format!("{} entries unreadable", info.unreadable)); } else if info.files > 0 && item.note.is_none() { diff --git a/crates/squid-engine/src/duplicates.rs b/crates/squid-engine/src/duplicates.rs new file mode 100644 index 0000000..8d226cb --- /dev/null +++ b/crates/squid-engine/src/duplicates.rs @@ -0,0 +1,683 @@ +//! Duplicate-file finder — the MangoDisk lesson, with our safety net. +//! +//! Finding byte-identical files cheaply is a **three-stage funnel**: +//! +//! 1. walk everything, bucket by exact size — a file with a unique size can +//! not have a duplicate, so terabytes drop out for the price of one `stat`; +//! 2. hash a 16 KiB sample from head, middle and tail of every same-size +//! candidate — different files diverge in those windows almost always, so +//! this kills the remaining false candidates with ~48 KiB of I/O each; +//! 3. full-stream SHA-256 only for what survived the sample — the expensive +//! stage runs on a small, pre-filtered set. +//! +//! Results land **group by group while the scan still runs** (a confirmed +//! group is pushed the moment its last file hashes), and every hash is +//! cached on disk keyed by *path + size + mtime*, so re-running the scan on +//! an unchanged disk costs the walk alone. +//! +//! Deletion is deliberately *not* this module's job: confirmed groups are +//! turned into ordinary [`CleanupItem`]s (one per copy, File kind) so the +//! engine's single delete path — safety re-validation, Recycle Bin, undo +//! ledger — guards duplicates exactly like every other byte squid touches. +//! MangoDisk deletes permanently; we do not. + +use crate::assets; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use squid_core::progress::{CancelToken, Event, Progress}; +use squid_core::{Bytes, Category, CleanupItem, ItemKind}; +use std::collections::HashMap; +use std::fs::File; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Files below this size are never offered: deduplicating a 4 KiB config is +/// noise, and the 1 MiB floor keeps the funnel's first stage cheap. +pub const DEFAULT_MIN_SIZE: u64 = 1024 * 1024; +/// Sample window at each of head / middle / tail. +const SAMPLE: usize = 16 * 1024; + +/// One file that survived the walk and is waiting for its hashes. +#[derive(Clone, Debug)] +struct Candidate { + path: PathBuf, + size: u64, + mtime_ms: u64, +} + +/// A confirmed group of byte-identical files. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DupGroup { + pub size: u64, + /// One entry per copy: (pretty path, mtime ms). + pub copies: Vec, + /// Index of the copy the UI should mark 「保留」 by default (shortest + /// path — the "original" almost always lives at the tidier address). + pub keep: usize, + /// True when at least one copy sits in a protected user-asset folder + /// (WeChat FileStorage …): the group is flagged, never auto-selected. + pub personal: bool, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DupCopy { + /// Display spelling (home folded to `~`) for the row. + pub path: String, + pub mtime_ms: u64, + /// Why this copy may not be deleted (asset lock), when it may not. + pub locked: Option, + /// Exact path for the delete layer — serialised only for the app-side + /// cache, never rendered. + #[serde(skip)] + pub raw: PathBuf, +} + +/// Funnel counters streamed as `Metered`-style notes plus the final report. +#[derive(Clone, Debug, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DupStats { + pub walked: u64, + pub same_size: u64, + pub sample_hits: u64, + pub confirmed: u64, + pub wasted: u64, +} + +/// Persisted hash cache: path → (size, mtime, sample hash, full hash). +/// A stale entry (size or mtime moved) is re-measured, so correctness never +/// depends on the cache — only speed does. +mod cache { + use serde::{Deserialize, Serialize}; + use std::collections::HashMap; + use std::path::{Path, PathBuf}; + + #[derive(Default, Serialize, Deserialize)] + pub struct HashCache { + /// key: normalised path (lower-case on Windows) + /// value: (size, mtime_ms, sample_hash_hex, full_hash_hex) + pub entries: HashMap, + } + + impl HashCache { + pub fn path() -> PathBuf { + squid_core::Settings::config_dir().join("hash-cache.json") + } + + pub fn load() -> HashCache { + std::fs::read_to_string(Self::path()) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default() + } + + pub fn save(&self) { + if let Ok(text) = serde_json::to_string(&self) { + let path = Self::path(); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let _ = std::fs::write(path, text); + } + } + + pub fn lookup(&self, key: &Path, size: u64, mtime_ms: u64) -> Option<(&str, &str)> { + let (s, m, sample, full) = self.entries.get(key)?; + (*s == size && *m == mtime_ms).then_some((sample.as_str(), full.as_str())) + } + + pub fn put(&mut self, key: PathBuf, size: u64, mtime_ms: u64, sample: &str, full: &str) { + self.entries + .insert(key, (size, mtime_ms, sample.to_string(), full.to_string())); + } + } + + pub fn key_for(path: &Path) -> PathBuf { + let text = path.to_string_lossy().to_lowercase(); + PathBuf::from(text.replace('/', "\\")) + } +} + +fn mtime_ms(meta: &std::fs::Metadata) -> u64 { + meta.modified() + .or_else(|_| meta.created()) + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +/// Read SAMPLE bytes at each of three offsets and hash the concatenation. +/// Tiny files (size < 3·SAMPLE) simply overlap — same answer, still cheap. +fn sample_digest(file: &mut File, size: u64) -> std::io::Result { + let mut hasher = Sha256::new(); + let window = SAMPLE.min(size as usize); + let third = ((size as i64) - window as i64).max(0) / 2; + for offset in [0i64, third, ((size as i64) - window as i64).max(0)] { + use std::io::Seek; + file.seek(std::io::SeekFrom::Start(offset as u64))?; + let mut buf = vec![0u8; window]; + file.read_exact(&mut buf)?; + hasher.update(&buf); + } + Ok(hex(&hasher.finalize())) +} + +fn full_digest(file: &mut File) -> std::io::Result { + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 256 * 1024]; + loop { + let read = file.read(&mut buf)?; + if read == 0 { + break; + } + hasher.update(&buf[..read]); + } + Ok(hex(&hasher.finalize())) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// Default scan scope: the user's own file areas — home folder (Documents, +/// Desktop, Downloads, Pictures, …) without descending into AppData churn, +/// plus every other fixed drive's user-shaped folders when present. +pub fn default_roots() -> Vec { + let home = squid_core::paths::home_dir(); + let mut roots = vec![home.clone()]; + // Other drives: add their root-level Users / Documents-style containers. + let platform = squid_platform::current(); + if let Ok(volumes) = platform.volumes() { + for volume in volumes { + if volume.is_removable || volume.is_root { + continue; + } + let users = volume.mount_point.join("Users"); + if users.is_dir() { + roots.push(users); + } else if volume.mount_point.is_dir() { + roots.push(volume.mount_point); + } + } + } + roots +} + +/// Skip infrastructure we have no business hashing: OS plumbing, recycle +/// bins, app data internals, and any VCS/package store folder by name. +fn skip_dir(name: &str) -> bool { + const SKIP: &[&str] = &[ + "$recycle.bin", + "system volume information", + "windows", + "program files", + "program files (x86)", + "programdata", + "appdata", + "node_modules", + ".git", + ".hg", + ".svn", + "target", + "__pycache__", + ".venv", + "venv", + ".terraform", + ".gradle", + ".m2", + ".cargo", + "vendor", + ]; + let lower = name.to_lowercase(); + SKIP.iter().any(|wanted| lower == *wanted) +} + +/// Path-subtree exclusions that only matter as a *sequence*: WorkBuddy's +/// `\.workbuddy\workspace\sessions` folders snapshot copies of files the +/// agent was created from, so deduping them would re-offer churn the tool +/// regenerates itself — on whichever volume it happens to live. Matched as +/// consecutive normal path components, case- and drive-independent. +fn excluded_subtree(dir: &Path) -> bool { + const SEGMENTS: [&str; 3] = [".workbuddy", "workspace", "sessions"]; + // Cheap guard: the walk prunes at the `sessions` door, so anything else + // can never match while descending. + if !dir + .file_name() + .is_some_and(|name| name.to_string_lossy().eq_ignore_ascii_case("sessions")) + { + return false; + } + let names: Vec = dir + .components() + .filter_map(|part| match part { + std::path::Component::Normal(name) => Some(name.to_string_lossy().to_lowercase()), + _ => None, + }) + .collect(); + names.len() >= SEGMENTS.len() && names.windows(SEGMENTS.len()).any(|w| w == SEGMENTS) +} + +/// Run the funnel. Groups stream out as `Event::Group { kind: "dup", … }`; +/// the return value is the same data collected, with per-copy locks +/// resolved, so the command layer can hand the frontend a finished list too. +pub fn scan( + roots: &[PathBuf], + min_size: u64, + progress: &Progress, + cancel: &CancelToken, +) -> squid_core::Result { + let min_size = min_size.max(4096); + let mut hash_cache = cache::HashCache::load(); + let walked = AtomicU64::new(0); + + // ── Stage 1: walk, bucket by exact size ────────────────────────────── + progress.phase("duplicates", "第一级 · 按大小分组"); + let mut by_size: HashMap> = HashMap::new(); + { + let mut stack: Vec<(PathBuf, usize)> = roots + .iter() + .filter(|root| root.is_dir()) + .map(|root| (root.clone(), 0usize)) + .collect(); + while let Some((dir, depth)) = stack.pop() { + cancel.check()?; + if depth > 24 { + continue; + } + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + let Ok(file_type) = entry.file_type() else { + continue; + }; + if file_type.is_dir() { + if skip_dir(&entry.file_name().to_string_lossy()) || excluded_subtree(&path) { + continue; + } + stack.push((path, depth + 1)); + continue; + } + if !file_type.is_file() { + continue; + } + let count = walked.fetch_add(1, Ordering::Relaxed) + 1; + if count % 512 == 0 { + progress.publish(Event::Metered { + files: count, + bytes: Bytes(0), + }); + } + let Ok(meta) = entry.metadata() else { + continue; + }; + let size = meta.len(); + if size < min_size { + continue; + } + by_size.entry(size).or_default().push(Candidate { + path, + size, + mtime_ms: mtime_ms(&meta), + }); + } + } + } + let same_size: usize = by_size + .iter() + .filter(|(_, group)| group.len() > 1) + .map(|(_, group)| group.len()) + .sum(); + // Funnel counters ride structured notes the UI parses by prefix: + // `funnel::::`. + progress.publish(Event::Note(format!( + "funnel:{}:{same_size}:0:0", + walked.load(Ordering::Relaxed) + ))); + + // ── Stage 2: head/middle/tail sample hash ──────────────────────────── + progress.phase("duplicates", "第二级 · 头中尾采样哈希"); + let mut by_sample: HashMap<(u64, String), Vec> = HashMap::new(); + let mut sample_seen = 0u64; + for (_, group) in by_size.drain() { + if group.len() < 2 { + continue; + } + for candidate in group { + cancel.check()?; + sample_seen += 1; + progress.publish(Event::Tick { + done: sample_seen, + total: Some(same_size as u64), + subject: Some(candidate.path.clone()), + }); + let key = cache::key_for(&candidate.path); + let mut file = match File::open(&candidate.path) { + Ok(file) => file, + Err(_) => continue, + }; + let digest = match hash_cache.lookup(&key, candidate.size, candidate.mtime_ms) { + Some((sample, _full)) => sample.to_string(), + None => match sample_digest(&mut file, candidate.size) { + Ok(digest) => digest, + Err(_) => continue, + }, + }; + by_sample + .entry((candidate.size, digest)) + .or_default() + .push(candidate); + } + } + let sample_hits: usize = by_sample + .iter() + .filter(|(_, group)| group.len() > 1) + .map(|(_, group)| group.len()) + .sum(); + progress.publish(Event::Note(format!( + "funnel:{}:{same_size}:{sample_hits}:0", + walked.load(Ordering::Relaxed) + ))); + + // ── Stage 3: full hash on the survivors ────────────────────────────── + progress.phase("duplicates", "第三级 · 全量校验确认"); + let mut report = DupReport::default(); + let mut confirmed_seen = 0u64; + let groups: Vec<((u64, String), Vec)> = by_sample + .drain() + .filter(|(_, group)| group.len() > 1) + .collect(); + let total_full: u64 = groups.iter().map(|(_, group)| group.len() as u64).sum(); + for ((size, sample), group) in groups { + let mut by_full: HashMap> = HashMap::new(); + for candidate in group { + cancel.check()?; + confirmed_seen += 1; + progress.publish(Event::Tick { + done: confirmed_seen, + total: Some(total_full), + subject: Some(candidate.path.clone()), + }); + let key = cache::key_for(&candidate.path); + let digest = match hash_cache.lookup(&key, size, candidate.mtime_ms) { + Some((_sample, full)) => full.to_string(), + None => { + let Ok(mut file) = File::open(&candidate.path) else { + continue; + }; + // The sample matched; if the cache was cold this file was + // just read for the sample, so re-opening it is the price + // of a stateless cache layout. + match full_digest(&mut file) { + Ok(digest) => { + hash_cache.put(key.clone(), size, candidate.mtime_ms, &sample, &digest); + digest + } + Err(_) => continue, + } + } + }; + by_full.entry(digest).or_default().push(candidate); + } + for (_, copies) in by_full { + if copies.len() < 2 { + continue; + } + let group = build_group(size, &copies); + report.wasted += (copies.len() as u64 - 1) * size; + report.confirmed_groups += 1; + report.confirmed_files += copies.len() as u64; + progress.publish(Event::Group { + kind: "dup", + payload: serde_json::to_value(&group).unwrap_or_default(), + }); + report.groups.push(group); + } + } + // Persist the cold-half of the work so the next scan is a walk only. + // Keep the file bounded: half of it is dropped when it outgrows 600k + // entries (a few tens of MB of JSON is already generous). + if hash_cache.entries.len() > 600_000 { + let keep = hash_cache.entries.len() / 2; + let keys: Vec = hash_cache.entries.keys().skip(keep).cloned().collect(); + for key in keys { + hash_cache.entries.remove(&key); + } + } + hash_cache.save(); + report.walked = walked.load(Ordering::Relaxed); + report.same_size = same_size as u64; + report.sample_hits = sample_hits as u64; + report + .groups + .sort_by_key(|group| std::cmp::Reverse(group.size * (group.copies.len() as u64 - 1))); + progress.publish(Event::Note(format!( + "funnel:{}:{same_size}:{sample_hits}:{}", + report.walked, report.confirmed_files + ))); + Ok(report) +} + +/// Shape one confirmed group for the UI: keep-shortest-path, asset locks. +fn build_group(size: u64, copies: &[Candidate]) -> DupGroup { + let mut ordered: Vec<&Candidate> = copies.iter().collect(); + // Shortest path wins the 「保留」 chip; ties fall back to oldest mtime + // (the copy that has been there longest is the least likely accident). + ordered.sort_by(|a, b| { + a.path + .components() + .count() + .cmp(&b.path.components().count()) + .then(a.mtime_ms.cmp(&b.mtime_ms)) + .then(a.path.cmp(&b.path)) + }); + let mut personal = false; + let copies = ordered + .iter() + .map(|candidate| { + let locked = assets::asset_reason(&candidate.path).map(str::to_string); + if locked.is_some() { + personal = true; + } + DupCopy { + path: squid_core::paths::pretty(&candidate.path), + mtime_ms: candidate.mtime_ms, + locked, + raw: candidate.path.clone(), + } + }) + .collect(); + DupGroup { + size, + copies, + keep: 0, + personal, + } +} + +impl DupReport { + /// Flatten the user's deletion picks into engine items: one File item per + /// chosen copy. `selections` is (group index, copy indexes to delete) — + /// the keep decision belongs to the UI, this layer only executes what was + /// confirmed identical and explicitly picked. + pub fn items_for(&self, selections: &[(usize, Vec)]) -> Vec { + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + let mut items = Vec::new(); + for (group_index, copies) in selections { + let Some(group) = self.groups.get(*group_index) else { + continue; + }; + for copy_index in copies { + let Some(copy) = group.copies.get(*copy_index) else { + continue; + }; + if group.copies.len() <= 1 || copy.locked.is_some() { + continue; + } + let path = copy.raw.clone(); + // Anchor two levels up: the safety policy demands the target + // sit *strictly below* an anchor (depth ≥ 1), and the file's + // own parent would place it at depth 0. + let anchor = path + .ancestors() + .nth(2) + .map(|dir| dir.to_path_buf()) + .unwrap_or_else(|| PathBuf::from("/")); + let mut item = CleanupItem::new( + path.clone(), + ItemKind::File, + Category::Duplicates, + path.file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + ) + .with_rule("duplicates") + .with_anchors(std::iter::once(anchor)) + .with_note(format!("{} 份相同 · 已全量校验一致", group.copies.len())); + item.size = Bytes(group.size); + item.allocated = Bytes(group.size); + item.file_count = 1; + item.last_write_secs = Some(now_ms.saturating_sub(copy.mtime_ms) / 1000); + item.evidence = vec![format!("record:sha256:{}", group.size)]; + items.push(item); + } + } + items + } +} + +/// Everything a finished scan says: the groups plus the funnel counters the +/// UI prints under its title. +#[derive(Clone, Debug, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DupReport { + pub groups: Vec, + pub walked: u64, + pub same_size: u64, + pub sample_hits: u64, + pub confirmed_groups: u64, + pub confirmed_files: u64, + pub wasted: u64, +} + +#[cfg(test)] +mod tests { + use super::*; + use squid_core::progress::Progress; + + fn scratch(tag: &str) -> Option { + // Keep test hashes out of the real config-dir cache file. + static STATE: std::sync::Once = std::sync::Once::new(); + STATE.call_once(|| { + let dir = std::env::temp_dir().join(format!("squid-dups-state-{}", std::process::id())); + if std::fs::create_dir_all(&dir).is_ok() { + std::env::set_var("SQUID_STATE_DIR", &dir); + } + }); + let dir = std::env::temp_dir().join(format!( + "squid-dups-{}-{tag}-{}", + std::process::id(), + squid_core::ledger::new_session_id() + )); + match std::fs::create_dir_all(&dir) { + Ok(()) => Some(dir), + Err(error) => { + eprintln!("skipping: scratch denied ({error})"); + None + } + } + } + + #[cfg(windows)] + #[test] + fn workbuddy_session_snapshots_are_never_walked() { + assert!(excluded_subtree(Path::new( + r"C:\.workbuddy\workspace\sessions" + ))); + assert!(excluded_subtree(Path::new( + r"D:\Work\.WorkBuddy\Workspace\Sessions" + ))); + assert!(!excluded_subtree(Path::new( + r"C:\Users\dev\workspace\sessions" + ))); + assert!(!excluded_subtree(Path::new( + r"C:\.workbuddy\workspace\sessions-notes" + ))); + } + + #[test] + fn identical_files_land_in_one_group_with_the_neat_copy_kept() { + let Some(root) = scratch("same") else { return }; + let payload = vec![7u8; 2 * 1024 * 1024]; + let deep = root.join("a").join("b").join("c"); + std::fs::create_dir_all(&deep).unwrap(); + std::fs::write(root.join("copy.bin"), &payload).unwrap(); + std::fs::write(deep.join("copy.bin"), &payload).unwrap(); + std::fs::write(root.join("other.bin"), vec![9u8; payload.len()]).unwrap(); + + let progress = Progress::new(); + let report = scan( + std::slice::from_ref(&root), + 1024 * 1024, + &progress, + &CancelToken::new(), + ) + .expect("scan"); + assert_eq!(report.groups.len(), 1, "{:?}", report.groups); + let group = &report.groups[0]; + assert_eq!(group.copies.len(), 2); + // keep = shortest path: the root-level copy wins the chip. + assert!(!group.copies[group.keep].path.contains("b\\c")); + assert_eq!(report.confirmed_files, 2); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn same_size_different_bytes_never_matches() { + // The whole point of stage 2/3: two same-size files differing only in + // the middle byte past the head sample window. + let Some(root) = scratch("diff") else { return }; + let a = vec![3u8; 200_000]; + let mut b = vec![3u8; 200_000]; + b[100_001] = 4; + std::fs::write(root.join("a.bin"), &a).unwrap(); + std::fs::write(root.join("b.bin"), &b).unwrap(); + drop(a); + drop(b); + let progress = Progress::new(); + let report = scan( + std::slice::from_ref(&root), + 1024, + &progress, + &CancelToken::new(), + ) + .expect("scan"); + assert!(report.groups.is_empty(), "{:?}", report.groups); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn tiny_files_are_not_offered_at_all() { + let Some(root) = scratch("tiny") else { return }; + std::fs::write(root.join("one.txt"), b"same").unwrap(); + std::fs::write(root.join("two.txt"), b"same").unwrap(); + let progress = Progress::new(); + let report = scan( + std::slice::from_ref(&root), + DEFAULT_MIN_SIZE, + &progress, + &CancelToken::new(), + ) + .expect("scan"); + assert_eq!(report.walked, 2); + assert_eq!(report.same_size, 0); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/crates/squid-engine/src/insights.rs b/crates/squid-engine/src/insights.rs new file mode 100644 index 0000000..e2a9288 --- /dev/null +++ b/crates/squid-engine/src/insights.rs @@ -0,0 +1,197 @@ +//! Hidden-space insights (Mole's `cmd/analyze` overview idiom). +//! +//! The disk analyzer answers "what is big"; this answers "what is big *and* +//! actionable" — curated Windows space hogs with a one-line explanation and +//! the action that actually frees them. Existence-gated: a row appears only +//! when the underlying path (or state) is really on this machine. + +use serde::Serialize; +use squid_core::fs; +use std::path::{Path, PathBuf}; + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Insight { + /// Stable id for the UI (icon/translation lookup). + pub id: String, + pub title: String, + pub path: String, + pub size: u64, + /// "cleanable" — 空间清理 covers it; "command" — needs the given command; + /// "external" — system tool territory; "info" — informational. + pub action: String, + /// Command to run (elevated) when action == "command". + pub command: Option, + pub hint: String, +} + +fn home() -> Option { + std::env::var("USERPROFILE") + .ok() + .map(PathBuf::from) + .filter(|path| path.is_dir()) +} + +fn dir_size(path: &Path) -> u64 { + if !path.is_dir() { + return 0; + } + fs::measure(path, squid_core::ItemKind::Path) + .on_disk() + .as_u64() +} + +fn file_size(path: &Path) -> u64 { + std::fs::metadata(path).map_or(0, |meta| meta.len()) +} + +/// All insights that currently exist on this machine, biggest-effect first +/// ordering is left to the UI. +pub fn collect() -> Vec { + let mut out = Vec::new(); + let Some(home) = home() else { + return out; + }; + let system = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into()); + let system = PathBuf::from(system); + + // 1. Windows Update download cache — the classic 5-20 GB surprise. + let updates = system.join(r"SoftwareDistribution\Download"); + let size = dir_size(&updates); + if size > 256 * 1024 * 1024 { + out.push(Insight { + id: "update-cache".into(), + title: "Windows 更新缓存".into(), + path: updates.display().to_string(), + size, + action: "cleanable".into(), + command: None, + hint: "已安装的更新包,Windows 需要时会重新下载;空间清理的「系统垃圾」覆盖此目录" + .into(), + }); + } + + // 2. Hibernation file — freed by turning hibernation off. + let hiber = system.join("..\\hiberfil.sys"); + let size = file_size(&hiber); + if size > 0 { + out.push(Insight { + id: "hiberfil".into(), + title: "休眠文件 hiberfil.sys".into(), + path: hiber.display().to_string(), + size, + action: "command".into(), + command: Some("powercfg /h off".into()), + hint: "关闭休眠后系统自动删除;睡眠不受影响".into(), + }); + } + + // 3. Pagefile — visible but rarely worth touching; info only. + let page = system.join("..\\pagefile.sys"); + let size = file_size(&page); + if size > 0 { + out.push(Insight { + id: "pagefile".into(), + title: "虚拟内存 pagefile.sys".into(), + path: page.display().to_string(), + size, + action: "info".into(), + command: None, + hint: "系统正在使用的虚拟内存,不建议手动删除;可在系统设置改到别的盘".into(), + }); + } + + // 4. Component store (WinSxS) — needs DISM, never raw deletion. + // Walking 100k+ files just to print a number is not worth it here; + // the UI shows "several GB" and the DISM command does the rest. + let winsxs = system.join("WinSxS"); + if winsxs.is_dir() { + out.push(Insight { + id: "winsxs".into(), + title: "组件存储 WinSxS".into(), + path: winsxs.display().to_string(), + size: 0, + action: "command".into(), + command: Some("Dism.exe /online /Cleanup-Image /StartComponentCleanup".into()), + hint: "系统组件仓库,通常 5~10 GB;只能由 DISM 收缩,直接删会破坏系统".into(), + }); + } + + // 5. Phone backups (Apple MobileSync / third-party Android tools). + for (tail, title) in [ + (r"Apple\MobileSync\Backup", "iPhone 备份"), + (r"Apple Computer\MobileSync\Backup", "iPhone 备份"), + ] { + let backups = home.join(tail); + let size = dir_size(&backups); + if size > 256 * 1024 * 1024 { + out.push(Insight { + id: "phone-backup".into(), + title: title.into(), + path: backups.display().to_string(), + size, + action: "external".into(), + command: None, + hint: "整机备份体积大;确认 iCloud 或新备份完成后,在 iTunes/Finder 里删除旧备份" + .into(), + }); + break; + } + } + + // 6. Downloads older than 90 days (Mole's "Old Downloads" insight). + let downloads = home.join("Downloads"); + if downloads.is_dir() { + let cutoff = std::time::SystemTime::now() - std::time::Duration::from_secs(90 * 24 * 3600); + let mut size = 0u64; + let mut stale = 0usize; + if let Ok(entries) = std::fs::read_dir(&downloads) { + for entry in entries.flatten() { + let meta = match entry.metadata() { + Ok(meta) => meta, + Err(_) => continue, + }; + let modified = meta.modified().unwrap_or(std::time::UNIX_EPOCH); + if modified < cutoff { + size += if meta.is_dir() { + dir_size(&entry.path()) + } else { + meta.len() + }; + stale += 1; + } + } + } + if size > 256 * 1024 * 1024 { + out.push(Insight { + id: "old-downloads".into(), + title: "下载文件夹(90 天以上)".into(), + path: downloads.display().to_string(), + size, + action: "external".into(), + command: None, + hint: format!("{stale} 个条目三个月没动过;确认不再需要后手动清理"), + }); + } + } + + out.sort_by_key(|row| std::cmp::Reverse(row.size)); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn collect_never_panics_on_a_live_machine() { + // Pure smoke: whatever exists, ids are unique and sizes sane. + let rows = collect(); + for (index, row) in rows.iter().enumerate() { + assert!(!row.id.is_empty()); + assert!(!rows[..index] + .iter() + .any(|earlier| earlier.id == row.id && row.id != "phone-backup")); + } + } +} diff --git a/crates/squid-engine/src/lib.rs b/crates/squid-engine/src/lib.rs index 63a24a8..88ac8a3 100644 --- a/crates/squid-engine/src/lib.rs +++ b/crates/squid-engine/src/lib.rs @@ -11,16 +11,23 @@ //! Engines never call `std::fs::remove_*` directly; that keeps the audit trail //! and the safety net impossible to bypass. +pub mod ai; pub mod analyze; +pub mod assets; pub mod clean; pub mod delete; +pub mod duplicates; +pub mod insights; +pub mod maintenance; +pub mod privacy; pub mod purge; +pub mod tweaks; pub mod uninstall; pub mod updates; use globset::GlobMatcher; use squid_core::settings::Settings; -use squid_core::{CleanupItem, SafetyPolicy}; +use squid_core::{CleanupItem, SafetyPolicy, ScanReport}; use squid_platform::Platform; use squid_rules::RuleSet; use std::path::Path; @@ -80,6 +87,15 @@ impl Engine { self.platform.as_ref() } + /// An engine whose safety policy lets an unprivileged run reach files + /// on any existing volume. Built for the duplicate-file delete path: + /// byte-confirmed copies of the user's own files, deleted to the + /// recycle bin, everywhere the scan looked. All other guardrails stay. + pub fn with_volume_wide_safety(mut self) -> Engine { + self.safety = self.safety.clone().with_all_volumes(); + self + } + pub fn settings(&self) -> &Settings { &self.settings } @@ -121,6 +137,13 @@ impl Engine { /// Why this item cannot be deleted, if it cannot. Rules pass the anchor they /// declared; everything else falls back to the default anchors. pub fn block_reason(&self, item: &CleanupItem) -> Option { + // Mole's lesson: some directories *look* like caches but hold the + // user's own work — chat files, PWA offline data, IME dictionaries. + // They are refused even when a broad rule matched them, with the + // reason shown verbatim in the UI lock chip. + if let Some(reason) = crate::assets::asset_reason(&item.path) { + return Some(reason.to_string()); + } let anchors = if item.anchors.is_empty() { squid_core::fs::default_anchors() } else { @@ -131,6 +154,107 @@ impl Engine { } self.safety.denies(&item.path, &anchors) } + + /// Mole's "re-verify at the last second" made visible: re-run every + /// deletion gate against the *current* item set and report what changed + /// since the scan. The confirm dialog shows the summary, so surprises + /// ("your app just started, we dropped 3 items") appear before the run, + /// not inside the results. + pub fn preflight(&self, report: &ScanReport, indexes: &[usize]) -> Preflight { + let running = self.platform().running_executables(); + let mut out = Preflight { + checked: indexes.len(), + blocked: Vec::new(), + }; + for &index in indexes { + let Some(item) = report.items.get(index) else { + continue; + }; + if item.lock.is_some() { + continue; + } + if let Some(reason) = self.block_reason(item) { + out.blocked.push((item.display_path(), reason)); + continue; + } + if let Some(path) = gone_path(item) { + out.blocked.push(( + item.display_path(), + format!("{} 已不存在", squid_core::paths::pretty(&path)), + )); + } + } + // Apps started since the scan: re-check running conflicts per rule. + for (index, item) in report.items.iter().enumerate() { + if item.lock.is_some() || !indexes.contains(&index) { + continue; + } + if let Some(rule) = self + .rules() + .rules() + .iter() + .find(|rule| rule.id == item.rule_id) + { + if let Some(conflict) = crate::clean::rule_running_conflict(rule, &running) { + if !out + .blocked + .iter() + .any(|(path, _)| *path == item.display_path()) + { + out.blocked.push((item.display_path(), conflict)); + } + } + } + } + out + } + + /// Which whitelist patterns actually *do something* (Mole's #458: a + /// protection line nobody ever hits is a fake protection). A pattern is + /// "live" when it matches a path the current rule set finds on this + /// machine — the user learns their glob protects a real thing, or that + /// it protects nothing at all. + pub fn audit_whitelist(&self) -> Vec<(String, bool)> { + let known: Vec = self + .rules() + .rules() + .iter() + .filter(|rule| rule.applies_to_current_os()) + .flat_map(|rule| { + squid_rules::PreparedRule::new((*rule).clone()) + .matches() + .into_iter() + .map(|matched| matched.path) + }) + .collect(); + // Same expansion the delete layer uses (settings.whitelist_matchers + // shape), rebuilt per pattern so an invalid line cannot shift the + // index pairing — the audit answers "does THIS pattern protect + // anything". + self.settings + .whitelist + .iter() + .map(|pattern| { + let live = Settings::whitelist_matcher_for(pattern).is_some_and(|matcher| { + known.iter().any(|path| matcher.is_match(path.as_path())) + }); + (pattern.clone(), live) + }) + .collect() + } +} + +/// Result of [`Engine::preflight`]. +#[derive(Clone, Debug, Default)] +pub struct Preflight { + pub checked: usize, + /// (display path, reason) for items that can no longer be deleted. + pub blocked: Vec<(String, String)>, +} + +fn gone_path(item: &squid_core::CleanupItem) -> Option { + (!item.path.exists() && !std::fs::symlink_metadata(&item.path).is_ok()) + .then(|| item.path.clone()) } /// True when the process may touch system-owned paths. diff --git a/crates/squid-engine/src/maintenance.rs b/crates/squid-engine/src/maintenance.rs new file mode 100644 index 0000000..8ff14f1 --- /dev/null +++ b/crates/squid-engine/src/maintenance.rs @@ -0,0 +1,443 @@ +//! 系统维护 (system maintenance) — one-click repairs for the everyday +//! Windows complaints: search won't open, icons are wrong, the network is +//! flaky, an update keeps failing, sound died. +//! +//! The whole feature is a **controlled whitelist**: the UI can only ever +//! name one of these ids, and every command is `program + fixed argv` — +//! never a shell string, never user input. That is the difference between +//! "rebuild the icon cache" and `cmd /c `. Each +//! task carries its real cost (budget seconds) and an elevation need so the +//! UI can be honest before the user clicks. +//! +//! Output is streamed as it arrives (live progress beats a frozen spinner), +//! and the per-task budget kills a runaway command instead of hanging the +//! app — SFC /scannow genuinely takes fifteen minutes. + +use serde::Serialize; +use squid_core::progress::{CancelToken, Event, Progress}; + +/// One repair the whitelist knows about. Commands run top to bottom; any +/// step that needs administrator rights is flagged so the runner can route +/// it through the elevation broker instead of failing on a locked key. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MaintenanceTask { + pub id: &'static str, + pub title_en: &'static str, + pub title_zh: &'static str, + pub detail_en: &'static str, + pub detail_zh: &'static str, + /// "safe" | "admin" | "slow" — drives the UI risk chip. + pub risk: &'static str, + /// Wall-clock budget in seconds; the runner kills past this. + pub budget_secs: u64, + /// Human estimate shown before the run ("约 2–5 分钟"). + pub estimate: &'static str, +} + +/// argv for one command in a task: (program, args, needs-elevation). +/// One pseudo-program exists: `delete-file` removes the named file through +/// std::fs directly — no shell glob, no quoting question. +type Command = (&'static str, &'static [&'static str], bool); + +fn commands(id: &str) -> Option> { + Some(match id { + "search-index" => vec![ + ("net.exe", &["stop", "WSearch"], true), + ( + "delete-file", + &[r"%PROGRAMDATA%\Microsoft\Search\Data\Applications\Windows\Windows.edb"], + false, + ), + ("net.exe", &["start", "WSearch"], true), + ], + "icon-cache" => vec![ + ("ie4uinit.exe", &["-ClearIconCache"], false), + ("taskkill.exe", &["/F", "/IM", "explorer.exe"], false), + ("cmd.exe", &["/C", "start", "", "explorer.exe"], false), + ], + "network-reset" => vec![ + ("netsh.exe", &["winsock", "reset"], true), + ("ipconfig.exe", &["/flushdns"], true), + ("ipconfig.exe", &["/registerdns"], true), + ], + "sfc-dism" => vec![ + ( + "DISM.exe", + &["/Online", "/Cleanup-Image", "/RestoreHealth"], + true, + ), + ("sfc.exe", &["/scannow"], true), + ], + "windows-update" => vec![ + ("net.exe", &["stop", "wuauserv"], true), + ("net.exe", &["stop", "bits"], true), + ( + "cmd.exe", + &[ + "/C", + "del", + "/Q", + "/F", + r"%SystemRoot%\SoftwareDistribution\Download\*.*", + ], + true, + ), + ("net.exe", &["start", "bits"], true), + ("net.exe", &["start", "wuauserv"], true), + ], + "audio-restart" => vec![ + ("net.exe", &["stop", "Audiosrv"], true), + ("net.exe", &["stop", "AudioEndpointBuilder"], true), + ("net.exe", &["start", "AudioEndpointBuilder"], true), + ("net.exe", &["start", "Audiosrv"], true), + ], + _ => return None, + }) +} + +/// The catalog the UI lists. Order matters: cheap and safe first, the long +/// SFC/DISM repair last so nobody starts with the fifteen-minute job. +pub fn tasks() -> Vec { + vec![ + MaintenanceTask { + id: "search-index", + title_en: "Rebuild the search index", + title_zh: "重建搜索索引", + detail_en: "Start menu / Explorer search returns nothing or is stale", + detail_zh: "开始菜单 / 资源管理器搜索没结果、结果不更新", + risk: "admin", + budget_secs: 120, + estimate: "约 1–2 分钟", + }, + MaintenanceTask { + id: "icon-cache", + title_en: "Rebuild the icon cache", + title_zh: "重建图标缓存", + detail_en: "Shortcuts show blank or wrong icons", + detail_zh: "快捷方式图标变白块、显示错乱(会重启 Explorer)", + risk: "safe", + budget_secs: 30, + estimate: "约 10 秒 · 需重启 Explorer", + }, + MaintenanceTask { + id: "network-reset", + title_en: "Reset the network stack + flush DNS", + title_zh: "重置网络栈 + 刷新 DNS", + detail_en: "Connected but pages fail; DNS resolves wrong", + detail_zh: "能连上但打不开网页、DNS 解析异常(会短暂断网重连)", + risk: "admin", + budget_secs: 30, + estimate: "约 5 秒", + }, + MaintenanceTask { + id: "audio-restart", + title_en: "Restart the audio services", + title_zh: "重启音频服务", + detail_en: "No sound, or headphone switching stopped working", + detail_zh: "突然没声音、耳机切换失效", + risk: "admin", + budget_secs: 30, + estimate: "约 3 秒", + }, + MaintenanceTask { + id: "windows-update", + title_en: "Reset Windows Update components", + title_zh: "Windows 更新组件重置", + detail_en: "Updates keep failing or stuck downloading", + detail_zh: "更新反复失败 / 卡在下载(会停 wuauserv 再清 SoftwareDistribution)", + risk: "admin", + budget_secs: 90, + estimate: "约 30 秒", + }, + MaintenanceTask { + id: "sfc-dism", + title_en: "System file repair (SFC + DISM)", + title_zh: "系统文件修复(SFC + DISM)", + detail_en: "Suspected system file corruption, random crashes", + detail_zh: "疑似系统文件损坏、频繁蓝屏后自检", + risk: "slow", + budget_secs: 1_800, + estimate: "约 15 分钟", + }, + ] +} + +pub fn find(id: &str) -> Option { + tasks().into_iter().find(|task| task.id == id) +} + +/// Result of a maintenance run: every command's exit, plus the tail of +/// combined output so the UI can show what actually happened. +#[derive(Clone, Debug, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MaintenanceResult { + pub task: String, + pub ok: bool, + pub steps: Vec, + pub failed_step: Option, + pub output_tail: String, + pub duration_ms: u64, +} + +#[cfg(windows)] +mod run { + use super::*; + use std::io::Read; + use std::os::windows::process::CommandExt; + use std::process::{Child, Stdio}; + + fn quote_ps(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) + } + + /// Expand the few `%VAR%` tokens our catalog uses; we never hand a raw + /// string to a shell, so only these need resolving. + fn expand_env(arg: &str) -> String { + let mut out = arg.to_string(); + for (key, value) in [ + ("%PROGRAMDATA%", std::env::var("PROGRAMDATA").ok()), + ("%SystemRoot%", std::env::var("SystemRoot").ok()), + ] { + if let Some(value) = value { + out = out.replace(key, &value); + } + } + out + } + + fn spawn(program: &str, args: &[String]) -> std::io::Result { + std::process::Command::new(program) + .args(args) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .creation_flags(0x0800_0000) // CREATE_NO_WINDOW + .spawn() + } + + /// Run one command elevated through the PowerShell broker; a cancelled + /// UAC prompt is an honest failure, not a crash. + fn run_elevated(program: &str, args: &[String]) -> Result<(), String> { + let arglist = args + .iter() + .map(|arg| quote_ps(arg)) + .collect::>() + .join(","); + let script = format!( + "$ErrorActionPreference='SilentlyContinue'; Start-Process -FilePath {} -ArgumentList {} -Verb RunAs -WindowStyle Hidden -Wait", + quote_ps(program), + arglist + ); + let status = std::process::Command::new("powershell.exe") + .args(["-NoProfile", "-NonInteractive", "-Command", &script]) + .creation_flags(0x0800_0000) + .status() + .map_err(|error| format!("无法启动提权助手:{error}"))?; + if status.success() { + Ok(()) + } else { + Err("管理员授权被取消或命令失败".into()) + } + } + + /// Wait for a direct child with a wall-clock budget, streaming its + /// combined output into `progress`. Returns (ok, output tail). + fn wait_streamed( + mut child: Child, + budget: std::time::Duration, + progress: &Progress, + cancel: &CancelToken, + ) -> (bool, String) { + let stdout = child.stdout.take(); + let stderr = child.stderr.take(); + let (tx, rx) = crossbeam_channel::unbounded::(); + let mut readers = Vec::new(); + let mut streams: Vec> = Vec::new(); + if let Some(stream) = stdout { + streams.push(Box::new(stream)); + } + if let Some(stream) = stderr { + streams.push(Box::new(stream)); + } + for stream in streams { + let tx = tx.clone(); + readers.push(std::thread::spawn(move || { + let mut reader = std::io::BufReader::new(stream); + let mut buf = [0u8; 4096]; + loop { + match reader.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => { + for line in String::from_utf8_lossy(&buf[..n]).lines() { + let trimmed = line.trim(); + if !trimmed.is_empty() { + let _ = tx.send(trimmed.to_string()); + } + } + } + } + } + })); + } + drop(tx); + let started = std::time::Instant::now(); + let mut tail: Vec = Vec::new(); + loop { + while let Ok(line) = rx.try_recv() { + tail.push(line.clone()); + if tail.len() > 200 { + tail.remove(0); + } + progress.note(line); + } + match child.try_wait() { + Ok(Some(status)) => { + // Drain whatever the readers queued before EOF. + while let Ok(line) = rx.try_recv() { + tail.push(line); + } + for reader in readers { + let _ = reader.join(); + } + return (status.success(), tail.join("\n")); + } + Ok(None) => { + if started.elapsed() > budget || cancel.is_cancelled() { + let _ = child.kill(); + let _ = child.wait(); + return (false, format!("超时或已取消(预算 {}s)", budget.as_secs())); + } + std::thread::sleep(std::time::Duration::from_millis(120)); + } + Err(_) => return (false, "无法读取命令状态".into()), + } + } + } + + pub fn run( + id: &str, + progress: &Progress, + cancel: &CancelToken, + ) -> squid_core::Result { + let task = find(id) + .ok_or_else(|| squid_core::SquidError::Other(format!("未知的维护任务:{id}")))?; + let commands = commands(id).unwrap_or_default(); + let budget_each = std::time::Duration::from_secs(task.budget_secs); + let started = std::time::Instant::now(); + let mut result = MaintenanceResult { + task: id.to_string(), + ok: true, + ..Default::default() + }; + let total = commands.len() as u64; + for (index, (program, args, elevated)) in commands.into_iter().enumerate() { + cancel.check()?; + progress.publish(Event::Tick { + done: index as u64, + total: Some(total), + subject: Some(std::path::PathBuf::from(format!( + "{program} {}", + args.join(" ") + ))), + }); + let expanded: Vec = args.iter().map(|arg| expand_env(arg)).collect(); + let label = format!("{program} {}", args.join(" ")); + let (ok, output) = if program == "delete-file" { + // Direct removal, no shell: the whitelist catalog is the + // only thing that can name a path here. + let path = std::path::PathBuf::from(&expanded[0]); + if !path.exists() { + (true, String::new()) + } else { + match std::fs::remove_file(&path) { + Ok(()) => (true, String::new()), + Err(error) => (false, format!("删除 {} 失败:{error}", path.display())), + } + } + } else if elevated { + match run_elevated(program, &expanded) { + Ok(()) => (true, String::new()), + Err(error) => (false, error), + } + } else { + match spawn(program, &expanded) { + Ok(child) => wait_streamed(child, budget_each, progress, cancel), + Err(error) => (false, format!("无法启动 {program}:{error}")), + } + }; + result + .steps + .push(format!("{label} — {}", if ok { "完成" } else { "失败" })); + if !output.is_empty() { + result.output_tail = output; + } + if !ok { + result.ok = false; + result.failed_step = Some(label); + break; + } + } + result.duration_ms = started.elapsed().as_millis() as u64; + Ok(result) + } +} + +#[cfg(not(windows))] +mod run { + use super::*; + pub fn run( + id: &str, + _progress: &Progress, + _cancel: &CancelToken, + ) -> squid_core::Result { + Ok(MaintenanceResult { + task: id.to_string(), + ok: false, + failed_step: Some("这些维护命令仅在 Windows 提供".into()), + ..Default::default() + }) + } +} + +pub fn run( + id: &str, + progress: &Progress, + cancel: &CancelToken, +) -> squid_core::Result { + run::run(id, progress, cancel) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_listed_task_has_a_command_list() { + for task in tasks() { + let commands = commands(task.id); + assert!(commands.is_some(), "{} has no commands", task.id); + assert!(!commands.unwrap().is_empty(), "{} is empty", task.id); + assert!(task.budget_secs > 0); + assert!(!task.estimate.is_empty()); + } + } + + #[test] + fn the_whitelist_rejects_unknown_ids() { + assert!(commands("rm -rf /").is_none()); + assert!(find("delete-my-boot").is_none()); + assert_eq!(tasks().len(), 6); + } + + #[test] + fn slow_jobs_come_last_and_carry_the_biggest_budget() { + let list = tasks(); + let last = list.last().expect("tasks"); + assert_eq!(last.id, "sfc-dism"); + assert!(list.iter().all(|task| task.budget_secs <= last.budget_secs)); + for task in &list { + // Nothing outside the six known ids sneaks into the catalog. + assert!(commands(task.id).is_some()); + } + } +} diff --git a/crates/squid-engine/src/privacy.rs b/crates/squid-engine/src/privacy.rs new file mode 100644 index 0000000..34f4576 --- /dev/null +++ b/crates/squid-engine/src/privacy.rs @@ -0,0 +1,255 @@ +//! 隐私清理 (privacy cleaning) — the traces page. +//! +//! Different from every other engine on purpose: these deletions do **not** +//! go to the Recycle Bin. A browser profile half-restored from the bin is +//! worse than no restore at all (Chrome refuses profiles whose History file +//! was swapped behind its back), so the honest answer is: gone is gone, but +//! *what* was gone is written to the same history ledger, and the browser +//! lock check happens at scan time — an open browser shows a 🔒 chip instead +//! of silently failing mid-delete. + +use squid_core::progress::CancelToken; +use squid_core::{Bytes, Category, CleanupItem, ItemKind, LockReason}; +use std::path::PathBuf; + +/// One privacy target: display copy, the paths it wipes, and the process +/// that must be closed first (browser profiles are exclusively locked). +struct PrivacySpec { + id: &'static str, + label_zh: &'static str, + detail_zh: &'static str, + /// (path, kind) pairs; Contents keeps the folder, deletes its children. + parts: &'static [(&'static str, ItemKind)], + /// Executable (lower-case, no path) that locks these files. + process: &'static str, +} + +const SPECS: &[PrivacySpec] = &[ + PrivacySpec { + id: "privacy-edge", + label_zh: "Edge 浏览记录与 Cookie", + detail_zh: "历史、Cookie、会话恢复数据;清空后需要重新登录网站", + parts: &[ + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\History", + ItemKind::File, + ), + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\History-journal", + ItemKind::File, + ), + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\Network\Cookies", + ItemKind::File, + ), + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\Network\Cookies-wal", + ItemKind::File, + ), + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\Network\Cookies-shm", + ItemKind::File, + ), + ( + r"AppData\Local\Microsoft\Edge\User Data\Default\Session Storage", + ItemKind::Contents, + ), + ], + process: "msedge.exe", + }, + PrivacySpec { + id: "privacy-chrome", + label_zh: "Chrome 浏览记录与 Cookie", + detail_zh: "历史、Cookie、会话恢复数据;清空后需要重新登录网站", + parts: &[ + ( + r"AppData\Local\Google\Chrome\User Data\Default\History", + ItemKind::File, + ), + ( + r"AppData\Local\Google\Chrome\User Data\Default\History-journal", + ItemKind::File, + ), + ( + r"AppData\Local\Google\Chrome\User Data\Default\Network\Cookies", + ItemKind::File, + ), + ( + r"AppData\Local\Google\Chrome\User Data\Default\Network\Cookies-wal", + ItemKind::File, + ), + ( + r"AppData\Local\Google\Chrome\User Data\Default\Network\Cookies-shm", + ItemKind::File, + ), + ( + r"AppData\Local\Google\Chrome\User Data\Default\Session Storage", + ItemKind::Contents, + ), + ], + process: "chrome.exe", + }, + PrivacySpec { + id: "privacy-recent", + label_zh: "最近使用的文件 / 跳转列表", + detail_zh: "开始菜单与任务栏右键里的最近记录(链接本身,不删文件)", + parts: &[ + ( + r"AppData\Roaming\Microsoft\Windows\Recent", + ItemKind::Contents, + ), + ( + r"AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations", + ItemKind::Contents, + ), + ( + r"AppData\Roaming\Microsoft\Windows\Recent\CustomDestinations", + ItemKind::Contents, + ), + ], + process: "", + }, + PrivacySpec { + id: "privacy-clipboard", + label_zh: "剪贴板历史(Win+V)", + detail_zh: "Win+V 面板里缓存的历史条目,删除后列表清空", + parts: &[(r"AppData\Local\Microsoft\Clipboard", ItemKind::Contents)], + process: "", + }, + PrivacySpec { + id: "privacy-activity", + label_zh: "活动历史记录(时间线)", + detail_zh: "设置→隐私→活动历史;删除后「恢复上次会话」不再可用", + parts: &[( + r"AppData\Local\ConnectedDevicesPlatform", + ItemKind::Contents, + )], + process: "", + }, +]; + +/// Catalog for the UI: id + copy + estimated size, current lock state. +pub fn collect(engine: &crate::Engine, cancel: &CancelToken) -> Vec { + let home = squid_core::paths::home_dir(); + let running: Vec = engine + .platform() + .running_executables() + .into_iter() + .map(|proc| { + proc.rsplit(['/', '\\']) + .next() + .unwrap_or_default() + .to_lowercase() + }) + .collect(); + let mut out = Vec::new(); + for spec in SPECS { + if cancel.is_cancelled() { + return out; + } + let blocked = !spec.process.is_empty() && running.iter().any(|p| p == spec.process); + for (tail, kind) in spec.parts { + let path = home.join(tail); + if !path.exists() { + continue; + } + let bytes = if path.is_dir() { + walkdir::WalkDir::new(&path) + .max_depth(4) + .into_iter() + .filter_entry(|e| !e.file_type().is_symlink()) + .flatten() + .filter(|e| e.file_type().is_file()) + .filter_map(|e| e.metadata().ok()) + .map(|m| m.len()) + .sum() + } else { + std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0) + }; + let mut item = CleanupItem::new(path.clone(), *kind, Category::Privacy, spec.label_zh) + .with_rule(spec.id) + .with_anchors(std::iter::once(home.clone())) + .with_note(spec.detail_zh); + item.size = Bytes(bytes); + item.allocated = Bytes(bytes); + item.selected = false; // privacy deletes are opt-in, always + item.evidence = vec!["record:privacy-trace".into()]; + if blocked { + item = item + .locked(LockReason::AppRunning) + .with_note(format!("{}:先完全退出浏览器再清理", spec.process)); + } + out.push(item); + } + } + out +} + +/// Expand a spec id back into the concrete paths it wipes. The delete layer +/// rebuilds Fresh items from these (never trusting the scan view). +pub fn paths_for(id: &str) -> Vec<(PathBuf, ItemKind)> { + let home = squid_core::paths::home_dir(); + let Some(spec) = SPECS.iter().find(|spec| spec.id == id) else { + return Vec::new(); + }; + spec.parts + .iter() + .map(|(tail, kind)| (home.join(tail), *kind)) + .filter(|(path, _)| path.exists()) + .collect() +} + +/// The lock reason if this spec cannot be cleaned right now. +pub fn lock_reason(engine: &crate::Engine, id: &str) -> Option { + let spec = SPECS.iter().find(|spec| spec.id == id)?; + if spec.process.is_empty() { + return None; + } + let running: Vec = engine + .platform() + .running_executables() + .into_iter() + .map(|proc| { + proc.rsplit(['/', '\\']) + .next() + .unwrap_or_default() + .to_lowercase() + }) + .collect(); + running + .iter() + .any(|p| p == spec.process) + .then(|| format!("{} 正在运行,请先完全退出", spec.process)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_spec_id_is_unique_and_prefixed() { + let mut seen = std::collections::HashSet::new(); + for spec in SPECS { + assert!(spec.id.starts_with("privacy-"), "{}", spec.id); + assert!(seen.insert(spec.id), "duplicate id {}", spec.id); + } + } + + #[test] + fn unknown_ids_expand_to_nothing() { + assert!(paths_for("privacy-nonsense").is_empty()); + assert!(paths_for("").is_empty()); + } + + #[test] + fn known_ids_expand_without_panicking() { + // Real machine: some paths exist, some do not — either way the + // expansion must be a subset of the home tree, never a foreign root. + let home = squid_core::paths::home_dir(); + for spec in SPECS { + for (path, _) in paths_for(spec.id) { + assert!(path.starts_with(&home) || home.join(&path).starts_with(&home)); + } + } + } +} diff --git a/crates/squid-engine/src/purge.rs b/crates/squid-engine/src/purge.rs index 813d7bb..c045b84 100644 --- a/crates/squid-engine/src/purge.rs +++ b/crates/squid-engine/src/purge.rs @@ -196,9 +196,17 @@ pub fn scan( let mut candidates: Vec = Vec::new(); let mut visited = 0usize; for root in &roots { - let top_level = roots.len() > 1 && root.components().count() <= 3; - let cap = if top_level { depth.min(4) } else { depth }; - walk(root, cap, &mut candidates, &mut visited, progress, cancel)?; + // Shallow roots (the home folder itself) only get a depth-reduced + // walk; project containers are worth the full depth. + let cap = if root.shallow { depth.min(4) } else { depth }; + walk( + &root.path, + cap, + &mut candidates, + &mut visited, + progress, + cancel, + )?; } candidates.sort_by(|a, b| a.path.cmp(&b.path)); candidates.dedup_by(|a, b| a.path == b.path); @@ -222,11 +230,13 @@ pub fn scan( ); let mut item = item_for(candidate); + // Evidence chain (B3): remember the git verdict + project root + age + // while checking, then attach machine tokens for the UI panel. + let evidence_project = + project_with_git(&candidate.path).unwrap_or_else(|| candidate.project.clone()); + let evidence_age = age_days(&candidate.path); if !options.force { - let project_root = match project_with_git(&candidate.path) { - Some(dir) => dir, - None => candidate.project.clone(), - }; + let project_root = evidence_project.clone(); let state = match git_cache.iter().find(|(dir, _)| *dir == project_root) { Some((_, state)) => *state, None => { @@ -237,14 +247,22 @@ pub fn scan( }; match state { GitState::Tracked => { + item.evidence.push("git:tracked".into()); item = item .locked(LockReason::Protected) .with_note("tracked by git — pass --all to delete anyway"); } - GitState::Ignored => item.note = Some("git-ignored build output".into()), - GitState::Untracked => item.note = Some("untracked by git".into()), + GitState::Ignored => { + item.evidence.push("git:ignored".into()); + item.note = Some("git-ignored build output".into()); + } + GitState::Untracked => { + item.evidence.push("git:untracked".into()); + item.note = Some("untracked by git".into()); + } GitState::Unknown => { - let age = age_days(&candidate.path); + item.evidence.push("git:none".into()); + let age = evidence_age; match age { Some(age) if age >= min_age as f64 => { item.note = Some(format!("no git repo · {:.0} days old", age)); @@ -288,6 +306,7 @@ pub fn scan( .locked(LockReason::NotOwned) .with_note("owned by another user"); } + collect_evidence(&mut item, &evidence_project, evidence_age); report.items.push(item); } @@ -310,6 +329,77 @@ pub fn scan( Ok(report) } +/// Mole's node_modules evidence chain, made visible (B3): +/// a lockfile proves the tree is *reinstallable*; the package manager's +/// install record inside the artefact proves nobody hand-edited it since — +/// any file newer than the record smells like patched code, so we count it. +/// Returns machine tokens for the UI detail panel; empty = not a node tree. +fn node_evidence(project: &Path, artifact: &Path) -> Vec { + const LOCKS: [(&str, &str); 3] = [ + ("package-lock.json", ".package-lock.json"), + ("pnpm-lock.yaml", ".modules.yaml"), + ("yarn.lock", ".yarn-integrity"), + ]; + let mut out = Vec::new(); + let Some((lock, record)) = LOCKS.iter().find(|(lock, _)| project.join(lock).is_file()) else { + return out; + }; + out.push(format!("lock:{lock}")); + let record_path = artifact.join(record); + let Ok(meta) = std::fs::metadata(&record_path) else { + out.push("record-missing".into()); + return out; + }; + out.push(format!("record:{record}")); + let Ok(stamp) = meta.modified() else { + return out; + }; + let mut modified = 0u32; + let mut seen = 0u32; + for entry in walkdir::WalkDir::new(artifact) + .follow_links(false) + .max_depth(8) + .into_iter() + .filter_map(Result::ok) + { + if !entry.file_type().is_file() { + continue; + } + seen += 1; + if entry + .metadata() + .ok() + .and_then(|file| file.modified().ok()) + .is_some_and(|when| when > stamp) + { + modified += 1; + if modified > 50 { + break; + } + } + if seen >= 40_000 { + break; + } + } + out.push(format!("modified:{modified}")); + out +} + +/// Collect the evidence tokens for one candidate after its checks ran. +fn collect_evidence(item: &mut CleanupItem, project: &Path, age: Option) { + if let Some(age) = age { + item.evidence.push(format!("age:{}", age.floor() as u64)); + } + let name = item + .path + .file_name() + .map(|name| name.to_string_lossy().to_lowercase()) + .unwrap_or_default(); + if name == "node_modules" { + item.evidence.extend(node_evidence(project, &item.path)); + } +} + fn item_for(candidate: &Candidate) -> CleanupItem { let category = if candidate.name.eq_ignore_ascii_case("DerivedData") { Category::Developer @@ -337,26 +427,120 @@ fn item_for(candidate: &Candidate) -> CleanupItem { .with_note(project) } -/// Default roots: everything the user configured, plus the home folder itself -/// (shallow) so a project in an unexpected place is still found. -fn resolve_roots(engine: &Engine, options: &PurgeOptions) -> Vec { +/// Default roots are auto-discovered (Mole habit, but without the config +/// file): the home folder, container-named children of the home +/// (`~/source`, `~/repos`, …) and container-named children sitting directly +/// under each fixed drive root (`D:\Projects`). A user who wants more passes +/// explicit roots; a user who edits `purge_roots` in settings.toml keeps +/// those extras honoured as well. +fn resolve_roots(engine: &Engine, options: &PurgeOptions) -> Vec { if !options.roots.is_empty() { - return options + let chosen: Vec = options .roots .iter() .map(|root| squid_core::paths::expand(&root.to_string_lossy())) .filter(|path| path.is_dir()) + .map(|path| RootSpec { + path, + shallow: false, + }) .collect(); + if !chosen.is_empty() { + return chosen; + } + } + let mut roots: Vec = Vec::new(); + let push = |path: PathBuf, shallow: bool, roots: &mut Vec| { + if path.is_dir() + && !roots + .iter() + .any(|seen| squid_core::paths::same_path(&seen.path, &path)) + { + roots.push(RootSpec { path, shallow }); + } + }; + // Extras the user maintains by hand in settings.toml (not a UI concept). + for root in engine.settings().purge_root_paths() { + push(root, false, &mut roots); } - let mut roots = engine.settings().purge_root_paths(); let home = squid_core::paths::home_dir(); - if !roots.iter().any(|root| root == &home) { - roots.push(home); + // Container-named homes: full depth, high value. + for container in container_children(&home) { + push(container, false, &mut roots); } - roots.retain(|root| root.is_dir()); + for mount in drive_roots(engine) { + for container in container_children(&mount) { + push(container, false, &mut roots); + } + } + // The home itself last, walked shallow: it still catches projects parked + // on Desktop / Documents without diving through the whole profile. + push(home, true, &mut roots); roots } +/// One walk start point. `shallow` roots (the home folder) get the reduced +/// depth cap; project containers are walked to the full depth. +struct RootSpec { + path: PathBuf, + shallow: bool, +} + +/// Names that, one level under the home or a drive root, mean "my projects +/// live here". `documents`/`desktop` belong on drive roots (Windows users +/// keep code under `D:\Documents`, VS writes `Documents\source\repos`); +/// under the home folder they are reached by the shallow home walk anyway. +const CONTAINER_NAMES: &[&str] = &[ + "repos", + "repo", + "git", + "github", + "code", + "coding", + "dev", + "develop", + "development", + "projects", + "project", + "workspace", + "workspaces", + "work", + "src", + "source", + "documents", + "desktop", +]; + +fn container_children(dir: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + entries + .flatten() + .filter(|entry| { + let name = entry.file_name().to_string_lossy().into_owned(); + CONTAINER_NAMES + .iter() + .any(|wanted| name.eq_ignore_ascii_case(wanted)) + && entry.path().is_dir() + }) + .map(|entry| entry.path()) + .collect() +} + +/// Fixed drive mount points (Windows) / the root volume only elsewhere — +/// removable and network media are not project homes worth walking. +fn drive_roots(engine: &Engine) -> Vec { + let Ok(volumes) = engine.platform().volumes() else { + return Vec::new(); + }; + volumes + .into_iter() + .filter(|volume| !volume.is_removable) + .map(|volume| volume.mount_point) + .collect() +} + fn walk( root: &Path, max_depth: usize, @@ -509,8 +693,21 @@ fn git_state(project: &Path, artifact: &Path) -> GitState { } } +/// Spawn helper: on Windows a GUI parent (Squid) would otherwise get a fresh +/// console window for every short-lived CLI call, flashing on the desktop. +fn hide_console(command: &mut Command) -> &mut Command { + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + } + #[cfg(not(windows))] + let _ = command; + command +} + fn run_git(project: &Path, args: &[&str]) -> Option { - let output = Command::new("git") + let output = hide_console(&mut Command::new("git")) .arg("-C") .arg(project) .args(args) @@ -522,7 +719,7 @@ fn run_git(project: &Path, args: &[&str]) -> Option { } fn run_git_raw(project: &Path, args: &[&str]) -> Option { - let output = Command::new("git") + let output = hide_console(&mut Command::new("git")) .arg("-C") .arg(project) .args(args) @@ -546,9 +743,31 @@ fn measure(report: &mut ScanReport, progress: &Progress, cancel: &CancelToken) { return; } progress.phase("measure", "measuring artefacts"); - let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| { + let meter = std::sync::Mutex::new((0u64, 0u64, std::time::Instant::now())); + let sizes = squid_core::fs::measure_all(&targets, cancel, |index, completed, info| { + let emit_line = { + let mut guard = meter + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + guard.0 += info.files; + guard.1 += info.on_disk().as_u64(); + if completed as u64 == targets.len() as u64 + || guard.2.elapsed() >= std::time::Duration::from_millis(90) + { + guard.2 = std::time::Instant::now(); + Some((guard.0, guard.1)) + } else { + None + } + }; + if let Some((files, bytes)) = emit_line { + progress.publish(squid_core::progress::Event::Metered { + files, + bytes: Bytes(bytes), + }); + } progress.tick( - index as u64 + 1, + completed as u64, Some(targets.len() as u64), targets.get(index).map(|(path, _)| path.clone()), ); @@ -556,6 +775,15 @@ fn measure(report: &mut ScanReport, progress: &Progress, cancel: &CancelToken) { for (item, info) in report.items.iter_mut().zip(sizes) { item.size = info.logical; item.allocated = info.allocated; + item.file_count = info.files; + item.last_write_secs = if info.newest_write == 0 { + None + } else { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |since| since.as_secs()); + Some(now.saturating_sub(info.newest_write)) + }; if info.unreadable > 0 { let suffix = format!("{} entries unreadable", info.unreadable); item.note = Some(match item.note.take() { diff --git a/crates/squid-engine/src/tweaks.rs b/crates/squid-engine/src/tweaks.rs new file mode 100644 index 0000000..424a37b --- /dev/null +++ b/crates/squid-engine/src/tweaks.rs @@ -0,0 +1,393 @@ +//! 系统优化 (system optimisation) — a curated, **reversible** tweaks catalog. +//! +//! MangoDisk keeps 83 Windows settings and a revert registry; we start with +//! the low-dispute subset and one hard rule each tweak must pass before it +//! ships here: (1) registry-only or documented-API, (2) the original value +//! is recorded before the first write, (3) 「恢复全部默认」 puts every recorded +//! value back exactly, (4) verified on a real machine, not just this file. +//! +//! The catalog is data. Each tweak declares its hive/key/value/type and the +//! bytes that mean on/off; everything else (state read, apply, revert) is +//! one shared code path, so adding a tweak cannot introduce new bugs in +//! reading, writing, or undoing. + +use serde::Serialize; +use squid_core::Settings; +use std::path::PathBuf; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum TweakKind { + Dword, + String, + NoneMeansZero, +} + +/// One catalog entry. `on` is the payload that enables the tweak; `restore` +/// describes what "back to default" means (delete the value, or write the +/// original bytes we recorded). +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Tweak { + pub id: &'static str, + pub title_zh: &'static str, + pub title_en: &'static str, + pub detail_zh: &'static str, + pub detail_en: &'static str, + /// "safe" | "notice" — notice carries a visible side-effect hint. + pub risk: &'static str, + /// HKCU | HKLM (we only ever touch HKCU-approved paths for now). + pub hive: &'static str, + pub key: &'static str, + pub value: &'static str, + pub kind: TweakKind, + /// Payload (DWORD as u32 text, or the string) meaning "enabled". + pub on: &'static str, + /// A restart / Explorer restart is needed to see the effect. + pub restart_hint: bool, +} + +/// The catalog — every entry verified on a real Windows 11 machine. +pub fn catalog() -> Vec { + vec![ + Tweak { + id: "transparency", + title_zh: "关闭透明效果", + title_en: "Turn off transparency", + detail_zh: "降低 GPU 合成负担,远程桌面里也更清晰", + detail_en: "Less compositor work; sharper over RDP", + risk: "safe", + hive: "HKCU", + key: r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", + value: "EnableTransparency", + kind: TweakKind::Dword, + on: "0", + restart_hint: false, + }, + Tweak { + id: "show-extensions", + title_zh: "资源管理器显示文件扩展名", + title_en: "Show file extensions", + detail_zh: "隐藏扩展名是误删与伪装文件事故的头号来源", + detail_en: "Hidden extensions cause mis-deletes and fake-file tricks", + risk: "safe", + hive: "HKCU", + key: r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", + value: "HideFileExt", + kind: TweakKind::Dword, + on: "0", + restart_hint: false, + }, + Tweak { + id: "widgets-web", + title_zh: "关闭小组件 Web 内容", + title_en: "Disable Widgets web content", + detail_zh: "任务栏小组件不再拉取新闻,减少后台联网与内存", + detail_en: "Taskbar Widgets stops fetching news feeds", + risk: "safe", + hive: "HKCU", + key: r"Software\Microsoft\Windows\CurrentVersion\Feeds", + value: "ShellWebContentSystemProvisioning", + kind: TweakKind::Dword, + on: "0", + restart_hint: true, + }, + Tweak { + id: "location", + title_zh: "禁止位置同步", + title_en: "Disable location", + detail_zh: "应用不能再读取本机地理位置", + detail_en: "Apps can no longer read this device's location", + risk: "safe", + hive: "HKCU", + key: r"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location", + value: "Value", + kind: TweakKind::String, + on: "Deny", + restart_hint: false, + }, + Tweak { + id: "recent-files", + title_zh: "关闭「最近使用的文件」", + title_en: "Turn off recent files", + detail_zh: "资源管理器与快速访问不再记录最近文件(隐私+微量性能)", + detail_en: "Explorer stops logging recent files", + risk: "notice", + hive: "HKCU", + key: r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", + value: "Start_TrackDocs", + kind: TweakKind::Dword, + on: "0", + restart_hint: true, + }, + ] +} + +pub fn find(id: &str) -> Option { + catalog().into_iter().find(|tweak| tweak.id == id) +} + +/// Row the UI sees: the tweak plus its live state and revert info. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TweakState { + #[serde(flatten)] + pub tweak: Tweak, + /// True when the on-payload is currently written. + pub enabled: bool, + /// The key/value could not be read at all (missing is NOT an error for + /// NoneMeansZero kinds). + pub unreadable: bool, + /// An original value was recorded → revert is possible. + pub recorded: bool, +} + +/// Recorded originals, persisted beside the other app state. +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] +pub struct TweakBackups { + /// tweak id → (kind marker + original payload text, or "absent") + pub originals: std::collections::HashMap, +} + +impl TweakBackups { + fn path() -> PathBuf { + Settings::config_dir().join("tweaks.json") + } + + pub fn load() -> TweakBackups { + std::fs::read_to_string(Self::path()) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default() + } + + fn save(&self) -> std::io::Result<()> { + let path = Self::path(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(path, serde_json::to_string_pretty(self).unwrap_or_default()) + } + + /// Record once: the FIRST original value is the one we restore to, no + /// matter how many times the user flips the switch afterwards. + fn record(&mut self, id: &str, original: String) -> std::io::Result<()> { + if self.originals.contains_key(id) { + return Ok(()); + } + self.originals.insert(id.to_string(), original); + self.save() + } +} + +#[cfg(windows)] +mod registry { + use super::{Tweak, TweakKind}; + use winreg::enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}; + use winreg::RegKey; + + fn open(hive: &str) -> Result { + match hive { + "HKCU" => Ok(RegKey::predef(HKEY_CURRENT_USER)), + other => Err(format!("不支持的注册表根:{other}")), + } + } + + /// Read the current payload as text; Ok(None) = value absent. + pub fn read(tweak: &Tweak) -> Result, String> { + let root = open(tweak.hive)?; + let Ok(key) = root.open_subkey_with_flags(tweak.key, KEY_READ) else { + return Ok(None); // key missing → value absent, not an error + }; + let value = match tweak.kind { + TweakKind::String => key + .get_value::(tweak.value) + .map(Some) + .unwrap_or(None), + _ => key + .get_value::(tweak.value) + .map(|number| Some(number.to_string())) + .unwrap_or(None), + }; + Ok(value) + } + + /// Write the payload; missing key is created with minimal rights + /// (create_subkey would ask KEY_ALL_ACCESS and security software says no). + pub fn write(tweak: &Tweak, payload: &str) -> Result<(), String> { + let root = open(tweak.hive)?; + let key = root + .create_subkey_with_flags(tweak.key, KEY_READ | KEY_WRITE) + .map_err(|error| format!("无法打开 {}:{error}", tweak.key))? + .0; + match tweak.kind { + TweakKind::String => key + .set_value(tweak.value, &payload.to_string()) + .map_err(|error| error.to_string())?, + _ => { + let number: u32 = payload + .parse() + .map_err(|_| format!("不是合法的 DWORD:{payload}"))?; + key.set_value(tweak.value, &number) + .map_err(|error| error.to_string())?; + } + } + Ok(()) + } + + pub fn remove(tweak: &Tweak) -> Result<(), String> { + let root = open(tweak.hive)?; + if let Ok(key) = root.open_subkey_with_flags(tweak.key, KEY_READ | KEY_WRITE) { + let _ = key.delete_value(tweak.value); + } + Ok(()) + } +} + +#[cfg(not(windows))] +mod registry { + use super::Tweak; + pub fn read(_tweak: &Tweak) -> Result, String> { + Err("tweaks 仅在 Windows 提供".into()) + } + pub fn write(_tweak: &Tweak, _payload: &str) -> Result<(), String> { + Err("tweaks 仅在 Windows 提供".into()) + } + pub fn remove(_tweak: &Tweak) -> Result<(), String> { + Ok(()) + } +} + +pub fn states() -> Vec { + let backups = TweakBackups::load(); + catalog() + .into_iter() + .map(|tweak| { + let raw = registry::read(&tweak); + let current = match &raw { + Ok(Some(value)) => Some(value.clone()), + // Absent DWORDs read as their documented default 0. + Ok(None) if tweak.kind != TweakKind::String => Some("0".to_string()), + Ok(None) => None, + Err(_) => None, + }; + let enabled = current + .as_ref() + .is_some_and(|value| value.eq_ignore_ascii_case(tweak.on)); + TweakState { + tweak: tweak.clone(), + enabled, + unreadable: raw.is_err(), + recorded: backups.originals.contains_key(tweak.id), + } + }) + .collect() +} + +/// Flip one tweak. The original value (including "absent") is recorded +/// before the first write so 「恢复全部默认」 can always undo the whole page. +pub fn set(id: &str, enabled: bool) -> Result { + let tweak = find(id).ok_or_else(|| format!("未知的优化项:{id}"))?; + let mut backups = TweakBackups::load(); + let original = registry::read(&tweak)?; + // Absent DWORDs read as their documented default 0 for comparison. + let current = original + .clone() + .or((tweak.kind != TweakKind::String).then(|| "0".to_string())); + let already = current + .as_ref() + .is_some_and(|value| value.eq_ignore_ascii_case(tweak.on)) + == enabled; + if already { + // No write, no recorded original — the machine is already where the + // switch says it should be; claiming a change would be a lie. + } else if enabled { + backups + .record( + tweak.id, + original.clone().unwrap_or_else(|| "absent".into()), + ) + .map_err(|error| error.to_string())?; + registry::write(&tweak, tweak.on)?; + } else { + // Turning off explicitly = restore the recorded original. + restore_one(&mut backups, &tweak)?; + } + Ok(states() + .into_iter() + .find(|state| state.tweak.id == id) + .expect("catalog round-trips")) +} + +fn restore_one(backups: &mut TweakBackups, tweak: &Tweak) -> Result<(), String> { + match backups.originals.get(tweak.id) { + Some(original) if original == "absent" || original.is_empty() => { + registry::remove(tweak)?; + } + Some(original) => { + registry::write(tweak, original)?; + } + None => registry::remove(tweak)?, + } + backups.originals.remove(tweak.id); + backups.save().map_err(|error| error.to_string()) +} + +/// 「恢复全部默认」: every recorded tweak back to its original value. +pub fn restore_all() -> Vec { + let mut backups = TweakBackups::load(); + let mut restored = Vec::new(); + for tweak in catalog() { + if backups.originals.contains_key(tweak.id) && restore_one(&mut backups, &tweak).is_ok() { + restored.push(tweak.id.to_string()); + } + } + restored +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn catalog_ids_are_unique_and_prefixed_hkcu() { + let mut seen = std::collections::HashSet::new(); + for tweak in catalog() { + assert!(seen.insert(tweak.id), "duplicate {}", tweak.id); + assert_eq!(tweak.hive, "HKCU", "batch 1 stays user-hive only"); + assert!(!tweak.key.is_empty() && !tweak.value.is_empty()); + } + } + + #[test] + fn unknown_ids_are_rejected() { + assert!(find("delete-my-boot").is_none()); + assert!(set("delete-my-boot", true).is_err()); + } + + #[cfg(windows)] + #[test] + fn a_tweak_round_trips_through_the_registry() { + // A private scratch value under a key we own; registry access can be + // denied by endpoint protection in sandboxes, so skip politely then. + let probe = find("show-extensions").expect("catalog"); + let before = match registry::read(&probe) { + Ok(value) => value, + Err(error) => { + eprintln!("skipping: registry read denied ({error})"); + return; + } + }; + if registry::write(&probe, "1").is_err() { + eprintln!("skipping: registry write denied"); + return; + } + assert_eq!(registry::read(&probe).ok().flatten().as_deref(), Some("1")); + // Restore the machine to exactly how we found it. + match &before { + Some(value) => registry::write(&probe, value).expect("restore"), + None => registry::remove(&probe).expect("remove"), + } + assert_eq!(registry::read(&probe).ok().flatten(), before); + } +} diff --git a/crates/squid-engine/src/uninstall.rs b/crates/squid-engine/src/uninstall.rs index 05a1acf..14e7045 100644 --- a/crates/squid-engine/src/uninstall.rs +++ b/crates/squid-engine/src/uninstall.rs @@ -136,7 +136,14 @@ pub fn build_plan( Some(version) => format!("{} · {}", app.source, version), None => app.source.clone(), }); - if system { + if app.dead || app.path.as_os_str().is_empty() { + // 安装不完整: there is no bundle to move to the bin — the plan + // carries only the leftovers and the registry record the page + // offers to drop. + bundle_item = bundle_item + .locked(LockReason::Protected) + .with_note("程序本体已不存在,仅需清理注册表记录与残留"); + } else if system { bundle_item = bundle_item .locked(LockReason::Protected) .with_note("system application"); @@ -248,9 +255,9 @@ fn measure( .iter() .map(|item| (item.path.clone(), item.kind)) .collect(); - let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| { + let sizes = squid_core::fs::measure_all(&targets, cancel, |index, completed, _info| { progress.tick( - index as u64 + 1, + completed as u64, Some(targets.len() as u64), targets.get(index).map(|(path, _)| path.clone()), ); @@ -473,6 +480,7 @@ mod tests { publisher: None, installed_ms: None, display_icon: None, + ..AppInfo::default() } } diff --git a/crates/squid-platform/src/advanced.rs b/crates/squid-platform/src/advanced.rs new file mode 100644 index 0000000..7fb7906 --- /dev/null +++ b/crates/squid-platform/src/advanced.rs @@ -0,0 +1,551 @@ +//! 进阶启动项 (advanced startup) — the Autoruns-shaped tail of the startup +//! story: Winlogon hooks, AppInit, IFEO debuggers, browser BHOs, and the +//! hidden corners of Task Scheduler and Services that ordinary listings +//! skip. Everything here can break boot or logon, so the contract is: +//! +//! * **display first** — the UI lists these read-mostly, with signature +//! trust and the exact registry location on every row; +//! * **disable is reversible** — the first disable records the original +//! value in `advanced-backup.json`; restoring puts the bytes back; +//! * hidden tasks and automatic services ride the *same* id scheme as the +//! normal startup list, so their toggles reuse the proven arms. +//! +//! Signature trust is a batched `Get-AuthenticodeSignature` PowerShell +//! call over the deduplicated exe set — one process, honest status +//! (微软 / 已知厂商 / 未签名 / 失效), no FFI. + +use serde::{Deserialize, Serialize}; + +/// One advanced row. `kind` decides how disabling works. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdvancedEntry { + /// `adv||||` (or task/service ids for the + /// reused arms). + pub id: String, + pub kind: String, + pub name: String, + /// Registry command line or task/service target. + pub command: String, + /// Human location, e.g. `HKLM\…\Winlogon\Userinit`. + pub location: String, + pub scope: String, + pub enabled: bool, + /// Digital-signature verdict: `microsoft` | `vendor` | `unsigned` | + /// `invalid` | `unknown` (no exe resolvable / non-Windows). + pub signature: String, + /// Subject of the signing certificate when known. + pub signer: Option, + /// A warning the UI must show: IFEO hijacks a program, Winlogon is + /// boot-critical, etc. + pub warning: Option, +} + +#[cfg(windows)] +pub(crate) mod windows { + use super::AdvancedEntry; + use std::path::PathBuf; + use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ}; + use winreg::RegKey; + + const WINLOGON: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Winlogon"; + const IFEO: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options"; + + fn hive(machine: bool) -> RegKey { + RegKey::predef(if machine { + HKEY_LOCAL_MACHINE + } else { + HKEY_CURRENT_USER + }) + } + + fn read_string(key: &RegKey, path: &str, value: &str) -> Option { + key.open_subkey_with_flags(path, KEY_READ) + .ok()? + .get_value::(value) + .ok() + .map(|text| text.trim().to_string()) + .filter(|text| !text.is_empty()) + } + + /// Strip quotes and arguments from a registry command to reach the exe. + pub(crate) fn exe_of(command: &str) -> Option { + let text = command.trim(); + if let Some(rest) = text.strip_prefix('"') { + return rest.split('"').next().map(str::to_string); + } + // Up to the first `.exe` boundary, else the first whitespace token. + if let Some(end) = text.to_ascii_lowercase().find(".exe") { + return Some(text[..end + 4].to_string()); + } + text.split_whitespace().next().map(str::to_string) + } + + fn winlogon_entries(out: &mut Vec) { + for (machine, hive_label) in [(true, "HKLM"), (false, "HKCU")] { + let root = hive(machine); + for (value, meaning) in [ + ("Shell", "登录外壳(正常情况下只有 explorer.exe)"), + ( + "Userinit", + "登录初始化链(正常情况下以 userinit.exe, 结尾)", + ), + ] { + let Some(text) = read_string(&root, WINLOGON, value) else { + continue; + }; + // The pristine value is a bare system component; anything + // extra rides alongside and is worth a warning. + let clean = text.split(',').all(|part| { + let part = part.trim().to_ascii_lowercase(); + part.is_empty() + || part + .replace("%systemroot%", "") + .replace("\\system32\\", "") + .starts_with(if value == "Shell" { + "explorer.exe" + } else { + "userinit.exe" + }) + }); + out.push(AdvancedEntry { + id: format!("adv|winlogon|{hive_label}|{WINLOGON}|{value}"), + kind: "winlogon".into(), + name: format!("Winlogon {value}"), + command: text, + location: format!("{hive_label}\\{WINLOGON} · {value}"), + scope: if machine { "machine" } else { "currentUser" }.into(), + enabled: true, + signature: "unknown".into(), + signer: None, + warning: (!clean) + .then(|| format!("{meaning};存在附加程序,请确认是否认识")) + .or_else(|| Some(format!("{meaning};改动需重启生效"))), + }); + } + } + } + + fn appinit_entries(out: &mut Vec) { + const KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Windows"; + for (machine, hive_label) in [(true, "HKLM"), (false, "HKCU")] { + let root = hive(machine); + let enabled = read_string(&root, KEY, "LoadAppInit_DLLs").as_deref() == Some("1"); + let Some(dlls) = read_string(&root, KEY, "AppInit_DLLs") else { + continue; + }; + out.push(AdvancedEntry { + id: format!("adv|appinit|{hive_label}|{KEY}|AppInit_DLLs"), + kind: "appinit".into(), + name: "AppInit_DLLs 全局注入".to_string(), + command: dlls, + location: format!("{hive_label}\\{KEY}"), + scope: if machine { "machine" } else { "currentUser" }.into(), + enabled, + signature: "unknown".into(), + signer: None, + warning: Some("每个 GUI 进程都会加载这些 DLL;除非认识每一个,否则保持关闭".into()), + }); + } + } + + fn ifeo_entries(out: &mut Vec) { + for (machine, hive_label) in [(true, "HKLM"), (false, "HKCU")] { + let root = hive(machine); + let Ok(ifeo) = root.open_subkey_with_flags(IFEO, KEY_READ) else { + continue; + }; + for name in ifeo.enum_keys().flatten() { + let Some(debugger) = read_string(&ifeo, &name, "Debugger") else { + continue; + }; + // A Debugger replaces the program's launch entirely — the + // classic persistence trick. Only flag non-microsoft ones. + let lower = debugger.to_ascii_lowercase(); + if lower.contains("mseone") + || lower.contains("hybridlaunch") + || lower.contains("msedge.exe --profile-directory") + { + continue; // Edge/IE protocol handlers live here legitimately + } + out.push(AdvancedEntry { + id: format!("adv|ifeo|{hive_label}|{IFEO}\\{name}|Debugger"), + kind: "ifeo".into(), + name: format!("{name} 被调试器接管"), + command: debugger, + location: format!("{hive_label}\\{IFEO}\\{name} · Debugger"), + scope: if machine { "machine" } else { "currentUser" }.into(), + enabled: true, + signature: "unknown".into(), + signer: None, + warning: Some(format!( + "启动 {name} 会先启动调试器;安全软件常用,也可能是流氓持久化" + )), + }); + } + } + } + + fn bho_entries(out: &mut Vec) { + const BHO: &str = + r"Software\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects"; + let root = hive(true); + let Ok(bho) = root.open_subkey_with_flags(BHO, KEY_READ) else { + return; + }; + for clsid in bho.enum_keys().flatten() { + let module = read_string(&root, &format!(r"Classes\{clsid}\InprocServer32"), ""); + let friendly = read_string(&root, &format!(r"Classes\{clsid}"), ""); + let load = bho + .open_subkey_with_flags(&clsid, KEY_READ) + .ok() + .and_then(|key| key.get_value::("LoadBehavior").ok()) + .unwrap_or(3); + out.push(AdvancedEntry { + id: format!("adv|bho|HKLM|{BHO}\\{clsid}|LoadBehavior"), + kind: "bho".into(), + name: friendly.unwrap_or_else(|| clsid.clone()), + command: module.unwrap_or_else(|| clsid.clone()), + location: format!("HKLM\\{BHO}\\{clsid} · LoadBehavior"), + scope: "machine".into(), + enabled: load & 1 != 0, + signature: "unknown".into(), + signer: None, + warning: Some("浏览器加载项(IE 模式);现代浏览器大多不再使用".into()), + }); + } + } + + pub fn scan() -> Vec { + let mut out = Vec::new(); + winlogon_entries(&mut out); + appinit_entries(&mut out); + ifeo_entries(&mut out); + bho_entries(&mut out); + enrich_signatures(&mut out); + out + } + + /// Signature trust is a batch pass: collect the unique exes, grade them + /// all in one PowerShell call, then stamp every entry from the map. + fn enrich_signatures(entries: &mut [AdvancedEntry]) { + let mut exes: Vec = Vec::new(); + for entry in entries.iter_mut() { + if let Some(exe) = exe_of(&entry.command).filter(|path| PathBuf::from(path).exists()) { + if !exes.iter().any(|seen| seen.eq_ignore_ascii_case(&exe)) { + exes.push(exe); + } + entry.signature = "pending".into(); + } + } + if exes.is_empty() { + return; + } + let grades = signature_grades(&exes); + for entry in entries.iter_mut() { + let Some(exe) = exe_of(&entry.command) else { + continue; + }; + if let Some((verdict, signer)) = grades.get(&exe.to_ascii_lowercase()) { + entry.signature = verdict.clone(); + entry.signer = signer.clone(); + } else if entry.signature == "pending" { + entry.signature = "unknown".into(); + } + } + } + + /// One PowerShell round-trip grading many binaries at once: + /// lowercase path → (`verdict`, `signer`). Shared with the startup scan so + /// a page never shells out per row. + pub(crate) fn signature_grades( + exes: &[String], + ) -> std::collections::HashMap)> { + let mut grades: std::collections::HashMap)> = + Default::default(); + if exes.is_empty() { + return grades; + } + let list = exes + .iter() + .map(|exe| format!("'{}'", exe.replace('\'', "''"))) + .collect::>() + .join(","); + let script = format!( + "$ErrorActionPreference='SilentlyContinue'; {list} | ForEach-Object {{ $s = Get-AuthenticodeSignature -FilePath $_; \"@@|$_|$($s.Status)|$($s.SignerCertificate.Subject)\" }} | Out-String -Width 4096" + ); + let mut command = std::process::Command::new("powershell.exe"); + command.args(["-NoProfile", "-NonInteractive", "-Command", &script]); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + // Squid is a GUI app: without this every scan flashed a console + // window for the duration of the signature batch. + command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + } + let Ok(output) = command.output() else { + return grades; + }; + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + // Out-String may pad lines; match on containment of the marker. + let Some(start) = line.find("@@|") else { + continue; + }; + let rest = &line[start + 3..]; + let mut parts = rest.splitn(3, '|'); + let (Some(path), Some(status)) = (parts.next(), parts.next()) else { + continue; + }; + let subject = parts.next().unwrap_or_default().to_string(); + let signer = subject + .split("CN=") + .nth(1) + .map(|tail| tail.split(',').next().unwrap_or(tail).to_string()) + .filter(|name| !name.is_empty()); + let verdict = match status { + "Valid" => match &signer { + Some(name) if name.contains("Microsoft") || name.contains("Windows") => { + "microsoft" + } + Some(_) => "vendor", + None => "vendor", + }, + "NotSigned" => "unsigned", + "HashMismatch" | "NotTrusted" | "CertificateExpired" | "UnknownError" + | "Missing" => "invalid", + _ => "unknown", + }; + grades.insert(path.to_ascii_lowercase(), (verdict.into(), signer)); + } + grades + } +} + +#[cfg(not(windows))] +mod windows { + use super::AdvancedEntry; + pub fn scan() -> Vec { + Vec::new() + } +} + +pub fn scan_advanced() -> Vec { + #[cfg(windows)] + { + windows::scan() + } + #[cfg(not(windows))] + { + Vec::new() + } +} + +/// Disable/enable one advanced entry. Winlogon/AppInit/IFEO/BHO write +/// registry values (original recorded on first disable); tasks and services +/// are not handled here — the caller routes them through `set_startup_enabled` +/// because their ids use the ordinary scheme. +pub fn set_advanced_enabled(entry: &AdvancedEntry, enabled: bool) -> Result<(), String> { + #[cfg(windows)] + { + windows_set(entry, enabled) + } + #[cfg(not(windows))] + { + let _ = (entry, enabled); + Err("进阶启动项管理仅在 Windows 提供".into()) + } +} + +#[cfg(windows)] +fn windows_set(entry: &AdvancedEntry, enabled: bool) -> Result<(), String> { + use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE}; + use winreg::RegKey; + + // id shape: adv|kind|HIVELABEL|key|value + let parts: Vec<&str> = entry.id.splitn(5, '|').collect(); + if parts.len() != 5 { + return Err("无法解析的进阶项 id".into()); + } + let (hive_label, key_path, value_name) = (parts[2], parts[3], parts[4]); + let root = RegKey::predef(if hive_label == "HKLM" { + HKEY_LOCAL_MACHINE + } else { + HKEY_CURRENT_USER + }); + let mut backups = Backups::load(); + match entry.kind.as_str() { + "winlogon" => { + let original = read_raw(&root, key_path, value_name)?; + if enabled { + let restore = backups + .originals + .get(&entry.id) + .cloned() + .unwrap_or_else(|| match value_name { + "Shell" => "explorer.exe".to_string(), + _ => r"C:\Windows\system32\userinit.exe,".to_string(), + }); + write_raw(&root, key_path, value_name, &restore)?; + backups.originals.remove(&entry.id); + } else { + // Keep the mandatory piece, drop the third-party tail. + let kept: Vec<&str> = original + .split(',') + .map(str::trim) + .filter(|part| !part.is_empty()) + .filter(|part| { + let lower = part.to_ascii_lowercase(); + lower.contains("explorer.exe") || lower.contains("userinit.exe") + }) + .collect(); + let joined = kept.join(","); + if joined != original { + backups + .originals + .entry(entry.id.clone()) + .or_insert_with(|| original.clone()); + } + write_raw(&root, key_path, value_name, &joined)?; + } + } + "appinit" => { + backups + .originals + .entry(entry.id.clone()) + .or_insert_with(|| if enabled { "1".into() } else { "0".into() }); + write_dword( + &root, + key_path, + "LoadAppInit_DLLs", + if enabled { 1 } else { 0 }, + )?; + } + "ifeo" => { + let original = read_raw(&root, key_path, value_name)?; + if enabled { + let restore = backups + .originals + .get(&entry.id) + .cloned() + .unwrap_or_else(|| original.clone()); + write_raw(&root, key_path, value_name, &restore)?; + backups.originals.remove(&entry.id); + } else { + backups.originals.insert(entry.id.clone(), original); + delete_value(&root, key_path, value_name)?; + } + } + "bho" => { + write_dword(&root, key_path, "LoadBehavior", if enabled { 3 } else { 0 })?; + } + other => return Err(format!("不支持的进阶类型:{other}")), + } + backups.save() +} + +#[cfg(windows)] +fn read_raw(root: &winreg::RegKey, key: &str, value: &str) -> Result { + use winreg::enums::KEY_READ; + Ok(root + .open_subkey_with_flags(key, KEY_READ) + .map_err(|error| error.to_string())? + .get_value::(value) + .unwrap_or_default()) +} + +#[cfg(windows)] +fn write_raw(root: &winreg::RegKey, key: &str, value: &str, text: &str) -> Result<(), String> { + use winreg::enums::{KEY_READ, KEY_WRITE}; + root.create_subkey_with_flags(key, KEY_READ | KEY_WRITE) + .map_err(|error| error.to_string())? + .0 + .set_value(value, &text.to_string()) + .map_err(|error| error.to_string()) +} + +#[cfg(windows)] +fn write_dword(root: &winreg::RegKey, key: &str, value: &str, number: u32) -> Result<(), String> { + use winreg::enums::{KEY_READ, KEY_WRITE}; + root.create_subkey_with_flags(key, KEY_READ | KEY_WRITE) + .map_err(|error| error.to_string())? + .0 + .set_value(value, &number) + .map_err(|error| error.to_string()) +} + +#[cfg(windows)] +fn delete_value(root: &winreg::RegKey, key: &str, value: &str) -> Result<(), String> { + use winreg::enums::{KEY_READ, KEY_WRITE}; + root.open_subkey_with_flags(key, KEY_READ | KEY_WRITE) + .map_err(|error| error.to_string())? + .delete_value(value) + .map_err(|error| error.to_string()) +} + +/// Original values for disabled advanced entries (restore data). +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +struct Backups { + originals: std::collections::HashMap, +} + +impl Backups { + #[cfg(windows)] + fn path() -> std::path::PathBuf { + squid_core::Settings::config_dir().join("advanced-backup.json") + } + + #[cfg(windows)] + fn load() -> Backups { + std::fs::read_to_string(Self::path()) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default() + } + + #[cfg(windows)] + fn save(&self) -> Result<(), String> { + let path = Self::path(); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + std::fs::write( + &path, + serde_json::to_string_pretty(self).unwrap_or_default(), + ) + .map_err(|error| error.to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scan_runs_and_ids_are_prefixed() { + // Real-machine smoke test: the scan must never panic and every id + // must carry the adv| prefix the parser in set_advanced_enabled + // depends on. + for entry in scan_advanced() { + assert!(entry.id.starts_with("adv|"), "{}", entry.id); + assert!(!entry.location.is_empty()); + } + } + + #[cfg(windows)] + #[test] + fn exe_extraction_handles_quotes_and_arguments() { + assert_eq!( + windows::exe_of(r#""C:\Program Files\Tool\warp.exe" --quiet""#).as_deref(), + Some(r"C:\Program Files\Tool\warp.exe") + ); + assert_eq!( + windows::exe_of(r"C:\Windows\System32\userinit.exe,").as_deref(), + Some(r"C:\Windows\System32\userinit.exe") + ); + assert_eq!( + windows::exe_of("mscandui.dll"), + Some("mscandui.dll".to_string()) + ); + } +} diff --git a/crates/squid-platform/src/apps.rs b/crates/squid-platform/src/apps.rs index 7160f30..dd03960 100644 --- a/crates/squid-platform/src/apps.rs +++ b/crates/squid-platform/src/apps.rs @@ -136,6 +136,7 @@ pub fn app_from_bundle( .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) .map(|d| d.as_millis() as u64), display_icon: None, + ..AppInfo::default() }; if app.name.to_lowercase() == "safari" { // Safari cannot be removed and its caches are managed by the OS. diff --git a/crates/squid-platform/src/lib.rs b/crates/squid-platform/src/lib.rs index d252ddc..053df0a 100644 --- a/crates/squid-platform/src/lib.rs +++ b/crates/squid-platform/src/lib.rs @@ -10,6 +10,7 @@ use squid_core::progress::CancelToken; use squid_core::{AppInfo, Bytes, Volume}; use std::path::{Path, PathBuf}; +pub mod advanced; pub mod apps; pub mod console; pub mod currency; diff --git a/crates/squid-platform/src/linux.rs b/crates/squid-platform/src/linux.rs index 0dab326..7150d3c 100644 --- a/crates/squid-platform/src/linux.rs +++ b/crates/squid-platform/src/linux.rs @@ -225,6 +225,7 @@ impl Platform for Linux { publisher: desktop.icon.clone(), installed_ms: None, display_icon: None, + ..AppInfo::default() }); } } @@ -261,6 +262,7 @@ impl Platform for Linux { publisher: None, installed_ms: None, display_icon: None, + ..AppInfo::default() }); } } diff --git a/crates/squid-platform/src/permissions.rs b/crates/squid-platform/src/permissions.rs index 0ed7f59..9c16963 100644 --- a/crates/squid-platform/src/permissions.rs +++ b/crates/squid-platform/src/permissions.rs @@ -28,10 +28,41 @@ pub struct StartupEntry { /// `currentUser` | `machine` pub scope: String, pub enabled: bool, + /// True once the entry was attributed to a real software product (the + /// binary carries a human FileDescription/ProductName). 电脑管家 groups + /// every entry it *cannot* attribute under 其他软件; this flag drives + /// that bucket on the UI side. + #[serde(default)] + pub named: bool, /// PNG bytes of the binary's default icon, extracted on Windows only — /// the 电脑管家 habit of showing the software icon next to its name. #[serde(default)] pub icon: Option>, + /// The executable this entry really runs (lnk targets resolved). Empty + /// when the command holds no path at all. + #[serde(default)] + pub target: String, + /// False when `target` does not exist on disk — the program was removed + /// but its autostart config survived: a 残留项 (leftover), removable via + /// [`remove_startup_entry`]. + #[serde(default)] + pub target_exists: bool, + /// When this fires: `boot` | `logon` | `background` | `unknown`, from the + /// registry value / task triggers / service start type. Shown as a chip. + #[serde(default)] + pub trigger: String, + /// Microsoft-signed or living under %SystemRoot% — the UI folds these + /// into a 系统组件 group that 「显示系统项」 can hide. + #[serde(default)] + pub system_item: bool, + /// Digital-signature verdict of `target`: `microsoft` | `vendor` | + /// `unsigned` | `invalid` | `unknown` (nothing resolvable / non-Windows). + /// Filled by the batch signature pass at the end of the scan. + #[serde(default)] + pub signature: String, + /// Subject of the signing certificate when known. + #[serde(default)] + pub signer: Option, } /// One registered context-menu ("右键菜单") handler. @@ -57,6 +88,12 @@ pub struct ShellExtEntry { /// PNG bytes of the owning module's icon (Windows only). #[serde(default)] pub icon: Option>, + /// True once the handler was attributed to a real software product (its + /// module carries usable FileDescription/ProductName strings). Drives the + /// same software-grouping rule the startup list uses; unattributed rows + /// land in 其他软件. + #[serde(default)] + pub named: bool, } /// A visible top-level window the popup blocker could act on. @@ -140,6 +177,22 @@ pub fn set_startup_enabled(entry: &StartupEntry, enabled: bool) -> Result<(), St } } +/// Delete a leftover autostart configuration (the program it points at is +/// gone). Only the *registration* disappears — registry value, Startup-folder +/// shortcut, task definition — never a program's files. Services are disabled +/// rather than uninstalled because other software may still reference them. +pub fn remove_startup_entry(entry: &StartupEntry) -> Result<(), String> { + #[cfg(windows)] + { + windows::remove_startup_entry(entry) + } + #[cfg(not(windows))] + { + let _ = entry; + Err("删除启动项仅在 Windows 提供".into()) + } +} + pub fn scan_shell_extensions() -> Vec { #[cfg(windows)] { @@ -266,21 +319,104 @@ mod windows { list: &str, value_name: &str, enabled: bool, - ) -> Result<(), String> { + ) -> std::io::Result<()> { let hive = RegKey::predef(if machine { HKEY_LOCAL_MACHINE } else { HKEY_CURRENT_USER }); - let (key, _) = hive - .create_subkey(format!(r"{base}\Explorer\StartupApproved\{list}")) - .map_err(registry_error)?; + // Minimal rights only: several security suites (and locked-down + // profiles) deny KEY_ALL_ACCESS-style opens on the startup trees even + // for the key's own owner, which used to make every toggle fail. + let (key, _) = hive.create_subkey_with_flags( + format!(r"{base}\Explorer\StartupApproved\{list}"), + KEY_READ | KEY_WRITE, + )?; let marker = winreg::RegValue { bytes: approved_marker(enabled), vtype: RegType::REG_BINARY, }; key.set_raw_value(value_name, &marker) - .map_err(registry_error) + } + + /// Task Manager's marker rendered for `reg.exe` (12 bytes, hex). + fn approved_marker_hex(enabled: bool) -> String { + let mut hex = String::from(if enabled { "02" } else { "03" }); + hex.push_str(&"0".repeat(22)); + hex + } + + /// Flip an approval marker, escalating through a one-shot UAC prompt when + /// the direct write is denied (machine-scope keys, protected hives). The + /// result is verified against the registry itself, so a cancelled prompt + /// reports failure instead of a silently dead switch. + fn flip_approved( + machine: bool, + base: &str, + list: &str, + value_name: &str, + enabled: bool, + ) -> Result<(), String> { + if let Err(why) = write_approved(machine, base, list, value_name, enabled) { + if why.kind() != std::io::ErrorKind::PermissionDenied { + return Err(registry_error(why)); + } + let hive_label = if machine { "HKLM" } else { "HKCU" }; + run_elevated( + "reg.exe", + &[ + "add".to_string(), + format!(r"{hive_label}\{base}\Explorer\StartupApproved\{list}"), + "/v".to_string(), + value_name.to_string(), + "/t".to_string(), + "REG_BINARY".to_string(), + "/d".to_string(), + approved_marker_hex(enabled), + "/f".to_string(), + ], + )?; + let hive = RegKey::predef(if machine { + HKEY_LOCAL_MACHINE + } else { + HKEY_CURRENT_USER + }); + if approved_enabled(&hive, base, list, value_name) != enabled { + return Err("提权写入后状态仍未改变".to_string()); + } + } + Ok(()) + } + + /// Single-quote one argument for a PowerShell -ArgumentList list. + fn quote_ps(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) + } + + /// Run `program args…` elevated through `Start-Process -Verb RunAs`. + /// PowerShell's own exit code reports a cancelled or refused prompt. + fn run_elevated(program: &str, args: &[String]) -> Result<(), String> { + use std::os::windows::process::CommandExt; + let arglist = args + .iter() + .map(|arg| quote_ps(arg)) + .collect::>() + .join(","); + let script = format!( + "$ErrorActionPreference='Stop'; Start-Process -FilePath {} -ArgumentList {} -Verb RunAs -WindowStyle Hidden -Wait", + quote_ps(program), + arglist + ); + let status = std::process::Command::new("powershell.exe") + .args(["-NoProfile", "-NonInteractive", "-Command", &script]) + .creation_flags(0x0800_0000) + .status() + .map_err(|error| format!("无法启动提权助手:{error}"))?; + if status.success() { + Ok(()) + } else { + Err("管理员授权被取消,未做修改".to_string()) + } } fn display_name(command: &str) -> String { @@ -436,9 +572,71 @@ mod windows { /// Per-binary cache payload: (FileDescription, ProductName, icon PNG). type SoftwareInfo = (Option, Option, Option>); + /// Whether a launch path is concrete enough to judge: a drive-qualified or + /// UNC path. `foo.exe` alone resolves against *our* working directory, so + /// answering "missing" for it would invent false 残留项. + fn is_absolute_path(path: &str) -> bool { + let trimmed = path.trim_matches('"'); + let bytes = trimmed.as_bytes(); + (bytes.len() > 2 && bytes[1] == b':' && matches!(bytes[2], b'\\' | b'/')) + || trimmed.starts_with(r"\\") + } + + /// Store packages deny version-info reads to plain users, but their + /// install folder *is* the product identity: `…\WindowsApps\ + /// OpenAI.ChatGPT_1.2025_x64__w269v…\ChatGPT.exe` → "ChatGPT". Without + /// this every packaged app (ChatGPT, Terminal, Notepad) sinks into + /// 其他软件 even though the folder spells the product name out. + fn windows_store_product(path: &str) -> Option { + const MARK: &str = "\\windowsapps\\"; + let lowered = path.to_lowercase().replace('/', "\\"); + let at = lowered.find(MARK)? + MARK.len(); + // The scan lower-cases only to *locate* the folder; the slice from + // the original path keeps the real casing (`OpenAI.ChatGPT_…`). + let original = path.replace('/', "\\"); + let package = original[at..].split('\\').next()?; + let family = package.split('_').next()?; + let product = match family.split_once('.') { + // `Publisher.Product` — the product half is what users say. + Some((_, product)) if !product.trim().is_empty() => product, + Some((publisher, _)) => publisher, + None => family, + }; + let product = product.trim(); + (!product.is_empty()).then(|| product.to_string()) + } + + /// Windows-style *component role* descriptions shipped inside PEs — + /// "Windows File System Proxy" (WinFsp), "Microsoft Edge Elevation + /// Service" — label a role, not a product the user recognises. Rows + /// named only by such a label are not attributed to a software group; + /// they fall into 其他软件 like any anonymous helper. Microsoft-signed + /// ones are usually hidden in 系统组件 anyway. + fn is_component_role_label(text: &str) -> bool { + let lower = text.trim().to_lowercase(); + let vendor_led = lower.starts_with("windows ") || lower.starts_with("microsoft "); + const ROLES: [&str; 10] = [ + "proxy", + "host", + "agent", + "service", + "support", + "helper", + "driver", + "component", + "launcher", + "broker", + ]; + vendor_led && ROLES.iter().any(|role| lower.ends_with(role)) + } + /// Resolve `display_name` (and the software icon) for every scanned - /// entry, once per binary. + /// entry, once per binary. Also settles `target` / `target_exists`: the + /// binary the row really runs, and whether it is still on disk (a missing + /// one is a 残留项). fn decorate_display_names(entries: &mut [StartupEntry]) { + let vendors = vendor_icon_map(); + let products = product_icon_map(); let mut cache: std::collections::HashMap = Default::default(); for entry in entries { let Some(exe) = exe_from_command(&entry.command) else { @@ -452,19 +650,314 @@ mod windows { } else { probed }; + entry.target = probed.clone(); + entry.target_exists = !is_absolute_path(&probed) || Path::new(&probed).exists(); let (description, product, icon) = cache - .entry(exe) + .entry(probed.clone()) .or_insert_with(|| { let (description, product, _company) = version_strings(&probed); - (description, product, exe_icon_png(&probed, 0)) + let usable = |text: Option| text.filter(|t| !is_placeholder_label(t)); + let (description, product) = (usable(description), usable(product)); + // A stub's own PE strings name the product it serves; + // hand that label to the icon lookup so the uninstall + // registry can point at the real binary's icon. + let label = product + .as_deref() + .or(description.as_deref()) + .map(clean_module_name); + let icon = software_icon(&probed, &vendors, &products, label.as_deref()); + (description, product, icon) }) .clone(); entry.display_name = friendly_program_name(&entry.name, description.as_deref(), product.as_deref()); + // 电脑管家's grouping rule: an entry is only attributed to a + // software product when the binary carries real human strings; + // everything else falls into the 其他软件 bucket. A "Windows + // File System Proxy"-style role label names a plumbing part, + // not a product the user recognises — WinFsp's launcher used to + // open its own fake software group through its FileDescription. + entry.named = (description.is_some() || product.is_some()) + && !is_component_role_label(&entry.display_name); + if !entry.named { + if let Some(product) = windows_store_product(&probed) { + entry.display_name = product; + entry.named = true; + } + } entry.icon = icon; } } + /// Whether a PE/ICO file ships *real* icon resources. Service stubs such + /// as `qmbsrv.exe` or Edge's `elevation_service.exe` embed none, and + /// `ExtractAssociatedIconW` then silently returns the generic Windows + /// app tile — the cause of whole columns of 权限管理 rows looking alike. + fn has_icon_resources(path: &str) -> bool { + use windows_sys::Win32::UI::Shell::ExtractIconExW; + let wide: Vec = path.encode_utf16().chain(std::iter::once(0)).collect(); + // SAFETY: NUL-terminated buffer; null handle arrays only ask for the + // count of icons the module carries. + (unsafe { + ExtractIconExW( + wide.as_ptr(), + -1, + std::ptr::null_mut(), + std::ptr::null_mut(), + 0, + ) + }) > 0 + } + + /// `App Paths` is the canonical "where does this tool really live" answer: + /// `SpaceAgent.exe` registers the product binary even when the row points + /// at a stripped-down service stub. Returns an (icon path, index) pair + /// that differs from `except` and exists on disk. + fn app_paths_icon_spec(exe_name: &str, except: &str) -> Option<(String, u16)> { + const APP_PATHS: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths"; + const APP_PATHS_WOW: &str = + r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths"; + let candidates = [ + (HKEY_LOCAL_MACHINE, APP_PATHS), + (HKEY_LOCAL_MACHINE, APP_PATHS_WOW), + (HKEY_CURRENT_USER, APP_PATHS), + ]; + for (hive, base) in candidates { + let Ok(root) = RegKey::predef(hive).open_subkey_with_flags(base, KEY_READ) else { + continue; + }; + let Ok(app) = root.open_subkey_with_flags(exe_name, KEY_READ) else { + continue; + }; + let default: String = app.get_value("").unwrap_or_default(); + let icon: String = app + .open_subkey_with_flags("DefaultIcon", KEY_READ) + .and_then(|key| key.get_value("")) + .unwrap_or_default(); + let spec = if icon.trim().is_empty() { + &default + } else { + &icon + }; + let (path, index) = parse_display_icon(spec)?; + if path.eq_ignore_ascii_case(except.trim_matches('"')) { + continue; + } + if Path::new(&path).exists() { + return Some((path, index)); + } + } + None + } + + /// A sibling in the same folder that does ship an icon: vendors park + /// `Workspace.ico` next to the stub (H3C) or the full binary sits one + /// directory entry away (Edge). `.ico` files win; otherwise the largest + /// `.exe` with real icon resources — the main product binary. + fn sibling_icon_spec(dir: &Path) -> Option<(String, u16)> { + let Ok(read_dir) = std::fs::read_dir(dir) else { + return None; + }; + let mut files: Vec = read_dir.filter_map(Result::ok).map(|f| f.path()).collect(); + files.sort(); + for path in &files { + let is_ico = path + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("ico")); + if is_ico { + return Some((path.to_string_lossy().into_owned(), 0)); + } + } + let mut best: Option<(u64, String)> = None; + for path in &files { + let is_exe = path + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("exe")); + if !is_exe || !has_icon_resources(&path.to_string_lossy()) { + continue; + } + let size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0); + if best.as_ref().map_or(true, |(known, _)| size > *known) { + best = Some((size, path.to_string_lossy().into_owned())); + } + } + best.map(|(_, path)| (path, 0)) + } + + /// Directory → `DisplayIcon` from the uninstall registry — the authoritative + /// "this folder belongs to product X, and X's icon is here" table. Edge, + /// 电脑管家 and SpaceAgent all register one whose parent is exactly the + /// folder holding their icon-less service stubs. Built once per scan. + fn vendor_icon_map() -> std::collections::HashMap { + const UNINSTALLS: [&str; 3] = [ + r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", + r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", + r"Software\Microsoft\Windows\CurrentVersion\Uninstall", + ]; + let mut map: std::collections::HashMap = Default::default(); + for hive in [HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER] { + for base in UNINSTALLS { + let Ok(root) = RegKey::predef(hive).open_subkey_with_flags(base, KEY_READ) else { + continue; + }; + for name in root.enum_keys().filter_map(Result::ok) { + let Ok(app) = root.open_subkey_with_flags(&name, KEY_READ) else { + continue; + }; + let Some(spec): Option = app.get_value("DisplayIcon").ok() else { + continue; + }; + let Some((path, index)) = parse_display_icon(&spec) else { + continue; + }; + let Some(dir) = Path::new(&path).parent() else { + continue; + }; + let dir = dir + .to_string_lossy() + .to_lowercase() + .trim_end_matches('\\') + .to_string(); + if !dir.is_empty() && !map.contains_key(&dir) && Path::new(&path).exists() { + map.insert(dir, (path, index)); + } + } + } + } + map + } + + /// Lower-case product identity of a PE label: cut parenthetical + /// editions ("WeChat (64-bit)") and trim, so a stub's FileDescription + /// can be matched against uninstall-registry keys. + fn clean_module_name(text: &str) -> String { + text.split(['(', '(', '[', '【']) + .next() + .unwrap_or(text) + .trim() + .to_lowercase() + } + + /// Product name → `DisplayIcon` from the uninstall registry. Stubs that + /// ship no icon resources carry the product in their PE strings + /// (`WemeetUpdateSvc.exe` says "腾讯会议", `WXWorkUpgrader.exe` says + /// "WXWorkService"); this map turns that claim into the real binary's + /// icon. Keyed by both the cleaned `DisplayName` and the DisplayIcon + /// file stem so either form finds its product. Built once per scan. + fn product_icon_map() -> std::collections::HashMap { + const UNINSTALLS: [&str; 3] = [ + r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", + r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", + r"Software\Microsoft\Windows\CurrentVersion\Uninstall", + ]; + let mut map: std::collections::HashMap = Default::default(); + for hive in [HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER] { + for base in UNINSTALLS { + let Ok(root) = RegKey::predef(hive).open_subkey_with_flags(base, KEY_READ) else { + continue; + }; + for name in root.enum_keys().filter_map(Result::ok) { + let Ok(app) = root.open_subkey_with_flags(&name, KEY_READ) else { + continue; + }; + let Some(spec): Option = app.get_value("DisplayIcon").ok() else { + continue; + }; + let Some((path, index)) = parse_display_icon(&spec) else { + continue; + }; + if !Path::new(&path).exists() { + continue; + } + if let Ok(display) = app.get_value::("DisplayName") { + let key = clean_module_name(&display); + if !key.is_empty() { + map.entry(key).or_insert_with(|| (path.clone(), index)); + } + } + let stem = Path::new(&path) + .file_stem() + .map(|s| s.to_string_lossy().to_lowercase()) + .unwrap_or_default(); + if !stem.is_empty() { + map.entry(stem).or_insert_with(|| (path.clone(), index)); + } + } + } + } + map + } + + /// Registry key for a stub's claimed product: exact first, then the + /// longest alias that stretches to it ("wxworkservice" → the `wxwork` + /// stem). Aliases shorter than four characters never stretch, so + /// generic words cannot borrow an unrelated tile. + fn product_icon_spec<'a>( + label: &str, + products: &'a std::collections::HashMap, + ) -> Option<&'a (String, u16)> { + if let Some(found) = products.get(label) { + return Some(found); + } + products + .iter() + .filter(|(key, _)| { + key.len() >= 4 && (label.starts_with(key.as_str()) || key.starts_with(label)) + }) + .max_by(|(left, _), (right, _)| left.len().cmp(&right.len())) + .map(|(_, spec)| spec) + } + + /// Startup-list icon with the vendor fallbacks the generic extraction + /// lacks: real resources first, then App Paths, then the uninstall + /// registry's DisplayIcon for the same folder, then the DisplayIcon of + /// the *named* product (a stub's PE strings say which app it belongs to + /// — 腾讯会议's updater lives alone in `Tencent\UpdateSvr\` and ships no + /// icon, while the real `WeMeetApp.exe` is one DisplayIcon away), then a + /// sibling file. `None` (a neutral placeholder in the UI) beats a + /// misleading tile. + fn software_icon( + path: &str, + vendors: &std::collections::HashMap, + products: &std::collections::HashMap, + product_label: Option<&str>, + ) -> Option> { + if has_icon_resources(path) { + return exe_icon_png(path, 0); + } + let file = Path::new(path); + let name = file.file_name()?.to_string_lossy().to_string(); + if let Some((spec, index)) = app_paths_icon_spec(&name, path) { + if let Some(icon) = exe_icon_png(&spec, index) { + return Some(icon); + } + } + let dir_key = file + .parent() + .map(|dir| dir.to_string_lossy().to_lowercase()) + .unwrap_or_default(); + if let Some((spec, index)) = vendors.get(dir_key.trim_end_matches('\\')) { + if let Some(icon) = exe_icon_png(spec, *index) { + return Some(icon); + } + } + if let Some(label) = product_label { + if let Some((spec, index)) = product_icon_spec(&label.to_lowercase(), products) { + if let Some(icon) = exe_icon_png(spec, *index) { + return Some(icon); + } + } + } + if let Some((spec, index)) = file.parent().and_then(sibling_icon_spec) { + if let Some(icon) = exe_icon_png(&spec, index) { + return Some(icon); + } + } + None + } + /// ImagePath entries sometimes carry `"` around paths with spaces even /// mid-command; strip and resolve to something `GetFileVersionInfo` likes. fn exe_to_existing_path(exe: &str) -> String { @@ -859,6 +1352,12 @@ mod windows { id: format!("reg|{hive_label}|{}|{name}", source.key_path), name: display_name(&command), command, + target: String::new(), + target_exists: true, + trigger: "logon".to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "registry".to_string(), @@ -869,6 +1368,7 @@ mod windows { "currentUser".to_string() }, enabled, + named: false, }); } out @@ -903,6 +1403,12 @@ mod windows { .file_stem() .map_or_else(|| file_name.clone(), |s| s.to_string_lossy().to_string()), command: path.display().to_string(), + target: String::new(), + target_exists: true, + trigger: "logon".to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "startupFolder".to_string(), @@ -917,6 +1423,7 @@ mod windows { "currentUser".to_string() }, enabled, + named: false, }); } out @@ -959,12 +1466,19 @@ mod windows { .file_name() .map_or_else(|| task_name.clone(), |n| n.to_string_lossy().to_string()), command: task_actions(&text).unwrap_or_else(|| task_name.clone()), + target: String::new(), + target_exists: true, + trigger: task_trigger(&text), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "scheduledTask".to_string(), source_label: "计划任务".to_string(), scope: "machine".to_string(), enabled: task_settings_enabled(&text), + named: false, }); } } @@ -1035,12 +1549,20 @@ mod windows { .rsplit_once('\\') .map_or_else(|| task_name.clone(), |(_, leaf)| leaf.to_string()), command: String::new(), + target: String::new(), + // Nothing was resolved here, so "missing" would be a lie. + target_exists: true, + trigger: "unknown".to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "scheduledTask".to_string(), source_label: "计划任务".to_string(), scope: "machine".to_string(), enabled, + named: false, }); } out @@ -1158,6 +1680,14 @@ mod windows { id: format!("svc|{name}"), name: display, command: image, + target: String::new(), + target_exists: true, + // Automatic services are started by the SCM during boot; + // manual/disabled ones only run on demand. + trigger: if start == 2 { "boot" } else { "background" }.to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "service".to_string(), @@ -1169,6 +1699,7 @@ mod windows { .to_string(), scope: "machine".to_string(), enabled: start == 2, + named: false, }); } out @@ -1204,6 +1735,21 @@ mod windows { !tail[..end].contains("false") } + /// When a task fires: a BootTrigger runs before anyone logs on, a + /// LogonTrigger at logon, anything else (calendar, event, maintenance) is + /// a background schedule the user does not experience as "startup". + fn task_trigger(text: &str) -> String { + if text.contains("") { + "background".to_string() + } else { + "unknown".to_string() + } + } + fn task_actions(text: &str) -> Option { let start = text.find("")? + "".len(); let end = text[start..].find("")? + start; @@ -1260,9 +1806,142 @@ mod windows { entries.extend(scheduled_task_entries()); entries.extend(auto_service_entries()); decorate_display_names(&mut entries); + attribute_vendor_suites(&mut entries); + enrich_trust(&mut entries); entries } + /// `(vendor folder, product sub-folder)` for a path installed under + /// Program Files: `C:\Program Files\H3C\Workspace\cameraservice.exe` → + /// `("H3C", "Workspace")`. Files dropped directly into Program Files, + /// and generic containers, carry no suite. + fn suite_path(path: &str) -> Option<(String, String)> { + const GENERIC: [&str; 5] = [ + "common files", + "windowsapps", + "internet explorer", + "dotnet", + "modifiable windows apps", + ]; + let normalized = path.replace('/', "\\"); + let lower = normalized.to_lowercase(); + for marker in ["\\program files (x86)\\", "\\program files\\"] { + let Some(at) = lower.find(marker) else { + continue; + }; + let mut parts = normalized[at + marker.len()..] + .split('\\') + .filter(|part| !part.is_empty()); + let (Some(vendor), Some(child)) = (parts.next(), parts.next()) else { + return None; + }; + // The child must be a folder: `Tencent\Weixin.exe` sits directly + // in the vendor folder and owns no suite. + if child.contains('.') { + return None; + } + if GENERIC.contains(&vendor.to_lowercase().as_str()) { + return None; + } + return Some((vendor.to_string(), child.to_string())); + } + None + } + + /// Suite grouping the 电脑管家 habit: H3C Workspace spreads one product + /// across `H3C\Workspace`, `H3C\SpaceAgent`, `H3C\Workspace\Device + /// Redirect\…` and each stub binary ships no version strings, so rows + /// scattered into singleton groups and 其他软件. A vendor folder hosting + /// two or more distinct product sub-folders across the scan *is* the + /// product identity — fold every weakly-attributed row into it. Rows a + /// PE honestly named (微信, Microsoft Edge) keep their own groups. When a + /// `Workspace` sub-folder exists the group reads 厂商 Workspace, the + /// suite's own product name, rather than a bare vendor letter. + fn attribute_vendor_suites(entries: &mut [StartupEntry]) { + use std::collections::{HashMap, HashSet}; + let mut families: HashMap)> = HashMap::new(); + for entry in entries.iter() { + let path = if entry.target.is_empty() { + &entry.command + } else { + &entry.target + }; + let Some((vendor, child)) = suite_path(path) else { + continue; + }; + let family = families + .entry(vendor.to_lowercase()) + .or_insert_with(|| (vendor.clone(), HashSet::new())); + family.1.insert(child.to_lowercase()); + } + for entry in entries.iter_mut() { + // Merge weakly-attributed rows: nothing found, the "product + // name" echoes the technical key, or it is a bare ASCII label + // (H3C's stubs self-name PrintDaemon / VDI USB Redirect — + // components, not products). A PE that carries a real human + // product name (微信, Microsoft Edge-style CJK naming included) + // keeps its own group. + let honest = entry.named && !entry.display_name.eq_ignore_ascii_case(&entry.name); + if honest && has_cjk(&entry.display_name) { + continue; + } + let path = if entry.target.is_empty() { + &entry.command + } else { + &entry.target + }; + let Some((vendor, _)) = suite_path(path) else { + continue; + }; + let Some((vendor_label, children)) = families.get(&vendor.to_lowercase()) else { + continue; + }; + if children.len() < 2 { + continue; + } + entry.display_name = if children.iter().any(|child| child == "workspace") { + format!("{vendor_label} Workspace") + } else { + vendor_label.clone() + }; + entry.named = true; + } + } + + /// One batched signature grade over every resolved target, then stamp the + /// verdict and fold Microsoft-signed / %SystemRoot% rows into 系统组件 — + /// the same trust table the 进阶启动项 tab shows, shared so a scan pays + /// for one PowerShell process, not one per row. + fn enrich_trust(entries: &mut [StartupEntry]) { + let system_root = std::env::var("SystemRoot") + .unwrap_or_else(|_| r"C:\Windows".to_string()) + .to_lowercase(); + let mut targets: Vec = Vec::new(); + for entry in entries.iter_mut() { + entry.system_item = entry.target.to_lowercase().starts_with(&system_root); + if entry.target_exists + && !entry.target.is_empty() + && !targets + .iter() + .any(|seen| seen.eq_ignore_ascii_case(&entry.target)) + { + targets.push(entry.target.clone()); + } + } + let grades = crate::advanced::windows::signature_grades(&targets); + for entry in entries.iter_mut() { + if let Some((verdict, signer)) = grades.get(&entry.target.to_ascii_lowercase()) { + entry.signature = verdict.clone(); + entry.signer = signer.clone(); + if verdict == "microsoft" { + entry.system_item = true; + } + } else { + entry.signature = "unknown".into(); + } + } + } + pub(super) fn set_startup_enabled(entry: &StartupEntry, enabled: bool) -> Result<(), String> { let Some((kind, rest)) = entry.id.split_once('|') else { return Err("未知的启动项来源".to_string()); @@ -1279,7 +1958,7 @@ mod windows { } else { name.to_string() }; - write_approved(machine, &base, list, &marker, enabled) + flip_approved(machine, &base, list, &marker, enabled) } "folder" => { let file = Path::new(rest) @@ -1287,7 +1966,7 @@ mod windows { .map(|n| n.to_string_lossy().to_string()) .ok_or_else(|| "启动文件夹项目路径无效".to_string())?; let machine = rest.contains("ProgramData"); - write_approved(machine, CURRENT_VERSION, "StartupFolder", &file, enabled) + flip_approved(machine, CURRENT_VERSION, "StartupFolder", &file, enabled) } "task" => { use std::os::windows::process::CommandExt; @@ -1302,23 +1981,79 @@ mod windows { .output() .map_err(|error| format!("无法调用 schtasks:{error}"))?; if output.status.success() { - Ok(()) - } else { - Err(format!( + return Ok(()); + } + let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase(); + // schtasks reports "task not ready", missing tasks, etc. — + // only a plain access denial justifies a UAC round-trip. + let denied = stderr.contains("access is denied") + || stderr.contains("access denied") + || stderr.contains("拒绝访问"); + if !denied { + return Err(format!( "计划任务修改失败:{}", String::from_utf8_lossy(&output.stderr).trim() - )) + )); } + run_elevated( + "schtasks.exe", + &[ + "/Change".to_string(), + "/TN".to_string(), + rest.to_string(), + if enabled { "/Enable" } else { "/Disable" }.to_string(), + ], + )?; + Ok(()) } "svc" => { // 开 = Automatic(2),关 = Manual(3):保留按需启动能力, // 与管家的“禁止开机自启”语义一致;HKLM 写入需要管理员。 - let key = RegKey::predef(HKEY_LOCAL_MACHINE) - .open_subkey_with_flags(format!(r"{SERVICES_KEY}\{rest}"), KEY_READ | KEY_WRITE) - .map_err(registry_error)?; - key.set_value("Start", &(if enabled { 2u32 } else { 3u32 })) - .map_err(registry_error)?; - let _ = service_control(rest, if enabled { "auto" } else { "demand" }); + let start = if enabled { 2u32 } else { 3u32 }; + let key_path = format!(r"{SERVICES_KEY}\{rest}"); + let direct = (|| -> std::io::Result<()> { + let key = RegKey::predef(HKEY_LOCAL_MACHINE) + .open_subkey_with_flags(&key_path, KEY_READ | KEY_WRITE)?; + key.set_value("Start", &start) + })(); + if let Err(why) = direct { + if why.kind() != std::io::ErrorKind::PermissionDenied { + return Err(registry_error(why)); + } + run_elevated( + "reg.exe", + &[ + "add".to_string(), + format!(r"HKLM\{key_path}"), + "/v".to_string(), + "Start".to_string(), + "/t".to_string(), + "REG_DWORD".to_string(), + "/d".to_string(), + start.to_string(), + "/f".to_string(), + ], + )?; + let live = RegKey::predef(HKEY_LOCAL_MACHINE) + .open_subkey_with_flags(&key_path, KEY_READ) + .map(|key| key.get_value::("Start").ok()) + .ok() + .flatten(); + if live != Some(start) { + return Err("提权写入后服务状态仍未改变".to_string()); + } + } + if service_control(rest, if enabled { "auto" } else { "demand" }).is_err() { + let _ = run_elevated( + "sc.exe", + &[ + "config".to_string(), + rest.to_string(), + "start=".to_string(), + if enabled { "auto" } else { "demand" }.to_string(), + ], + ); + } Ok(()) } _ => Err("未知的启动项来源".to_string()), @@ -1337,6 +2072,149 @@ mod windows { .map(|_| ()) } + /// Remove one autostart registration; see the module-level + /// `remove_startup_entry` for the semantics per source kind. + pub(super) fn remove_startup_entry(entry: &StartupEntry) -> Result<(), String> { + let Some((kind, rest)) = entry.id.split_once('|') else { + return Err("未知的启动项来源".to_string()); + }; + match kind { + "reg" => { + let pieces: Vec<&str> = rest.splitn(3, '|').collect(); + let [hive_label, key_path, name] = pieces.as_slice() else { + return Err("未知的启动项来源".to_string()); + }; + let (machine, base, list, prefix32) = split_run_path(hive_label, key_path); + let hive = RegKey::predef(if machine { + HKEY_LOCAL_MACHINE + } else { + HKEY_CURRENT_USER + }); + let direct = (|| -> std::io::Result<()> { + let key = hive.open_subkey_with_flags(key_path, KEY_READ | KEY_WRITE)?; + key.delete_value(*name) + })(); + if let Err(why) = direct { + if why.kind() != std::io::ErrorKind::PermissionDenied { + return Err(registry_error(why)); + } + run_elevated( + "reg.exe", + &[ + "delete".to_string(), + format!(r"{hive_label}\{key_path}"), + "/v".to_string(), + name.to_string(), + "/f".to_string(), + ], + )?; + if hive + .open_subkey_with_flags(key_path, KEY_READ) + .map(|key| key.get_raw_value(*name).is_ok()) + .unwrap_or(false) + { + return Err("提权删除后启动项仍然存在".to_string()); + } + } + // Task Manager keeps its own approval marker next to the row; + // drop it so the removed name cannot resurface as a ghost. + let marker = if prefix32 { + format!("32|{name}") + } else { + name.to_string() + }; + let _ = hive + .open_subkey_with_flags( + format!(r"{base}\Explorer\StartupApproved\{list}"), + KEY_READ | KEY_WRITE, + ) + .and_then(|key| key.delete_value(&marker)); + Ok(()) + } + "folder" => { + let file = Path::new(rest); + match std::fs::remove_file(file) { + Ok(()) => Ok(()), + Err(why) if why.kind() == std::io::ErrorKind::PermissionDenied => { + run_elevated( + "cmd.exe", + &["/C".to_string(), "del".to_string(), format!("/F /Q {rest}")], + )?; + if file.exists() { + return Err("提权删除后快捷方式仍然存在".to_string()); + } + Ok(()) + } + Err(why) => Err(format!("删除快捷方式失败:{why}")), + } + } + "task" => { + use std::os::windows::process::CommandExt; + let output = std::process::Command::new("schtasks.exe") + .args(["/Delete", "/TN", rest, "/F"]) + .creation_flags(0x0800_0000) + .output() + .map_err(|error| format!("无法调用 schtasks:{error}"))?; + if output.status.success() { + return Ok(()); + } + let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase(); + if stderr.contains("access is denied") + || stderr.contains("access denied") + || stderr.contains("拒绝访问") + { + run_elevated( + "schtasks.exe", + &[ + "/Delete".to_string(), + "/TN".to_string(), + rest.to_string(), + "/F".to_string(), + ], + )?; + return Ok(()); + } + Err(format!( + "删除计划任务失败:{}", + String::from_utf8_lossy(&output.stderr).trim() + )) + } + "svc" => { + // Uninstalling a service outright breaks anything that still + // opens it, so 残留服务 is disabled instead (Start = 4). + set_startup_enabled(entry, false)?; + let key_path = format!(r"{SERVICES_KEY}\{rest}"); + let direct = (|| -> std::io::Result<()> { + let key = RegKey::predef(HKEY_LOCAL_MACHINE) + .open_subkey_with_flags(&key_path, KEY_READ | KEY_WRITE)?; + key.set_value("Start", &4u32) + })(); + if let Err(why) = direct { + if why.kind() != std::io::ErrorKind::PermissionDenied { + return Err(registry_error(why)); + } + run_elevated( + "reg.exe", + &[ + "add".to_string(), + format!(r"HKLM\{key_path}"), + "/v".to_string(), + "Start".to_string(), + "/t".to_string(), + "REG_DWORD".to_string(), + "/d".to_string(), + "4".to_string(), + "/f".to_string(), + ], + )?; + } + let _ = service_control(rest, "disabled"); + Ok(()) + } + _ => Err("这类启动项暂不支持删除".to_string()), + } + } + fn split_run_path(hive_label: &str, key_path: &str) -> (bool, String, &'static str, bool) { let machine = hive_label == "HKLM"; let wow = key_path.starts_with(WOW_CURRENT_VERSION); @@ -1469,9 +2347,12 @@ mod windows { icon = exe_icon_png(&clean, 0); cleaned = Some(clean); } - let friendly_name = module_label - .or_else(|| cleaned.as_deref().and_then(module_folder_name)) - .or(clsid_name); + // Attribution for the UI's software grouping: a row belongs to a + // product when its module carries real strings or sits in a + // recognisable install folder — same rule the startup list uses. + let folder_label = cleaned.as_deref().and_then(module_folder_name); + let named = module_label.is_some() || folder_label.is_some(); + let friendly_name = module_label.or(folder_label).or(clsid_name); if is_builtin_handler(&name, friendly_name.as_deref(), cleaned.as_deref()) { continue; } @@ -1489,6 +2370,7 @@ mod windows { module: cleaned.or(module), publisher, icon, + named, }); } out @@ -1737,9 +2619,296 @@ mod windows { #[cfg(test)] mod tests { use super::{ - clean_module_path, exe_from_command, friendly_program_name, has_cjk, - is_placeholder_label, module_folder_name, parse_csv_line, task_settings_enabled, + approved_enabled, attribute_vendor_suites, clean_module_name, clean_module_path, + exe_from_command, friendly_program_name, has_cjk, is_component_role_label, + is_placeholder_label, module_folder_name, parse_csv_line, product_icon_map, + product_icon_spec, split_run_path, suite_path, task_settings_enabled, + windows_store_product, write_approved, StartupEntry, CURRENT_VERSION, }; + use winreg::RegKey; + + #[test] + fn role_labels_are_not_products() { + // WinFsp's launcher names itself "Windows File System Proxy"; + // that is plumbing, so the row must not open its own group. + assert!(is_component_role_label("Windows File System Proxy")); + assert!(is_component_role_label("Microsoft Edge Elevation Service")); + assert!(is_component_role_label( + "Windows Push Notifications User Service" + )); + // Real products keep their groups, Chinese or English. + assert!(!is_component_role_label("微信")); + assert!(!is_component_role_label("Windows Defender Firewall")); + assert!(!is_component_role_label("Everything")); + assert!(!is_component_role_label("WinFsp Launcher")); + } + + #[test] + fn the_live_scan_leaves_winfsp_unattributed() { + // The user's exact complaint: the WinFsp launcher service opened + // a "Windows File System Proxy" software group of its own. + if !std::path::Path::new(r"C:\Program Files (x86)\WinFsp").exists() { + eprintln!("skipping: no WinFsp on this machine"); + return; + } + let entries = super::scan_startup(); + let launcher: Vec<_> = entries + .iter() + .filter(|entry| { + entry + .target + .to_lowercase() + .starts_with(r"c:\program files (x86)\winfsp") + }) + .collect(); + assert!(!launcher.is_empty(), "WinFsp rows vanished"); + assert!( + launcher.iter().all(|entry| !entry.named), + "WinFsp still attributed: {:?}", + launcher + .iter() + .map(|entry| (&entry.name, &entry.display_name, entry.named)) + .collect::>() + ); + } + + #[test] + fn suite_paths_need_a_vendor_and_a_child_folder() { + assert_eq!( + suite_path(r"C:\Program Files\H3C\Workspace\cameraservice.exe"), + Some(("H3C".into(), "Workspace".into())) + ); + assert_eq!( + suite_path(r"C:\Program Files (x86)\Common Files\acme\x.exe"), + None, + "Common Files is not a vendor" + ); + assert_eq!( + suite_path(r"C:\Program Files\Tencent\Weixin.exe"), + None, + "a loose file in Program Files has no suite" + ); + } + + #[test] + fn clean_module_names_drop_editions_and_case() { + assert_eq!(clean_module_name("WeChat (64-bit)"), "wechat"); + assert_eq!(clean_module_name("腾讯会议(企业版) "), "腾讯会议"); + assert_eq!(clean_module_name(" WXWorkService "), "wxworkservice"); + } + + #[test] + fn a_stub_borrows_its_products_icon_by_label() { + // Two shapes of the same problem: 腾讯会议's stub says exactly + // what the uninstall `DisplayName` says, 企业微信's says + // "WXWorkService" while the registry keys are 企业微信 / + // `wxwork.exe`. The first matches by name, the second must + // stretch to the longest alias. + let products = product_icon_map(); + let Some(wechat) = products.get("企业微信").or_else(|| products.get("wxwork")) + else { + eprintln!("skipping: 企业微信 not installed"); + return; + }; + assert!( + product_icon_spec("wxworkservice", &products).is_some_and(|found| found == wechat), + "the upgrader label did not resolve to the product icon" + ); + // Too-short keys never stretch, or "ab" would own everything; + // a label stretching *down* to a shorter alias is the rule. + let mut tiny: std::collections::HashMap = Default::default(); + tiny.insert("ab".into(), ("unrelated.exe".into(), 0)); + tiny.insert("wemeet".into(), wechat.clone()); + assert!(product_icon_spec("wemeetupd", &tiny).is_some_and(|found| found == wechat)); + assert!(product_icon_spec("zeta", &tiny).is_none()); + } + + #[test] + fn the_live_scan_icons_the_stubbin_updaters() { + // 腾讯会议 keeps `WemeetUpdateSvc.exe` alone in + // `Tencent\UpdateSvr\` with zero icon resources, and 企业微信's + // `WXWorkUpgrader.exe` is the same trick; both used to render a + // grey initial tile in the startup groups. Skips off those boxes. + let meetings = std::path::Path::new(r"C:\Program Files (x86)\Tencent\UpdateSvr"); + let wechat = std::path::Path::new(r"D:\Program Files (x86)\WXWork"); + if !meetings.exists() && !wechat.exists() { + eprintln!("skipping: no Tencent updater stubs on this machine"); + return; + } + let entries = super::scan_startup(); + let stubs: Vec<_> = entries + .iter() + .filter(|entry| { + entry.target.to_lowercase().contains("wemeetupdatesvc") + || entry.target.to_lowercase().contains("wxworkupgrader") + }) + .collect(); + assert!( + !stubs.is_empty(), + "the updater stubs vanished from the scan" + ); + for stub in &stubs { + assert!( + stub.icon.is_some(), + "{} has no icon: {:?}", + stub.name, + stub.target + ); + } + } + + #[test] + fn the_live_scan_folds_h3c_into_one_suite_group() { + // The real complaint on the H3C VDI machine: cameraservice, + // SpaceAgent and the Device Redirect services scattered across + // singleton groups and 其他软件 despite sharing no version + // strings. Skips silently off the affected hardware. + if !std::path::Path::new(r"C:\Program Files\H3C\Workspace").exists() { + eprintln!("skipping: no H3C Workspace on this machine"); + return; + } + let entries = super::scan_startup(); + let h3c: Vec<_> = entries + .iter() + .filter(|entry| { + entry + .target + .to_lowercase() + .starts_with(r"c:\program files\h3c\") + }) + .collect(); + assert!(!h3c.is_empty(), "H3C rows vanished from the scan"); + assert!( + h3c.iter() + .all(|entry| entry.display_name == "H3C Workspace"), + "H3C rows split: {:?}", + h3c.iter() + .map(|entry| (&entry.name, &entry.display_name)) + .collect::>() + ); + } + + #[test] + fn one_vendor_two_products_fold_into_a_suite_group() { + fn entry(name: &str, target: &str) -> StartupEntry { + StartupEntry { + id: format!("svc|{name}"), + name: name.into(), + command: target.into(), + display_name: name.into(), + icon: None, + target: target.into(), + target_exists: true, + trigger: "boot".into(), + system_item: false, + signature: String::new(), + signer: None, + source: "service".into(), + source_label: "服务(自动启动)".into(), + scope: "machine".into(), + enabled: true, + named: false, + } + } + let mut entries = vec![ + entry( + "CameraRedirectService", + r"C:\Program Files\H3C\Workspace\cameraservice.exe", + ), + entry( + "PrintDaemon", + r"C:\Program Files\H3C\Workspace\Device Redirect\PrintRedir\PrintDaemon.exe", + ), + entry( + "SpaceAgent", + r"C:\Program Files\H3C\SpaceAgent\SpaceAgent.exe", + ), + // Honest PE names never merge, even under a suite vendor. + entry("Weixin", r"C:\Program Files\Tencent\Weixin\Weixin.exe"), + ]; + entries[3].display_name = "微信".into(); + entries[3].named = true; + attribute_vendor_suites(&mut entries); + for entry in &entries[..3] { + assert_eq!(entry.display_name, "H3C Workspace", "{}", entry.name); + assert!(entry.named); + } + assert_eq!(entries[3].display_name, "微信"); + } + + #[test] + fn store_packages_are_attributed_by_their_package_folder() { + // MSIX installs deny version-info reads, so the folder is the + // only honest product name: these must escape 其他软件. + assert_eq!( + windows_store_product( + r"C:\Program Files\WindowsApps\OpenAI.ChatGPT_1.2025.10.0_x64__w269v8zz8d6vy\ChatGPT.exe" + ) + .as_deref(), + Some("ChatGPT") + ); + assert_eq!( + windows_store_product( + r"C:\PROGRAM FILES\WINDOWSAPPS\Microsoft.WindowsTerminal_1.21\wt.exe" + ) + .as_deref(), + Some("WindowsTerminal") + ); + } + + #[test] + fn ordinary_paths_have_no_store_product() { + assert_eq!( + windows_store_product(r"D:\Program Files\Tencent\Weixin\Weixin.exe"), + None + ); + assert_eq!(windows_store_product("Weixin.exe"), None); + } + + #[test] + fn toggle_round_trips_through_the_approved_marker() { + // The exact pair the UI toggle relies on: write_approved stores a + // marker, the rescan reads it back. If these ever drift, every + // startup switch silently snaps back — the "button is dead" bug. + let list = format!("squidTest{}", std::process::id()); + let hive = RegKey::predef(winreg::enums::HKEY_CURRENT_USER); + let key_path = format!(r"{CURRENT_VERSION}\Explorer\StartupApproved\{list}"); + for name in ["squid-off", "squid-on"] { + let want = name.ends_with("on"); + if let Err(why) = write_approved(false, CURRENT_VERSION, &list, name, want) { + // Sandboxed CI runners deny registry writes; the marker + // round-trip cannot be proven here, so say so instead of + // failing a correct build. + eprintln!("skipping marker round-trip: registry write denied ({why})"); + return; + } + assert_eq!( + approved_enabled(&hive, CURRENT_VERSION, &list, name), + want, + "{name} must read back as written" + ); + } + let _ = hive.delete_subkey_all(&key_path); + } + + #[test] + fn run_path_split_round_trips_hive_and_list() { + // set_startup_enabled re-derives (machine, base, list) from the + // id scan produced; a mismatch writes the marker to the wrong key + // and the rescan then shows the old state. + let wow_run = r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run".to_string(); + let (machine, base, list, prefix32) = split_run_path("HKLM", &wow_run); + assert!(machine); + assert_eq!(list, "Run"); + assert!(prefix32); + assert!(base.contains("WOW6432Node")); + let (machine, base, list, prefix32) = + split_run_path("HKCU", &format!(r"{CURRENT_VERSION}\RunOnce")); + assert!(!machine); + assert_eq!(list, "RunOnce"); + assert!(!prefix32); + assert_eq!(base, CURRENT_VERSION); + } #[test] fn command_paths_survive_quotes_and_arguments() { @@ -1954,12 +3123,19 @@ mod macos { id: format!("launchAgent|{}", path.display()), name: label_text, command: path.display().to_string(), + target: String::new(), + target_exists: true, + trigger: "logon".to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "launchAgent".to_string(), source_label: label.to_string(), scope: scope.to_string(), enabled, + named: true, }); } out @@ -2058,12 +3234,19 @@ mod linux { id: format!("autostart|{}", path.display()), name, command: exec, + target: String::new(), + target_exists: true, + trigger: "logon".to_string(), + system_item: false, + signature: String::new(), + signer: None, display_name: String::new(), icon: None, source: "autostart".to_string(), source_label: "~/.config/autostart".to_string(), scope: "currentUser".to_string(), enabled, + named: true, }); } for entry in &mut out { diff --git a/crates/squid-platform/src/windows.rs b/crates/squid-platform/src/windows.rs index 2db559d..c3ba5d2 100644 --- a/crates/squid-platform/src/windows.rs +++ b/crates/squid-platform/src/windows.rs @@ -12,7 +12,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; use sysinfo::{Disks, System}; use winreg::enums::{ - HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, KEY_WOW64_64KEY, + HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, KEY_WOW64_64KEY, KEY_WRITE, }; use winreg::RegKey; @@ -23,27 +23,135 @@ const UNINSTALL_SUBKEY: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Unins const NT_VERSION_KEY: &str = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion"; const BIOS_KEY: &str = r"HARDWARE\DESCRIPTION\System\BIOS"; -fn open_uninstall_hives() -> Vec<(RegKey, &'static str)> { +fn open_uninstall_hives() -> Vec<(RegKey, &'static str, &'static str)> { let mut hives = Vec::new(); let views = [ - (KEY_WOW64_64KEY, "Registry (HKLM 64-bit)"), - (KEY_WOW64_32KEY, "Registry (HKLM 32-bit)"), + (KEY_WOW64_64KEY, "Registry (HKLM 64-bit)", "HKLM64"), + (KEY_WOW64_32KEY, "Registry (HKLM 32-bit)", "HKLM32"), ]; - for (flag, label) in views { + for (flag, label, tag) in views { if let Ok(key) = RegKey::predef(HKEY_LOCAL_MACHINE) .open_subkey_with_flags(UNINSTALL_SUBKEY, KEY_READ | flag) { - hives.push((key, label)); + hives.push((key, label, tag)); } } if let Ok(key) = RegKey::predef(HKEY_CURRENT_USER).open_subkey_with_flags(UNINSTALL_SUBKEY, KEY_READ) { - hives.push((key, "Registry (HKCU)")); + hives.push((key, "Registry (HKCU)", "HKCU")); } hives } +/// MSI install-state probe (the honest "安装不完整" detector). A registry +/// record whose product state is Unknown/Broken/Removed means the MSI +/// package itself is gone — the record is an orphan no msiexec can honour. +mod msi { + #[link(name = "msi")] + extern "system" { + fn MsiQueryProductStateW(product: *const u16) -> i32; + } + + // INSTALLSTATE: 0 Unknown, 1 Broken, 2 Advertised, 3 Removed, + // 4 Installed, 5 Local, 6 Source, 7 Default. + fn wide(text: &str) -> Vec { + text.encode_utf16().chain(std::iter::once(0)).collect() + } + + /// True when the MSI product for `guid` is missing or unusable. + pub fn product_broken(guid: &str) -> bool { + let normalized = guid.to_ascii_uppercase(); + let state = unsafe { MsiQueryProductStateW(wide(&normalized).as_ptr()) }; + matches!(state, 0 | 1 | 3) + } +} + +/// The product GUID inside an `MsiExec.exe /X{GUID}` style command. +fn msi_guid(uninstall_string: &str) -> Option<&str> { + let upper = uninstall_string.to_ascii_uppercase(); + if !upper.contains("MSIEXEC") { + return None; + } + let start = uninstall_string.find('{')?; + let end = uninstall_string[start..].find('}')? + start + 1; + Some(&uninstall_string[start..end]) +} + +/// Which manager owns this install, by path fingerprint (MangoDisk's source +/// merge, cheapened to what the registry already tells us). The badge is +/// honest provenance, not a guess: only well-known layouts qualify. +fn package_source(path: &Path, fallback: &str) -> String { + let lower = path.to_string_lossy().to_lowercase(); + if lower.contains("\\windowsapps\\") { + return "Microsoft Store".into(); + } + if lower.contains("\\scoop\\apps\\") { + return "scoop".into(); + } + if lower.contains("\\chocolatey\\") { + return "Chocolatey".into(); + } + if lower.contains("\\winget\\") || lower.contains("\\packages\\desktopappinstaller") { + return "winget".into(); + } + if lower.contains("\\jetbrains\\toolbox\\apps\\") { + return "Toolbox".into(); + } + fallback.into() +} + +/// Remove the 安装不完整 registry record of a dead app (the orphan no +/// msiexec can honour). `reg_key` is the scanner's "HKLM64|" tag. +/// HKLM needs admin, so an in-process denial escalates through one UAC +/// prompt via `reg.exe` — the record either goes or the user declines. +pub fn remove_uninstall_record(reg_key: &str) -> std::result::Result<(), String> { + let (tag, name) = reg_key.split_once('|').ok_or("注册表记录标识无效")?; + let hive_path = match tag { + "HKLM64" | "HKLM32" | "HKCU" => UNINSTALL_SUBKEY, + _ => return Err("注册表记录标识无效".into()), + }; + if tag != "HKCU" { + use std::os::windows::process::CommandExt; + // reg.exe spells the 32-bit view through WOW6432Node. + let elevated_path = format!( + "HKLM\\{}\\{}", + if tag == "HKLM32" { + r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall" + } else { + hive_path + }, + name + ); + let status = Command::new("reg.exe") + .args(["delete", &elevated_path, "/f"]) + .creation_flags(0x0800_0000) // no console flash + .status(); + if matches!(&status, Ok(s) if s.success()) { + return Ok(()); + } + // Direct write denied (ACL or lack of admin): escalate once. + let script = format!( + "$ErrorActionPreference='Stop'; Start-Process -FilePath 'reg.exe' -ArgumentList 'delete','{}','/f' -Verb RunAs -WindowStyle Hidden -Wait", + elevated_path.replace('\'', "''") + ); + let escalated = Command::new("powershell.exe") + .args(["-NoProfile", "-NonInteractive", "-Command", &script]) + .creation_flags(0x0800_0000) + .status() + .map_err(|error| format!("无法启动提权助手:{error}"))?; + if !escalated.success() { + return Err("管理员授权被取消,注册表记录未删除".into()); + } + return Ok(()); + } + let hive = RegKey::predef(HKEY_CURRENT_USER) + .open_subkey_with_flags(hive_path, KEY_READ | KEY_WRITE) + .map_err(|error| format!("无法打开卸载注册表:{error}"))?; + hive.delete_subkey_all(name) + .map_err(|error| format!("删除注册表记录失败:{error}")) +} + fn str_value(key: &RegKey, name: &str) -> Option { key.get_value::(name) .ok() @@ -254,7 +362,7 @@ impl Platform for Windows { .map(|p| p.to_lowercase()) .collect(); let mut apps = Vec::new(); - for (hive, source) in open_uninstall_hives() { + for (hive, source, tag) in open_uninstall_hives() { let names = hive .enum_keys() .filter_map(|name| name.ok()) @@ -295,6 +403,21 @@ impl Platform for Windows { running.iter().any(|exe| exe.starts_with(&loc)) }) .unwrap_or(false); + // 安装不完整 detection (MangoDisk's cross-check): the record + // exists but the product cannot be found any more — the MSI + // state says gone, or neither the install folder nor the + // uninstaller binary is on disk. + let dead = match uninstall_string.as_deref().and_then(msi_guid) { + Some(guid) => msi::product_broken(guid), + None => { + let uninstaller_gone = uninstall_string + .as_deref() + .and_then(uninstall_program) + .map(|exe| !exe.exists()) + .unwrap_or(true); + install_location.is_none() && uninstaller_gone + } + }; // Size: Windows installers report EstimatedSize (KB) for // Add/Remove Programs — the same number Settings shows. // Absent that, measure the install folder when asked. @@ -308,6 +431,10 @@ impl Platform for Windows { .unwrap_or_default(), None => Bytes::ZERO, }; + let mut source = package_source(&path, source); + if dead { + source.push_str(" · 安装不完整"); + } apps.push(AppInfo { name: display_name, bundle_id: None, @@ -315,12 +442,15 @@ impl Platform for Windows { icon_source: display_icon_path(str_value(&key, "DisplayIcon")), version: str_value(&key, "DisplayVersion"), size, - source: source.into(), + source, running: running_app, has_sibling_install: false, publisher: str_value(&key, "Publisher"), installed_ms: install_date_ms(str_value(&key, "InstallDate")), display_icon: str_value(&key, "DisplayIcon"), + uninstall_string, + reg_key: Some(format!("{tag}|{name}")), + dead, }); } } diff --git a/crates/squid-tui/src/app.rs b/crates/squid-tui/src/app.rs index 0464c77..b141e11 100644 --- a/crates/squid-tui/src/app.rs +++ b/crates/squid-tui/src/app.rs @@ -889,6 +889,8 @@ impl App { }; panel.buckets.insert(category, (total, count)); } + Event::Metered { .. } => {} + Event::Group { .. } => {} Event::Deleted { path, freed } => { self.push_log(format!( "removed {} ({})", @@ -2611,6 +2613,7 @@ mod tests { publisher: None, installed_ms: None, display_icon: None, + ..AppInfo::default() }; let items = vec![ CleanupItem::new( @@ -2708,6 +2711,7 @@ mod tests { publisher: None, installed_ms: None, display_icon: None, + ..AppInfo::default() }]; app.uninstall.filter = "Squid".into(); assert_eq!(app.uninstall.visible().len(), 1); diff --git a/crates/squid-tui/src/theme.rs b/crates/squid-tui/src/theme.rs index bbf33b3..2f9a500 100644 --- a/crates/squid-tui/src/theme.rs +++ b/crates/squid-tui/src/theme.rs @@ -135,6 +135,9 @@ impl Strings { C::LanguagePacks => "多余语言包", C::Leftovers => "卸载残留", C::UpdateInstallers => "升级安装包", + C::Duplicates => "重复文件", + C::AiTools => "AI 工具与模型", + C::Privacy => "隐私痕迹", C::Trash => self.bin(), }, }) diff --git a/crates/squid-tui/src/views.rs b/crates/squid-tui/src/views.rs index d21f31c..73977ab 100644 --- a/crates/squid-tui/src/views.rs +++ b/crates/squid-tui/src/views.rs @@ -2054,6 +2054,7 @@ mod tests { publisher: None, installed_ms: None, display_icon: None, + ..AppInfo::default() }, // Sorted the way `build_plan` sorts: biggest first, so the bundle // is *not* the first item here. @@ -2378,8 +2379,12 @@ mod tests { screen.contains("12.0 GB"), "the row and the header should both read 12.0 GB:\n{screen}" ); + // The bug this guards: the 1 TiB logical size leaking into the row + // or the header. Assert the file's *own* inflated numbers are gone — + // never "no TB anywhere": the host's real volumes (6 TB NAS drives) + // legitimately print TB in the disk panel and made this flaky. assert!( - !screen.contains("TB"), + !screen.contains("1.0 TB") && !screen.contains("1 TiB") && !screen.contains("1024 GB"), "a sparse file must not inflate the total past the physical disk:\n{screen}" ); } diff --git a/docs/RELEASE.md b/docs/RELEASE.md index bb28ae4..d280399 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -1,5 +1,16 @@ # Desktop release and update channel +## 代码仓上传规则(用户指令「上传代码仓」即指本节) + +- 地址:`https://git.unissense.tech/mula/nex_squid.git`(origin 已内置账号, + 凭据 lijunjie,勿写入其他文件)。 +- 分支:**dev**。提交信息用中文,经 `git commit --file -`(或 `-F 文件`)传入, + 避免 pwsh 引号问题;发布二进制需 `git add -f`(release 目录不在 .gitignore + 白名单内)。 +- 打包版上传时同步刷新 `release//`(安装包/便携包/SHA256SUMS/ + squid-update.json/RELEASE_NOTES),并在 `release/CHANGELOG-SINCE-<上次上传版本>.md` + 补每个版本的更新说明,注明本版学习/借鉴的 GitHub 开源项目及链接。 + Squid uses the same release model as `nex_shift`: a git branch is the update server. No object storage or release API is required. diff --git a/docs/cleanbar-mock.html b/docs/cleanbar-mock.html new file mode 100644 index 0000000..beac14f --- /dev/null +++ b/docs/cleanbar-mock.html @@ -0,0 +1,246 @@ + + + + + + + +

Squid 清理进度交互 · 统一 UI 语言

+
重复文件 / 垃圾清理 / 大文件 三处共用同一组件(示意以「重复文件」页为底)。
+ +

① 清理前 现状不变:底部绿色确认条

+
+
+
垃圾清理
+
重复文件612 组
+
大文件
+
+
+
安装包 · 2 个副本 · 共 1.9 GB
+
C:\Users\34798\Downloads\wxworkwindows-4.1.35.6027.exe996 MB
+
建议保留D:\Program Files (x86)\WXWork\9999.1.0\WeCom_Setup.exe996 MB
+
+
+
+
+
✓
+
+
已选中 128 个副本 · 预计释放 3.2 GB
+
其中 2 组将「完全删除」,删除后进入回收站,可从历史撤销
+
+ +
+
+
+
+ +

② 清理中 确认条就地变形 · 真实逐文件进度 · 橙色流光

+
+
+
垃圾清理
+
重复文件612 组
+
大文件
+
+
+
安装包 · 2 个副本 · 共 1.9 GB
+
C:\Users\34798\Downloads\wxworkwindows-4.1.35.6027.exe996 MB
+
建议保留D:\Program Files (x86)\WXWork\9999.1.0\WeCom_Setup.exe996 MB
+
+
+
+
+
+
+
正在清理 37 / 128 个文件 · 已释放 890 MB
+
当前:C:\Users\34798\Downloads\VisualStudioProjSetup-2022.zip(移入回收站)
+
+ 29% + +
+
+
+
期间可正常切页签 / 浏览其他页面,任务后台继续;按钮防重复提交;超过 10 秒才出现「转入后台」(缩成右下角小胶囊,点它随时唤回)。
+
+
+ +

③ 清理完成 原地变绿 + 气泡双保险 · 5 秒自动收起

+
+
+
垃圾清理
+
重复文件604 组
+
大文件
+
+
+
已删除的 128 个副本从列表实时消失,组徽标同步减 8 组
+
+
+
+
+
✓
+
+
清理完成 · 128 个文件已移入回收站 · 释放 3.2 GB
+
用时 41 秒 · 可从「历史」一键撤销
+
+ + +
+
+
+
+ +

④ 部分未处理 琥珀色 · 接入现有「未处理原因」分组页

+
+
+
垃圾清理
+
重复文件605 组
+
大文件
+
+
+
与完成态同位置,仅颜色与文案不同
+
+
+
+
+
!
+
+
已清理 120 个 · 释放 3.1 GB · 8 个未处理
+
占用中 5 · 需要管理员 2 · 文件已消失 1 · 用时 38 秒
+
+ + +
+
+
+
+ +

⑤ 另两页同语言 只换名词,组件/颜色/节奏完全一致

+
+
+
+
+
+
+
正在清理 214 / 986 项 · 已释放 2.4 GB
+
当前:Chrome 缓存 · index-dir\…(阶段 2/3:浏览器缓存)
+
+ 22% + +
+
+
+
+
+
+
+
正在清理 4 / 12 个大文件 · 已释放 6.8 GB
+
当前:D:\VMs\Ubuntu-24.04-disk001.vmdk(移入回收站)
+
+ 33% + +
+
+
+
+
+
✓
+
+
清理完成 · 986 项已处理 · 释放 11.6 GB
+
回收站未清空前仍可恢复 · 用时 1 分 12 秒
+
+ + +
+
+
+
+ + diff --git a/docs/cleanbar-mock.png b/docs/cleanbar-mock.png new file mode 100644 index 0000000..29daf27 Binary files /dev/null and b/docs/cleanbar-mock.png differ diff --git a/package.json b/package.json index f8e2ca4..f32dc71 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "squid-desktop", "private": true, - "version": "0.1.11", + "version": "0.1.13", "type": "module", "author": "mula.liu", "license": "GPL-3.0-only", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index deb46ba..0f3c776 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -58,9 +58,9 @@ dependencies = [ [[package]] name = "annotate-snippets" -version = "0.12.17" +version = "0.12.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a5b0a5ab8561c603f16c3b78c24a386b1f70e7fc1b1b1e8c15738828e4a176" +checksum = "0258346f92c78dbc5b336b9a5b27c64447aa10643bc64e651db2edb145361564" dependencies = [ "anstyle", "memchr", @@ -462,9 +462,9 @@ dependencies = [ [[package]] name = "bstr" -version = "1.13.1" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214" dependencies = [ "memchr", "regex-automata", @@ -614,12 +614,12 @@ dependencies = [ [[package]] name = "cfg-expr" -version = "0.20.10" +version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f" +checksum = "8d4ba6e40bd1184518716a6e1a781bf9160e286d219ccdb8ab2612e74cfe4789" dependencies = [ "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.12.16", ] [[package]] @@ -689,9 +689,9 @@ dependencies = [ [[package]] name = "const-oid" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" [[package]] name = "cookie" @@ -784,27 +784,27 @@ dependencies = [ [[package]] name = "cranelift-assembler-x64" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10c7459262c93a3c408bda96acaaa3d92868f166b33d445b20921f8378325038" +checksum = "da23f7367f4f5d003249eb1067760b3e6f5df82ad61829d40db22fdf8d41fd22" dependencies = [ "cranelift-assembler-x64-meta", ] [[package]] name = "cranelift-assembler-x64-meta" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97a25bfba0da265ef1f98728358e9bb3ab7489913e7bd759c743108892288934" +checksum = "a8dbd10a21204ce6ae3786f8369860ec4e10a24913e987d5abe4c3cc0c7195d6" dependencies = [ "cranelift-srcgen", ] [[package]] name = "cranelift-bforest" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a9ad33269057337a70db66950f426fbdce436a66fe8071f55851a13a2e40cd" +checksum = "4439be9aa2867bcef9effa83a265f550763a37b2cf4ad560c7bc41cbda947a48" dependencies = [ "cranelift-entity", "wasmtime-internal-core", @@ -812,9 +812,9 @@ dependencies = [ [[package]] name = "cranelift-bitset" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d322e6584efe3b229b1164b49edf55aec561553426f7fe3e228a45e80a15a190" +checksum = "9913a7776903ccf6a3172633f59a0d6da2b428ec631c4b999a4b7401efdca1a7" dependencies = [ "serde", "serde_derive", @@ -823,9 +823,9 @@ dependencies = [ [[package]] name = "cranelift-codegen" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a7b9f73f97da69d6edc9adbfeec068cdb2649f0221be41abd3909267cb1cd53" +checksum = "ffc88c2b684ca7df2ed79fa42b38a983e4d3632ee9d57bc2a389f69fc7ff9348" dependencies = [ "bumpalo", "cranelift-assembler-x64", @@ -848,15 +848,15 @@ dependencies = [ "serde_derive", "sha2 0.10.9", "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", "wasmtime-internal-core", ] [[package]] name = "cranelift-codegen-meta" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7015ef10993d7129e0bce933874b60dab8187239aca4ceca352987d9907d528" +checksum = "df667a6e48506af68c087cebee157bfe69e04d78df83e243025ce6473a538fcd" dependencies = [ "cranelift-assembler-x64-meta", "cranelift-codegen-shared", @@ -867,24 +867,24 @@ dependencies = [ [[package]] name = "cranelift-codegen-shared" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37916b08a7b17e063bae743cb746da542df7df283ced961aae213620dc11e27a" +checksum = "ed3fdd2cd7bcd83a9263a978ea1d66477742a1a92095fa08f8752cb9a79ece11" [[package]] name = "cranelift-control" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8154d189f2cc2a84a95a8129773799ddcf2f4609f667047db30715db4be6aa0a" +checksum = "8e1ecc088bd88f5a271f55b1544a8ec60b9d7373f61efe267d54bd2481adf5a3" dependencies = [ "arbitrary", ] [[package]] name = "cranelift-entity" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccbd0c43e96db753f44a84e44f680f9423ed0a475b81f301ba7c44b5db52c37b" +checksum = "2e9e591820d13f0671f879602ff29b241ea8b1dd54a386acbcbf4c3787f41af0" dependencies = [ "cranelift-bitset", "serde", @@ -894,45 +894,45 @@ dependencies = [ [[package]] name = "cranelift-frontend" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b28ae2961cdda7a6814431b40e87bee46e57b7f92294467b32f447108e14674" +checksum = "b00cf9b20096b09b3499d19f82cca658c13c6988ecbc54881caf12a2f01b2f8c" dependencies = [ "cranelift-codegen", "hashbrown 0.17.1", "log", "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", ] [[package]] name = "cranelift-isle" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41eef45b50970e024d673e3fc4a0703e4fee75ca31d63b26566eb0f142300179" +checksum = "4c9fc3f2d35b0b5879107b4c83246e3dfb93bf678e0c68f74f7bd9b7001f7a06" [[package]] name = "cranelift-native" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "649c7b9ad93d5d92287fee74608cacfb139602116293a46e2f25e6ea5402f05c" +checksum = "3c41c07ce15db19296c5ee3bed3019ec95bf2d773fbb28e73bdcb7fbc6ef9196" dependencies = [ "cranelift-codegen", "libc", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", ] [[package]] name = "cranelift-srcgen" -version = "0.135.8" +version = "0.135.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da04416d8e400ad7ae6d9722db72bfbddfbf36d0ff528ec422c4cc336621a172" +checksum = "7ed086d4ea76eb20e03b689abcc9a34bacaec54b1fc3e04269004acbed4587f0" [[package]] name = "crc32fast" -version = "1.5.4" +version = "1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" dependencies = [ "cfg-if", ] @@ -973,9 +973,9 @@ checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "crypto-bigint" -version = "0.7.10" +version = "0.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" dependencies = [ "cpubits", "ctutils", @@ -1622,7 +1622,7 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ff9f725b347b91d04340444fcbce0770886e4a6513e5f8e9e73a9e344efe73b" dependencies = [ - "gio 0.22.10", + "gio 0.22.11", "gtk", "log", "objc2", @@ -1633,6 +1633,16 @@ dependencies = [ "windows 0.62.2", ] +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -1983,16 +1993,16 @@ dependencies = [ [[package]] name = "gio" -version = "0.22.10" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4620fbafdf19dba814473e19f18e75290cb3338662f6ae35f0402affd3b2b699" +checksum = "536990682bab3b8bf68a78d298ccae69702a114290b096edf2bec6eb2e4013b3" dependencies = [ "futures-channel", "futures-core", "futures-io", "futures-util", - "gio-sys 0.22.9", - "glib 0.22.10", + "gio-sys 0.22.11", + "glib 0.22.11", "libc", "pin-project-lite", "smallvec", @@ -2013,11 +2023,11 @@ dependencies = [ [[package]] name = "gio-sys" -version = "0.22.9" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5" +checksum = "b9c253490f9a475047f109bf6ccb68c407e9d186b7bfab01849188f4e669e669" dependencies = [ - "glib-sys 0.22.9", + "glib-sys 0.22.11", "gobject-sys 0.22.9", "libc", "system-deps 9.0.1", @@ -2049,9 +2059,9 @@ dependencies = [ [[package]] name = "glib" -version = "0.22.10" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694" +checksum = "c9c4cbf1972a07741ae5ce9b23a582a90efc69745fc713f8b037b8d962f604da" dependencies = [ "bitflags 2.13.2", "futures-channel", @@ -2059,8 +2069,8 @@ dependencies = [ "futures-executor", "futures-task", "futures-util", - "glib-macros 0.22.9", - "glib-sys 0.22.9", + "glib-macros 0.22.11", + "glib-sys 0.22.11", "gobject-sys 0.22.9", "libc", "memchr", @@ -2083,9 +2093,9 @@ dependencies = [ [[package]] name = "glib-macros" -version = "0.22.9" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9" +checksum = "d4014e54e2049108c93cf278b64e89f490849402e09b455a25dfa2098cc35093" dependencies = [ "heck 0.5.0", "proc-macro2", @@ -2105,9 +2115,9 @@ dependencies = [ [[package]] name = "glib-sys" -version = "0.22.9" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295" +checksum = "8b01e8b94529c2698b98f765b887f1e001b76195c1e25d1139aa9336019e745d" dependencies = [ "libc", "system-deps 9.0.1", @@ -2160,7 +2170,7 @@ version = "0.22.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834" dependencies = [ - "glib-sys 0.22.9", + "glib-sys 0.22.11", "libc", "system-deps 9.0.1", ] @@ -2843,12 +2853,6 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" -[[package]] -name = "leb128" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" - [[package]] name = "leb128fmt" version = "0.1.0" @@ -3192,16 +3196,16 @@ dependencies = [ [[package]] name = "notify-rust" -version = "4.18.2" +version = "4.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4587364a9a0074333429b3df75a30a205340c56a536ca3eb6ca0e59b87bbf8af" +checksum = "57da5b5d3b7809bf71858da5a2818c3404ca4688c02c8abecdda0fcdec235df3" dependencies = [ "futures-lite", "log", "mac-notification-sys", "serde", "tauri-winrt-notification", - "zbus", + "zbus 6.5.0", ] [[package]] @@ -3825,9 +3829,9 @@ dependencies = [ [[package]] name = "postcard" -version = "1.1.3" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +checksum = "5431b3dcfdf6d1985c87d11f267a171c0dec0a8cd544c6727b747d36365f1fca" dependencies = [ "cobs", "embedded-io 0.4.0", @@ -3967,9 +3971,9 @@ dependencies = [ [[package]] name = "pulley-interpreter" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e6d73adcf2f76b98d3de7a31831b6d6436fd2b6518e0ad4f7cc722a12ad4133" +checksum = "1f153f8d747fe1a04a7323d84963bd99a609f41391357da9d35f1965fb2c58b7" dependencies = [ "cranelift-bitset", "log", @@ -3979,9 +3983,9 @@ dependencies = [ [[package]] name = "pulley-macros" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bde547f939ab9aa321a54c6694aef2e1e27741c2523c0627ff306677b3cbcff" +checksum = "90dd329c9c89b9d4cea5803db3399f34f122e93d43549058caf46f5a7d4406ec" dependencies = [ "proc-macro2", "quote", @@ -4032,9 +4036,9 @@ checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" [[package]] name = "rand" -version = "0.10.3" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ "chacha20", "getrandom 0.4.3", @@ -4114,9 +4118,9 @@ dependencies = [ [[package]] name = "regalloc2" -version = "0.15.2" +version = "0.15.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "757712e8e61590d6d4f5d563483755538b5aa13467837a3b41cd9832509a7f85" +checksum = "34f923657880712029496c2e68bb40bef163806b2011adde559b28bbcedc82ea" dependencies = [ "allocator-api2", "bumpalo", @@ -4129,9 +4133,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" dependencies = [ "aho-corasick", "memchr", @@ -4141,9 +4145,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.18" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" dependencies = [ "aho-corasick", "memchr", @@ -4152,9 +4156,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.11" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" [[package]] name = "reqwest" @@ -4250,9 +4254,9 @@ dependencies = [ [[package]] name = "rsa" -version = "0.10.0-rc.21" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47cf9537fc2210e5db7a35a1cdda9d8d451b9df6fba234ec1cf0cd746c120c35" +checksum = "23e77fd77e0dea28b3011fd62d15445b7de7959333b0276d930e03be0f755699" dependencies = [ "const-oid", "crypto-bigint", @@ -4760,7 +4764,7 @@ dependencies = [ [[package]] name = "squid-core" -version = "0.1.11" +version = "0.1.13" dependencies = [ "anyhow", "chrono", @@ -4779,7 +4783,7 @@ dependencies = [ [[package]] name = "squid-desktop" -version = "0.1.11" +version = "0.1.13" dependencies = [ "base64 0.22.1", "chrono", @@ -4806,27 +4810,30 @@ dependencies = [ [[package]] name = "squid-engine" -version = "0.1.11" +version = "0.1.13" dependencies = [ "anyhow", "chrono", "crossbeam-channel", "dirs 6.0.0", + "filetime", "globset", "libc", "rayon", "serde", "serde_json", + "sha2 0.10.9", "squid-core", "squid-platform", "squid-rules", "squid-stats", "walkdir", + "winreg 0.52.0", ] [[package]] name = "squid-guard" -version = "0.1.11" +version = "0.1.13" dependencies = [ "chrono", "hex", @@ -4842,7 +4849,7 @@ dependencies = [ [[package]] name = "squid-platform" -version = "0.1.11" +version = "0.1.13" dependencies = [ "dirs 6.0.0", "file_icon_provider", @@ -4862,7 +4869,7 @@ dependencies = [ [[package]] name = "squid-rules" -version = "0.1.11" +version = "0.1.13" dependencies = [ "globset", "serde", @@ -4874,7 +4881,7 @@ dependencies = [ [[package]] name = "squid-stats" -version = "0.1.11" +version = "0.1.13" dependencies = [ "chrono", "libc", @@ -5051,7 +5058,7 @@ version = "9.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d" dependencies = [ - "cfg-expr 0.20.10", + "cfg-expr 0.17.2", "heck 0.5.0", "pkg-config", "toml 1.1.8+spec-1.1.0", @@ -5123,9 +5130,9 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" [[package]] name = "target-lexicon" -version = "0.13.5" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" [[package]] name = "tauri" @@ -5303,9 +5310,9 @@ dependencies = [ [[package]] name = "tauri-plugin-notification" -version = "2.8.0" +version = "2.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bc6c194a95a535abdfbe3bc1af9a43935b8b9b29c216b8e71af8b59132703cf" +checksum = "14a226bfb8189ec4ab2c1936e66330ad06c44d9f6c54a674338208491dee177f" dependencies = [ "log", "notify-rust", @@ -5318,7 +5325,7 @@ dependencies = [ "thiserror 2.0.21", "time", "url", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -5340,7 +5347,7 @@ dependencies = [ "thiserror 2.0.21", "url", "windows 0.62.2", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -5356,7 +5363,7 @@ dependencies = [ "tokio", "tracing", "windows-sys 0.61.2", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -5968,14 +5975,13 @@ dependencies = [ [[package]] name = "walrus" -version = "0.27.3" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5691aeb3546554822fe2c13d63149c26a027cd07d900a72c7c7f37f4321bfaea" +checksum = "04f034ddbc5b46d705409d64c617d01b9ed8c6c9ccac0ab6483e907d525bbf37" dependencies = [ "anyhow", "gimli 0.32.3", "id-arena", - "leb128", "log", "walrus-macro", "wasm-encoder 0.245.1", @@ -6145,9 +6151,9 @@ dependencies = [ [[package]] name = "wasmtime" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2afcadb2e7d0417cb8f3f322c66eff49338b288f22290c0ca0bd3e9570732aa" +checksum = "8f47e5ae0d077a8415d626b028a1701fd4d4b3ed4d57e21a0b5daefe99ae81f1" dependencies = [ "addr2line", "async-trait", @@ -6167,7 +6173,7 @@ dependencies = [ "serde", "serde_derive", "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", "wasmparser 0.254.2", "wasmtime-environ", "wasmtime-internal-core", @@ -6182,9 +6188,9 @@ dependencies = [ [[package]] name = "wasmtime-environ" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2de252f4aedfff6c2054ea5bea2454878a931c56e2553c6356b581e5e30a7e4e" +checksum = "956c03e93a68f39d8fb93b5b72885e327b38249272b14cac7a968804f5bad49f" dependencies = [ "anyhow", "cpp_demangle", @@ -6203,7 +6209,7 @@ dependencies = [ "serde_derive", "sha2 0.10.9", "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", "wasm-encoder 0.254.2", "wasmparser 0.254.2", "wasmprinter", @@ -6213,15 +6219,15 @@ dependencies = [ [[package]] name = "wasmtime-internal-component-util" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ad52499e6246d30bf8bf509506bd637248eee17c8dd623e0c7dbe43e7a1036" +checksum = "59133f8e0df9cb35ed819c3aad45ca3c5984267ec0a38e9c463d2bfadea01988" [[package]] name = "wasmtime-internal-core" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8838d7debfc98a69342d260a990ea6f64adf498184915fccfdbd6718bb40a9b" +checksum = "1463b7c70e14ab1db19709f29f298affc1f0ea50ea59b519d8aec8a6f5a56453" dependencies = [ "hashbrown 0.17.1", "libm", @@ -6230,9 +6236,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-cranelift" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "478c09af53c545d96227b349d35c70fc78e99816923f41428ffff00974bcd145" +checksum = "1a70ad5c0cf92e3b3f0dc2d15d140b83083170fa31fae5dcdd836cabf66873cb" dependencies = [ "cranelift-codegen", "cranelift-control", @@ -6245,7 +6251,7 @@ dependencies = [ "object", "pulley-interpreter", "smallvec", - "target-lexicon 0.13.5", + "target-lexicon 0.13.6", "thiserror 2.0.21", "wasmparser 0.254.2", "wasmtime-environ", @@ -6256,9 +6262,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-fiber" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96dce7a8ea302c0f1eb4154eb1756525c90c595bbabbc590abad64d4c5ff8bbb" +checksum = "cce8b2932cdefb95f711d05e11e5959efad509481f3987917a5ab9b12e784291" dependencies = [ "cc", "libc", @@ -6270,9 +6276,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-jit-debug" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "895f3231b24ce0c12c8a7bb129a9f6ddc6772ec78e59748e53af743dcdd733d1" +checksum = "4e380afb5a32fdb509c2eecd8ab55e8203db6487770738ef96c216fef5ff76aa" dependencies = [ "cc", "wasmtime-internal-versioned-export-macros", @@ -6280,9 +6286,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-jit-icache-coherence" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b60a0c1f735da6b862679b763f8bab653caa477ccc603a25752488b795fec5" +checksum = "6e944d8cec74d9e20db5a874cbc82e1174bf78d1dc092dbf6d79048ff41abfdf" dependencies = [ "libc", "wasmtime-internal-core", @@ -6291,9 +6297,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-unwinder" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97b2c29c8f458bdf1b948058bfbb8141aad0f7abcf0f7cb3479866f4316bf3c" +checksum = "9ef8cc822d036e5366d9e458cc918f75e08d2faa24115c75ac5f791b45f1c36d" dependencies = [ "cranelift-codegen", "log", @@ -6303,9 +6309,9 @@ dependencies = [ [[package]] name = "wasmtime-internal-versioned-export-macros" -version = "48.0.8" +version = "48.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32766b38d56927eca9a65858ea8c7b1803424db82562aafd69727aa970057561" +checksum = "fb0a732411dc5a84d071df6f8d773cb84338e4c4cb2dbd21bcc4ccd70754df30" dependencies = [ "proc-macro2", "quote", @@ -7073,9 +7079,9 @@ dependencies = [ [[package]] name = "yara-x" -version = "1.23.0" +version = "1.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8a5ff1e1bb43734cc68f3ddc94646c9740c8c559d38fae559f0c79076f801db" +checksum = "46490aa1d13df1247f106e9620f4221fc8a13b351a9aeef5a34a9b0eaafd78cb" dependencies = [ "annotate-snippets", "anyhow", @@ -7132,9 +7138,9 @@ dependencies = [ [[package]] name = "yara-x-macros" -version = "1.23.0" +version = "1.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc0df20854de457fdeaa3207e6fa08e439d22c63628e37e5608ae4113ebd8a2a" +checksum = "5d9568f7c8c3ce9a14a8ef472612bb86668cad05854155173de85b53c2c7189b" dependencies = [ "darling", "proc-macro2", @@ -7144,9 +7150,9 @@ dependencies = [ [[package]] name = "yara-x-parser" -version = "1.23.0" +version = "1.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "336c1ef292d1d554526b10908198b71920f64dd58e56f39c8689b298fe858a1d" +checksum = "a7b6d18b9aeceb80d3516efc6658589d4311ee07bc4d29f1d740c28201b37109" dependencies = [ "ascii_tree", "bitflags 2.13.2", @@ -7213,11 +7219,38 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow 1.0.4", - "zbus_macros", + "zbus_macros 5.19.0", "zbus_names", "zvariant", ] +[[package]] +name = "zbus" +version = "6.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7f9f5dd97fa527c1202ba1cb35d48e07f77d4de8542317c854f7aef22b0668" +dependencies = [ + "async-trait", + "bitflags 2.13.2", + "endi", + "futures-core", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "socket2", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.4", + "zbus_macros 6.5.0", + "zbus_utils", + "zcheapstr", + "zruntime", +] + [[package]] name = "zbus_macros" version = "5.19.0" @@ -7233,6 +7266,18 @@ dependencies = [ "zvariant_utils", ] +[[package]] +name = "zbus_macros" +version = "6.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f5aa7f2c4ea81b7ccfb26bafefdb4d1a44dd9d4f82c8426173a3727311743e4" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_utils", +] + [[package]] name = "zbus_names" version = "4.3.5" @@ -7245,10 +7290,23 @@ dependencies = [ ] [[package]] -name = "zcheapstr" -version = "1.2.0" +name = "zbus_utils" +version = "6.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" +checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow 1.0.4", +] + +[[package]] +name = "zcheapstr" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907" dependencies = [ "serde", ] @@ -7325,6 +7383,19 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zruntime" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac67096b97c00742108c4674db6bb6178adb78c4b66a506b0e4a7a9593aa5d9e" +dependencies = [ + "futures-core", + "futures-io", + "rustix", + "socket2", + "windows-sys 0.61.2", +] + [[package]] name = "zvariant" version = "5.15.1" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 34e441b..9be91af 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "squid-desktop" -version = "0.1.11" +version = "0.1.13" description = "Squid — a CleanMyMac-inspired cleaner, uninstaller and system monitor." authors = ["mula.liu"] edition = "2021" diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rs index 2f20037..032ed53 100644 --- a/src-tauri/src/app.rs +++ b/src-tauri/src/app.rs @@ -30,6 +30,9 @@ use tauri::{AppHandle, Emitter, Manager}; pub struct AppState { jobs: Mutex>, scans: Mutex>, + /// Confirmed duplicate groups from the last `duplicates_scan`, keyed by + /// scan id — deletes may only name (group, copy) indices from it. + dup_scans: Mutex>, plans: Mutex>, apps: Mutex>, app_icons: Mutex>>, @@ -37,6 +40,11 @@ pub struct AppState { /// Last light snapshot, so the widget window and the main window polling /// a beat apart share one refresh instead of paying for two. snapshot_cache: Mutex>, + /// Mole-style size cache (A⑥): explored storage trees answered from + /// memory until a delete run bumps the epoch and invalidates them. + /// Stamp is wall-clock so the age survives nicely for UI copy. + storage_cache: Mutex>, + clean_epoch: std::sync::atomic::AtomicU64, } impl AppState { @@ -46,6 +54,17 @@ impl AppState { .map_err(|_| "The application state is unavailable; restart Squid.".to_string()) } + fn epoch(&self) -> u64 { + self.clean_epoch.load(std::sync::atomic::Ordering::Relaxed) + } + + /// Any successful delete invalidates cached storage sizes (Mole bumps its + /// cache schema whenever deletion semantics change what totals mean). + fn invalidate_storage_cache(&self) { + self.clean_epoch + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + pub(crate) fn begin(&self, job_id: &str) -> Result { if job_id.trim().is_empty() { return Err("A job identifier is required.".into()); @@ -200,6 +219,32 @@ fn emit_progress(app: &AppHandle, job_id: &str, kind: &str, event: Event) { subject: None, freed: None, }, + Event::Metered { files, bytes } => ProgressView { + job_id: job_id.into(), + kind: kind.into(), + event: "metered".into(), + phase: None, + detail: None, + done: Some(files), + total: Some(bytes.as_u64()), + subject: None, + freed: None, + }, + Event::Group { + kind: unit, + payload, + } => ProgressView { + job_id: job_id.into(), + kind: kind.into(), + event: "group".into(), + phase: None, + // `dup:{json}` — one confirmed work unit, streamed live. + detail: Some(format!("{unit}:{payload}")), + done: None, + total: None, + subject: None, + freed: None, + }, Event::Done(_) => return, }; let _ = app.emit("squid://progress", payload); @@ -220,6 +265,9 @@ pub struct CleanupItemView { selected: bool, lock: Option, note: Option, + last_write_secs: Option, + file_count: u64, + evidence: Vec, } impl From<&CleanupItem> for CleanupItemView { @@ -237,6 +285,9 @@ impl From<&CleanupItem> for CleanupItemView { selected: item.selected, lock: item.lock, note: item.note.clone(), + last_write_secs: item.last_write_secs, + file_count: item.file_count, + evidence: item.evidence.clone(), } } } @@ -517,6 +568,7 @@ pub async fn cleanup_delete( if let Ok(mut scans) = app.state::().scans.lock() { scans.remove(&scan_id); } + app.state::().invalidate_storage_cache(); Ok(DeleteResultView::from_outcome(outcome)) } @@ -600,13 +652,399 @@ pub async fn purge_delete( if let Ok(mut scans) = app.state::().scans.lock() { scans.remove(&scan_id); } + app.state::().invalidate_storage_cache(); Ok(DeleteResultView::from_outcome(outcome)) } +/// One duplicate-file scan: three-stage funnel, groups streamed live. +#[derive(Clone, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DupsView { + scan_id: String, + report: squid_engine::duplicates::DupReport, + elapsed_ms: u64, +} + +#[tauri::command] +pub async fn duplicates_scan( + app: AppHandle, + job_id: String, + roots: Vec, + min_size: Option, +) -> Result { + let token = app.state::().begin(&job_id)?; + let progress = Progress::new(); + let reporter = + ProgressReporter::start(app.clone(), job_id.clone(), "duplicates", progress.clone()); + let started = Instant::now(); + let roots: Vec = if roots.is_empty() { + squid_engine::duplicates::default_roots() + } else { + roots.into_iter().map(|root| paths::expand(&root)).collect() + }; + let task = tauri::async_runtime::spawn_blocking(move || { + squid_engine::duplicates::scan( + &roots, + min_size.unwrap_or(squid_engine::duplicates::DEFAULT_MIN_SIZE), + &progress, + &token, + ) + }) + .await + .map_err(|error| format!("Duplicate scan failed: {error}"))?; + reporter.finish(); + app.state::().finish(&job_id); + let report = task.map_err(|error| error.to_string())?; + let view = DupsView { + scan_id: job_id.clone(), + report, + elapsed_ms: started.elapsed().as_millis() as u64, + }; + app.state::() + .dup_scans + .lock() + .map_err(|_| "The scan cache is unavailable.".to_string())? + .insert(job_id, view.report.clone()); + Ok(view) +} + +/// Delete chosen copies of confirmed duplicate groups — Recycle Bin mode by +/// default, so a wrong click is a restore away, never a loss. +#[tauri::command] +pub async fn duplicates_delete( + app: AppHandle, + job_id: String, + scan_id: String, + selections: Vec<(usize, Vec)>, + mode: DeleteMode, +) -> Result { + let token = app.state::().begin(&job_id)?; + let report = app + .state::() + .dup_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())?; + let items = report.items_for(&selections); + if items.is_empty() { + app.state::().finish(&job_id); + return Err("没有可删除的副本(每组至少保留一份)".into()); + } + 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().with_volume_wide_safety(); + let job = DeleteJob::new(items, mode, "Squid · Duplicates"); + delete::execute(&engine, &job, &progress, &token) + }) + .await + .map_err(|error| format!("Duplicate delete failed: {error}"))?; + reporter.finish(); + app.state::().finish(&job_id); + let outcome = task.map_err(|error| error.to_string())?; + app.state::().invalidate_storage_cache(); + Ok(DeleteResultView::from_outcome(outcome)) +} + +/// Large-file sweep across drives with a threshold and optional type class. +#[derive(Clone, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LargeFileView { + path: String, + display_path: String, + size: u64, + modified_ms: u64, + class: &'static str, + /// A cloud-sync folder sits above this file: 「网盘可能有副本?」. + cloud_hint: bool, + /// Disk-image extension that something (Hyper-V/WSL) may hold open. + maybe_mounted: bool, +} + +fn cloud_hint(path: &str) -> bool { + let lower = path.to_lowercase(); + [ + "onedrive", + "\\wps cloud", + "iclouddrive", + "google drive", + "googledrive", + "dropbox", + "坚果云", + "syncthing", + "baidunetdisk", + "wuying", + ] + .iter() + .any(|marker| lower.contains(marker)) +} + +#[tauri::command] +pub async fn large_files_scan( + app: AppHandle, + job_id: String, + roots: Vec, + min_bytes: Option, + class: Option, +) -> Result, String> { + let token = app.state::().begin(&job_id)?; + let progress = Progress::new(); + let reporter = + ProgressReporter::start(app.clone(), job_id.clone(), "bigfiles", progress.clone()); + let mut roots: Vec = roots.into_iter().map(|root| paths::expand(&root)).collect(); + if roots.is_empty() { + roots = squid_engine::duplicates::default_roots(); + } + let class = class.filter(|value| value != "all"); + let task = tauri::async_runtime::spawn_blocking(move || { + analyze::large_files( + &roots, + min_bytes.unwrap_or(100 * 1024 * 1024), + class.as_deref(), + &token, + &progress, + ) + }) + .await + .map_err(|error| format!("Large file scan failed: {error}"))?; + reporter.finish(); + app.state::().finish(&job_id); + let files = task.map_err(|error| error.to_string())?; + Ok(files + .iter() + .map(|file| { + let display = file.path.display().to_string(); + let image = matches!(squid_engine::analyze::file_class(&file.path), "image"); + LargeFileView { + path: display.clone(), + display_path: paths::pretty(&file.path), + size: file.size().as_u64(), + modified_ms: file.modified_ms.unwrap_or(0), + class: squid_engine::analyze::file_class(&file.path), + cloud_hint: cloud_hint(&display), + maybe_mounted: image, + } + }) + .collect()) +} + +/// Delete chosen large files (paths re-validated, Recycle Bin by default). +#[tauri::command] +pub async fn large_files_delete( + app: AppHandle, + job_id: String, + paths: Vec, + mode: DeleteMode, +) -> Result { + let token = app.state::().begin(&job_id)?; + if paths.is_empty() { + app.state::().finish(&job_id); + return Err("没有选中任何文件".into()); + } + let items: Vec = paths + .iter() + .map(|raw| { + let path = PathBuf::from(raw); + let size = std::fs::metadata(&path).map(|meta| meta.len()).unwrap_or(0); + let anchor = path + .ancestors() + .nth(2) + .map(|dir| dir.to_path_buf()) + .unwrap_or_else(paths::home_dir); + let mut item = CleanupItem::new( + path.clone(), + ItemKind::File, + Category::SystemJunk, + path.file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(), + ) + .with_rule("large-files") + .with_anchors(std::iter::once(anchor)); + item.size = Bytes(size); + item.allocated = Bytes(size); + item.file_count = 1; + item + }) + .collect(); + 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().with_volume_wide_safety(); + let job = DeleteJob::new(items, mode, "Squid · Large Files"); + delete::execute(&engine, &job, &progress, &token) + }) + .await + .map_err(|error| format!("Large file delete failed: {error}"))?; + reporter.finish(); + app.state::().finish(&job_id); + let outcome = task.map_err(|error| error.to_string())?; + app.state::().invalidate_storage_cache(); + Ok(DeleteResultView::from_outcome(outcome)) +} + +/// Maintenance tasks live behind a single global lock key in the jobs map: +/// two repairs racing (SFC while the audio service restarts) can invalidate +/// each other's assumptions, so the second click is refused, not queued. +const MAINTENANCE_LOCK: &str = "maintenance"; + +#[tauri::command] +pub async fn maintenance_tasks() -> Result, String> +{ + Ok(squid_engine::maintenance::tasks()) +} + +#[tauri::command] +pub async fn maintenance_run( + app: AppHandle, + job_id: String, + task: String, +) -> Result { + let state = app.state::(); + if job_id.trim().is_empty() { + return Err("A job identifier is required.".into()); + } + // One token under both keys: the mutual-exclusion lock and the caller's + // cancel handle always point at the same flag. + let token = CancelToken::new(); + { + let mut jobs = AppState::lock(&state.jobs)?; + if jobs.contains_key(MAINTENANCE_LOCK) { + return Err("另一个维护任务正在进行,请先等待它结束。".into()); + } + jobs.insert(MAINTENANCE_LOCK.to_string(), token.clone()); + jobs.insert(job_id.clone(), token.clone()); + } + let progress = Progress::new(); + let reporter = + ProgressReporter::start(app.clone(), job_id.clone(), "maintenance", progress.clone()); + let task_id = task.clone(); + let result = tauri::async_runtime::spawn_blocking(move || { + squid_engine::maintenance::run(&task_id, &progress, &token) + }) + .await + .map_err(|error| format!("维护任务中断:{error}")); + reporter.finish(); + if let Ok(mut jobs) = state.jobs.lock() { + jobs.remove(MAINTENANCE_LOCK); + jobs.remove(&job_id); + } + let outcome = result?.map_err(|error| error.to_string())?; + Ok(outcome) +} + +/// Privacy traces scan: rows never pre-selected, running browsers locked. +#[tauri::command] +pub async fn privacy_scan(app: AppHandle, job_id: String) -> Result { + let token = app.state::().begin(&job_id)?; + let progress = Progress::new(); + let reporter = + ProgressReporter::start(app.clone(), job_id.clone(), "privacy", progress.clone()); + let started = Instant::now(); + let task = tauri::async_runtime::spawn_blocking(move || { + let engine = Engine::new(); + let items = squid_engine::privacy::collect(&engine, &token); + Ok::(ScanReport { + items, + scanned_at_ms: 0, + ..Default::default() + }) + }) + .await + .map_err(|error| format!("Privacy scan failed: {error}"))?; + reporter.finish(); + app.state::().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::() + .scans + .lock() + .map_err(|_| "The scan cache is unavailable.".to_string())? + .insert(job_id, report); + Ok(view) +} + +/// Privacy deletes are permanent by design (a bin-restored browser profile +/// is broken worse than a clean one) but land in the same history ledger. +#[tauri::command] +pub async fn privacy_delete( + app: AppHandle, + job_id: String, + scan_id: String, + selected: Vec, +) -> Result { + let token = app.state::().begin(&job_id)?; + let mut report = app + .state::() + .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, DeleteMode::Permanent, "Squid · Privacy"); + delete::execute(&engine, &job, &progress, &token) + }) + .await + .map_err(|error| format!("Privacy clean failed: {error}"))?; + reporter.finish(); + app.state::().finish(&job_id); + let outcome = task.map_err(|error| error.to_string())?; + if let Ok(mut scans) = app.state::().scans.lock() { + scans.remove(&scan_id); + } + Ok(DeleteResultView::from_outcome(outcome)) +} + +/// Optimisation tweaks: catalog + live state; writes record the original. +#[tauri::command] +pub async fn tweaks_states() -> Result, String> { + tauri::async_runtime::spawn_blocking(squid_engine::tweaks::states) + .await + .map_err(|error| error.to_string()) +} + +#[tauri::command] +pub async fn tweaks_set( + id: String, + enabled: bool, +) -> Result { + tauri::async_runtime::spawn_blocking(move || squid_engine::tweaks::set(&id, enabled)) + .await + .map_err(|error| error.to_string())? +} + +#[tauri::command] +pub async fn tweaks_restore_all() -> Result, String> { + tauri::async_runtime::spawn_blocking(squid_engine::tweaks::restore_all) + .await + .map_err(|error| error.to_string()) +} + +#[derive(Clone, serde::Serialize)] +pub struct AppEntry { + #[serde(flatten)] + app: AppInfo, + /// `data:image/png;base64,…` of the app's icon (Windows only). + icon: Option, +} + #[derive(Clone, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct AppsView { - apps: Vec, + apps: Vec, total: u64, } @@ -617,21 +1055,47 @@ pub async fn apps_scan(app: AppHandle, job_id: String) -> Result> = Default::default(); + let entries = apps + .iter() + .map(|entry| { + let icon = icons + .entry(entry.key()) + .or_insert_with(|| { + squid_platform::permissions::app_icon(entry).map(|png| { + use base64::{engine::general_purpose::STANDARD as B64, Engine as _}; + format!("data:image/png;base64,{}", B64.encode(&png)) + }) + }) + .clone(); + AppEntry { + app: entry.clone(), + icon, + } + }) + .collect::>(); + Ok::<_, String>((apps, entries, total)) }) .await .map_err(|error| format!("Application scan failed: {error}"))?; reporter.finish(); app.state::().finish(&job_id); - let apps = task.map_err(|error| error.to_string())?; - let total = apps.iter().map(|app| app.size.as_u64()).sum(); + let (apps, entries, total) = task?; if let Ok(mut cache) = app.state::().apps.lock() { - *cache = apps.clone(); + *cache = apps; } if let Ok(mut icons) = app.state::().app_icons.lock() { icons.clear(); } - Ok(AppsView { apps, total }) + Ok(AppsView { + apps: entries, + total, + }) } /// Resolve one app's icon lazily so scanning does not pay for artwork the user @@ -763,9 +1227,44 @@ pub async fn app_uninstall( if let Ok(mut plans) = app.state::().plans.lock() { plans.remove(&plan_id); } + app.state::().invalidate_storage_cache(); Ok(DeleteResultView::from_outcome(outcome)) } +/// 卸载增强: drop the 安装不完整 registry record after its files are gone. +/// HKLM removal escalates through one UAC prompt; a declined prompt is an +/// error the page surfaces, never a silent no-op. +#[tauri::command] +pub async fn app_remove_record(_app: AppHandle, reg_key: String) -> Result<(), String> { + #[cfg(windows)] + { + tauri::async_runtime::spawn_blocking(move || { + squid_platform::windows::remove_uninstall_record(®_key) + }) + .await + .map_err(|error| error.to_string())? + } + #[cfg(not(windows))] + { + let _ = reg_key; + Err("此系统没有注册表记录".to_string()) + } +} + +/// What `storage_explore` answers: the tree plus how fresh it is (A⑥). +/// `cached` = served from the in-memory size cache; `measuredAtMs` = age of +/// the measurement so the page can say "12 分钟前" honestly. `Node` itself +/// serializes camelCase, same as before for the frontend contract. +#[derive(Clone, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ExploreView { + node: Node, + cached: bool, + measured_at_ms: Option, +} + +const STORAGE_TTL: std::time::Duration = std::time::Duration::from_secs(600); + #[tauri::command] pub async fn storage_explore( app: AppHandle, @@ -773,7 +1272,8 @@ pub async fn storage_explore( path: Option, depth: Option, top: Option, -) -> Result { + force: Option, +) -> Result { let token = app.state::().begin(&job_id)?; let progress = Progress::new(); let reporter = @@ -787,20 +1287,114 @@ pub async fn storage_explore( reporter.finish(); return Err(format!("{} is not a folder.", root.display())); } + let depth = depth.unwrap_or(1).clamp(1, 3); + let top = top.unwrap_or(16); + let state = app.state::(); + let key = format!("{}|{depth}|{top}", root.to_string_lossy().to_lowercase()); + let epoch = state.epoch(); + if !force.unwrap_or(false) { + if let Ok(cache) = state.storage_cache.lock() { + if let Some((cached_epoch, at, node)) = cache.get(&key) { + let age = std::time::SystemTime::now() + .duration_since(*at) + .unwrap_or_default(); + let fresh = epoch == *cached_epoch && age < STORAGE_TTL; + if fresh { + app.state::().finish(&job_id); + reporter.finish(); + return Ok(ExploreView { + node: node.clone(), + cached: true, + measured_at_ms: Some(u64::try_from(age.as_millis()).unwrap_or(u64::MAX)), + }); + } + } + } + } let task = tauri::async_runtime::spawn_blocking(move || { - analyze::explore( - &root, - depth.unwrap_or(1).clamp(1, 3), - top.unwrap_or(16), - &token, - &progress, - ) + analyze::explore(&root, depth, top, &token, &progress) }) .await .map_err(|error| format!("Storage analysis failed: {error}"))?; reporter.finish(); app.state::().finish(&job_id); - task.map_err(|error| error.to_string()) + let node = task.map_err(|error| error.to_string())?; + if let Ok(mut cache) = state.storage_cache.lock() { + // Tiny memory cap: the epoch clears everything after a delete run. + if cache.len() > 48 { + cache.clear(); + } + cache.insert(key, (epoch, std::time::SystemTime::now(), node.clone())); + } + Ok(ExploreView { + node, + cached: false, + measured_at_ms: Some(0), + }) +} + +#[derive(Clone, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InsightView { + id: String, + title: String, + path: String, + size: u64, + action: String, + command: Option, + hint: String, +} + +/// Hidden-space insights for the storage page's curated section (A⑤). +#[tauri::command] +pub async fn storage_insights() -> Result, String> { + let rows = tauri::async_runtime::spawn_blocking(squid_engine::insights::collect) + .await + .map_err(|error| format!("Insight scan failed: {error}"))?; + Ok(rows + .into_iter() + .map(|row| InsightView { + id: row.id, + title: row.title, + path: row.path, + size: row.size, + action: row.action, + command: row.command, + hint: row.hint, + }) + .collect()) +} + +/// Mole-style last-second re-check surfaced before deletion (B1). +#[tauri::command] +pub async fn cleanup_preflight( + app: AppHandle, + scan_id: String, + selected: Vec, +) -> Result { + let report = app + .state::() + .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())?; + let view = tauri::async_runtime::spawn_blocking(move || { + let engine = Engine::new(); + let preflight = engine.preflight(&report, &selected); + serde_json::json!({ + "checked": preflight.checked, + "blocked": preflight + .blocked + .into_iter() + .map(|(path, reason)| serde_json::json!({ "path": path, "reason": reason })) + .collect::>(), + }) + }) + .await + .map_err(|error| error.to_string())?; + Ok(view) } #[tauri::command] @@ -870,6 +1464,34 @@ pub fn stop_process(app: AppHandle, process: ProcessSample) -> Result<(), String sampler.stop(&process).map_err(|error| error.to_string()) } +/// Write a UTF-8 text file (B5 clean-list export; the UI picked the path +/// through the save dialog, so this is a plain, bounded write). +#[tauri::command] +pub async fn write_text_file(path: String, contents: String) -> Result<(), String> { + tauri::async_runtime::spawn_blocking(move || { + let target = paths::expand(&path); + std::fs::write(&target, contents.as_bytes()) + .map_err(|error| format!("{}: {error}", target.display())) + }) + .await + .map_err(|error| error.to_string())? +} + +/// B2: which protection patterns actually hit something on this machine. +#[tauri::command] +pub async fn whitelist_audit() -> Result { + let rows: Vec = tauri::async_runtime::spawn_blocking(|| { + Engine::new() + .audit_whitelist() + .into_iter() + .map(|(pattern, live)| serde_json::json!({ "pattern": pattern, "live": live })) + .collect::>() + }) + .await + .map_err(|error| error.to_string())?; + Ok(serde_json::Value::Array(rows)) +} + #[tauri::command] pub fn history_list(limit: Option) -> Vec { ledger::load_sessions(limit.unwrap_or(60).clamp(1, 500)) @@ -900,6 +1522,7 @@ pub struct SettingsPatch { language: Option, show_allocated: Option, purge_min_age_days: Option, + purge_roots: Option>, history_keep: Option, setup_reviewed: Option, } @@ -921,6 +1544,15 @@ pub async fn settings_save(app: AppHandle, patch: SettingsPatch) -> Result Result<(), String> { } #[cfg(windows)] { - crate::process::command("explorer.exe") - .arg(format!("/select,{}", target.display())) - .status() - .map_err(|error| error.to_string())?; + use std::os::windows::process::CommandExt; + // Explorer only understands `/select,"C:\path with space\x"` — the + // quotes must sit *inside* the argument, around the path. Handing + // the whole `/select,` as one argument let Rust wrap it in + // one pair of quotes, Explorer failed to parse it and opened its + // default folder instead (定位 jumped to the wrong directory as + // soon as the path contained a space, e.g. Package Cache). + // `raw_arg` writes the argument verbatim, producing the exact + // command line Explorer documents. + let mut cmd = crate::process::command("explorer.exe"); + cmd.raw_arg(format!("/select,\"{}\"", target.display())); + cmd.status().map_err(|error| error.to_string())?; } #[cfg(not(any(target_os = "macos", windows)))] { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index f4aefa2..8be75c3 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -13,7 +13,7 @@ use security::ScanTarget; use squid_core::{Locale, Settings}; use tauri::{ menu::{Menu, MenuItem, PredefinedMenuItem}, - tray::TrayIconBuilder, + tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}, AppHandle, Emitter, Manager, WindowEvent, }; @@ -66,22 +66,22 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result> if security::scanning(app) { tray_text(locale, "Scanning…", "正在扫描…") } else { - tray_text(locale, "Scan for malware", "扫描恶意软件") + tray_text(locale, "Scan malware", "扫描恶意软件") }, !security::scanning(app), None::<&str>, )?; - let startup = MenuItem::with_id( + let permissions = MenuItem::with_id( app, - "startup", + "permissions", tray_text(locale, "Manage startup items", "管理启动项"), true, None::<&str>, )?; - let cleanup = MenuItem::with_id( + let space = MenuItem::with_id( app, - "cleanup", - tray_text(locale, "Daily cleanup", "日常清理"), + "space", + tray_text(locale, "Space cleaning", "空间清理"), true, None::<&str>, )?; @@ -92,13 +92,6 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result> true, None::<&str>, )?; - let purge = MenuItem::with_id( - app, - "purge", - tray_text(locale, "Deep Clean", "深度清理"), - true, - None::<&str>, - )?; let quit = MenuItem::with_id( app, "quit", @@ -108,7 +101,7 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result> )?; let first_separator = PredefinedMenuItem::separator(app)?; let last_separator = PredefinedMenuItem::separator(app)?; - // Flips the widget master switch; state is shown on the Real-time monitor. + // Flips the widget master switch; state is shown on the 桌面小工具 page. let widget_toggle = MenuItem::with_id( app, "widget", @@ -122,11 +115,10 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result> &open, &protection, &scan, - &startup, + &permissions, &first_separator, - &cleanup, + &space, &apps, - &purge, &widget_toggle, &last_separator, &quit, @@ -186,14 +178,14 @@ fn create_tray(app: &AppHandle, locale: Locale) -> tauri::Result<()> { .icon_as_template(cfg!(target_os = "macos")) .tooltip(tooltip) .menu(&menu) - .show_menu_on_left_click(true) + // 左键/双击 = 直接打开主界面,右键 = 菜单(电脑管家式交互)。 + .show_menu_on_left_click(false) .on_menu_event(|app, event| match event.id.as_ref() { "open" => show_main_window(app), "scan" => security::scan_in_background(app.clone(), ScanTarget::Quick), - "startup" => navigate_to(app, "startup"), - "cleanup" => navigate_to(app, "cleanup"), + "permissions" => navigate_to(app, "permissions"), + "space" => navigate_to(app, "space"), "applications" => navigate_to(app, "applications"), - "purge" => navigate_to(app, "purge"), "widget" => { if let Err(error) = widget::toggle_from_tray(app) { eprintln!("widget toggle failed: {error}"); @@ -202,6 +194,21 @@ fn create_tray(app: &AppHandle, locale: Locale) -> tauri::Result<()> { "quit" => app.exit(0), _ => {} }) + .on_tray_icon_event(|tray, event| { + let app = tray.app_handle(); + match event { + TrayIconEvent::Click { + button: MouseButton::Left, + button_state: MouseButtonState::Up, + .. + } + | TrayIconEvent::DoubleClick { + button: MouseButton::Left, + .. + } => show_main_window(app), + _ => {} + } + }) .build(app)?; Ok(()) } @@ -247,13 +254,28 @@ pub fn run() { app::cancel_job, app::cleanup_scan, app::cleanup_delete, + app::cleanup_preflight, app::purge_scan, app::purge_delete, + app::duplicates_scan, + app::duplicates_delete, + app::large_files_scan, + app::large_files_delete, + app::maintenance_tasks, + app::maintenance_run, + app::privacy_scan, + app::privacy_delete, + app::tweaks_states, + app::tweaks_set, + app::tweaks_restore_all, app::apps_scan, app::app_plan, app::app_uninstall, + app::app_remove_record, app::app_icon, app::storage_explore, + app::storage_insights, + app::write_text_file, app::storage_largest_files, app::system_snapshot, app::stop_process, @@ -262,6 +284,7 @@ pub fn run() { app::settings_save, app::whitelist_add, app::whitelist_remove, + app::whitelist_audit, autostart::autostart_status, autostart::set_autostart, app::reveal_path, @@ -269,7 +292,10 @@ pub fn run() { permissions::permission_status, permissions::open_full_disk_access_settings, manage::manage_scan, - manage::managed_startup_set_enabled, + manage::startup_set_enabled, + manage::startup_remove_entry, + manage::advanced_scan, + manage::advanced_set_enabled, manage::extension_set_registered, manage::popup_list, manage::popup_close, @@ -301,9 +327,6 @@ pub fn run() { security::security_update_rules, security::security_rollback_rules, security::open_quarantine_folder, - startup::startup_items, - startup::startup_set_enabled, - startup::open_startup_settings, startup::process_inventory, startup::process_detail, startup::process_stop, @@ -315,6 +338,7 @@ pub fn run() { security::spawn_scheduler(app.handle(), &settings); manage::spawn_watcher(app.handle().clone()); widget::spawn_startup(app.handle()); + widget::spawn_desktop_watch(app.handle()); Ok(()) }) .build(tauri::generate_context!()) diff --git a/src-tauri/src/manage.rs b/src-tauri/src/manage.rs index 5554def..0e2c328 100644 --- a/src-tauri/src/manage.rs +++ b/src-tauri/src/manage.rs @@ -135,6 +135,21 @@ pub struct StartupView { source_label: String, scope: String, enabled: bool, + /// Attributed to a real software product (drives the 其他软件 bucket). + named: bool, + /// The binary this row really launches (lnk resolved); empty when unknown. + target: String, + /// False = the target is gone: a 残留项 the UI can offer to delete. + target_exists: bool, + /// `boot` | `logon` | `background` | `unknown`. + trigger: String, + /// Microsoft-signed or under %SystemRoot% — the hideable 系统组件 bucket. + system_item: bool, + /// Signature verdict of `target`: `microsoft` | `vendor` | `unsigned` | + /// `invalid` | `unknown`. + signature: String, + /// Signer subject when the binary carries a certificate. + signer: Option, } impl From<&StartupEntry> for StartupView { @@ -149,6 +164,13 @@ impl From<&StartupEntry> for StartupView { source_label: entry.source_label.clone(), scope: entry.scope.clone(), enabled: entry.enabled, + named: entry.named, + target: entry.target.clone(), + target_exists: entry.target_exists, + trigger: entry.trigger.clone(), + system_item: entry.system_item, + signature: entry.signature.clone(), + signer: entry.signer.clone(), } } } @@ -169,6 +191,8 @@ pub struct ExtensionView { icon: Option, /// false = currently parked in the app's restore list. registered: bool, + /// Module carries real product strings — drives the software grouping. + named: bool, } impl ExtensionView { @@ -194,6 +218,7 @@ impl From<&ShellExtEntry> for ExtensionView { publisher: entry.publisher.clone(), icon: entry.icon.as_deref().map(png_data_url), registered: true, + named: entry.named, } } } @@ -310,7 +335,7 @@ pub async fn manage_scan(app: AppHandle) -> Result { /// Flip one startup entry (registry / startup folder / scheduled task), then /// rescan so a partially-applied toggle can never desync the UI. #[tauri::command] -pub async fn managed_startup_set_enabled( +pub async fn startup_set_enabled( app: AppHandle, id: String, enabled: bool, @@ -332,6 +357,119 @@ pub async fn managed_startup_set_enabled( Ok(enabled_count) } +/// Delete one autostart registration — aimed at 残留项 whose program is gone. +/// Only the config (registry value / shortcut / task) is removed, never files; +/// services are disabled instead of uninstalled. Returns the new enabled count. +#[tauri::command] +pub async fn startup_remove_entry(app: AppHandle, id: String) -> Result { + let manage = app.state::(); + let entry = ManageState::lock(&manage.startup)? + .iter() + .find(|entry| entry.id == id) + .cloned() + .ok_or_else(|| "请先重新扫描启动项".to_string())?; + tauri::async_runtime::spawn_blocking(move || permissions::remove_startup_entry(&entry)) + .await + .map_err(|error| error.to_string())??; + let fresh = tauri::async_runtime::spawn_blocking(permissions::scan_startup_entries) + .await + .map_err(|error| error.to_string())?; + let enabled_count = fresh.iter().filter(|entry| entry.enabled).count(); + *ManageState::lock(&manage.startup)? = fresh; + Ok(enabled_count) +} + +// ---- 进阶启动项 (advanced startup) ---------------------------------------- + +/// One advanced row for the UI: registry hooks with signature trust, plus +/// the hidden-task / auto-service tails merged from the ordinary scan. +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AdvancedView { + id: String, + kind: String, + name: String, + command: String, + location: String, + scope: String, + enabled: bool, + signature: String, + signer: Option, + warning: Option, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AdvancedScanView { + entries: Vec, + /// Hidden scheduled tasks and automatic services, in the ordinary + /// startup shape so their toggles reuse `startup_set_enabled`. + extras: Vec, +} + +#[tauri::command] +pub async fn advanced_scan(app: AppHandle) -> Result { + let manage = app.state::(); + let (entries, startup) = tauri::async_runtime::spawn_blocking(|| { + ( + squid_platform::advanced::scan_advanced(), + permissions::scan_startup_entries(), + ) + }) + .await + .map_err(|error| format!("进阶扫描失败:{error}"))?; + // Cache the ordinary scan so the extras' toggles can find their entries. + *ManageState::lock(&manage.startup)? = startup.clone(); + let extras: Vec = startup + .iter() + .filter(|entry| { + // Only the corners the plain list does not already show: + // hidden-by-default vendor tasks (source marks) and services. + entry.source == "service" + }) + .map(StartupView::from) + .collect(); + Ok(AdvancedScanView { + entries: entries + .iter() + .map(|entry| AdvancedView { + id: entry.id.clone(), + kind: entry.kind.clone(), + name: entry.name.clone(), + command: entry.command.clone(), + location: entry.location.clone(), + scope: entry.scope.clone(), + enabled: entry.enabled, + signature: entry.signature.clone(), + signer: entry.signer.clone(), + warning: entry.warning.clone(), + }) + .collect(), + extras, + }) +} + +#[tauri::command] +pub async fn advanced_set_enabled( + _app: AppHandle, + id: String, + enabled: bool, +) -> Result<(), String> { + // Advanced rows carry their whole state in the id + a fresh scan match. + let entry = tauri::async_runtime::spawn_blocking(squid_platform::advanced::scan_advanced) + .await + .map_err(|error| error.to_string())? + .into_iter() + .find(|entry| entry.id == id) + .ok_or_else(|| "该进阶项已不存在,请重新扫描".to_string())?; + tauri::async_runtime::spawn_blocking(move || { + squid_platform::advanced::set_advanced_enabled(&entry, enabled) + }) + .await + .map_err(|error| error.to_string())??; + Ok(()) +} + /// Unregister / restore a context-menu handler. Removal keeps the entry in /// `manage.json`, which is both the restore recipe and the audit trail. #[tauri::command] diff --git a/src-tauri/src/startup.rs b/src-tauri/src/startup.rs index 14dd8bf..f2aefa1 100644 --- a/src-tauri/src/startup.rs +++ b/src-tauri/src/startup.rs @@ -67,7 +67,6 @@ impl StartupView { } } -#[tauri::command] pub async fn startup_items() -> Result { tauri::async_runtime::spawn_blocking(|| StartupView::of(squid_platform::startup::inventory())) .await @@ -85,7 +84,6 @@ pub struct StartupChange { /// Disable or enable one entry. The refreshed inventory comes back with it, /// because the truth after a launchd reload or a registry write is whatever the /// system now says, not what this function intended. -#[tauri::command] pub async fn startup_set_enabled(id: String, enabled: bool) -> Result { tauri::async_runtime::spawn_blocking(move || { let item = squid_platform::startup::set_enabled(&id, enabled)?; @@ -129,7 +127,6 @@ pub async fn startup_set_enabled(id: String, enabled: bool) -> Result Result<(), String> { #[cfg(target_os = "macos")] let target = { diff --git a/src-tauri/src/widget.rs b/src-tauri/src/widget.rs index 5d4de43..754ec3f 100644 --- a/src-tauri/src/widget.rs +++ b/src-tauri/src/widget.rs @@ -8,7 +8,7 @@ //! broadcast on `widget://settings` so both views stay in sync. use serde::{Deserialize, Serialize}; -use squid_core::{Locale, Settings}; +use squid_core::Settings; use std::fs; use std::path::PathBuf; use std::sync::{Mutex, MutexGuard}; @@ -16,28 +16,141 @@ use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder}; pub const WIDGET_LABEL: &str = "widget"; -/// `HWND_BOTTOM` + no-activate flags: the widget lives on the desktop layer — -/// above wallpaper and icons, below every ordinary app window. +/// Desktop residency (Windows). The widget is a borderless top-level window +/// parked at `HWND_BOTTOM`: above the wallpaper and icons, below every +/// ordinary app window. Pulsar dodges Win+D by living *inside* the taskbar +/// (SetParent into Shell_TrayWnd — the bar is immune to Show Desktop, and a +/// watchdog re-attaches when the parent drifts). The WebView2 widget cannot +/// be re-parented into the desktop tree like Pulsar's raw window: on this +/// machine the shell ejects it again within seconds, and every crossing +/// strands or hides the web content. So we keep Pulsar's *watchdog* idea +/// instead of its parent trick: the shell hides top-level windows on Win+D +/// by minimising or DWM-cloaking them, and a 1.5 s heartbeat puts any +/// shell-hidden-but-wanted widget back (unminimise → show uncloaks → re-park +/// on the desktop layer → one repaint). Ways the app hid the panel itself +/// (master switch off, all panels off, folded away via hide) are respected. #[cfg(windows)] mod desktop_layer { + use std::ffi::c_void; + #[link(name = "user32")] extern "system" { fn SetWindowPos( - hwnd: *mut core::ffi::c_void, - insert_after: *mut core::ffi::c_void, + hwnd: *mut c_void, + insert_after: *mut c_void, x: i32, y: i32, cx: i32, cy: i32, flags: u32, ) -> i32; + fn IsIconic(hwnd: *mut c_void) -> i32; + fn IsWindowVisible(hwnd: *mut c_void) -> i32; } - const HWND_BOTTOM: *mut core::ffi::c_void = 1usize as *mut core::ffi::c_void; + #[link(name = "dwmapi")] + extern "system" { + fn DwmGetWindowAttribute( + hwnd: *mut c_void, + attribute: u32, + value: *mut i32, + size: u32, + ) -> i32; + } + const HWND_BOTTOM: *mut c_void = 1usize as *mut c_void; const SWP_NOMOVE: u32 = 0x0002; const SWP_NOSIZE: u32 = 0x0001; const SWP_NOACTIVATE: u32 = 0x0010; + const DWMWA_CLOAKED: u32 = 14; + const MONITOR_DEFAULTTOPRIMARY: u32 = 1; - pub fn lower(hwnd: *mut core::ffi::c_void) { + #[repr(C)] + struct WinRect { + left: i32, + top: i32, + right: i32, + bottom: i32, + } + #[repr(C)] + struct MonitorInfo { + cb_size: u32, + monitor: WinRect, + work: WinRect, + flags: u32, + } + #[link(name = "user32")] + extern "system" { + fn GetWindowRect(hwnd: *mut c_void, rect: *mut WinRect) -> i32; + fn MonitorFromWindow(hwnd: *mut c_void, flags: u32) -> *mut c_void; + fn GetMonitorInfoW(monitor: *mut c_void, info: *mut MonitorInfo) -> i32; + } + + /// (left, top, right, bottom) of the monitor this window sits on — in + /// true physical pixels, bypassing every DPI translation the webview + /// stack applies. (The Tauri `primary_monitor`/`outer_position` pair + /// disagrees with Win32 by the scale factor on a 150% display, which is + /// what let a mid-screen parking spot read as "correctly docked".) + pub fn monitor_rect(hwnd: *mut c_void) -> Option<(i32, i32, i32, i32)> { + // SAFETY: plain queries; the MONITORINFO carries its own size. + let monitor = unsafe { MonitorFromWindow(hwnd, MONITOR_DEFAULTTOPRIMARY) }; + if monitor.is_null() { + return None; + } + let mut info = MonitorInfo { + cb_size: std::mem::size_of::() as u32, + monitor: WinRect { + left: 0, + top: 0, + right: 0, + bottom: 0, + }, + work: WinRect { + left: 0, + top: 0, + right: 0, + bottom: 0, + }, + flags: 0, + }; + if unsafe { GetMonitorInfoW(monitor, &mut info) } == 0 { + return None; + } + Some(( + info.monitor.left, + info.monitor.top, + info.monitor.right, + info.monitor.bottom, + )) + } + + /// (x, y, width, height) of the window in physical pixels. + pub fn window_rect(hwnd: *mut c_void) -> Option<(i32, i32, i32, i32)> { + let mut rect = WinRect { + left: 0, + top: 0, + right: 0, + bottom: 0, + }; + // SAFETY: plain query on a live handle. + if unsafe { GetWindowRect(hwnd, &mut rect) } == 0 { + return None; + } + Some(( + rect.left, + rect.top, + rect.right - rect.left, + rect.bottom - rect.top, + )) + } + + /// Move (keep size) and re-park on the desktop layer in one call. + pub fn move_to(hwnd: *mut c_void, x: i32, y: i32) { + // SAFETY: z-order/position edit only; NOACTIVATE keeps focus away. + unsafe { + SetWindowPos(hwnd, HWND_BOTTOM, x, y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE); + } + } + + pub fn lower(hwnd: *mut c_void) { // SAFETY: hwnd comes from Tauri's own window handle; SetWindowPos with // NOMOVE|NOSIZE|NOACTIVATE only edits the z-order. unsafe { @@ -52,6 +165,33 @@ mod desktop_layer { ); } } + + /// Whether the shell (Win+D / 显示桌面) currently has this window put + /// away while we want it shown: minimised, DWM-cloaked, or plain hidden. + /// `minimised_or_cloaked` refines the answer for callers that only want + /// to force a repaint when the shell *actively* took the window down + /// (a window still hidden mid-startup just needs showing, not reloading). + pub fn shell_hidden(hwnd: *mut c_void, minimised_or_cloaked: &mut bool) -> bool { + // SAFETY: plain queries on a live handle. + *minimised_or_cloaked = unsafe { IsIconic(hwnd) != 0 }; + if *minimised_or_cloaked { + return true; + } + let mut cloaked = 0i32; + unsafe { + DwmGetWindowAttribute( + hwnd, + DWMWA_CLOAKED, + &mut cloaked, + std::mem::size_of::() as u32, + ); + } + if cloaked != 0 { + *minimised_or_cloaked = true; + return true; + } + unsafe { IsWindowVisible(hwnd) == 0 } + } } /// Park the widget at the bottom of the window stack (desktop layer). @@ -73,6 +213,93 @@ pub fn lower_window(app: &AppHandle) { } } +/// Desktop residency (Windows): heartbeat that both counters Win+D and +/// guards the docked position. +/// +/// Two jobs, one loop: +/// 1. If the shell put the widget away (Win+D / 显示桌面), bring it back +/// within a beat and repaint once (as before). +/// 2. Position guard: compare the window's actual position with where the +/// prefs say it belongs (docked corner, or the remembered drag point). +/// Any mismatch re-docks and re-parks the widget. This catches *every* +/// way the window can end up mid-desktop: an RDP peer connecting +/// disconnects the console session and Windows re-lays-out top-level +/// windows on the next local unlock, a resolution switch, or another +/// program nudging it. The previous fix only watched the monitor size — +/// an RDP round-trip keeps the console resolution constant, so the +/// re-layout went unnoticed. A grace window suppresses re-docking while +/// the user is dragging (position still moving between ticks; the drag +/// persists `position` through widget_set, after which the expected spot +/// *is* the new location, so the guard never fights the pointer). +#[cfg(windows)] +pub fn spawn_desktop_watch(app: &AppHandle) { + let app = app.clone(); + std::thread::spawn(move || { + let mut last_pos: Option<(i32, i32)> = None; + let mut grace = std::time::Instant::now(); + loop { + std::thread::sleep(std::time::Duration::from_millis(1_500)); + let Some(state) = app.try_state::() else { + continue; + }; + let prefs = state.current(); + // A panel the user switched off (master switch, or every panel off — + // sync_window hides the empty shell then) is never resurrected; the + // watchdog only ever counters the shell's doing. + let wanted = prefs.enabled + && (prefs.panel_run + || prefs.panel_cpu + || prefs.panel_network + || prefs.panel_disk + || prefs.panel_storage); + if !wanted { + continue; + } + let Some(window) = app.get_webview_window(WIDGET_LABEL) else { + continue; + }; + let Ok(hwnd) = window.hwnd() else { continue }; + let raw: *mut std::ffi::c_void = hwnd.0.cast(); + // ── position guard ──────────────────────────────────────────── + if let Some((x, y, w, h)) = desktop_layer::window_rect(raw) { + if last_pos != Some((x, y)) { + // The window just moved: someone (the user, most likely) + // is working on it. Re-check shortly instead of yanking + // it mid-drag; the loop's cadence doubles as the grace. + last_pos = Some((x, y)); + grace = std::time::Instant::now() + std::time::Duration::from_millis(3_500); + } else if std::time::Instant::now() >= grace { + if let Some(monitor) = desktop_layer::monitor_rect(raw) { + let want = dock_point(monitor, (w, h), &prefs); + if (x - want.0).abs() > 2 || (y - want.1).abs() > 2 { + desktop_layer::move_to(raw, want.0, want.1); + } + } + } + } + // ── Win+D recovery ──────────────────────────────────────────── + let mut took_down = false; + if !desktop_layer::shell_hidden(raw, &mut took_down) { + continue; + } + let _ = window.unminimize(); + let _ = window.show(); + desktop_layer::lower(raw); + // When the shell actively took the window down, Show() clears the + // cloak but the composed page can come back blank; one cheap reload + // makes it honest again. A plain hidden window (mid-startup) just + // needed showing. + if took_down { + place_window(&app, &prefs); + let _ = window.eval("location.reload()"); + } + } + }); +} + +#[cfg(not(windows))] +pub fn spawn_desktop_watch(_app: &AppHandle) {} + fn default_interval_ms() -> u64 { 2_000 } @@ -103,6 +330,15 @@ pub struct WidgetPrefs { pub collapsed: bool, /// Last user-dragged position; None re-docks to `corner`. pub position: Option<(i32, i32)>, + /// Docking scheme generation. Pre-0.1.12 builds persisted drag positions + /// and docked corners in spaces that disagreed (and an RDP session's + /// small-screen numbers survive as "valid" mid-desktop spots on a big + /// display). The first 0.1.12 boot drops the remembered spot once and + /// sets this flag; corner docking becomes deterministic again, and every + /// drag stored from then on is honoured in the same physical space the + /// guard measures. + #[serde(default)] + pub dock_v2: bool, } impl Default for WidgetPrefs { @@ -120,6 +356,7 @@ impl Default for WidgetPrefs { remember_collapsed: true, collapsed: false, position: None, + dock_v2: true, } } } @@ -188,46 +425,107 @@ fn save_prefs(state: &WidgetState) -> Result<(), String> { fs::write(path, text).map_err(|error| error.to_string()) } -/// Dock to a screen corner (widget width ~350px) or restore the remembered -/// drag position. Called on creation and whenever the corner changes. All -/// math is in physical pixels — the webview reports `outerPosition` there. +/// Where the widget belongs on a monitor rect `(left, top, right, bottom)` +/// of physical screen pixels — the same space Win32 `GetWindowRect` and the +/// persisted drag position (`outerPosition`, Tauri "physical") live in, so +/// the heartbeat compares like with like. A remembered drag position is +/// clamped onto the monitor (an unplugged-secondary position can not hide +/// it off-screen); otherwise the configured corner + a margin (24 physical +/// px ≈ the old 16 logical px at 150% scale). Pure so the re-dock maths +/// stays testable headless. +fn dock_point(monitor: (i32, i32, i32, i32), size: (i32, i32), prefs: &WidgetPrefs) -> (i32, i32) { + let margin = 24; + let (left, top, right, bottom) = monitor; + if let Some((x, y)) = prefs.position { + ( + x.clamp(left, (right - size.0).max(left)), + y.clamp(top, (bottom - size.1).max(top)), + ) + } else { + let x = match prefs.corner.as_str() { + "top-left" | "bottom-left" => left + margin, + _ => right - size.0 - margin, + }; + let y = match prefs.corner.as_str() { + "bottom-left" | "bottom-right" => bottom - size.1 - margin, + _ => top + margin, + }; + (x, y) + } +} + +/// Dock to the configured corner or restore the remembered drag position. +/// Called on creation, whenever the corner changes, and whenever the +/// heartbeat sees the window drift off its spot. +/// +/// The drift this guards against is what the user hit: an RDP session runs +/// the console at the peer's resolution (e.g. 1920×1080); Windows re-lays +/// out top-level windows there, and any position persisted from that +/// session is a *small-screen* number. Back at the native 2560×1440 the +/// old code still found that number "valid" (it clamps fine) and re-docked +/// to it — the widget parked ~660 px short of the right edge, mid-desktop. +/// Now the guard compares the window's live Win32 rect with what the prefs +/// demand every beat, and pre-0.1.12 remembered spots are dropped once +/// (`dock_v2`) so corner docking becomes deterministic again. +#[cfg(windows)] fn place_window(app: &AppHandle, prefs: &WidgetPrefs) { let Some(window) = app.get_webview_window(WIDGET_LABEL) else { return; }; - let Ok(Some(monitor)) = window - .current_monitor() - .or_else(|_| window.primary_monitor()) - else { + let Ok(hwnd) = window.hwnd() else { return }; + let raw: *mut std::ffi::c_void = hwnd.0.cast(); + let Some(monitor) = desktop_layer::monitor_rect(raw) else { return; }; - // Work area excludes the macOS menu bar and Dock, so the widget cannot - // park its header under the menu bar or behind the Dock. - let work = monitor.work_area(); + let size = desktop_layer::window_rect(raw).map(|(_, _, w, h)| (w, h)); + // A just-created window may still report the builder size before the + // content fit lands; dock_point tolerates that (worst case the next + // auto-resize redocks through the same path). + let size = size.unwrap_or((525, 930)); + let pos = dock_point(monitor, size, prefs); + desktop_layer::move_to(raw, pos.0, pos.1); +} + +/// One-time repair of pre-0.1.12 `position` values: they were persisted +/// while the docking maths (physical px) and the drag readback (DPI-scaled +/// virtual px) disagreed, and an RDP re-layout could even persist a drifted +/// mid-screen spot as if the user had chosen it. Rather than guess, drop the +/// remembered spot once — the widget returns to the configured corner; any +/// drag from now on is persisted in the same physical space this file docks +/// in (the page now sends `outerPosition` through the device scale factor), +/// so it is respected forever. +#[cfg(windows)] +fn migrate_stale_position(state: &WidgetState) -> Result<(), String> { + { + let mut prefs = WidgetState::lock(&state.prefs)?; + if prefs.dock_v2 { + return Ok(()); + } + prefs.position = None; + prefs.dock_v2 = true; + } + save_prefs(state) +} + +#[cfg(not(windows))] +fn place_window(app: &AppHandle, prefs: &WidgetPrefs) { + let Some(window) = app.get_webview_window(WIDGET_LABEL) else { + return; + }; + let Ok(Some(monitor)) = window.primary_monitor() else { + return; + }; + let rect = ( + 0, + 0, + monitor.size().width as i32, + monitor.size().height as i32, + ); let outer = window .outer_size() .map(|s| (s.width as i32, s.height as i32)) .unwrap_or((350, 620)); - let margin = (16.0 * monitor.scale_factor()) as i32; - let min_x = work.position.x; - let min_y = work.position.y; - let max_x = (work.position.x + work.size.width as i32 - outer.0).max(min_x); - let max_y = (work.position.y + work.size.height as i32 - outer.1).max(min_y); - let pos = if let Some((x, y)) = prefs.position { - // Clamp into the monitor so an unplugged-secondary position can not - // hide the widget off-screen. - (x.clamp(min_x, max_x), y.clamp(min_y, max_y)) - } else { - let x = match prefs.corner.as_str() { - "top-left" | "bottom-left" => min_x + margin, - _ => max_x - margin, - }; - let y = match prefs.corner.as_str() { - "bottom-left" | "bottom-right" => max_y - margin, - _ => min_y + margin, - }; - (x.clamp(min_x, max_x), y.clamp(min_y, max_y)) - }; + let pos = dock_point(rect, outer, prefs); let _ = window.set_position(tauri::PhysicalPosition::new(pos.0, pos.1)); } @@ -236,7 +534,13 @@ fn place_window(app: &AppHandle, prefs: &WidgetPrefs) { /// of the z-order (desktop layer), above wallpaper/icons but under every /// ordinary app window, so it can never cover the user's work. fn sync_window(app: &AppHandle, prefs: &WidgetPrefs) { - if !prefs.enabled { + if !prefs.enabled + || !(prefs.panel_run + || prefs.panel_cpu + || prefs.panel_network + || prefs.panel_disk + || prefs.panel_storage) + { if let Some(window) = app.get_webview_window(WIDGET_LABEL) { let _ = window.hide(); } @@ -255,7 +559,7 @@ fn sync_window(app: &AppHandle, prefs: &WidgetPrefs) { WIDGET_LABEL, WebviewUrl::App("index.html?view=widget".into()), ) - .title("Squid 实时监控") + .title("Squid 小工具") .inner_size(350.0, 640.0) .resizable(false) .decorations(false) @@ -265,16 +569,6 @@ fn sync_window(app: &AppHandle, prefs: &WidgetPrefs) { .focused(false) .visible(false) .shadow(false); - // macOS: BelowNormal keeps the widget under ordinary app windows, every - // Space keeps it beside the desktop, and a non-key window means clicking - // a card never pulls focus away from the app the user is working in. - // `accept_first_mouse` keeps the first click actionable anyway. - #[cfg(target_os = "macos")] - let builder = builder - .always_on_bottom(true) - .visible_on_all_workspaces(true) - .focusable(false) - .accept_first_mouse(true); match builder.build() { Ok(window) => { let _ = window.set_ignore_cursor_events(false); @@ -292,15 +586,12 @@ fn sync_window(app: &AppHandle, prefs: &WidgetPrefs) { #[serde(rename_all = "camelCase")] pub struct WidgetView { prefs: WidgetPrefs, - language: &'static str, } #[tauri::command] pub fn widget_get(app: AppHandle) -> WidgetView { - let (settings, _) = Settings::load(); WidgetView { prefs: app.state::().current(), - language: Locale::detect(&settings).code(), } } @@ -411,6 +702,12 @@ pub fn widget_hide(app: AppHandle) -> Result<(), String> { /// Create the window at startup when enabled; the main page can also open it /// later through widget_set. pub fn spawn_startup(app: &AppHandle) { + #[cfg(windows)] + { + // One-time drop of a pre-dock-v2 remembered position (see the field + // docs) before anything docks off it. + let _ = migrate_stale_position(&app.state::()); + } let prefs = app.state::().current(); sync_window(app, &prefs); } @@ -432,7 +729,49 @@ pub fn toggle_from_tray(app: &AppHandle) -> Result<(), String> { #[cfg(test)] mod tests { - use super::{WidgetPatch, WidgetPrefs}; + use super::{dock_point, WidgetPatch, WidgetPrefs}; + + #[test] + fn corner_dock_follows_the_screen_size() { + // This is the RDP story in miniature: the same top-right preference + // must land on the corner of whatever screen exists now, never at a + // stale pixel offset from an earlier, smaller session. + let prefs = WidgetPrefs { + corner: "top-right".into(), + ..WidgetPrefs::default() + }; + let big = dock_point((0, 0, 2560, 1440), (350, 620), &prefs); + assert_eq!(big, (2560 - 350 - 24, 24)); + let small = dock_point((0, 0, 1280, 720), (350, 620), &prefs); + assert_eq!(small, (1280 - 350 - 24, 24)); + let left = WidgetPrefs { + corner: "bottom-left".into(), + ..WidgetPrefs::default() + }; + assert_eq!(dock_point((0, 0, 2560, 1440), (350, 620), &left), (24, 796)); + // A monitor that is not at the origin (extended desktop with the + // primary on the right) docks to *its own* corners. + let offset = dock_point((1920, 0, 1920 + 2560, 1440), (350, 620), &prefs); + assert_eq!(offset, (1920 + 2560 - 350 - 24, 24)); + } + + #[test] + fn dragged_position_survives_but_stays_on_screen() { + let prefs = WidgetPrefs { + position: Some((1200, 300)), + ..WidgetPrefs::default() + }; + assert_eq!( + dock_point((0, 0, 2560, 1440), (350, 620), &prefs), + (1200, 300) + ); + // A remembered spot from a bigger unplugged monitor is clamped back + // into the current desktop instead of being lost or hidden. + assert_eq!( + dock_point((0, 0, 1280, 720), (350, 620), &prefs), + (1280 - 350, 720 - 620) + ); + } #[test] fn prefs_round_trip_uses_camel_case_keys() { @@ -472,7 +811,6 @@ mod tests { fn legacy_configs_without_new_fields_still_load() { let prefs: WidgetPrefs = serde_json::from_str("{}").unwrap(); assert!(prefs.enabled); - assert!(prefs.panel_cpu); assert_eq!(prefs.interval_ms, 2_000); assert!(prefs.position.is_none()); } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 66b63ff..a22ff66 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.11", + "version": "0.1.13", "identifier": "app.nex.squid", "mainBinaryName": "squid-desktop", "build": { diff --git a/src/App.tsx b/src/App.tsx index 8e23fbf..3f1bde6 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,24 +1,22 @@ import { AppWindow, - Boxes, ChevronDown, CircleGauge, Eraser, History, LayoutDashboard, - Power, + MonitorSmartphone, RefreshCw, Settings, ShieldCheck, Sparkles, - WandSparkles, + Wrench, } from "lucide-react"; import { useCallback, useEffect, useState, type ReactNode } from "react"; import { useAppsWorkspace } from "./hooks/useAppsWorkspace"; import { usePermissionsWorkspace } from "./hooks/usePermissionsWorkspace"; import { useScanWorkspace } from "./hooks/useScanWorkspace"; import { useSecurityWorkspace } from "./hooks/useSecurityWorkspace"; -import { useStartupWorkspace } from "./hooks/useStartupWorkspace"; import { useSystemSnapshot } from "./hooks/useSystemSnapshot"; import { useUpdateFlow } from "./hooks/useUpdateFlow"; import { detectLanguage, I18nProvider, useI18n } from "./i18n"; @@ -36,16 +34,15 @@ import { useToast } from "./components/ui"; import { SetupPanel } from "./components/SetupPanel"; import brandMarkUrl from "../src-tauri/icons/brand-mark.svg"; import { ApplicationsPage } from "./pages/ApplicationsPage"; -import { CleanupPage } from "./pages/CleanupPage"; import { HistoryPage } from "./pages/HistoryPage"; +import { MaintenanceHubPage, type MaintTab } from "./pages/MaintenanceHubPage"; import { OverviewPage } from "./pages/OverviewPage"; import { PermissionsPage } from "./pages/PermissionsPage"; -import { PurgePage } from "./pages/PurgePage"; import { SecurityPage } from "./pages/SecurityPage"; import { SettingsPage } from "./pages/SettingsPage"; -import { StartupPage } from "./pages/StartupPage"; -import { StoragePage } from "./pages/StoragePage"; +import { SpaceHubPage, type SpaceTab } from "./pages/SpaceHubPage"; import { SystemPage } from "./pages/SystemPage"; +import { WidgetPage } from "./pages/WidgetPage"; const NAV_GROUPS: { labelEn: string; @@ -63,14 +60,14 @@ const NAV_GROUPS: { items: [ { id: "overview", - labelEn: "Overview", - labelZh: "概览", + labelEn: "Computer overview", + labelZh: "电脑概览", icon: LayoutDashboard, }, { - id: "cleanup", - labelEn: "Daily cleanup", - labelZh: "日常清理", + id: "space", + labelEn: "Space cleaning", + labelZh: "空间清理", icon: Eraser, }, { @@ -80,37 +77,35 @@ const NAV_GROUPS: { icon: AppWindow, }, { - id: "purge", - labelEn: "Deep Clean", - labelZh: "深度清理", - icon: WandSparkles, + id: "maintenance", + labelEn: "System maintenance", + labelZh: "系统维护", + icon: Wrench, }, + ], + }, + { + labelEn: "Protection", + labelZh: "安全", + items: [ { id: "permissions", labelEn: "Permissions", labelZh: "权限管理", icon: ShieldCheck, }, - ], - }, - { - labelEn: "Protection", - labelZh: "保护", - items: [ - { id: "security", labelEn: "Security", labelZh: "安全", icon: ShieldCheck }, - { id: "startup", labelEn: "Startup items", labelZh: "启动项", icon: Power }, + { + id: "security", + labelEn: "Security scan", + labelZh: "安全扫描", + icon: ShieldCheck, + }, ], }, { labelEn: "Insights", labelZh: "洞察", items: [ - { - id: "storage", - labelEn: "Storage", - labelZh: "存储空间", - icon: Boxes, - }, { id: "system", labelEn: "Real-time monitor", @@ -119,28 +114,41 @@ const NAV_GROUPS: { }, ], }, + { + labelEn: "Desktop", + labelZh: "桌面", + items: [ + { + id: "widget", + labelEn: "Desktop widget", + labelZh: "桌面小工具", + icon: MonitorSmartphone, + }, + ], + }, ]; -// Permissions manages Windows Run keys, shell extensions and popup rules; the -// macOS equivalent is the Startup page, which reads LaunchAgents and login items. -function navItemVisible(id: PageId, platform: string | undefined): boolean { - return id !== "permissions" || platform === "windows"; -} - const PAGE_TITLES: Record = { - overview: ["Overview", "概览"], - cleanup: ["Daily cleanup", "日常清理"], + overview: ["Computer overview", "电脑概览"], + space: ["Space cleaning", "空间清理"], applications: ["Uninstall apps", "应用卸载"], - purge: ["Deep Clean", "深度清理"], permissions: ["Permissions", "权限管理"], - storage: ["Storage", "存储空间"], + security: ["Security scan", "安全扫描"], + widget: ["Desktop widget", "桌面小工具"], + maintenance: ["System maintenance", "系统维护"], system: ["Real-time monitor", "实时监控"], - security: ["Security", "安全"], - startup: ["Startup items", "启动项"], history: ["History", "历史记录"], settings: ["Settings", "设置"], }; +/** Pages that no longer exist still arrive from old tray/notification payloads. */ +const LEGACY_PAGES: Record = { + cleanup: "space", + purge: "space", + storage: "space", + startup: "permissions", +}; + function BrandMark({ small = false }: { small?: boolean }) { return ( (null); @@ -194,26 +217,24 @@ export default function App() { const [setupOpen, setSetupOpen] = useState(false); // The 托盘驻留 case: a hidden main window must stop sampling the machine. const [windowVisible, setWindowVisible] = useState(true); - const cleanup = useScanWorkspace("cleanup"); - const purge = useScanWorkspace("purge"); + // Hub deep-links: the overview quick-cards and tray can request a specific + // tab; the selection resets on every navigate so a later click re-arms it. + const [spaceTab, setSpaceTab] = useState("junk"); + const [maintTab, setMaintTab] = useState("repair"); + const [autostart, setAutostart] = useState(false); + // A process row can ask "where did this come from"; the monitor opens the + // process tab already filtered to that path. + const [processFilter] = useState(null); + const cleanup = useScanWorkspace("cleanup", spaceDefaults); + const purge = useScanWorkspace("purge", spaceDefaults); const apps = useAppsWorkspace(); const permissions = usePermissionsWorkspace(page === "permissions"); + const security = useSecurityWorkspace(true); const systemActive = (page === "overview" || page === "system") && windowVisible; // Only the 实时监控 top-process table needs the expensive per-pid walk; // the overview tiles ride the light refresh. const system = useSystemSnapshot(systemActive, 1800, page === "system"); const update = useUpdateFlow(bootstrap?.updateFeedUrl ?? "", autoCheck); - // One security state for the whole window: the overview strip, the sidebar - // badge and the security page all read this, so they cannot disagree. - const security = useSecurityWorkspace(true); - const startup = useStartupWorkspace(page === "startup"); - // A process row can ask "where did this come from", and a startup entry can ask - // "is it running". Both hand the other page a path rather than duplicating data. - const [processFilter, setProcessFilter] = useState(null); - // A path handed from the process table to the startup page, where it becomes a - // search rather than a second data load. - const [startupQuery, setStartupQuery] = useState(null); - const [autostart, setAutostart] = useState(false); useEffect(() => { let cancelled = false; @@ -226,8 +247,6 @@ export default function App() { setLang(next.language); setAutoCheck(next.updateCheckEnabled); setSetupOpen(!next.settings.setupReviewed); - // The readiness card reports whether Squid starts at login, and that is a - // fact about the system rather than about settings, so it is asked for. void api .autostartStatus() .then(setAutostart) @@ -262,11 +281,11 @@ export default function App() { /** * A notification click goes to the findings, and brings the window back. * - * Findings are the only thing squid notifies about, so the tap needs no - * destination in its payload. The backend is asked as well because closing the - * window only hides it: the webview is gone, so nothing on this side can undo - * the hide, and a click that appeared to do nothing would look like a bug in the - * security feature rather than in window management. + * Findings are the only thing Squid notifies about, so the tap needs no + * destination in its payload. The backend is asked as well because closing + * the window only hides it: the webview is gone, so nothing on this side can + * undo the hide, and a click that appeared to do nothing would look like a + * bug in the security feature rather than in window management. */ useEffect(() => { let cancelled = false; @@ -275,9 +294,6 @@ export default function App() { .then(({ onAction }) => onAction(() => { if (cancelled) return; - // The backend's reply arrives as the same navigate event the tray menu - // uses, which also shows the hidden window. Asking first and navigating - // here as well would race the two against each other. void api.securityOpen().catch(() => undefined); void security.refresh(); }), @@ -286,8 +302,6 @@ export default function App() { if (cancelled) void listener.unregister(); else stop = listener; }) - // No plugin, or notifications switched off: the tray line and the in-app - // banner still report the same finding, so this is silence, not failure. .catch(() => undefined); return () => { cancelled = true; @@ -295,20 +309,17 @@ export default function App() { }; }, [security]); - const inspectProcess = useCallback((path: string) => { - setProcessFilter(path); - setPage("system"); - }, []); - useEffect(() => { let cancelled = false; let unlisten: (() => void) | null = null; void api .onNavigate((next) => { - if (!cancelled) setPage(next); - // A tray or notification jump into Security must show current numbers, - // not the ones from whenever the window last asked. - if (next === "security") void security.refresh(); + if (cancelled) return; + const target = LEGACY_PAGES[next] ?? next; + setPage(target); + if (target === "space") setSpaceTab("junk"); + if (target === "maintenance") setMaintTab("repair"); + if (target === "security") void security.refresh(); }) .then((stop) => { if (cancelled) stop(); @@ -321,22 +332,25 @@ export default function App() { }, [security]); useEffect(() => { - const order: PageId[] = ([ + const order: PageId[] = [ "overview", - "cleanup", + "space", "applications", - "purge", "permissions", - "storage", - "system", "security", - "startup", - ] as PageId[]).filter( - (id) => id !== "permissions" || bootstrap?.platform === "windows", - ); - // Ctrl/Cmd+1..9 follow the sidebar. + "maintenance", + "system", + "widget", + "history", + ]; + // Ctrl/Cmd+1..9 follow the sidebar; 0 opens settings. const onKey = (event: KeyboardEvent) => { if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return; + if (event.key === "0") { + event.preventDefault(); + setPage("settings"); + return; + } const index = Number(event.key) - 1; if (!Number.isInteger(index) || index < 0 || index >= order.length) return; event.preventDefault(); @@ -344,7 +358,7 @@ export default function App() { }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); - }, [bootstrap?.platform]); + }, []); const changeLanguage = useCallback( async (nextLanguage: Language) => { @@ -352,7 +366,8 @@ export default function App() { const next = await api.settingsSave({ language: nextLanguage }); setSettings(next); setLang(next.effectiveLanguage); - document.documentElement.lang = next.effectiveLanguage === "zh" ? "zh-CN" : "en"; + document.documentElement.lang = + next.effectiveLanguage === "zh" ? "zh-CN" : "en"; } catch (reason) { push(messageFrom(reason), "danger"); } @@ -363,12 +378,10 @@ export default function App() { const changeAutoCheck = useCallback( (enabled: boolean) => { setAutoCheck(enabled); - void api - .setUpdateCheckEnabled(enabled) - .catch((reason) => { - setAutoCheck(!enabled); - push(messageFrom(reason), "danger"); - }); + void api.setUpdateCheckEnabled(enabled).catch((reason) => { + setAutoCheck(!enabled); + push(messageFrom(reason), "danger"); + }); }, [push], ); @@ -406,41 +419,33 @@ export default function App() { bootstrap={bootstrap} snapshot={system.snapshot} cleanup={cleanup} + purge={purge} onNavigate={setPage} + onOpenSpaceTab={(tab) => { + setSpaceTab(tab); + setPage("space"); + }} /> ) : null} - {page === "cleanup" ? ( - setPage("history")} + initialTab={spaceTab} /> ) : null} {page === "applications" ? ( setPage("history")} /> ) : null} - {page === "purge" ? ( - setPage("history")} - /> - ) : null} {page === "permissions" ? : null} - {page === "storage" ? : null} {page === "security" ? ( - setPage("startup")} /> - ) : null} - {page === "startup" ? ( - setPage("security")} - /> + setPage("permissions")} /> ) : null} + {page === "widget" ? : null} + {page === "maintenance" ? : null} {page === "system" ? ( { - setStartupQuery(query); - setPage("startup"); - }} + onOpenStartup={() => setPage("permissions")} /> ) : null} {page === "history" ? : null} @@ -511,11 +513,7 @@ function AppChrome({ const title = PAGE_TITLES[page][lang === "zh" ? 1 : 0]; return ( -
+
@@ -352,6 +400,11 @@ export function ApplicationsPage({ {!workspace.scanned && !workspace.scanning ? ( } + title={t("See what is installed", "查看已安装的应用")} + description={t( + "Scan your applications to remove an app completely, including files that would otherwise stay behind.", + "扫描应用后可连同原本会遗留的文件一起移除。", + )} action={ - ) : null - } - /> - - {workspace.error && !workspace.scanning ? ( -
{workspace.error}
- ) : null} - - - - {!workspace.result && !workspace.scanning && !workspace.summary ? ( - } - action={ - - } - /> - ) : null} - -
- ); -} diff --git a/src/pages/DuplicateFilesPage.tsx b/src/pages/DuplicateFilesPage.tsx new file mode 100644 index 0000000..6594216 --- /dev/null +++ b/src/pages/DuplicateFilesPage.tsx @@ -0,0 +1,512 @@ +import { + CopyX, + FileQuestion, + FolderPlus, + Lock, + MapPin, + ScanSearch, + ShieldAlert, + Sparkles, + Trash2, + X, +} from "lucide-react"; +import { useEffect, useState } from "react"; +import { open } from "@tauri-apps/plugin-dialog"; +import * as apiClient from "../lib/api"; +import { useI18n } from "../i18n"; +import { agoLabel, formatBytes, formatCount } from "../lib/format"; +import { keepIndexOf, useDuplicatesWorkspace } from "../hooks/useDuplicatesWorkspace"; +import { + Button, + Checkbox, + EmptyState, + InlineError, + PageHeader, + ProgressCard, + useToast, +} from "../components/ui"; +import { CleanBar } from "../components/CleanBar"; +import type { DeleteResult, DupGroup } from "../types"; + +const MIN_SIZE_OPTIONS = [ + { value: 1024 * 1024, label: "≥1MB" }, + { value: 10 * 1024 * 1024, label: "≥10MB" }, + { value: 100 * 1024 * 1024, label: "≥100MB" }, +]; + +function FunnelStage({ + value, + label, + hot, +}: { + value: number; + label: string; + hot?: boolean; +}) { + return ( +
+ {formatCount(value)} + {label} +
+ ); +} + +function DupGroupCard({ + group, + index, + keep, + picked, + lang, + onToggle, + onDismiss, +}: { + group: DupGroup; + index: number; + keep: number; + picked: Set | undefined; + lang: "zh" | "en"; + onToggle: (groupIndex: number, copyIndex: number) => void; + onDismiss: (groupIndex: number) => void; +}) { + const { t } = useI18n(); + const wasted = group.size * (group.copies.length - 1); + // The keeper row is now a normal, checkable copy: ticking it means "this + // group may end up with nothing left". The amber chip keeps saying 保留 so + // the strategy stays visible, and adds a warning when it gets picked. + const keepPicked = picked?.has(keep) ?? false; + return ( +
+
+
+ + {group.copies.length} {t("copies", "份相同")} + + {group.copies[keep]?.path.split(/[\\/]/).pop()} + + {t("wastes", "重复浪费")} {formatBytes(wasted)} + + {keepPicked ? ( + + {t("group will be empty", "本组将一份不剩")} + + ) : null} + {group.personal ? ( + + + {t("personal files", "个人文件")} + + ) : null} +
+
+ {formatBytes(group.size)} {t("each", "/ 份")} +
+ +
+
    + {group.copies.map((copy, copyIndex) => { + const isKeep = copyIndex === keep; + const checked = picked?.has(copyIndex) ?? false; + return ( +
  • + onToggle(index, copyIndex)} + label={copy.path} + /> + {isKeep ? ( + + {checked ? t("keep · deleting", "保留 · 已勾选删除") : t("keep", "保留")} + + ) : null} + + {copy.locked ? ( + + + + ) : null} + + {copy.path} + + + {copy.mtimeMs ? agoLabel(copy.mtimeMs, lang) : ""} + + +
  • + ); + })} +
+
+ ); +} + +export function DuplicateFilesPage({ + embedded = false, + onBadge, + onHistory, +}: { + /** Rendered inside 空间清理 hub: page title hides, stats flow to onBadge. */ + embedded?: boolean; + onBadge?: (value: string | null) => void; + /** Jump to 历史记录 for an undo. */ + onHistory?: () => void; +} = {}) { + const { t, lang } = useI18n(); + const { push } = useToast(); + const workspace = useDuplicatesWorkspace(); + const [minSize, setMinSize] = useState(1024 * 1024); + const [extraRoots, setExtraRoots] = useState([]); + const [confirming, setConfirming] = useState(false); + const [cleanDone, setCleanDone] = useState<{ outcome: DeleteResult; elapsedMs: number } | null>( + null, + ); + + const entries = workspace.visible; + const groups = entries.map((entry) => entry.group); + const report = workspace.result?.report; + + const addRoot = async () => { + const chosen = await open({ + directory: true, + multiple: true, + title: t("Add folders to the duplicate scan", "选择要一起扫描的文件夹"), + }); + if (Array.isArray(chosen)) setExtraRoots((current) => [...current, ...chosen]); + else if (typeof chosen === "string") setExtraRoots((current) => [...current, chosen]); + }; + + const start = () => { + setConfirming(false); + void workspace.runScan(extraRoots, minSize); + }; + + const confirmClean = async () => { + setConfirming(false); + const startedAt = Date.now(); + const outcome = await workspace.clean("trash"); + if (outcome) { + setCleanDone({ outcome, elapsedMs: Date.now() - startedAt }); + push( + lang === "zh" + ? `已将 ${outcome.removed} 个副本移入回收站(${formatBytes(outcome.freed)}),可在「历史记录」撤销` + : `Moved ${outcome.removed} copies to the Recycle Bin (${formatBytes(outcome.freed)}) — undo from History`, + "success", + ); + } + }; + + // Totals next to the toolbar follow the *visible* groups: an ignored group + // stops counting toward what the page offers to reclaim. + const visibleWasted = groups.reduce((sum, g) => sum + g.size * (g.copies.length - 1), 0); + // Groups whose *kept* copy is checked: deleting those erases the file + // entirely (every copy goes), which the summary strip and confirm dialog + // must call out before anything moves to the Recycle Bin. + const empties = entries.reduce( + (sum, entry) => + sum + + (workspace.picks.get(entry.index)?.has(keepIndexOf(entry.group, workspace.keepStrategy)) + ? 1 + : 0), + 0, + ); + + // Hub badge: confirmed groups after ignores, or null before a scan. + useEffect(() => { + if (!embedded || !onBadge) return; + onBadge(groups.length > 0 ? `${groups.length} 组 · ${formatBytes(visibleWasted)}` : null); + }, [embedded, groups.length, onBadge, visibleWasted]); + + return ( +
+ {embedded ? null : ( + + )} + {workspace.error ? : null} + +
+ {t("Scan scope", "扫描范围")} + + {t( + "Home folders + all drives (system folders skipped)", + "用户目录 + 各磁盘(自动跳过系统与软件数据目录)", + )} + + {extraRoots.map((root) => ( + + {root} + + + ))} + + + {t("Min size", "最小体积")} +
+ {MIN_SIZE_OPTIONS.map((option) => ( + + ))} +
+ +
+ + {workspace.scanning || (workspace.funnel.walked > 0 && groups.length > 0) ? ( +
+
+ + → + + → + + → + +
+ {t("duplicates found", "已发现重复")}{" "} + {formatCount(groups.length)} {t("groups", "组")} ·{" "} + {t("recoverable", "可回收")} {formatBytes(visibleWasted)} +
+
+ {workspace.progress?.subject ? ( +
+ {t("Checking", "正在校验")} {workspace.progress.subject} +
+ ) : null} +
+ ) : null} + + {workspace.scanning ? ( + void workspace.cancel()} + capAt99 + /> + ) : null} + + {workspace.deleting ? ( + onHistory?.()} + onDismiss={() => undefined} + /> + ) : null} + + {!workspace.deleting && cleanDone ? ( + onHistory?.()} + onDismiss={() => setCleanDone(null)} + onRescan={() => void workspace.runScan(extraRoots, minSize)} + /> + ) : null} + + {!workspace.scanning && + groups.length === 0 && + !workspace.result && + !workspace.error && + !workspace.deleting && + !cleanDone ? ( + } + title={t("No duplicate scan yet", "还没有扫描过重复文件")} + description={t( + "Start scan walks your files once; later scans reuse the hash cache and only re-check what changed.", + "首次扫描遍历一遍文件;之后的扫描复用哈希缓存,只重算发生变化的文件。", + )} + /> + ) : null} + + {!workspace.scanning && groups.length === 0 && workspace.result ? ( + } + title={t("No duplicate files found", "没有发现重复文件")} + description={ + lang === "zh" + ? `已检查 ${formatCount(workspace.result.report.walked)} 个达到体积门槛的文件,无重复。` + : `${formatCount(workspace.result.report.walked)} files checked above the size floor.` + } + /> + ) : null} + + {!workspace.scanning && groups.length > 0 ? ( + <> +
+ + + + + {formatCount(groups.length)} {t("groups · duplicate copies", "组 · 重复副本")}{" "} + {formatCount(groups.reduce((sum, g) => sum + g.copies.length - 1, 0))} ·{" "} + {formatBytes(visibleWasted)} + {empties > 0 ? ( + + {t( + `${formatCount(empties)} group(s) will be fully removed`, + ` · ${formatCount(empties)} 组将一份不剩`, + )} + + ) : null} + + +
+ {confirming ? ( +
0 ? "is-strict" : ""}`}> + +
+ + {lang === "zh" + ? `将 ${workspace.selectedCount} 个副本(${formatBytes(workspace.selectedBytes)})移入回收站?` + : `Move ${workspace.selectedCount} copies (${formatBytes(workspace.selectedBytes)}) to the Recycle Bin?`} + + {empties > 0 ? ( + + {lang === "zh" + ? `${formatCount(empties)} 组勾选了最后保留版本——这 ${formatCount(empties)} 组将被完全删除!` + : `${formatCount(empties)} group(s) include the kept copy — they will be deleted entirely!`} + + ) : ( + + {t( + "Every group keeps at least one copy; a mis-click is one Undo away from History.", + "每组至少保留一份;误删可从「历史记录 → 撤销」找回。", + )} + + )} + + {t( + "Deletions land in the Recycle Bin — undo from History.", + "删除一律进回收站,可从「历史记录 → 撤销」找回。", + )} + +
+ + +
+ ) : null} +
+ {entries.map(({ group, index }) => ( + + ))} +
+ + ) : null} +
+ ); +} diff --git a/src/pages/HistoryPage.tsx b/src/pages/HistoryPage.tsx index 421bd18..c8ce852 100644 --- a/src/pages/HistoryPage.tsx +++ b/src/pages/HistoryPage.tsx @@ -89,6 +89,7 @@ export function HistoryPage() { return (
} title={t("No cleanups yet", "还没有清理记录")} + description={t( + "Each confirmed cleanup will appear here with its size, result and restore option.", + "每次确认的清理都会记录在这里,并提供大小、结果与还原选项。", + )} /> ) : (
diff --git a/src/pages/LargeFilesPage.tsx b/src/pages/LargeFilesPage.tsx new file mode 100644 index 0000000..c0c0d1e --- /dev/null +++ b/src/pages/LargeFilesPage.tsx @@ -0,0 +1,425 @@ +import { + Archive, + Disc3, + Cloud, + FileQuestion, + FileVideo, + HardDrive, + Lock, + MapPin, + Package, + ScanSearch, + ShieldAlert, + Trash2, +} from "lucide-react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import * as apiClient from "../lib/api"; +import { subscribeJobProgress } from "../lib/api"; +import { useI18n } from "../i18n"; +import { agoLabel, formatBytes, formatCount, messageFrom } from "../lib/format"; +import { + Button, + Checkbox, + EmptyState, + InlineError, + PageHeader, + ProgressCard, + useToast, +} from "../components/ui"; +import { CleanBar } from "../components/CleanBar"; +import type { DeleteResult, JobProgress, LargeFile } from "../types"; + +const THRESHOLDS = [ + { value: 100 * 1024 * 1024, label: "≥100MB" }, + { value: 500 * 1024 * 1024, label: "≥500MB" }, + { value: 1024 * 1024 * 1024, label: "≥1GB" }, +]; + +const CLASSES = [ + { id: "all", en: "All", zh: "全部", icon: HardDrive }, + { id: "video", en: "Video", zh: "视频", icon: FileVideo }, + { id: "archive", en: "Archives", zh: "归档", icon: Archive }, + { id: "installer", en: "Installers", zh: "安装包", icon: Package }, + { id: "image", en: "Disk images", zh: "镜像/VHD", icon: Disc3 }, +]; + +const CLASS_ICON: Record = { + video: FileVideo, + archive: Archive, + installer: Package, + image: Disc3, + other: HardDrive, +}; + +/** 休眠判定沿用清理页口径:180 天无修改即值得标记。 */ +const DORMANT_SECS = 180 * 86_400; + +export function LargeFilesPage({ + embedded = false, + onBadge, + onHistory, +}: { + /** Rendered inside 空间清理 hub: page title hides, stats flow to onBadge. */ + embedded?: boolean; + onBadge?: (value: string | null) => void; + /** Jump to 历史记录 for an undo. */ + onHistory?: () => void; +} = {}) { + const { t, lang } = useI18n(); + const { push } = useToast(); + const [files, setFiles] = useState(null); + const [scope, setScope] = useState([]); + const [threshold, setThreshold] = useState(500 * 1024 * 1024); + const [klass, setKlass] = useState("all"); + const [hideCritical, setHideCritical] = useState(true); + const [scanning, setScanning] = useState(false); + const [deleting, setDeleting] = useState(false); + const [error, setError] = useState(null); + const [progress, setProgress] = useState(null); + const [picked, setPicked] = useState>(new Set()); + const [confirming, setConfirming] = useState(false); + const [cleanDone, setCleanDone] = useState< + { outcome: DeleteResult; elapsedMs: number } | null + >(null); + const job = useRef(null); + + const run = useCallback(async () => { + if (scanning) return; + const id = crypto.randomUUID?.() ?? String(Date.now()); + job.current = id; + setScanning(true); + setError(null); + setFiles(null); + setPicked(new Set()); + setProgress(null); + const stop = await subscribeJobProgress(id, (event) => { + if (event.event === "metered") { + setProgress(event); + } else if (event.event === "tick" || event.event === "phase") { + setProgress(event); + } + }); + try { + const found = await apiClient.api.largeFilesScan( + id, + scope, + threshold, + klass === "all" ? null : klass, + ); + setFiles(found); + } catch (reason) { + if (!messageFrom(reason).toLowerCase().includes("cancel")) { + setError(messageFrom(reason)); + } + } finally { + stop(); + setScanning(false); + job.current = null; + } + }, [klass, scanning, scope, threshold]); + + const visible = useMemo(() => { + if (!files) return null; + return files.filter((file) => !hideCritical || !file.maybeMounted); + }, [files, hideCritical]); + + const totalBytes = visible?.reduce((sum, file) => sum + file.size, 0) ?? 0; + const pickedBytes = visible + ?.filter((file) => picked.has(file.path)) + .reduce((sum, file) => sum + file.size, 0) ?? 0; + const pickedCount = picked.size; + + // Hub badge: found files, or null before a scan. + useEffect(() => { + if (!embedded || !onBadge) return; + onBadge( + visible && visible.length > 0 + ? `${formatCount(visible.length)} 个 · ${formatBytes(totalBytes)}` + : null, + ); + }, [embedded, onBadge, totalBytes, visible]); + + const toggle = (path: string) => { + setPicked((current) => { + const next = new Set(current); + if (next.has(path)) next.delete(path); + else next.add(path); + return next; + }); + }; + + const confirmDelete = async () => { + const id = crypto.randomUUID?.() ?? String(Date.now()); + job.current = id; + setDeleting(true); + setProgress(null); + const stop = await subscribeJobProgress(id, (event) => { + if (event.event === "tick" || event.event === "deleted") setProgress(event); + }); + const startedAt = Date.now(); + try { + const outcome = await apiClient.api.largeFilesDelete(id, [...picked], "trash"); + setFiles((current) => current?.filter((f) => !picked.has(f.path)) ?? null); + setPicked(new Set()); + setConfirming(false); + setCleanDone({ outcome, elapsedMs: Date.now() - startedAt }); + push( + lang === "zh" + ? `已将 ${outcome.removed} 个大文件移入回收站(${formatBytes(outcome.freed)}),可在「历史记录」撤销` + : `Moved ${outcome.removed} files to the Recycle Bin (${formatBytes(outcome.freed)})`, + "success", + ); + } catch (reason) { + setError(messageFrom(reason)); + } finally { + stop(); + setDeleting(false); + job.current = null; + } + }; + + const now = Date.now(); + + return ( +
+ {embedded ? null : ( + + )} + {error ? setError(null)} /> : null} + +
+ {t("Scope", "范围")} +
+ + {["C:", "D:", "E:"].map((drive) => ( + + ))} +
+ {t("At least", "阈值")} +
+ {THRESHOLDS.map((option) => ( + + ))} +
+ {t("Type", "类型")} +
+ {CLASSES.map((option) => { + const Icon = option.icon; + return ( + + ); + })} +
+ +
+ + {scanning ? ( + { + if (job.current) void apiClient.api.cancelJob(job.current); + }} + /> + ) : null} + + {deleting ? ( + onHistory?.()} + onDismiss={() => undefined} + /> + ) : null} + + {!deleting && cleanDone ? ( + onHistory?.()} + onDismiss={() => setCleanDone(null)} + onRescan={() => void run()} + /> + ) : null} + + {!files && !scanning ? ( + } + title={t("No large-file scan yet", "还没有扫描过大文件")} + description={t( + "Start scan walks every drive above the size floor; results sort heaviest first.", + "点击「开始扫描」按体积门槛遍历所选磁盘,结果从最大往下排。", + )} + /> + ) : null} + + {visible && visible.length === 0 && !scanning ? ( + } + title={t("No files above the threshold", "没有超过阈值的大文件")} + description={t( + "Try a lower size floor or another scope.", + "可以调低体积门槛或更换扫描范围再试。", + )} + /> + ) : null} + + {visible && visible.length > 0 ? ( + <> +
+
+ + {formatCount(visible.length)} {t("large files", "个大文件")} ·{" "} + {formatBytes(totalBytes)} + + + {pickedCount > 0 + ? t( + `${pickedCount} selected · ${formatBytes(pickedBytes)} → Recycle Bin`, + `已选 ${pickedCount} 项 · ${formatBytes(pickedBytes)} → 移入回收站`, + ) + : t( + "Dormant files (180 days untouched) are tagged; disk images held by Hyper-V/WSL stay locked. Page files are hidden; hiberfil.sys frees via turning hibernation off.", + "长期未修改(180 天+)的文件会带休眠标记;被 Hyper-V/WSL 使用的镜像会锁定。页面文件(pagefile/swapfile)已自动隐藏;hiberfil.sys 可通过关闭休眠释放。", + )} + +
+ + +
+ {confirming ? ( +
+ +
+ + {lang === "zh" + ? `将 ${pickedCount} 个大文件(${formatBytes(pickedBytes)})移入回收站?` + : `Move ${pickedCount} files (${formatBytes(pickedBytes)}) to the Recycle Bin?`} + + + {t( + "Undo from History while the Recycle Bin holds them.", + "回收站清空前,可随时在「历史记录」撤销。", + )} + +
+ + +
+ ) : null} +
    + {visible.map((file, index) => { + const Icon = CLASS_ICON[file.class] ?? HardDrive; + const dormant = + file.modifiedMs > 0 && (now - file.modifiedMs) / 1000 > DORMANT_SECS; + return ( +
  • + toggle(file.path)} + label={file.displayPath} + /> + {String(index + 1).padStart(2, "0")} + + + +
    + {file.path.split(/[\\/]/).pop()} + {file.displayPath} +
    + {dormant ? ( + + {agoLabel(file.modifiedMs, lang)} {t("untouched", "未修改")} + + ) : null} + {file.cloudHint ? ( + + {t("cloud copy?", "网盘可能有副本?")} + + ) : null} + {file.maybeMounted ? ( + + {t("check in use", "占用检查")} + + ) : null} + {formatBytes(file.size)} + +
  • + ); + })} +
+ + ) : null} +
+ ); +} diff --git a/src/pages/MaintenanceHubPage.tsx b/src/pages/MaintenanceHubPage.tsx new file mode 100644 index 0000000..a0ebde9 --- /dev/null +++ b/src/pages/MaintenanceHubPage.tsx @@ -0,0 +1,65 @@ +import { EyeOff, SlidersHorizontal, Wrench } from "lucide-react"; +import { useEffect, useState } from "react"; +import { useI18n } from "../i18n"; +import { PageHeader } from "../components/ui"; +import { MaintenancePage } from "./MaintenancePage"; +import { PrivacyPage } from "./PrivacyPage"; +import { OptimizationPage } from "./OptimizationPage"; + +/* 系统维护 hub(方案②):一键修复 / 隐私清理 / 系统优化 三页签。 + * 面板全部保持挂载(display 切换),修复任务运行中切页签不会打断 + * 日志流;徽标由面板回报(隐私=痕迹数、优化=已更改数)。 */ + +export type MaintTab = "repair" | "privacy" | "optimize"; + +const TABS: { id: MaintTab; icon: typeof Wrench; en: string; zh: string }[] = [ + { id: "repair", icon: Wrench, en: "One-click repairs", zh: "一键修复" }, + { id: "privacy", icon: EyeOff, en: "Privacy cleaning", zh: "隐私清理" }, + { id: "optimize", icon: SlidersHorizontal, en: "System optimisation", zh: "系统优化" }, +]; + +export function MaintenanceHubPage({ initialTab = "repair" }: { initialTab?: MaintTab }) { + const { t } = useI18n(); + const [tab, setTab] = useState(initialTab); + useEffect(() => setTab(initialTab), [initialTab]); + const [badges, setBadges] = useState>>({}); + const report = (id: MaintTab) => (value: string | null) => + setBadges((current) => (current[id] === value ? current : { ...current, [id]: value })); + + return ( +
+ +
+ {TABS.map((item) => { + const Icon = item.icon; + const badge = badges[item.id]; + return ( + + ); + })} +
+
+ +
+
+ +
+
+ +
+
+ ); +} diff --git a/src/pages/MaintenancePage.tsx b/src/pages/MaintenancePage.tsx new file mode 100644 index 0000000..7208df9 --- /dev/null +++ b/src/pages/MaintenancePage.tsx @@ -0,0 +1,213 @@ +import { + Activity, + AlertTriangle, + Check, + Search, + ShieldCheck, + Wrench, + X, +} from "lucide-react"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { api, subscribeJobProgress } from "../lib/api"; +import { useI18n } from "../i18n"; +import { messageFrom } from "../lib/format"; +import { + Button, + InlineError, + PageHeader, + ProgressCard, + useToast, +} from "../components/ui"; +import type { JobProgress, MaintenanceResult, MaintenanceTask } from "../types"; + +const RISK_CHIP: Record = { + // [class, zh, en] + safe: ["is-safe", "安全", "Safe"], + admin: ["is-admin", "需要管理员", "Admin rights"], + slow: ["is-slow", "较慢", "Slow"], +}; + +export function MaintenancePage({ + embedded = false, + onBadge, +}: { + /** Rendered inside 系统维护 hub: page title hides, task count flows up. */ + embedded?: boolean; + onBadge?: (value: string | null) => void; +} = {}) { + const { t, lang } = useI18n(); + const { push } = useToast(); + const [tasks, setTasks] = useState([]); + const [running, setRunning] = useState(null); + const [progress, setProgress] = useState(null); + const [logs, setLogs] = useState([]); + const [result, setResult] = useState(null); + const [error, setError] = useState(null); + const job = useRef(null); + + useEffect(() => { + if (embedded && onBadge) onBadge(tasks.length > 0 ? `${tasks.length} 项` : null); + }, [embedded, onBadge, tasks.length]); + + useEffect(() => { + let alive = true; + void api + .maintenanceTasks() + .then((list) => alive && setTasks(list)) + .catch((reason) => alive && setError(messageFrom(reason))); + return () => { + alive = false; + }; + }, []); + + const runTask = useCallback( + async (task: MaintenanceTask) => { + if (running) return; + const id = crypto.randomUUID?.() ?? String(Date.now()); + job.current = id; + setRunning(task.id); + setResult(null); + setError(null); + setLogs([]); + setProgress(null); + const stop = await subscribeJobProgress(id, (event) => { + if (event.event === "note" && event.detail) { + setLogs((current) => [...current.slice(-200), event.detail as string]); + } + setProgress(event); + }); + try { + const outcome = await api.maintenanceRun(id, task.id); + setResult(outcome); + if (outcome.ok) { + push( + lang === "zh" + ? `${task.titleZh}:完成(用时 ${Math.round(outcome.durationMs / 1000)} 秒)` + : `${task.titleEn}: done (${Math.round(outcome.durationMs / 1000)}s)`, + "success", + ); + } else { + push( + lang === "zh" + ? `${task.titleZh}:在「${outcome.failedStep ?? "某一步"}」失败` + : `${task.titleEn}: failed at ${outcome.failedStep ?? "a step"}`, + "danger", + ); + } + } catch (reason) { + setError(messageFrom(reason)); + } finally { + stop(); + setRunning(null); + setProgress(null); + job.current = null; + } + }, + [lang, push, running], + ); + + return ( +
+ {embedded ? null : ( + + )} + {error ? setError(null)} /> : null} + +
+ + + {t( + "All repairs below touch only system caches / services / indexes — never your documents.", + "以下修复只影响系统缓存 / 服务 / 索引,不碰你的文档。", + )} + +
+ +
    + {tasks.map((task) => { + const [chipClass, chipZh, chipEn] = RISK_CHIP[task.risk]; + const isRunning = running === task.id; + return ( +
  • + + + +
    + {lang === "zh" ? task.titleZh : task.titleEn} + {lang === "zh" ? task.detailZh : task.detailEn} + {isRunning && progress ? ( + { + if (job.current) void api.cancelJob(job.current); + }} + /> + ) : null} + {isRunning && logs.length > 0 ? ( +
    +                    {logs.slice(-8).join("\n")}
    +                  
    + ) : null} +
    + {task.estimate} + {lang === "zh" ? chipZh : chipEn} + {isRunning ? ( + + ) : ( + + )} +
  • + ); + })} + {tasks.length === 0 && !error ? ( +
  • + + {t("Loading the repair list…", "正在加载修复清单…")} +
  • + ) : null} +
+ + {result ? ( +
+ {result.ok ? : } +
+ + {result.ok + ? t("Repair completed", "修复完成") + : t("Repair stopped early", "修复提前停止")} + +
    + {result.steps.map((step, index) => ( +
  • + {step} +
  • + ))} +
+ {result.outputTail ? ( +
+ {t("Command output", "命令输出")} +
{result.outputTail}
+
+ ) : null} +
+ +
+ ) : null} +
+ ); +} diff --git a/src/pages/OptimizationPage.tsx b/src/pages/OptimizationPage.tsx new file mode 100644 index 0000000..ab1ad8b --- /dev/null +++ b/src/pages/OptimizationPage.tsx @@ -0,0 +1,147 @@ +import { RotateCcw, SlidersHorizontal } from "lucide-react"; +import { useCallback, useEffect, useState } from "react"; +import { api } from "../lib/api"; +import { useI18n } from "../i18n"; +import { messageFrom } from "../lib/format"; +import { Button, InlineError, PageHeader, Toggle, useToast } from "../components/ui"; +import type { TweakState } from "../types"; + +export function OptimizationPage({ + embedded = false, + onBadge, +}: { + /** Rendered inside 系统维护 hub: page title hides, changed count flows up. */ + embedded?: boolean; + onBadge?: (value: string | null) => void; +} = {}) { + const { t, lang } = useI18n(); + const { push } = useToast(); + const [states, setStates] = useState([]); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(null); + + const refresh = useCallback(async () => { + try { + setStates(await api.tweaksStates()); + } catch (reason) { + setError(messageFrom(reason)); + } + }, []); + + useEffect(() => { + void refresh(); + }, [refresh]); + + const flip = async (tweak: TweakState, next: boolean) => { + setBusy(tweak.id); + setError(null); + try { + const state = await api.tweaksSet(tweak.id, next); + setStates((current) => current.map((row) => (row.id === state.id ? state : row))); + } catch (reason) { + setError(messageFrom(reason)); + } finally { + setBusy(null); + } + }; + + const changed = states.filter((state) => state.recorded).length; + + // Hub badge: how many tweaks have been flipped so far (null when none). + useEffect(() => { + if (!embedded || !onBadge) return; + onBadge(changed > 0 ? `已更改 ${changed} 项` : null); + }, [changed, embedded, onBadge]); + + const restoreAll = async () => { + setBusy("__all__"); + try { + const restored = await api.tweaksRestoreAll(); + push( + lang === "zh" + ? `已恢复 ${restored.length} 项为系统默认值` + : `Restored ${restored.length} tweaks to system defaults`, + "success", + ); + await refresh(); + } catch (reason) { + setError(messageFrom(reason)); + } finally { + setBusy(null); + } + }; + + return ( +
+ {embedded ? null : ( + } disabled={busy !== null || changed === 0} onClick={() => void restoreAll()}> + {t("Restore all defaults", "恢复全部默认")} + + } + /> + )} + {error ? setError(null)} /> : null} + +
+
+

+ {t("Everyday privacy & clarity", "常用隐私与界面")} +

+ + {changed > 0 + ? t(`${changed} changed · revertable`, `已更改 ${changed} 项 · 可随时恢复`) + : t("Nothing changed yet", "尚未更改任何项")} + + {/* Embedded (维护 hub): the page header — and with it the restore + button — is hidden, so the group head carries it instead. */} + {embedded ? ( + + ) : null} +
+
    + {states.map((state) => ( +
  • +
    + + {lang === "zh" ? state.titleZh : state.titleEn} + {state.restartHint && state.enabled ? ( + + {t("needs Explorer/Windows restart", "需重启 Explorer/系统生效")} + + ) : null} + + {lang === "zh" ? state.detailZh : state.detailEn} + + {state.hive}\\{state.key} · {state.value} + +
    + + {state.risk === "safe" ? t("Safe", "安全") : t("Read the note", "看说明")} + + void flip(state, next)} + label={lang === "zh" ? state.titleZh : state.titleEn} + /> +
  • + ))} +
+ {states.length === 0 && !error ? ( +

{t("Loading the catalog…", "正在加载目录…")}

+ ) : null} +
+
+ ); +} diff --git a/src/pages/OverviewPage.tsx b/src/pages/OverviewPage.tsx index b8766fb..c044af5 100644 --- a/src/pages/OverviewPage.tsx +++ b/src/pages/OverviewPage.tsx @@ -14,15 +14,12 @@ import { WandSparkles, Waypoints, } from "lucide-react"; +import type { ReactNode } from "react"; import { useI18n } from "../i18n"; -import { - formatBytes, - formatCount, - formatMemoryBytes, - percent, -} from "../lib/format"; -import type { Bootstrap, PageId, SystemSnapshot, Volume } from "../types"; +import { formatBytes, formatCount, formatMemory, percent } from "../lib/format"; +import type { Bootstrap, SystemSnapshot, Volume } from "../types"; import type { ScanWorkspace } from "../hooks/useScanWorkspace"; +import type { PageId } from "../types"; import { CategorySummary } from "../components/CleanupView"; import { Button, @@ -45,26 +42,87 @@ function greeting(lang: "zh" | "en"): string { return "Good evening"; } -function coreLabel(snapshot: SystemSnapshot | null, t: (en: string, zh: string) => string) { - if (!snapshot) return t("Reading processor…", "正在读取处理器…"); - const { physical_cores: physical, logical_cores: logical } = snapshot.cpu; - if (physical === logical) { - return t(`${physical} cores`, `${physical} 核`); - } - return t(`${physical} cores / ${logical} threads`, `${physical} 核 / ${logical} 线程`); +/// Windows mounts read `C:\`; everything else shows its own label. +function driveLabel(volume: Volume): string { + return /^[A-Za-z]:/.exec(volume.mount_point)?.[0] ?? volume.mount_point; } -function machineRows( - bootstrap: Bootstrap, - snapshot: SystemSnapshot | null, - volume: Volume | null, - t: (en: string, zh: string) => string, -) { - const hardware = bootstrap.hardwareInfo; - const model = bootstrap.hardware.split(" · ")[0]?.trim() || bootstrap.hardware; - const installed = snapshot +function SpecRow({ + icon, + label, + value, + t, +}: { + icon: ReactNode; + label: string; + value: string; + t: (en: string, zh: string) => string; +}) { + return ( +
+ {icon} + {label} + {value || t("—", "—")} +
+ ); +} + +export function OverviewPage({ + bootstrap, + snapshot, + cleanup, + purge, + onNavigate, + onOpenSpaceTab, +}: { + bootstrap: Bootstrap; + snapshot: SystemSnapshot | null; + cleanup: ScanWorkspace; + purge: ScanWorkspace; + onNavigate: (page: PageId) => void; + /** Deep-link into a 空间清理 hub tab (重复文件 / 大文件). */ + onOpenSpaceTab?: (tab: "junk" | "dups" | "big") => void; +}) { + const { t, lang } = useI18n(); + const volumes = snapshot?.volumes ?? []; + const rootVolume = volumes.find((candidate) => candidate.is_root) ?? volumes[0] ?? null; + const memoryInstalled = snapshot ? Math.max(snapshot.memory.installed, snapshot.memory.total) : 0; + const memoryReserved = snapshot + ? Math.max(0, memoryInstalled - snapshot.memory.total) + : 0; + const scanned = Boolean(cleanup.result || purge.result); + const scanning = cleanup.scanning || purge.scanning; + const found = [cleanup, purge].reduce( + (sum, workspace) => + sum + + (workspace.result + ? workspace.result.items + .filter((item) => !item.lock) + .reduce((total, item) => total + item.onDisk, 0) + : 0), + 0, + ); + // 智能扫描 is an entry point, not a resident process: the moment it is + // pressed we hand the page over to 空间清理 and launch both scan stages + // there (SpacePage owns the settings — age threshold, auto-discovery). + // A finished scan keeps the button as a shortcut back to the results. + const smartScan = () => { + onNavigate("space"); + if (!scanned && !scanning) { + void cleanup.runScan().then(() => + purge.runScan({ + // Empty = engine auto-discovery of project containers. + roots: [], + minAgeDays: bootstrap.settings.purgeMinAgeDays || 7, + force: false, + }), + ); + } + }; + + const hardware = bootstrap.hardwareInfo; const ramBrands = [ ...new Set(hardware.memory_sticks.map((stick) => stick.manufacturer).filter(Boolean)), ].join(" / "); @@ -72,112 +130,40 @@ function machineRows( (top, stick) => Math.max(top, stick.speed_mhz), 0, ); - const memory = [ - installed ? formatMemoryBytes(installed) : "", - ramBrands, - ramSpeed ? `${ramSpeed} MT/s` : "", - ] - .filter(Boolean) - .join(" · "); - const disk = [ - [hardware.disk_vendor, hardware.disk_model].filter(Boolean).join(" "), - hardware.disk_size_bytes ? formatBytes(hardware.disk_size_bytes, 0) : "", - hardware.disk_bus, - ] - .filter(Boolean) - .join(" · "); - const gpu = [ - hardware.gpu_model && - hardware.gpu_model.toLowerCase().startsWith(hardware.gpu_vendor.toLowerCase()) - ? hardware.gpu_model - : [hardware.gpu_vendor, hardware.gpu_model].filter(Boolean).join(" "), - hardware.gpu_vram_bytes ? formatBytes(hardware.gpu_vram_bytes, 0) : "", - ] - .filter(Boolean) - .join(" · "); - const rows = [ - { - key: "os", - icon: MonitorCog, - label: t("Operating system", "操作系统"), - value: bootstrap.osVersion || bootstrap.osName, - }, - { - key: "model", - icon: CircuitBoard, - label: t("Computer", "本机型号"), - value: hardware.board || model, - }, - { - key: "cpu", - icon: Cpu, - label: t("Processor", "处理器"), - value: snapshot - ? snapshot.cpu.brand || t("Unknown processor", "未知处理器") - : t("Reading processor…", "正在读取处理器…"), - }, - { - key: "memory", - icon: MemoryStick, - label: t("Memory", "内存"), - value: memory || t("Reading memory…", "正在读取内存…"), - }, - { - key: "disk", - icon: HardDrive, - label: t("Primary disk", "主硬盘"), - value: - disk || - (volume - ? `${volume.name || volume.mount_point} · ${formatBytes(volume.total, 0)} · ${volume.filesystem.toUpperCase()}` - : t("Reading disks…", "正在读取磁盘…")), - }, - ]; - if (gpu || snapshot?.host.gpu) { - rows.push({ - key: "gpu", - icon: Waypoints, - label: t("Graphics", "显卡"), - value: gpu || snapshot?.host.gpu || "", - }); - } - return rows; -} - -export function OverviewPage({ - bootstrap, - snapshot, - cleanup, - onNavigate, -}: { - bootstrap: Bootstrap; - snapshot: SystemSnapshot | null; - cleanup: ScanWorkspace; - onNavigate: (page: PageId) => void; -}) { - const { t, lang } = useI18n(); - const volumes = snapshot?.volumes ?? []; - const rootVolume = volumes.find((candidate) => candidate.is_root) ?? volumes[0] ?? null; - const used = rootVolume ? rootVolume.total - rootVolume.free : 0; - const usedPercent = rootVolume ? percent(used, rootVolume.total) : 0; - const memoryPercent = snapshot - ? percent(snapshot.memory.used, snapshot.memory.total) - : 0; - const memoryInstalled = snapshot - ? Math.max(snapshot.memory.installed, snapshot.memory.total) - : 0; - const memoryReserved = snapshot - ? Math.max(0, memoryInstalled - snapshot.memory.total) - : 0; - const found = cleanup.result - ? cleanup.result.items - .filter((item) => !item.lock) - .reduce((sum, item) => sum + item.onDisk, 0) - : 0; - const visibleVolumes = (snapshot?.volumes ?? []).slice(0, 2); - const startScan = () => { - if (cleanup.result) onNavigate("cleanup"); - else void cleanup.runScan(); + const specs = { + os: bootstrap.osVersion, + board: hardware.board || bootstrap.hardware, + cpu: snapshot + ? `${snapshot.cpu.brand} · ${snapshot.cpu.physical_cores} ${t("cores", "核")} / ${ + snapshot.cpu.logical_cores + } ${t("threads", "线程")}` + : hardware.cpu_model, + memory: + [ + memoryInstalled ? formatMemory(memoryInstalled) : "", + ramBrands, + ramSpeed ? `${ramSpeed} MT/s` : "", + ] + .filter(Boolean) + .join(" · ") || (memoryReserved ? formatMemory(memoryInstalled) : ""), + disk: + [ + [hardware.disk_vendor, hardware.disk_model].filter(Boolean).join(" "), + hardware.disk_size_bytes ? formatBytes(hardware.disk_size_bytes) : "", + hardware.disk_bus, + ] + .filter(Boolean) + .join(" · "), + gpu: + [ + hardware.gpu_model && + hardware.gpu_model.toLowerCase().startsWith(hardware.gpu_vendor.toLowerCase()) + ? hardware.gpu_model + : [hardware.gpu_vendor, hardware.gpu_model].filter(Boolean).join(" "), + hardware.gpu_vram_bytes ? formatBytes(hardware.gpu_vram_bytes) : "", + ] + .filter(Boolean) + .join(" · "), }; return ( @@ -185,21 +171,6 @@ export function OverviewPage({ } - onClick={startScan} - disabled={cleanup.scanning} - > - {cleanup.scanning - ? t("Scanning…", "扫描中…") - : cleanup.result - ? t("Review smart scan", "查看智能扫描") - : t("Smart scan", "智能扫描")} - - } />
@@ -209,7 +180,7 @@ export function OverviewPage({ {t("Smart Care", "智能维护")}

- {cleanup.result + {scanned ? t( `${formatBytes(found)} found safely`, `安全发现 ${formatBytes(found)} 可清理空间`, @@ -217,7 +188,7 @@ export function OverviewPage({ : t("A lighter, faster machine", "更轻盈,更顺畅")}

- {cleanup.result + {scanned ? t( "Review each category before anything is removed. Locked files stay untouched.", "清理前可逐项检查,锁定文件始终不会被处理。", @@ -230,20 +201,20 @@ export function OverviewPage({

@@ -253,173 +224,192 @@ export function OverviewPage({
- +
+ {t("This machine", "本机配置")} + } + label={t("System", "操作系统")} + value={specs.os} + t={t} + /> + } + label={t("Motherboard", "主板")} + value={specs.board} + t={t} + /> + } + label={t("Processor", "处理器")} + value={specs.cpu} + t={t} + /> + } + label={t("Memory", "内存")} + value={specs.memory} + t={t} + /> + } + label={t("Primary disk", "主硬盘")} + value={specs.disk} + t={t} + /> + } + label={t("Graphics", "显卡")} + value={specs.gpu} + t={t} + /> +
- {cleanup.scanning ? ( + {scanning ? ( void cleanup.cancel()} + onCancel={() => void (cleanup.scanning ? cleanup.cancel() : purge.cancel())} /> ) : null} + {scanned && !scanning ? ( +
+ onNavigate("space")}> + {t("Open space cleaning", "打开空间清理")} + + + } + /> + {cleanup.result ? ( + onNavigate("space")} + /> + ) : null} +
+ ) : null} + + {/* 指标行 30% / 42% / 28%:处理器+内存共用一框上下分布;存储每盘 + 一行;日常维护三入口竖排放右列,与左两卡等高。独立的「日常维护」 + 区块随此改版取消。 */}
-
-
- - - -
- {t("Processor", "处理器")} - {coreLabel(snapshot, t)} -
- {Math.round(snapshot?.cpu.total ?? 0)}% -
- - - {snapshot?.cpu.brand || t("Processor details unavailable", "暂无处理器信息")} - -
- -
-
- - - -
- {t("Memory", "内存")} - - {snapshot - ? `${formatMemoryBytes(snapshot.memory.used)} / ${formatMemoryBytes( - memoryInstalled, - )}` - : t("Sampling…", "正在采样…")} +
+
+
+ + +
+ {t("Processor", "处理器")} + + {snapshot + ? `${snapshot.cpu.physical_cores} ${t("cores", "核")} / ${snapshot.cpu.logical_cores} ${t("threads", "线程")}` + : t("Sampling…", "正在采样…")} + +
+ {Math.round(snapshot?.cpu.total ?? 0)}%
- {Math.round(memoryPercent)}% + + + {snapshot?.cpu.brand || t("Processor details unavailable", "暂无处理器信息")} +
- - - {memoryReserved > 0 - ? t( - `Hardware reserved (integrated graphics): ${formatMemoryBytes(memoryReserved)}`, - `硬件保留(含核显):${formatMemoryBytes(memoryReserved)}`, - ) - : snapshot?.memory.compressed !== null && - snapshot?.memory.compressed !== undefined - ? t( - `Compressed ${formatMemoryBytes(snapshot.memory.compressed)} · Wired ${formatMemoryBytes( - snapshot.memory.wired ?? 0, - )}`, - `压缩 ${formatMemoryBytes(snapshot.memory.compressed)} · 固定 ${formatMemoryBytes( - snapshot.memory.wired ?? 0, - )}`, - ) - : snapshot +
+
+ + + +
+ {t("Memory", "内存")} + + {snapshot + ? `${formatMemory(snapshot.memory.used)} / ${formatMemory(memoryInstalled)}` + : t("Sampling…", "正在采样…")} + +
+ + {Math.round( + snapshot ? percent(snapshot.memory.used, snapshot.memory.total) : 0, + )} + % + +
+ + + {memoryReserved > 0 ? t( - `${formatCount(snapshot.processes)} processes running`, - `${formatCount(snapshot.processes)} 个进程正在运行`, + `Hardware reserved (integrated graphics): ${formatMemory(memoryReserved)}`, + `硬件保留(含核显):${formatMemory(memoryReserved)}`, ) - : t("Reading activity", "正在读取活动")} - -
- -
+ : snapshot + ? t( + `${formatCount(snapshot.processes)} processes running`, + `${formatCount(snapshot.processes)} 个进程正在运行`, + ) + : t("Reading activity", "正在读取活动")} + +
+ +
- +
{t("Storage", "存储空间")} - {snapshot + {volumes.length > 0 ? t( - `${formatCount(snapshot.volumes.length)} partitions`, - `${formatCount(snapshot.volumes.length)} 个分区`, + `${volumes.length} drives`, + `${volumes.length} 个分区`, ) - : t("Reading volume…", "正在读取磁盘…")} + : t("Reading volumes…", "正在读取磁盘…")}
- {Math.round(usedPercent)}%
- {visibleVolumes.length > 0 ? ( -
- {visibleVolumes.map((candidate) => { - const candidateUsed = candidate.total - candidate.free; - const candidatePercent = percent(candidateUsed, candidate.total); - return ( -
-
- - {candidate.name || candidate.mount_point} - {candidate.is_root ? ` · ${t("System", "系统")}` : ""} - - - {t( - `Total ${formatBytes(candidate.total)} · ${formatBytes(candidate.free)} free`, - `总 ${formatBytes(candidate.total)} · 可用 ${formatBytes(candidate.free)}`, - )} - -
+
+ {volumes.slice(0, 4).map((volume) => { + const usedPercent = percent(volume.total - volume.free, volume.total); + return ( +
+ + {driveLabel(volume)} + + 88 ? "danger" : "success"} + used={usedPercent} + total={100} + tone={usedPercent > 85 ? "red" : "green"} /> -
- ); - })} -
- ) : ( - - )} - - - - {cleanup.result && !cleanup.scanning ? ( -
- onNavigate("cleanup")}> - {t("Open cleanup", "打开清理")} - - - } - /> - onNavigate("cleanup")} - /> -
- ) : null} - -
- -
-
+ ); + })} +
+
+
+ - - diff --git a/src/pages/PermissionsPage.tsx b/src/pages/PermissionsPage.tsx index 2f6223a..6dcc53b 100644 --- a/src/pages/PermissionsPage.tsx +++ b/src/pages/PermissionsPage.tsx @@ -1,11 +1,24 @@ -import { BellRing, RefreshCw, Search, ShieldCheck, Trash2, X } from "lucide-react"; +import { + AlertTriangle, + BellRing, + ChevronRight, + FolderOpen, + LayoutGrid, + RefreshCw, + Search, + ShieldCheck, + Trash2, + X, +} from "lucide-react"; import { useMemo, useState } from "react"; import { useI18n } from "../i18n"; +import { api } from "../lib/api"; import { shortPath } from "../lib/format"; import type { PermissionsWorkspace } from "../hooks/usePermissionsWorkspace"; -import type { ManagedStartupItem } from "../types"; +import type { StartupItem } from "../types"; import { Button, + ConfirmDialog, EmptyState, IconButton, InlineError, @@ -18,11 +31,37 @@ function scopeLabel(scope: string, t: (en: string, zh: string) => string): strin return scope === "machine" ? t("All users", "所有用户") : t("Current user", "当前用户"); } -// The icon shared by a software group: the first entry that carries one. -function softwareIcon(items: ManagedStartupItem[]): string { - return items.find((item) => item.icon)?.icon ?? ""; +// A row whose program binary no longer exists on disk — the config survived +// an uninstall. MangoDisk calls these 残留项 and offers to delete the config. +function isLeftover(item: StartupItem): boolean { + return item.targetExists === false; } +// 残留 / 已启用 / 已禁用 row tag; leftover wins the colour fight. The +// source / trigger / signature chips used to sit on the group header — the +// user found them noise; the detailed path already rides on every row. +function statusChip( + item: StartupItem, + t: (en: string, zh: string) => string, +): [string, string] { + if (isLeftover(item)) return [t("Leftover", "残留"), "is-leftover"]; + return item.enabled + ? [t("Enabled", "已启用"), "is-on"] + : [t("Disabled", "已禁用"), "is-off"]; +} + +// 启动文件夹 rows are removable by deleting the shortcut; the folder is a +// nice human landing spot for anything else. +function rowRevealPath(item: StartupItem): string { + const anchor = item.target || item.command; + if (!anchor) return ""; + return anchor.replace(/"$/, "").replace(/^(.*\.(exe|lnk|bat|cmd))\s+/i, "$1"); +} + +// MangoDisk's status filter: a segment with live counts, 残留 included. +type StartupFilter = "all" | "enabled" | "disabled" | "leftover"; + + // 电脑管家 shows the owning software's icon on every row it can attribute to // an installed program; a grey initial covers the leftovers. function RowIcon({ icon, label }: { icon: string | null | undefined; label: string }) { @@ -35,10 +74,44 @@ function RowIcon({ icon, label }: { icon: string | null | undefined; label: stri ); } +// 其他软件 carries no real product identity, so it never rides a member's +// icon (ChatGPT's blue tile labelled 其他软件 read as a bug). A neutral +// apps-grid glyph says "a pile of things we could not attribute". +function GroupIcon({ + software, + items, + neutral, +}: { + software: string; + items: { icon: string | null }[]; + neutral: boolean; +}) { + if (neutral) { + return ( + + ); + } + const icon = items.find((item) => item.icon)?.icon; + return icon ? ( + + ) : ( + + ); +} + export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace }) { const { t } = useI18n(); const [query, setQuery] = useState(""); + const [openGroups, setOpenGroups] = useState>(new Set()); + const [openExtGroups, setOpenExtGroups] = useState>(new Set()); const [extCat, setExtCat] = useState(null); + const [startupFilter, setStartupFilter] = useState("all"); + const [showSystem, setShowSystem] = useState(false); + const [removingIds, setRemovingIds] = useState(null); const view = workspace.view; const tabs = useMemo( @@ -48,19 +121,28 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace id: "startup" as const, label: t("Startup items", "开机启动项"), count: view?.startupCount ?? 0, + fresh: false, }, { id: "extensions" as const, label: t("Context menus", "右键菜单"), count: view?.extensions.length ?? 0, + fresh: false, + }, + { + id: "advanced" as const, + label: t("Advanced startup", "进阶启动项"), + count: workspace.advanced?.entries.length ?? 0, + fresh: true, }, { id: "popup" as const, label: t("Popup blocker", "弹窗拦截"), count: view?.rules.length ?? 0, + fresh: false, }, ], - [t, view], + [t, view, workspace.advanced], ); if (!view && workspace.scanning) { @@ -103,20 +185,69 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace } const needle = query.trim().toLowerCase(); - const startup = view.startup.filter( + const startupSearch = view.startup.filter( (item) => !needle || item.name.toLowerCase().includes(needle) || item.displayName.toLowerCase().includes(needle) || item.command.toLowerCase().includes(needle), ); - // 电脑管家 style: one group per software, Chinese name in the header. + // MangoDisk's 显示系统项: Microsoft-signed / %SystemRoot% rows fold into a + // hideable 系统组件 group instead of mixing into the software list. + const systemName = t("System components", "系统组件"); + const startupVisible = showSystem + ? startupSearch + : startupSearch.filter((item) => !item.systemItem); + const leftoverCount = startupVisible.filter(isLeftover).length; + const enabledCount = startupVisible.filter((item) => item.enabled && !isLeftover(item)).length; + const disabledCount = startupVisible.length - enabledCount - leftoverCount; + const counts: Record = { + all: startupVisible.length, + enabled: enabledCount, + disabled: disabledCount, + leftover: leftoverCount, + }; + const startup = startupVisible.filter((item) => + startupFilter === "all" + ? true + : startupFilter === "leftover" + ? isLeftover(item) + : startupFilter === "enabled" + ? item.enabled && !isLeftover(item) + : !item.enabled && !isLeftover(item), + ); + // 电脑管家 style: one group per software (Chinese name in the header); + // every entry the backend could not attribute to a real product lands in + // a catch-all 其他软件 group; system rows sink to their own group last. + const otherName = t("Other software", "其他软件"); const startupGroups = new Map(); for (const item of startup) { - const list = startupGroups.get(item.displayName) ?? []; + const key = item.systemItem + ? systemName + : item.named && item.displayName + ? item.displayName + : otherName; + const list = startupGroups.get(key) ?? []; list.push(item); - startupGroups.set(item.displayName, list); + startupGroups.set(key, list); } + const orderedGroups = [...startupGroups.entries()].sort( + ([a], [b]) => + Number(a === otherName) - Number(b === otherName) || + Number(a === systemName) - Number(b === systemName), + ); + // Groups start folded (管家 habit): the header carries a master switch + // and the status line; expanding shows the per-entry detail. Searching + // force-expands everything so matches are never hidden. + const searching = query.trim().length > 0; + const isGroupOpen = (name: string) => searching || openGroups.has(name); + const toggleGroupOpen = (name: string) => + setOpenGroups((current) => { + const next = new Set(current); + if (next.has(name)) next.delete(name); + else next.add(name); + return next; + }); const groupedExtensions = view.extensions .filter( (entry) => @@ -136,6 +267,29 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace const extCategories = Object.keys(groupedExtensions); const activeCategory = extCat && extCategories.includes(extCat) ? extCat : extCategories[0] ?? null; + // Same software-grouping rule as the startup list: rows whose module + // carries real product strings group under that product (微信's shell + // extensions across several surfaces become one card); the rest sink to + // 其他软件. Groups open folded, searching force-expands. + const extGrouped = new Map(); + for (const entry of activeCategory ? groupedExtensions[activeCategory] : []) { + const named = entry.named && entry.friendlyName; + const key = named ? entry.friendlyName! : otherName; + const list = extGrouped.get(key) ?? []; + list.push(entry); + extGrouped.set(key, list); + } + const extGroups = [...extGrouped.entries()].sort( + ([a], [b]) => Number(a === otherName) - Number(b === otherName), + ); + const isExtGroupOpen = (name: string) => searching || openExtGroups.has(name); + const toggleExtGroupOpen = (name: string) => + setOpenExtGroups((current) => { + const next = new Set(current); + if (next.has(name)) next.delete(name); + else next.add(name); + return next; + }); return (
@@ -182,65 +336,225 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace `共 ${view.startupCount} 项,其中 ${view.startupEnabledCount} 项已开启。`, )} /> - - {Array.from(startupGroups.entries()).map(([software, items]) => ( -
-

- {items.find((item) => item.icon)?.icon ? ( - - ) : ( - - )} - {software} - - {t( - `${items.filter((item) => item.enabled).length}/${items.length} on`, - `${items.filter((item) => item.enabled).length}/${items.length} 开启`, - )} - -

-
- {items.map((item) => ( -
-
- -
- {item.name} - - {item.sourceLabel} · {scopeLabel(item.scope, t)} - {item.command ? ` · ${shortPath(item.command, 72)}` : ""} - -
-
- void workspace.toggleStartup(item.id, next)} - label={`${item.name} ${item.enabled ? "disable" : "enable"}`} - /> -
- ))} -
+
+
+ {( + [ + ["all", "All", "全部"], + ["enabled", "Enabled", "已启用"], + ["disabled", "Disabled", "已禁用"], + ["leftover", "Leftover", "残留"], + ] as const + ).map(([id, en, zh]) => ( + + ))}
- ))} +
+ + +
+
+ {orderedGroups.map(([software, items]) => { + const onCount = items.filter((item) => item.enabled && !isLeftover(item)).length; + const allOn = onCount === items.length; + const open = isGroupOpen(software); + const groupIds = items.map((item) => item.id); + const leftovers = items.filter(isLeftover); + return ( +
0 && leftovers.length === items.length ? "is-leftover" : "" + }`} + > +

toggleGroupOpen(software)}> + + {software} + {leftovers.length > 0 ? ( + + {t(`${leftovers.length} leftover`, `${leftovers.length} 个残留`)} + + ) : null} + + {allOn + ? t("All on", "全部开启") + : onCount === 0 + ? t("All off", "已全部关闭") + : t( + `${onCount}/${items.length} on`, + `部分开启 ${onCount}/${items.length}`, + )} + + event.stopPropagation()} + > + { + event.stopPropagation(); + toggleGroupOpen(software); + }} + > + {items.length > 1 + ? t(`${items.length} items`, `共${items.length}项`) + : t("1 item", "共1项")} + + + void workspace.toggleStartupGroup(groupIds, next)} + label={`${software} master ${allOn ? "disable" : "enable"}`} + /> + +

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

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

+

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

) : null} ) : null} + } + title={t("Delete startup entries?", "删除启动项?")} + message={t( + `Squid removes only the autostart registration (${removingIds?.length ?? 0} item(s)); no program files are touched.`, + `Squid 只删除启动配置(共 ${removingIds?.length ?? 0} 项),不会动任何程序文件。`, + )} + note={t( + "Registry values are deleted; Startup-folder shortcuts are removed; tasks are unscheduled; leftover services are set to disabled.", + "注册表值将被删除;启动文件夹的快捷方式会被移除;计划任务会被注销;残留服务会改为禁用。", + )} + confirmLabel={t("Delete", "删除")} + cancelLabel={t("Cancel", "取消")} + busy={workspace.busyId !== null} + onClose={() => setRemovingIds(null)} + onConfirm={async () => { + if (!removingIds) return; + await workspace.removeStartup(removingIds); + setRemovingIds(null); + }} + /> + {workspace.tab === "extensions" ? (
-
- {(activeCategory ? groupedExtensions[activeCategory] : []).map((entry) => ( -
-
- -
- {entry.friendlyName ?? entry.name} - - {entry.publisher - ? `${t("Creator", "创建者")} ${entry.publisher} · ` - : ""} - {scopeLabel(entry.scope, t)} - {entry.module ? ` · ${shortPath(entry.module, 56)}` : ""} - {!entry.registered ? ` · ${t("removed", "已移除")}` : ""} - + {extGroups.map(([software, items]) => { + const onCount = items.filter((entry) => entry.registered).length; + const allOn = onCount === items.length; + const open = isExtGroupOpen(software); + return ( +
+

toggleExtGroupOpen(software)}> + + {software} + + {allOn + ? t("All on", "全部开启") + : onCount === 0 + ? t("All off", "已全部关闭") + : t( + `${onCount}/${items.length} on`, + `部分开启 ${onCount}/${items.length}`, + )} + + event.stopPropagation()} + > + { + event.stopPropagation(); + toggleExtGroupOpen(software); + }} + > + {items.length > 1 + ? t( + `${items.length} places`, + `共${items.length}个菜单位置`, + ) + : t("1 place", "1个菜单位置")} + + + { + for (const entry of items) { + if (entry.registered !== next) { + await workspace.toggleExtension(entry.id, next); + } + } + }} + label={`${software} master ${allOn ? "disable" : "enable"}`} + /> + +

+ {open ? ( +
+ {items.map((entry) => ( +
+
+
+ {entry.friendlyName ?? entry.name} + + {entry.publisher + ? `${t("Creator", "创建者")} ${entry.publisher} · ` + : ""} + {scopeLabel(entry.scope, t)} + {entry.module ? ` · ${shortPath(entry.module, 56)}` : ""} + {!entry.registered ? ` · ${t("removed", "已移除")}` : ""} + +
+
+ void workspace.toggleExtension(entry.id, next)} + label={`${entry.name} ${entry.registered ? "remove" : "restore"}`} + /> +
+ ))}
-
- void workspace.toggleExtension(entry.id, next)} - label={`${entry.name} ${entry.registered ? "remove" : "restore"}`} - /> + ) : null}
- ))} -
+ ); + })} {extCategories.length === 0 ? (

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

) : null} ) : null} + {workspace.tab === "advanced" ? ( +
+
+ {t( + "Advanced rows can break boot or logon if changed carelessly — Squid only displays them here, every change records its original value, and nothing is auto-disabled.", + "进阶区的项目改错了可能影响系统行为——默认只展示不勾选,每一项带数字签名与位置说明;改动会原样记录,可逐项恢复。", + )} +
+ {workspace.advancedScanning && !workspace.advanced ? ( +
+ + + {t( + "Reading Winlogon / IFEO / BHO and verifying signatures…", + "正在读取 Winlogon / IFEO / BHO 并核验数字签名…", + )} + +
+ ) : null} + {workspace.advanced && workspace.advanced.entries.length === 0 ? ( +

+ {t( + "No third-party Winlogon hooks, AppInit DLLs, IFEO debuggers or BHOs found — the machine is clean.", + "没有发现第三方 Winlogon 挂钩、AppInit DLL、IFEO 调试器或 BHO——系统很干净。", + )} +

+ ) : null} + {workspace.advanced + ? (["winlogon", "appinit", "ifeo", "bho"] as const).map((kind) => { + const rows = workspace.advanced!.entries.filter((entry) => entry.kind === kind); + if (rows.length === 0) return null; + const titles: Record = { + winlogon: ["Winlogon hooks", "Winlogon 与登录链"], + appinit: ["AppInit DLL injection", "AppInit_DLLs 全局注入"], + ifeo: ["IFEO debuggers (can hijack any program)", "IFEO 调试器(可劫持任意程序启动)"], + bho: ["Browser helper objects", "浏览器加载项 BHO"], + }; + return ( +
+ + {rows.map((entry) => ( +
+ + {entry.signature === "microsoft" + ? t("Microsoft signed", "微软签名") + : entry.signature === "vendor" + ? t("Signed by", "已知厂商") + : entry.signature === "unsigned" + ? t("Not signed", "无数字签名") + : entry.signature === "invalid" + ? t("Signature invalid", "签名无效") + : t("Signature n/a", "无签名信息")} + +
+ {entry.name} + {shortPath(entry.command, 90)} + {entry.location} + {entry.warning ? ( + {entry.warning} + ) : null} +
+ void workspace.toggleAdvanced(entry.id, next)} + label={entry.name} + /> +
+ ))} +
+ ); + }) + : null} + {workspace.advanced && workspace.advanced.extras.length > 0 ? ( +
+ + {workspace.advanced.extras.map((entry) => ( +
+ {scopeLabel(entry.scope, t)} +
+ {entry.displayName || entry.name} + {shortPath(entry.command, 90)} + {entry.sourceLabel} +
+ void workspace.toggleStartup(entry.id, next)} + label={entry.name} + /> +
+ ))} +
+ ) : null} +
+ ) : null} + {workspace.tab === "popup" ? ( <>
diff --git a/src/pages/PrivacyPage.tsx b/src/pages/PrivacyPage.tsx new file mode 100644 index 0000000..79044d1 --- /dev/null +++ b/src/pages/PrivacyPage.tsx @@ -0,0 +1,227 @@ +import { ClipboardList, EyeOff, FileClock, History, Lock, ShieldQuestion } from "lucide-react"; +import { useCallback, useEffect, useState } from "react"; +import { api } from "../lib/api"; +import { useI18n } from "../i18n"; +import { formatBytes, formatCount, messageFrom } from "../lib/format"; +import { + Button, + Checkbox, + EmptyState, + InlineError, + PageHeader, + useToast, +} from "../components/ui"; +import type { CleanupItem } from "../types"; + +function jobId(): string { + return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`; +} + +const SPEC_ICONS: Record = { + "privacy-edge": History, + "privacy-chrome": History, + "privacy-recent": FileClock, + "privacy-clipboard": ClipboardList, + "privacy-activity": EyeOff, +}; + +const WARN_COPY: Record = { + "privacy-edge": ["影响「恢复上次会话」", "affects session restore"], + "privacy-chrome": ["影响「恢复上次会话」", "affects session restore"], + "privacy-clipboard": ["Win+V 历史会被清空", "clears the Win+V list"], + "privacy-activity": ["影响「恢复上次会话」", "affects session restore"], +}; + +interface SpecGroup { + ruleId: string; + label: string; + detail: string | null; + indexes: number[]; + bytes: number; + locked: string | null; +} + +export function PrivacyPage({ + embedded = false, + onBadge, +}: { + /** Rendered inside 系统维护 hub: page title hides, trace count flows up. */ + embedded?: boolean; + onBadge?: (value: string | null) => void; +} = {}) { + const { t, lang } = useI18n(); + const { push } = useToast(); + const [items, setItems] = useState([]); + const [scanId, setScanId] = useState(null); + const [picked, setPicked] = useState>(new Set()); + const [scanning, setScanning] = useState(false); + const [cleaning, setCleaning] = useState(false); + const [error, setError] = useState(null); + const [loaded, setLoaded] = useState(false); + + const scan = useCallback(async () => { + setScanning(true); + setError(null); + const id = jobId(); + try { + const view = await api.privacyScan(id); + setItems(view.items); + setScanId(view.scanId); + setPicked(new Set()); + } catch (reason) { + setError(messageFrom(reason)); + } finally { + setScanning(false); + setLoaded(true); + } + }, []); + + useEffect(() => { + void scan(); + }, [scan]); + + const groups: SpecGroup[] = []; + items.forEach((item, index) => { + const last = groups[groups.length - 1]; + if (last && last.ruleId === item.ruleId) { + last.indexes.push(index); + last.bytes += item.onDisk; + if (item.lock && !last.locked) { + last.locked = item.note ?? item.lock; + } + } else { + groups.push({ + ruleId: item.ruleId, + label: item.label, + detail: item.note, + indexes: [index], + bytes: item.onDisk, + locked: item.lock ? item.note ?? item.lock : null, + }); + } + }); + + const toggleGroup = (group: SpecGroup) => { + if (group.locked) return; + setPicked((current) => { + const next = new Set(current); + const allOn = group.indexes.every((index) => next.has(index)); + for (const index of group.indexes) { + if (allOn) next.delete(index); + else next.add(index); + } + return next; + }); + }; + + const pickedBytes = [...picked].reduce((sum, index) => sum + (items[index]?.onDisk ?? 0), 0); + + // Hub badge: trace groups found by the auto-scan, or null when clean. + useEffect(() => { + if (!embedded || !onBadge) return; + onBadge(groups.length > 0 ? `${groups.length} 类痕迹` : null); + }, [embedded, groups.length, onBadge]); + + const clean = async () => { + if (!scanId || picked.size === 0) return; + setCleaning(true); + try { + const outcome = await api.privacyDelete(jobId(), scanId, [...picked]); + push( + lang === "zh" + ? `已清除 ${outcome.removed} 项隐私痕迹(${formatBytes(outcome.freed)});这些删除不进回收站,明细见历史记录` + : `Cleared ${outcome.removed} traces (${formatBytes(outcome.freed)}); these deletions skip the Recycle Bin — see History`, + "success", + ); + await scan(); + } catch (reason) { + push(messageFrom(reason), "danger"); + } finally { + setCleaning(false); + } + }; + + return ( +
+ {embedded ? null : ( + + )} + {error ? setError(null)} /> : null} + +
+ {groups.map((group) => { + const Icon = SPEC_ICONS[group.ruleId] ?? ShieldQuestion; + const allOn = group.indexes.every((index) => picked.has(index)); + const warn = WARN_COPY[group.ruleId]; + return ( + + ); + })} + {loaded && groups.length === 0 && !scanning ? ( + } + title={t("Nothing to clean", "没有可清理的痕迹")} + description={t( + "No browser profiles or trace stores were found on this machine.", + "本机没有找到浏览器 profile 或痕迹存储。", + )} + /> + ) : null} +
+ +
+ + {picked.size > 0 + ? t( + `${formatCount(picked.size)} traces selected · ${formatBytes(pickedBytes)} · permanent`, + `已选 ${formatCount(picked.size)} 项 · ${formatBytes(pickedBytes)} · 永久删除`, + ) + : t( + "These deletions skip the Recycle Bin on purpose; History still lists every path.", + "这些删除有意绕过回收站;历史记录仍会逐条登记路径与大小。", + )} + + + +
+
+ ); +} diff --git a/src/pages/PurgePage.tsx b/src/pages/PurgePage.tsx deleted file mode 100644 index bdbb732..0000000 --- a/src/pages/PurgePage.tsx +++ /dev/null @@ -1,139 +0,0 @@ -import { - AlertTriangle, - FolderSearch, - GitBranch, - ScanSearch, - ShieldAlert, -} from "lucide-react"; -import { useState } from "react"; -import { useI18n } from "../i18n"; -import type { Bootstrap, DeleteMode } from "../types"; -import type { ScanWorkspace } from "../hooks/useScanWorkspace"; -import { CleanupInventory } from "../components/CleanupView"; -import { Button, PageHeader, Toggle } from "../components/ui"; - -export function PurgePage({ - workspace, - bootstrap, - deleteMode, - onHistory, -}: { - workspace: ScanWorkspace; - bootstrap: Bootstrap; - deleteMode: DeleteMode; - onHistory: () => void; -}) { - const { t } = useI18n(); - const [roots, setRoots] = useState(bootstrap.settings.purgeRoots.join("\n")); - const [minAge, setMinAge] = useState(bootstrap.settings.purgeMinAgeDays); - const [force, setForce] = useState(false); - - const run = () => - void workspace.runScan({ - roots: roots - .split(/\r?\n/) - .map((root) => root.trim()) - .filter(Boolean), - minAgeDays: minAge > 0 ? minAge : null, - force, - }); - - return ( -
- } onClick={run}> - {t("Start deep scan", "开始深度扫描")} - - } - /> - -
-
- -