Windows shell replacement in Rust: taskbar, file manager, NTFS search, task manager, disk cleaner. One installer exe.
Rust
README: copy and ZIP benchmark, current binary sizes; rust-explorer bench test
Lemxy2c741fdc8262
diff --git a/Cargo.lock b/Cargo.lockindex c25c41e..7b17640 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2,6 +2,12 @@# It is not intended for manual editing.version = 4+[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"+[[package]]name = "bitflags"version = "1.3.2"@@ -14,6 +20,21 @@ version = "2.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"+[[package]]+name = "bumpalo"+version = "3.20.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"++[[package]]+name = "bzip2"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"+dependencies = [+ "libbz2-rs-sys",+]+[[package]]name = "cc"version = "1.11.2"@@ -30,6 +51,30 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"+[[package]]+name = "cfg_aliases"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"++[[package]]+name = "constant_time_eq"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9"+dependencies = [+ "rustversion",+]++[[package]]+name = "crc32fast"+version = "1.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"+dependencies = [+ "cfg-if",+]+[[package]]name = "debloat"version = "0.1.0"@@ -64,6 +109,54 @@ version = "0.1.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"+[[package]]+name = "flate2"+version = "1.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"+dependencies = [+ "crc32fast",+ "miniz_oxide",+ "zlib-rs",+]++[[package]]+name = "futures-core"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"++[[package]]+name = "futures-task"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"++[[package]]+name = "futures-util"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"+dependencies = [+ "futures-core",+ "futures-task",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "r-efi",+ "wasm-bindgen",+]+[[package]]name = "hashbrown"version = "0.17.1"@@ -80,24 +173,63 @@ dependencies = ["hashbrown",]+[[package]]+name = "js-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]+[[package]]name = "lazy_static"version = "1.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"+[[package]]+name = "libbz2-rs-sys"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5314d1d545fce0307c770d791adf20d997e0b63b64e1ffeed8a920e290eabe4"+[[package]]name = "libc"version = "0.2.191"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"+[[package]]+name = "log"+version = "0.4.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"++[[package]]+name = "lzma-rust2"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef1d73c59a56771343712b22ea5615092c612c16ba291c0979e3105dfeec4890"+[[package]]name = "memchr"version = "2.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"+[[package]]+name = "miniz_oxide"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"+dependencies = [+ "adler2",+ "simd-adler32",+]+[[package]]name = "muldiv"version = "0.2.1"@@ -117,6 +249,18 @@ dependencies = ["winapi-build",]+[[package]]+name = "nix"+version = "0.32.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc"+dependencies = [+ "bitflags 2.13.2",+ "cfg-if",+ "cfg_aliases",+ "libc",+]+[[package]]name = "ntapi"version = "0.4.3"@@ -155,6 +299,12 @@ dependencies = ["winrust-common",]+[[package]]+name = "pin-project-lite"+version = "0.2.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"+[[package]]name = "plugin-launcher"version = "0.5.0"@@ -164,6 +314,12 @@ dependencies = ["winrust-common",]+[[package]]+name = "ppmd-rust"+version = "1.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd4acc8d264ea385db64ccfdcdfd5909ee9eda0975666723d59f3bfec80b3611"+[[package]]name = "proc-macro2"version = "1.0.107"@@ -189,6 +345,12 @@ dependencies = ["proc-macro2",]+[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"+[[package]]name = "reshell"version = "0.1.0"@@ -233,10 +395,12 @@ name = "rust-explorer"version = "0.1.0"dependencies = ["embed-resource",+ "sevenz-rust2","windows","windows-core","windows-sys","winrust-common",+ "zip",][[package]]@@ -259,6 +423,12 @@ dependencies = ["semver",]+[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"+[[package]]name = "semver"version = "1.0.28"@@ -294,12 +464,39 @@ dependencies = ["serde_core",]+[[package]]+name = "sevenz-rust2"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5e465701779cbc6d0d10cf907f175035cfdd50b8d3cb628d7f1f435ef02972f"+dependencies = [+ "bzip2",+ "crc32fast",+ "flate2",+ "js-sys",+ "lzma-rust2",+ "ppmd-rust",+ "wasm-bindgen",+]+[[package]]name = "shlex"version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"+[[package]]+name = "simd-adler32"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"+[[package]]name = "syn"version = "2.0.119"@@ -385,6 +582,12 @@ dependencies = ["winrust-common",]+[[package]]+name = "typed-path"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e"+[[package]]name = "unicode-ident"version = "1.0.27"@@ -411,6 +614,50 @@ dependencies = ["libc",]+[[package]]+name = "wasm-bindgen"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"+dependencies = [+ "cfg-if",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 3.0.10",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"+dependencies = [+ "unicode-ident",+]+[[package]]name = "winapi"version = "0.3.9"@@ -589,3 +836,61 @@ dependencies = ["windows-sys","winrust-common",]++[[package]]+name = "zeroize"+version = "1.9.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"+dependencies = [+ "zeroize_derive",+]++[[package]]+name = "zeroize_derive"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "zip"+version = "9.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9534624d547e3f516ecde0ed9a70d37788f01d340efcfdd03bf3ea8e163c1d0"+dependencies = [+ "constant_time_eq",+ "crc32fast",+ "flate2",+ "getrandom",+ "indexmap",+ "libc",+ "memchr",+ "nix",+ "typed-path",+ "windows-sys",+ "zeroize",+ "zopfli",+]++[[package]]+name = "zlib-rs"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"++[[package]]+name = "zopfli"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"+dependencies = [+ "bumpalo",+ "crc32fast",+ "log",+ "simd-adler32",+]diff --git a/README.md b/README.mdindex 2a8be4b..18116ff 100644--- a/README.md+++ b/README.md@@ -35,9 +35,9 @@ The installer is in English. The **Русский** button in its corner (or "Wi| Plugin | What you get | What it changes in Windows ||---|---|---|| **rust-search** | File search over all NTFS drives, Alt+Space | Disables the Windows Search service, blocks SearchHost.exe, hides the taskbar search box |-| **rtaskmgr-win32** | Task Manager (Ctrl+Shift+Esc opens it) | `taskmgr.exe` is redirected to it (the system file is untouched). Also installs the **rs-du** disk cleaner |+| **rtaskmgr-win32** | Task Manager (Ctrl+Shift+Esc opens it) | `taskmgr.exe` is redirected to it (the system file is untouched). Also installs the **rs-du** disk cleaner. The **Speed** page has opt-in, reversible switches: Game / Work profiles (stop background services, close launchers or sync apps, start them again), clear the memory standby cache (now, or automatically while topbar runs), block the Windows Start menu, widgets and Phone Link processes, one weekly `winget upgrade` instead of third-party updaters, Defender exclusions for build caches and game libraries, faster NTFS (no last-access times, no 8.3 names), an ad-blocking hosts file. **Startup** also lists logon/boot tasks and third-party auto-start services, with how much each slowed the last boots (Windows' own boot log). **What's slow** shows driver time (DPC/interrupts), hung windows, slow disk and boot times. Uninstall turns all of it back || **topbar** | A Windows 11-style bottom bar: windows, clock, volume, menus | Hides the stock taskbar. Also installs **reshell** (hotkeys: Win+1/2/3 and Win+\` switch desktops, Win+D shows the desktop, Win+I opens Settings, Win+E the file manager; brings the taskbar back if the bar dies), **rs-du**, and a block in your PowerShell profile (`zoxide`, `grep`=rg, `ll`=eza, `cat`=bat; does nothing if they are missing) |-| **rust-explorer** | A file manager with tabs, and the desktop | Folders and drives open in it; **Explorer stops being the shell** (comes back by itself if topbar fails). Disables PcaSvc, InventorySvc, lfsvc, cbdhsvc, sets DoSvc to manual, merges svchost processes. Requires topbar |+| **rust-explorer** | A file manager with tabs, and the desktop | Folders and drives open in it; **Explorer stops being the shell** (comes back by itself if topbar fails). Disables PcaSvc, InventorySvc, lfsvc, cbdhsvc, sets DoSvc to manual, merges svchost processes. Its own copier (several files at once on SSDs, unbuffered for big files, progress in the status line) and right-click **Compress to ZIP** (all cores) / **Extract here** (ZIP and 7z). Requires topbar || **wiztree** | A disk-usage map ("WinRust Disk" in Start) | Nothing, apart from the file and a shortcut || **photoview** | A fast photo viewer | Adds it to "Open with" (it does not become the default) || **rust-settings** | Settings in Rust: display (resolution, refresh rate), sound (volume), power plan and drive space, per-app volume and device choice, night light, display arrangement by dragging, network adapters, Wi-Fi on every adapter (password or 802.1X), VPN and proxy, Bluetooth, apps, Windows Update, disk cleanup, theme, about | Nothing, apart from the file and a shortcut. Win+I and the bar menus open this window instead of Windows Settings (only a few rare pages still open the system ones) |@@ -72,11 +72,14 @@ One-off measurements on one machine (Windows 11 IoT Enterprise 10.0.26300, RTX 4| Open a folder window (rust-explorer, median of 5 runs) | 420 ms | 60 ms | **86%** faster || Shell memory (topbar + rust-explorer + rs-shell + reshell vs explorer.exe) | 366 MB | 46 MB | **87%** less || Same, plus the search index (53 MB) | 366 MB | 99 MB | **73%** less |-| File manager binary size | 3,280 KB | 498 KB | **85%** smaller |-| Task manager binary size | 5,791 KB | 869 KB | **85%** smaller |+| File manager binary size (now with ZIP and 7z inside) | 3,280 KB | 1,179 KB | **64%** smaller |+| Task manager binary size | 5,791 KB | 954 KB | **84%** smaller || Idle CPU of the bar (topbar after optimization, % of one core) | 0.00–0.10% (explorer) | 0.05–0.10% | on par with Explorer |+| Copy 5,000 small files, ~160 MB (rust-explorer: IFileOperation, Explorer's engine, vs its own copier) | 16.3 s | 2.3 s | **86%** faster (7x) |+| Copy one 1 GB file (same) | 0.58 s | 0.60 s | equal |+| Pack the same 5,000 files into ZIP (`Compress-Archive` vs rust-explorer's Compress to ZIP) | 48.4 s | 0.75 s | **98%** faster (64x) |-In short: **85–99% faster or smaller in every size/speed test, and equal on idle CPU.** Caveats: rs searches a ready-made MFT index (it pays 53 MB of memory for that), while `dir` and PowerShell walk the disk from scratch; explorer.exe was still running with its windows during the test, so the memory gain is slightly overstated; Windows Search and the stock Task Manager were not compared.+In short: **64–99% faster or smaller in the size/speed tests, equal on idle CPU and on copying one big file.** Caveats: rs searches a ready-made MFT index (it pays 53 MB of memory for that), while `dir` and PowerShell walk the disk from scratch; explorer.exe was still running with its windows during the test, so the memory gain is slightly overstated; Windows Search and the stock Task Manager were not compared. The copy and ZIP runs (`cargo test -p rust-explorer --release bench -- --ignored`) were single runs on data that was just written, so both sides read from the memory cache; our ZIP was slightly bigger (0.9 MB vs 0.7 MB) because each file is compressed on its own core.## Screenshotsdiff --git a/README.ru.md b/README.ru.mdindex 7012eb5..dbd4ccd 100644--- a/README.ru.md+++ b/README.ru.md@@ -35,9 +35,9 @@| Плагин | Что вы получаете | Что меняется в Windows ||---|---|---|| **rust-search** | Поиск файлов по всем NTFS-дискам, Alt+Space | Отключается служба поиска Windows, блокируется SearchHost.exe, прячется строка поиска на панели |-| **rtaskmgr-win32** | Диспетчер задач (Ctrl+Shift+Esc открывает его) | Запуск `taskmgr.exe` перенаправляется на него (системный файл не трогается). Заодно ставится чистильщик диска **rs-du** |+| **rtaskmgr-win32** | Диспетчер задач (Ctrl+Shift+Esc открывает его) | Запуск `taskmgr.exe` перенаправляется на него (системный файл не трогается). Заодно ставится чистильщик диска **rs-du**. На странице **«Ускорение»** обратимые переключатели, всё по желанию: профили «Игра» и «Работа» (останавливают фоновые службы, закрывают лаунчеры или синхронизацию и потом запускают обратно), очистка кэша памяти standby (сейчас или автоматически, пока работает topbar), блок процессов меню «Пуск» Windows, виджетов и «Связи с телефоном», один еженедельный `winget upgrade` вместо сторонних апдейтеров, исключения Defender для кэшей сборки и библиотек игр, быстрее NTFS (без времени последнего доступа и имён 8.3), блокировка рекламы через hosts. **«Автозагрузка»** показывает ещё задачи при входе и загрузке и сторонние службы с автозапуском и то, насколько каждая замедлила последние загрузки (журнал самой Windows). **«Что тормозит»** показывает время драйверов (DPC и прерывания), зависшие окна, медленный диск и время загрузки. Удаление всё возвращает || **topbar** | Нижняя панель в стиле Windows 11: окна, часы, громкость, меню | Стандартная панель задач прячется. Заодно ставятся **reshell** (хоткеи: Win+1/2/3 и Win+\` переключают рабочие столы, Win+D показывает рабочий стол, Win+I открывает Параметры, Win+E файловый менеджер; возвращает панель задач, если topbar упал), **rs-du** и блок в профиле PowerShell (`zoxide`, `grep`=rg, `ll`=eza, `cat`=bat; молчит, если их нет) |-| **rust-explorer** | Файловый менеджер с вкладками и рабочий стол | Папки и диски открываются в нём; **Проводник перестаёт быть оболочкой** (возвращается сам, если topbar не работает). Отключаются PcaSvc, InventorySvc, lfsvc, cbdhsvc, DoSvc ставится вручную, процессы svchost объединяются. Нужен topbar |+| **rust-explorer** | Файловый менеджер с вкладками и рабочий стол | Папки и диски открываются в нём; **Проводник перестаёт быть оболочкой** (возвращается сам, если topbar не работает). Отключаются PcaSvc, InventorySvc, lfsvc, cbdhsvc, DoSvc ставится вручную, процессы svchost объединяются. Своё копирование (на SSD несколько файлов сразу, большие файлы без кэша, прогресс в строке состояния) и в меню правой кнопки **«Compress to ZIP»** (на всех ядрах) и **«Extract here»** (ZIP и 7z). Нужен topbar || **wiztree** | Карта занятого места на диске («WinRust Disk» в Пуске) | Ничего, кроме файла и ярлыка || **photoview** | Быстрый просмотр фото | Добавляется в «Открыть с помощью» (по умолчанию не назначается) || **rust-settings** | Параметры на Rust: экран (разрешение, частота, ночной свет, расположение мониторов перетаскиванием), звук (устройства, громкость по приложениям), схема питания, место на дисках и очистка, сетевые адаптеры, Wi-Fi на всех адаптерах (пароль или 802.1X), VPN и прокси, Bluetooth, приложения, Центр обновления, тема, о системе | Ничего, кроме файла и ярлыка. Win+I и меню панели открывают это окно вместо Параметров Windows (лишь несколько редких разделов по-прежнему системные) |@@ -72,11 +72,14 @@| Открыть окно с папкой (rust-explorer, медиана 5 запусков) | 420 мс | 60 мс | быстрее на **86%** || Память оболочки (topbar + rust-explorer + rs-shell + reshell против explorer.exe) | 366 МБ | 46 МБ | меньше на **87%** || То же вместе с индексом поиска (53 МБ) | 366 МБ | 99 МБ | меньше на **73%** |-| Размер файлового менеджера | 3 280 КБ | 498 КБ | меньше на **85%** |-| Размер диспетчера задач | 5 791 КБ | 869 КБ | меньше на **85%** |+| Размер файлового менеджера (теперь с ZIP и 7z внутри) | 3 280 КБ | 1 179 КБ | меньше на **64%** |+| Размер диспетчера задач | 5 791 КБ | 954 КБ | меньше на **84%** || CPU панели в простое (topbar после оптимизации, % одного ядра) | 0,00–0,10% (explorer) | 0,05–0,10% | на уровне Проводника |+| Копирование 5000 мелких файлов, ~160 МБ (rust-explorer: IFileOperation, движок Проводника, против своего копирования) | 16,3 с | 2,3 с | быстрее на **86%** (в 7 раз) |+| Копирование одного файла 1 ГБ (то же) | 0,58 с | 0,60 с | одинаково |+| Упаковка тех же 5000 файлов в ZIP (`Compress-Archive` против «Compress to ZIP» в rust-explorer) | 48,4 с | 0,75 с | быстрее на **98%** (в 64 раза) |-В сумме: **в 85–99% случаев быстрее или меньше, по CPU в простое равны.** Оговорки: rs ищет по готовому индексу MFT (за это платит 53 МБ памяти), а `dir` и PowerShell обходят диск заново; explorer.exe при замере всё ещё работал и держал окна, поэтому выигрыш по памяти немного завышен; поиск Windows и диспетчер задач не сравнивались.+В сумме: **по скорости и размеру быстрее или меньше на 64–99%, по CPU в простое и копированию одного большого файла равны.** Оговорки: rs ищет по готовому индексу MFT (за это платит 53 МБ памяти), а `dir` и PowerShell обходят диск заново; explorer.exe при замере всё ещё работал и держал окна, поэтому выигрыш по памяти немного завышен; поиск Windows и диспетчер задач не сравнивались. Копирование и ZIP (`cargo test -p rust-explorer --release bench -- --ignored`) мерились один раз на только что записанных файлах, поэтому обе стороны читали из кэша памяти; наш ZIP чуть больше (0,9 МБ против 0,7 МБ), потому что каждый файл сжимается на своём ядре отдельно.## Снимки экранаdiff --git a/ROADMAP.md b/ROADMAP.mdindex a184c89..4c2cf9e 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -45,6 +45,8 @@ emoved.txt`. `purge.exe` lists, `--ask` asks for YES (the bar's right-click menu- **v0.5.0, from the issue tracker**: the gear menu has "Hide the bar automatically" (`%ProgramData%\WinRust\autohide.txt`, off by default); Win+Shift+S is our own region clipper (a dimmed copy of the desktop, drag a rectangle, it goes to the clipboard and `Pictures\Screenshots`); the volume keys and Surface's power + volume-up work without Explorer; a keyboard button sits in the Start search; brightness goes through the video driver (`\\.\LCD`); the Wi-Fi switch goes through Windows' radio manager (the WLAN API cannot undo airplane mode); rust-explorer shows desktop shortcut names and mapped network drives, and Space opens a picture in photoview. *built, tests; brightness read and write ran on a laptop; the clipper, volume keys, Surface buttons, Wi-Fi and Bluetooth fixes not run on a live device*+- **Speed (after v0.5.0)**: rtaskmgr's new Speed page: Game / Work profiles (services stopped and apps closed are written to `%ProgramData%\WinRust\profile.txt` and started again, apps with the token of the session's `sihost.exe` so they do not inherit admin rights), clearing the memory standby list now or automatically (topbar's thread, `%ProgramData%\WinRust\autopurge.txt`), IFEO blocks for StartMenuExperienceHost / Widgets / WidgetService / PhoneExperienceHost (only with topbar), and four new debloat groups with their own undo files: `updaters` (third-party updater services and tasks off, a weekly `winget upgrade --all` task; browsers are left alone), `defender` (exclusions for cargo/rustup/npm/pip/NuGet/Gradle caches and Steam/Epic libraries, after a confirmation), `ntfs` (no last-access times, no 8.3 names), `dns` (about 170 ad domains in hosts, no Microsoft ones). debloat.exe ships next to the task manager; uninstalling the task manager runs `--undo-speed` first. Startup lists logon/boot tasks and third-party auto-start services and the slowdown each caused (events 100/101/103 of Diagnostics-Performance); What's slow shows DPC/interrupt time, hung windows, slow disk, free vs standby memory and boot times. rust-explorer: own copier for copies and moves to another drive (parallel unless a disk has a seek penalty, `COPY_FILE_NO_BUFFERING` from 256 MB, sources deleted only after every file arrived), Compress to ZIP (files up to 64 MB compressed on all cores) and Extract here for ZIP and 7z. Emptying working sets was left out on purpose: trimmed pages go to the standby list, which already counts as available, so it only adds page faults. *tests (debloat parsing, hosts round trip, boot log parsing, task XML, profile file, copy/move, ZIP and 7z round trips); dry runs of the debloat groups ran; nothing applied on a live system yet, the boot log and the memory lists need admin and were not read here*+## Next (in order)0. **Phones and safe removal in rust-explorer** (#2): not started, too big for a quick fix. (a) MTP/PTP phones have no drive letter, so they need the Windows Portable Devices API (`IPortableDeviceManager`, `IPortableDeviceContent`, enumerate objects, read and write through `IPortableDeviceResources` streams) behind a second "file system" in rust-explorer next to the path-based one; copy, paste, delete and drag and drop have to be redone on it. (b) Safe removal: a tray icon in topbar (it already hosts tray icons) that lists removable drives, and `CM_Request_Device_Eject` on the device node of the chosen drive (flush first, report "in use" with the process that holds it). (b) is the smaller half and works for USB sticks and disks; (a) is what the issue is mostly about. Needs a real phone and a USB stick to test: nothing here can be checked by unit tests alone.0. **Taskbar-style reordering in topbar** (#6, wish): dragging a file onto the bar already pins it. Missing: dragging the window buttons to change their order, and dragging a button off the bar to unpin. Needs the order stored (like `topbar-start.txt`) and a drag state in `topbar` (mouse capture, an insertion marker, a repaint per move).diff --git a/ROADMAP.ru.md b/ROADMAP.ru.mdindex 14a9c46..c54e92a 100644--- a/ROADMAP.ru.md+++ b/ROADMAP.ru.md@@ -45,6 +45,8 @@ emoved.txt`. `purge.exe` показывает список, `--ask` просит- **v0.5.0, по тикетам**: в меню шестерёнки есть «Скрывать панель автоматически» (`%ProgramData%\WinRust\autohide.txt`, по умолчанию выключено); Win+Shift+S — собственный выбор области (затемнённая копия рабочего стола, выделите прямоугольник, он попадает в буфер и в `Pictures\Screenshots`); клавиши громкости и «питание + громкость вверх» на Surface работают без Проводника; кнопка клавиатуры в поиске «Пуска»; яркость идёт через видеодрайвер (`\\.\LCD`); переключатель Wi-Fi идёт через менеджер радио Windows (WLAN API не отменяет режим «в самолёте»); rust-explorer показывает имена ярлыков рабочего стола и сетевые диски, а Пробел открывает картинку в photoview. *собрано, тесты; чтение и запись яркости проверены на ноутбуке; выбор области, клавиши громкости, кнопки Surface, правки Wi-Fi и Bluetooth на живом устройстве не запускались*+- **Ускорение (после v0.5.0)**: новая страница «Ускорение» в rtaskmgr: профили «Игра» и «Работа» (остановленные службы и закрытые программы записываются в `%ProgramData%\WinRust\profile.txt` и запускаются обратно; программы с токеном `sihost.exe` своего сеанса, чтобы не унаследовать права администратора), очистка списка standby сейчас или автоматически (поток в topbar, `%ProgramData%\WinRust\autopurge.txt`), блок через IFEO для StartMenuExperienceHost / Widgets / WidgetService / PhoneExperienceHost (только при topbar) и четыре новые группы debloat со своими файлами отката: `updaters` (службы и задачи сторонних апдейтеров отключены, задача `winget upgrade --all` раз в неделю; браузеры не трогаются), `defender` (исключения для кэшей cargo/rustup/npm/pip/NuGet/Gradle и библиотек Steam/Epic, после подтверждения), `ntfs` (без времени последнего доступа и имён 8.3), `dns` (около 170 рекламных доменов в hosts, без доменов Microsoft). debloat.exe лежит рядом с диспетчером; удаление диспетчера сначала запускает `--undo-speed`. «Автозагрузка» показывает задачи при входе и загрузке и сторонние службы с автозапуском и то, насколько каждая замедлила загрузку (события 100/101/103 журнала Diagnostics-Performance); «Что тормозит» показывает время DPC и прерываний, зависшие окна, медленный диск, свободную память против standby и время загрузки. rust-explorer: своё копирование для копий и переносов на другой диск (параллельно, если у дисков нет штрафа за поиск; `COPY_FILE_NO_BUFFERING` от 256 МБ; источник удаляется, только когда дошли все файлы), «Compress to ZIP» (файлы до 64 МБ сжимаются на всех ядрах) и «Extract here» для ZIP и 7z. Очистку рабочих наборов не сделали сознательно: вытесненные страницы уходят в standby, который и так считается доступной памятью, так что она только добавляет ошибок страниц. *тесты (разбор debloat, hosts туда и обратно, журнал загрузки, XML задач, файл профиля, копирование и перенос, ZIP и 7z туда и обратно); сухой прогон групп debloat запускался; на живой системе ничего не применялось, журнал загрузки и списки памяти требуют администратора и здесь не читались*+## Дальше (по порядку)0. **Телефоны и безопасное извлечение в rust-explorer** (#2): не начато, для быстрой правки слишком много. (а) У MTP/PTP-телефонов нет буквы диска, поэтому нужен Windows Portable Devices API (`IPortableDeviceManager`, `IPortableDeviceContent`, перечисление объектов, чтение и запись через потоки `IPortableDeviceResources`) как вторая «файловая система» в rust-explorer рядом с путевой; копирование, вставку, удаление и перетаскивание придётся переделать под неё. (б) Безопасное извлечение: значок в трее topbar (трей там уже есть), список съёмных дисков и `CM_Request_Device_Eject` для узла выбранного диска (сначала сброс буферов, при «занято» показать, какой процесс держит). Часть (б) меньше и работает для флешек и дисков; (а) это то, о чём в основном issue. Для проверки нужны настоящий телефон и флешка: одними юнит-тестами не обойтись.0. **Перестановка кнопок на панели как на панели задач** (#6, пожелание): перетаскивание файла на панель уже закрепляет его. Нет: перетаскивания кнопок окон для смены порядка и вытаскивания кнопки с панели для открепления. Нужно хранить порядок (как `topbar-start.txt`) и состояние перетаскивания в `topbar` (захват мыши, маркер вставки, перерисовка на каждое движение).diff --git a/common/Cargo.toml b/common/Cargo.tomlindex 87854ff..1b45b2d 100644--- a/common/Cargo.toml+++ b/common/Cargo.toml@@ -5,4 +5,4 @@ edition = "2024"license = "MIT OR Apache-2.0"[dependencies]-windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_UI_WindowsAndMessaging"] }+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_WindowsAndMessaging"] }diff --git a/common/src/journal.rs b/common/src/journal.rsnew file mode 100644index 0000000..d48bcac--- /dev/null+++ b/common/src/journal.rs@@ -0,0 +1,115 @@+//! The installer's change journal, one file per plugin: every system value a plugin changes is written down, old value first,+//! BEFORE the change; uninstall plays it back newest first. So the oldest line of a value holds the original (an update records+//! nothing new) and one playback restores everything. One change per line, the last field may contain `|`:+//! reg|<key>|<name>|- the value did not exist: undo deletes it+//! reg|<key>|<name>|<TYPE>|<data> undo writes it back (reg add /t TYPE /d data)+//! svc|<name>|<mode> undo: sc config <name> start= <mode>++#[derive(Debug, PartialEq, Clone)]+pub enum Entry {+ Reg { key: String, name: String, old: Option<(String, String)> },+ Svc { name: String, mode: String },+}++/// Types reg.exe writes back exactly from what `reg query` printed (DWORD data is kept as decimal).+const TYPES: [&str; 3] = ["REG_SZ", "REG_EXPAND_SZ", "REG_DWORD"];++impl Entry {+ /// The journal line; None when the entry cannot be stored faithfully (then the change must not be made).+ pub fn line(&self) -> Option<String> {+ let ok = |s: &str| !s.contains(['\r', '\n']);+ match self {+ Entry::Reg { key, name, old } => {+ // shortcut: no default values ((Default) prints localized text when unset), add them when a plugin needs one+ if name.is_empty() || !ok(key) || !ok(name) || key.contains('|') || name.contains('|') {+ return None;+ }+ match old {+ None => Some(format!("reg|{key}|{name}|-")),+ Some((ty, d)) if TYPES.contains(&ty.as_str()) && ok(d) => Some(format!("reg|{key}|{name}|{ty}|{d}")),+ Some(_) => None,+ }+ }+ Entry::Svc { name, mode } => (ok(name) && !name.contains('|') && ["auto", "delayed-auto", "demand", "disabled"].contains(&mode.as_str())).then(|| format!("svc|{name}|{mode}")),+ }+ }++ pub fn parse(l: &str) -> Option<Entry> {+ let f: Vec<&str> = l.trim_end_matches(['\r', '\n']).splitn(5, '|').collect();+ let s = |i: usize| f[i].to_string();+ match f.as_slice() {+ ["reg", _, n, "-"] if !n.is_empty() => Some(Entry::Reg { key: s(1), name: s(2), old: None }),+ ["reg", _, n, ty, _] if !n.is_empty() && TYPES.contains(ty) => Some(Entry::Reg { key: s(1), name: s(2), old: Some((s(3), s(4))) }),+ ["svc", _, _] => Some(Entry::Svc { name: s(1), mode: s(2) }).filter(|e| e.line().is_some()),+ _ => None,+ }+ }++ /// Both describe the same value or service: the later one is not recorded.+ pub fn same(&self, o: &Entry) -> bool {+ match (self, o) {+ (Entry::Reg { key: a, name: b, .. }, Entry::Reg { key: c, name: d, .. }) => a.eq_ignore_ascii_case(c) && b.eq_ignore_ascii_case(d),+ (Entry::Svc { name: a, .. }, Entry::Svc { name: b, .. }) => a.eq_ignore_ascii_case(b),+ _ => false,+ }+ }+}++/// Every readable line, oldest first; unknown lines are skipped.+pub fn parse_all(text: &str) -> Vec<Entry> {+ text.lines().filter_map(Entry::parse).collect()+}++/// `sc config` start mode from a service's Start and DelayedAutostart values. None = boot/system driver or unknown: never touched.+pub fn svc_mode(start: Option<u32>, delayed: Option<u32>) -> Option<&'static str> {+ match (start?, delayed.unwrap_or(0)) {+ (2, 0) => Some("auto"),+ (2, _) => Some("delayed-auto"),+ (3, _) => Some("demand"),+ (4, _) => Some("disabled"),+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn reg(old: Option<(&str, &str)>) -> Entry {+ Entry::Reg { key: r"HKLM\SOFTWARE\X".into(), name: "Debugger".into(), old: old.map(|(t, d)| (t.into(), d.into())) }+ }++ #[test]+ fn lines_round_trip() {+ for e in [reg(None), reg(Some(("REG_SZ", r#""C:\a|b.exe" /x"#))), reg(Some(("REG_DWORD", "26"))), Entry::Svc { name: "WSearch".into(), mode: "delayed-auto".into() }] {+ assert_eq!(Entry::parse(&e.line().unwrap()), Some(e));+ }+ assert_eq!(parse_all("reg|K|V|-\r\ngarbage\nsvc|S|auto\n").len(), 2);+ }++ #[test]+ fn refuses_what_it_cannot_restore() {+ assert_eq!(reg(Some(("REG_BINARY", "00ff"))).line(), None);+ assert_eq!(reg(Some(("REG_SZ", "a\nb"))).line(), None);+ assert_eq!(Entry::Reg { key: "K".into(), name: "".into(), old: None }.line(), None);+ assert_eq!(Entry::Svc { name: "S".into(), mode: "boot".into() }.line(), None);+ assert_eq!(Entry::parse("svc|S|boot"), None);+ assert_eq!(Entry::parse("reg|K|V|REG_BINARY|00"), None);+ }++ #[test]+ fn same_value_any_case() {+ let other = Entry::Reg { key: r"hklm\software\x".into(), name: "DEBUGGER".into(), old: Some(("REG_SZ".into(), "y".into())) };+ assert!(reg(None).same(&other));+ assert!(!reg(None).same(&Entry::Svc { name: "Debugger".into(), mode: "auto".into() }));+ }++ #[test]+ fn service_modes() {+ assert_eq!(svc_mode(Some(2), None), Some("auto"));+ assert_eq!(svc_mode(Some(2), Some(1)), Some("delayed-auto"));+ assert_eq!(svc_mode(Some(4), Some(1)), Some("disabled"));+ assert_eq!(svc_mode(Some(1), None), None);+ assert_eq!(svc_mode(None, None), None);+ }+}diff --git a/common/src/lib.rs b/common/src/lib.rsindex 4b03634..b66202b 100644--- a/common/src/lib.rs+++ b/common/src/lib.rs@@ -9,6 +9,8 @@ use std::{};pub mod desktop;+pub mod journal;+pub mod mem;pub mod mft;pub mod reg;pub mod settings;diff --git a/common/src/mem.rs b/common/src/mem.rsnew file mode 100644index 0000000..044a7a9--- /dev/null+++ b/common/src/mem.rs@@ -0,0 +1,139 @@+//! The memory lists (free / standby) and purging the standby list, as ISLC does: when a game needs memory and the free list is+//! empty, Windows has to repurpose standby pages one by one, which shows as stutter. Needs administrator rights.+//! Not done on purpose: emptying working sets. Trimmed pages land on the standby list, which already counts as available+//! memory, and the trimmed program faults them back in: slower, not faster.+use std::{ffi::c_void, path::PathBuf, thread, time::Duration};+use windows_sys::Win32::{+ Foundation::{CloseHandle, HANDLE, LUID},+ Security::{AdjustTokenPrivileges, LookupPrivilegeValueW, SE_PRIVILEGE_ENABLED, TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES},+ System::{+ SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX},+ Threading::{GetCurrentProcess, OpenProcessToken},+ },+};++#[link(name = "ntdll")]+unsafe extern "system" {+ fn NtQuerySystemInformation(class: u32, info: *mut c_void, len: u32, ret: *mut u32) -> i32;+ fn NtSetSystemInformation(class: u32, info: *const c_void, len: u32) -> i32;+}++const SYSTEM_MEMORY_LIST_INFORMATION: u32 = 80;+const MEMORY_PURGE_STANDBY_LIST: u32 = 4;+const PAGE: u64 = 4096;++#[repr(C)]+#[derive(Default)]+struct MemoryLists {+ zero: usize,+ free: usize,+ modified: usize,+ modified_no_write: usize,+ bad: usize,+ standby_by_priority: [usize; 8],+ repurposed_by_priority: [usize; 8],+ modified_pagefile: usize,+}++/// Free and standby memory in bytes.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Lists {+ pub free: u64,+ pub standby: u64,+}++fn enable_privilege(name: &str) -> bool {+ unsafe {+ let mut tok: HANDLE = std::ptr::null_mut();+ if OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &mut tok) == 0 {+ return false;+ }+ let w: Vec<u16> = name.encode_utf16().chain(Some(0)).collect();+ let mut luid = LUID { LowPart: 0, HighPart: 0 };+ let mut ok = LookupPrivilegeValueW(std::ptr::null(), w.as_ptr(), &mut luid) != 0;+ if ok {+ let tp = TOKEN_PRIVILEGES { PrivilegeCount: 1, Privileges: [windows_sys::Win32::Security::LUID_AND_ATTRIBUTES { Luid: luid, Attributes: SE_PRIVILEGE_ENABLED }] };+ // succeeds without the privilege too; GetLastError would say ERROR_NOT_ALL_ASSIGNED+ ok = AdjustTokenPrivileges(tok, 0, &tp, 0, std::ptr::null_mut(), std::ptr::null_mut()) != 0 && windows_sys::Win32::Foundation::GetLastError() == 0;+ }+ CloseHandle(tok);+ ok+ }+}++/// None without administrator rights (the query needs SeProfileSingleProcessPrivilege).+pub fn lists() -> Option<Lists> {+ if !enable_privilege("SeProfileSingleProcessPrivilege") {+ return None;+ }+ let mut m = MemoryLists::default();+ let st = unsafe { NtQuerySystemInformation(SYSTEM_MEMORY_LIST_INFORMATION, &mut m as *mut _ as *mut c_void, size_of::<MemoryLists>() as u32, std::ptr::null_mut()) };+ (st >= 0).then(|| Lists { free: (m.zero + m.free) as u64 * PAGE, standby: m.standby_by_priority.iter().sum::<usize>() as u64 * PAGE })+}++/// Drops the standby list (cached file data nobody holds). Err(NTSTATUS) without administrator rights.+pub fn purge_standby() -> Result<(), i32> {+ if !enable_privilege("SeProfileSingleProcessPrivilege") {+ return Err(0xC000_0061u32 as i32); // STATUS_PRIVILEGE_NOT_HELD+ }+ let cmd = MEMORY_PURGE_STANDBY_LIST;+ let st = unsafe { NtSetSystemInformation(SYSTEM_MEMORY_LIST_INFORMATION, &cmd as *const u32 as *const c_void, 4) };+ if st >= 0 { Ok(()) } else { Err(st) }+}++pub fn total_ram() -> u64 {+ let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };+ m.dwLength = size_of::<MEMORYSTATUSEX>() as u32;+ unsafe { GlobalMemoryStatusEx(&mut m) };+ m.ullTotalPhys+}++/// When the auto purge acts: the free list below max(512 MB, 5% of RAM) while the standby list holds over 1 GB.+pub fn should_purge(l: Lists, total: u64) -> bool {+ l.free < (512 << 20).max(total / 20) && l.standby > 1 << 30+}++/// The switch file of the auto purge (rtaskmgr's Speed page writes it, topbar's thread acts on it).+pub fn auto_file() -> Option<PathBuf> {+ std::env::var_os("ProgramData").map(|p| PathBuf::from(p).join(r"WinRust\autopurge.txt"))+}++pub fn auto_on() -> bool {+ auto_file().is_some_and(|f| f.is_file())+}++/// Endless loop for a resident elevated program (topbar): every 10 s, while the switch file exists, purges when `should_purge`,+/// at most once a minute.+pub fn auto_loop() {+ let total = total_ram();+ let mut last: Option<std::time::Instant> = None;+ loop {+ thread::sleep(Duration::from_secs(10));+ if !auto_on() || last.is_some_and(|t| t.elapsed() < Duration::from_secs(60)) {+ continue;+ }+ if lists().is_some_and(|l| should_purge(l, total)) && purge_standby().is_ok() {+ last = Some(std::time::Instant::now());+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn purge_rule() {+ let gb = 1u64 << 30;+ assert!(should_purge(Lists { free: 100 << 20, standby: 4 * gb }, 16 * gb));+ assert!(!should_purge(Lists { free: 2 * gb, standby: 4 * gb }, 16 * gb), "enough free memory");+ assert!(!should_purge(Lists { free: 100 << 20, standby: 500 << 20 }, 16 * gb), "nothing worth dropping");+ assert!(should_purge(Lists { free: 1 * gb, standby: 8 * gb }, 64 * gb), "5% of 64 GB is 3.2 GB");+ }++ #[test]+ fn struct_matches_the_kernel_layout() {+ assert_eq!(size_of::<MemoryLists>(), 22 * size_of::<usize>());+ assert!(total_ram() > 0);+ }+}diff --git a/plugins/debloat/src/main.rs b/plugins/debloat/src/main.rsindex 6db6330..320b4d4 100644--- a/plugins/debloat/src/main.rs+++ b/plugins/debloat/src/main.rs@@ -1,15 +1,21 @@-// debloat show what would change (nothing is modified)-// debloat --apply apply (admin); the old value of every change is written to the undo file BEFORE the change-// debloat --undo put every value and service back exactly as it was+// debloat show what would change (nothing is modified)+// debloat --apply apply (admin); the old value of every change is written to the undo file BEFORE the change+// debloat --undo put every value and service back exactly as it was+// debloat <cmd> <group> the same for one optional group, each with its own undo file (rtaskmgr's Speed page uses them):+// updaters third-party updater services and tasks off, one weekly `winget upgrade --all` task instead (browsers keep theirs)+// defender Defender exclusions for build caches and game libraries (opt-in: those folders are no longer scanned)+// ntfs NTFS stops updating last-access times and creating 8.3 short names (after a reboot)+// dns ad and tracker domains blocked in the hosts file+// debloat --status <group> prints on/off; exit code 0 = applied (its undo file exists)//-// Only reversible things: a few services and registry policies. Not touched on purpose: Windows Update, Defender, Print Spooler,-// Xbox/Game services, SysMain, and installed apps (removing an AppX package cannot be undone from here).+// Only reversible things. Not touched on purpose: Windows Update, Print Spooler, Xbox/Game services, SysMain, installed apps,+// browser updaters (a browser must patch itself quickly), Microsoft domains in hosts (Defender flags that as hijacking).// Side effect worth knowing: Edge shows "managed by your organization" while its two policies below are set.use std::{env,- fs::{self, OpenOptions},+ fs::{self, File, OpenOptions},io::Write,- path::PathBuf,+ path::{Path, PathBuf},process::Command,};@@ -49,15 +55,130 @@ const REGS: &[(&str, &str, u32, &str)] = &[(r"HKCU\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager", "RotatingLockScreenOverlayEnabled", 0, "no ads on the lock screen"),];+// ---------- optional groups ----------++/// Updater services of non-browser apps; winget updates the apps instead.+const UPD_SERVICES: &[(&str, &str)] = &[+ ("AdobeARMservice", "Adobe Acrobat updater"),+ ("AdobeUpdateService", "Adobe updater"),+ ("AGSService", "Adobe Genuine Software check"),+ ("AGMService", "Adobe Genuine Monitor"),+ ("MozillaMaintenance", "Mozilla maintenance (Firefox still updates itself while it runs)"),+ ("dbupdate", "Dropbox updater"),+ ("dbupdatem", "Dropbox updater"),+ ("ccleaner", "CCleaner updater"),+ ("ccleanerm", "CCleaner updater"),+];++/// Scheduled tasks whose path starts with one of these (case ignored).+const UPD_TASKS: &[&str] = &[+ r"\Adobe Acrobat Update Task",+ r"\AdobeGCInvoker",+ r"\Mozilla\Firefox Background Update",+ r"\Mozilla\Firefox Default Browser Agent",+ r"\DropboxUpdateTaskMachine",+ r"\CCleaner Update",+ r"\CCleanerSkipUAC",+ r"\Opera scheduled Autoupdate",+ r"\Opera GX scheduled Autoupdate",+ r"\Opera scheduled assistant Autoupdate",+ r"\AppleSoftwareUpdate",+ r"\OneDrive Standalone Update Task",+ r"\OneDrive Reporting Task",+ r"\ZoomUpdateTask",+];++const WINGET_TASK: &str = r"\WinRust\Update apps";++const NTFS_REGS: &[(&str, &str, u32, &str)] = &[+ (r"HKLM\SYSTEM\CurrentControlSet\Control\FileSystem", "NtfsDisableLastAccessUpdate", 0x8000_0001, "no last-access time written on every read"),+ (r"HKLM\SYSTEM\CurrentControlSet\Control\FileSystem", "NtfsDisable8dot3NameCreation", 1, "no 8.3 short name created with every new file"),+];++const DEF_PROCS: &[&str] = &["cargo.exe", "rustc.exe"];++const HOSTS_BEGIN: &str = "# >>> WinRust DNS block >>>";+const HOSTS_END: &str = "# <<< WinRust DNS block <<<";++/// Ad and tracker hosts. No Microsoft domains: Defender reports hosts entries for them as SettingsModifier:Win32/HostsFileHijack.+const BLOCK: &[&str] = &[+ "doubleclick.net", "ad.doubleclick.net", "static.doubleclick.net", "stats.g.doubleclick.net", "googleads.g.doubleclick.net",+ "pubads.g.doubleclick.net", "securepubads.g.doubleclick.net", "cm.g.doubleclick.net", "googleadservices.com", "www.googleadservices.com",+ "pagead2.googlesyndication.com", "tpc.googlesyndication.com", "adservice.google.com", "partner.googleadservices.com",+ "google-analytics.com", "www.google-analytics.com", "ssl.google-analytics.com", "analytics.google.com", "googletagservices.com",+ "www.googletagservices.com", "app-measurement.com", "adnxs.com", "ib.adnxs.com", "secure.adnxs.com", "acdn.adnxs.com",+ "ads.yahoo.com", "analytics.yahoo.com", "advertising.com", "ads.pubmatic.com", "image6.pubmatic.com", "simage2.pubmatic.com",+ "ads.rubiconproject.com", "fastlane.rubiconproject.com", "pixel.rubiconproject.com", "openx.net", "us-ads.openx.net",+ "rtb.openx.net", "criteo.com", "static.criteo.net", "bidder.criteo.com", "dis.criteo.com", "taboola.com", "cdn.taboola.com",+ "trc.taboola.com", "outbrain.com", "widgets.outbrain.com", "log.outbrain.com", "amazon-adsystem.com", "aax.amazon-adsystem.com",+ "c.amazon-adsystem.com", "s.amazon-adsystem.com", "adsrvr.org", "match.adsrvr.org", "insight.adsrvr.org", "casalemedia.com",+ "as.casalemedia.com", "smartadserver.com", "www.smartadserver.com", "moatads.com", "z.moatads.com", "px.moatads.com",+ "scorecardresearch.com", "sb.scorecardresearch.com", "b.scorecardresearch.com", "quantserve.com", "pixel.quantserve.com",+ "quantcount.com", "hotjar.com", "static.hotjar.com", "script.hotjar.com", "vars.hotjar.com", "mouseflow.com", "cdn.mouseflow.com",+ "crazyegg.com", "script.crazyegg.com", "mixpanel.com", "api.mixpanel.com", "cdn.mxpnl.com", "segment.io", "api.segment.io",+ "cdn.segment.com", "amplitude.com", "api.amplitude.com", "api2.amplitude.com", "branch.io", "api2.branch.io", "app.adjust.com",+ "adjust.com", "appsflyer.com", "t.appsflyer.com", "inapps.appsflyer.com", "adcolony.com", "ads30.adcolony.com", "unityads.unity3d.com",+ "auction.unityads.unity3d.com", "applovin.com", "ms.applovin.com", "rt.applovin.com", "mopub.com", "ads.mopub.com", "inmobi.com",+ "chartboost.com", "live.chartboost.com", "vungle.com", "api.vungle.com", "yieldmo.com", "sharethrough.com", "btlr.sharethrough.com",+ "33across.com", "ssc.33across.com", "media.net", "contextual.media.net", "zedo.com", "revcontent.com", "trends.revcontent.com",+ "mgid.com", "servicer.mgid.com", "propellerads.com", "popads.net", "popcash.net", "exoclick.com", "syndication.exoclick.com",+ "adform.net", "track.adform.net", "serving-sys.com", "bs.serving-sys.com", "flashtalking.com", "servedby.flashtalking.com",+ "bluekai.com", "tags.bluekai.com", "krxd.net", "cdn.krxd.net", "demdex.net", "dpm.demdex.net", "everesttech.net",+ "omtrdc.net", "2o7.net", "tapad.com", "addthis.com", "s7.addthis.com", "sharethis.com", "w.sharethis.com", "ads.tiktok.com",+ "analytics.tiktok.com", "ads-api.tiktok.com", "an.facebook.com", "pixel.facebook.com", "ads.linkedin.com", "px.ads.linkedin.com",+ "ads.twitter.com", "static.ads-twitter.com", "ads-api.twitter.com", "analytics.twitter.com", "ads.reddit.com", "events.reddit.com",+ "ads.pinterest.com", "ct.pinterest.com", "an.yandex.ru", "mc.yandex.ru", "adfox.yandex.ru", "ads.adfox.ru", "top-fwz1.mail.ru",+ "ad.mail.ru", "rs.mail.ru", "counter.yadro.ru", "ssp.rambler.ru", "kraken.rambler.ru",+];++#[derive(Clone, Copy, PartialEq, Debug)]+enum Group {+ Base,+ Updaters,+ Defender,+ Ntfs,+ Dns,+}++impl Group {+ fn parse(s: &str) -> Option<Group> {+ Some(match s {+ "updaters" => Group::Updaters,+ "defender" => Group::Defender,+ "ntfs" => Group::Ntfs,+ "dns" => Group::Dns,+ _ => return None,+ })+ }+ fn file(self) -> &'static str {+ match self {+ Group::Base => "undo.txt",+ Group::Updaters => "undo-updaters.txt",+ Group::Defender => "undo-defender.txt",+ Group::Ntfs => "undo-ntfs.txt",+ Group::Dns => "undo-dns.txt",+ }+ }+}+fn run(prog: &str, args: &[&str]) -> (bool, String) {// HKCU = the signed-in user's when the installer was elevated as another administrator (WINRUST_SID)- let args: Vec<String> = if prog == "reg" { winrust_common::reg::user_args(args) } else { args.iter().map(|a| a.to_string()).collect() };+ let args: Vec<String> = if prog == "reg.exe" { winrust_common::reg::user_args(args) } else { args.iter().map(|a| a.to_string()).collect() };match Command::new(prog).args(&args).output() {Ok(o) => (o.status.success(), String::from_utf8_lossy(&o.stdout).into_owned()),Err(e) => (false, e.to_string()),}}+fn ps(script: &str) -> (bool, String) {+ run("powershell.exe", &["-NoProfile", "-NonInteractive", "-Command", script])+}++/// A PowerShell single-quoted string.+fn psq(s: &str) -> String {+ format!("'{}'", s.replace('\'', "''"))+}+/// Current start mode as `sc config` spells it. None = service missing, or boot/system driver (never touched).fn start_mode(svc: &str) -> Option<&'static str> {let (ok, out) = run("sc.exe", &["qc", svc]);@@ -96,20 +217,129 @@ fn reg_val(key: &str, value: &str) -> Val {parse_val(ok, &out)}-fn undo_path() -> PathBuf {- PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join("winrust-debloat").join("undo.txt")+fn undo_path(g: Group) -> PathBuf {+ PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join("winrust-debloat").join(g.file())}-fn plan() {+fn hosts_path() -> PathBuf {+ PathBuf::from(env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into())).join(r"System32\drivers\etc\hosts")+}++/// Task paths (`\Folder\Name`) from `schtasks /query /fo csv /nh`: the first column, quoted.+fn parse_task_names(csv: &str) -> Vec<String> {+ let mut v: Vec<String> = csv.lines().filter_map(|l| l.strip_prefix('"')?.split('"').next().map(str::to_string)).filter(|n| n.starts_with('\\')).collect();+ v.dedup();+ v+}++fn updater_tasks() -> Vec<String> {+ let (_, out) = run("schtasks.exe", &["/query", "/fo", "csv", "/nh"]);+ parse_task_names(&out).into_iter().filter(|n| UPD_TASKS.iter().any(|p| n.to_lowercase().starts_with(&p.to_lowercase()))).collect()+}++/// The task's own Enabled flag (inside <Settings>; triggers carry their own flags).+fn task_enabled(name: &str) -> Option<bool> {+ let (ok, xml) = run("schtasks.exe", &["/query", "/tn", name, "/xml"]);+ if !ok {+ return None;+ }+ let settings = xml.split("<Settings>").nth(1)?.split("</Settings>").next()?;+ Some(!settings.contains("<Enabled>false</Enabled>"))+}++fn has_winget() -> bool {+ run("where.exe", &["winget"]).0+}++/// Folders where a build or a game reads thousands of files: caches of cargo, rustup, npm, pip, NuGet, and game libraries.+fn defender_paths() -> Vec<String> {+ let mut v = vec![];+ if let Some(home) = env::var_os("USERPROFILE").map(PathBuf::from) {+ for d in [".cargo", ".rustup", r".nuget\packages", r".gradle\caches", r".m2\repository"] {+ v.push(home.join(d));+ }+ }+ if let Some(la) = env::var_os("LOCALAPPDATA").map(PathBuf::from) {+ v.push(la.join("npm-cache"));+ v.push(la.join(r"pip\cache"));+ v.push(la.join(r"Yarn\Cache"));+ v.push(la.join(r"pnpm\store"));+ }+ if let Some(pf) = env::var_os("ProgramFiles").map(PathBuf::from) {+ v.push(pf.join("Epic Games"));+ }+ v.extend(steam_libraries());+ // SteamPath is stored with forward slashes and in lower case: one spelling per folder+ let mut seen = std::collections::HashSet::new();+ v.into_iter().filter(|p| p.is_dir()).map(|p| p.display().to_string().replace('/', "\\")).filter(|p| seen.insert(p.to_lowercase())).collect()+}++fn steam_libraries() -> Vec<PathBuf> {+ let (_, out) = run("reg.exe", &["query", r"HKCU\Software\Valve\Steam", "/v", "SteamPath"]);+ let Some(("REG_SZ", root)) = winrust_common::reg::value(&out) else { return vec![] };+ let vdf = fs::read_to_string(Path::new(root).join(r"steamapps\libraryfolders.vdf")).unwrap_or_default();+ let mut libs = vec![PathBuf::from(root)];+ libs.extend(parse_vdf_paths(&vdf).into_iter().map(PathBuf::from));+ libs.into_iter().map(|l| l.join(r"steamapps\common")).collect()+}++/// `"path" "D:\\SteamLibrary"` lines of libraryfolders.vdf (backslashes are escaped there).+fn parse_vdf_paths(vdf: &str) -> Vec<String> {+ vdf.lines()+ .filter_map(|l| {+ let f: Vec<&str> = l.split('"').collect();+ (f.len() >= 4 && f[1] == "path").then(|| f[3].replace(r"\\", r"\"))+ })+ .collect()+}++/// Current Defender exclusions (paths and processes), lower case. Err when Defender is not running (another antivirus).+fn defender_exclusions() -> Result<Vec<String>, String> {+ let (ok, out) = ps("$p=Get-MpPreference -ErrorAction Stop; $p.ExclusionPath; $p.ExclusionProcess");+ if !ok {+ return Err("Microsoft Defender is not active here (another antivirus?): nothing to exclude".into());+ }+ Ok(out.lines().map(|l| l.trim().to_lowercase()).filter(|l| !l.is_empty()).collect())+}++fn hosts_block() -> String {+ let mut s = format!("{HOSTS_BEGIN}\r\n");+ for d in BLOCK {+ s += &format!("0.0.0.0 {d}\r\n");+ }+ s + HOSTS_END + "\r\n"+}++/// The hosts text without our block (and without the empty line we put before it).+fn strip_block(text: &str) -> String {+ let (Some(a), Some(b)) = (text.find(HOSTS_BEGIN), text.find(HOSTS_END)) else { return text.to_string() };+ if b < a {+ return text.to_string();+ }+ let mut end = b + HOSTS_END.len();+ let rest = &text[end..];+ end += if rest.starts_with("\r\n") { 2 } else { rest.starts_with('\n') as usize };+ let head = text[..a].trim_end_matches(['\r', '\n']);+ let tail = &text[end..];+ if head.is_empty() { tail.to_string() } else { format!("{head}\r\n{tail}") }+}++fn plan(g: Group) {println!("Dry run: nothing is changed. Add --apply (admin) to do it, --undo to revert.\n");- for (svc, why) in SERVICES {+ let (svcs, regs): (&[(&str, &str)], &[(&str, &str, u32, &str)]) = match g {+ Group::Base => (SERVICES, REGS),+ Group::Updaters => (UPD_SERVICES, &[]),+ Group::Ntfs => (&[], NTFS_REGS),+ _ => (&[], &[]),+ };+ for (svc, why) in svcs {match start_mode(svc) {None => println!(" service {svc:<18} not present"),Some("disabled") => println!(" service {svc:<18} already disabled"),Some(m) => println!(" service {svc:<18} {m} -> disabled ({why})"),}}- for (key, value, data, why) in REGS {+ for (key, value, data, why) in regs {let state = match reg_val(key, value) {Val::Dword(d) if d == *data => "already set".to_string(),Val::Dword(d) => format!("{d} -> {data}"),@@ -118,20 +348,42 @@ fn plan() {};println!(" policy {value:<34} {state} ({why})");}+ match g {+ Group::Updaters => {+ for t in updater_tasks() {+ println!(" task {t} -> disabled");+ }+ println!(" task {WINGET_TASK} {}", if has_winget() { "weekly winget upgrade --all" } else { "skipped: winget is not installed" });+ }+ Group::Defender => {+ for p in defender_paths() {+ println!(" exclude {p}");+ }+ for p in DEF_PROCS {+ println!(" exclude process {p}");+ }+ }+ Group::Dns => println!(" hosts {} ad/tracker domains -> 0.0.0.0", BLOCK.len()),+ _ => {}+ }}-fn apply() -> Result<(), String> {- let path = undo_path();- let dir = path.parent().unwrap();- fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e} (run as admin)", dir.display()))?;- let mut log = OpenOptions::new().create(true).append(true).open(&path).map_err(|e| format!("{}: {e}", path.display()))?;+struct Log(File);++impl Log {+ fn line(&mut self, s: &str) -> Result<(), String> {+ writeln!(self.0, "{s}").and_then(|_| self.0.flush()).map_err(|e| e.to_string())+ }+}++fn apply_services(list: &[(&str, &str)], log: &mut Log) -> Result<u32, String> {let mut failed = 0;- for (svc, _) in SERVICES {+ for (svc, _) in list {match start_mode(svc) {None => println!("skip {svc}: not present"),Some("disabled") => println!("skip {svc}: already disabled"),Some(mode) => {- writeln!(log, "svc|{svc}|{mode}").map_err(|e| e.to_string())?; // log BEFORE changing+ log.line(&format!("svc|{svc}|{mode}"))?; // log BEFORE changinglet ok = run("sc.exe", &["config", svc, "start=", "disabled"]).0;let _ = run("sc.exe", &["stop", svc]);failed += !ok as u32;@@ -139,7 +391,12 @@ fn apply() -> Result<(), String> {}}}- for (key, value, data, _) in REGS {+ Ok(failed)+}++fn apply_regs(list: &[(&str, &str, u32, &str)], log: &mut Log) -> Result<u32, String> {+ let mut failed = 0;+ for (key, value, data, _) in list {let old = match reg_val(key, value) {Val::Dword(d) if d == *data => {println!("skip {value}: already {data}");@@ -152,17 +409,116 @@ fn apply() -> Result<(), String> {Val::Dword(d) => d.to_string(),Val::Missing => "-".into(),};- writeln!(log, "reg|{key}|{value}|{old}").map_err(|e| e.to_string())?;+ log.line(&format!("reg|{key}|{value}|{old}"))?;let ok = run("reg.exe", &["add", key, "/v", value, "/t", "REG_DWORD", "/d", &data.to_string(), "/f"]).0;failed += !ok as u32;println!("{} {value} = {data}", if ok { "done " } else { "FAILED" });}+ Ok(failed)+}++fn apply_updaters(log: &mut Log) -> Result<u32, String> {+ let mut failed = apply_services(UPD_SERVICES, log)?;+ for t in updater_tasks() {+ if task_enabled(&t) != Some(true) {+ println!("skip {t}: already disabled");+ continue;+ }+ log.line(&format!("task|{t}"))?;+ let ok = run("schtasks.exe", &["/change", "/tn", &t, "/disable"]).0;+ failed += !ok as u32;+ println!("{} {t}: disabled", if ok { "done " } else { "FAILED" });+ }+ if !has_winget() {+ println!("skip {WINGET_TASK}: winget is not installed (App Installer from the Store)");+ } else if task_enabled(WINGET_TASK).is_some() {+ println!("skip {WINGET_TASK}: already there");+ } else {+ log.line(&format!("newtask|{WINGET_TASK}"))?;+ // as the signed-in user (winget is a per-user app), elevated so installers do not ask; no window (conhost --headless)+ let user = env::var(winrust_common::reg::SID_ENV).ok().filter(|s| winrust_common::reg::valid_sid(s)).map_or("([Security.Principal.WindowsIdentity]::GetCurrent().Name)".to_string(), |s| psq(&s));+ let script = format!(+ "$a=New-ScheduledTaskAction -Execute 'conhost.exe' -Argument '--headless cmd.exe /c winget upgrade --all --silent --accept-source-agreements --accept-package-agreements --disable-interactivity'; \+ $t=New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 12:00; \+ $s=New-ScheduledTaskSettingsSet -StartWhenAvailable -RunOnlyIfNetworkAvailable -AllowStartIfOnBatteries -ExecutionTimeLimit (New-TimeSpan -Hours 2); \+ $p=New-ScheduledTaskPrincipal -UserId {user} -LogonType Interactive -RunLevel Highest; \+ Register-ScheduledTask -TaskPath '\\WinRust\\' -TaskName 'Update apps' -Action $a -Trigger $t -Settings $s -Principal $p -Force -ErrorAction Stop | Out-Null"+ );+ let ok = ps(&script).0;+ failed += !ok as u32;+ println!("{} {WINGET_TASK}: weekly winget upgrade --all (Sunday 12:00, or at the next start)", if ok { "done " } else { "FAILED" });+ }+ Ok(failed)+}++fn apply_defender(log: &mut Log) -> Result<u32, String> {+ let have = defender_exclusions()?;+ let paths: Vec<String> = defender_paths().into_iter().filter(|p| !have.contains(&p.to_lowercase())).collect();+ let procs: Vec<&str> = DEF_PROCS.iter().copied().filter(|p| !have.contains(&p.to_lowercase())).collect();+ if paths.is_empty() && procs.is_empty() {+ println!("skip nothing new to exclude");+ return Ok(0);+ }+ for p in &paths {+ log.line(&format!("mpx|path|{p}"))?;+ }+ for p in &procs {+ log.line(&format!("mpx|proc|{p}"))?;+ }+ let list = |v: &[&str]| v.iter().map(|s| psq(s)).collect::<Vec<_>>().join(",");+ let mut cmd = "Add-MpPreference -ErrorAction Stop".to_string();+ if !paths.is_empty() {+ cmd += &format!(" -ExclusionPath {}", list(&paths.iter().map(String::as_str).collect::<Vec<_>>()));+ }+ if !procs.is_empty() {+ cmd += &format!(" -ExclusionProcess {}", list(&procs));+ }+ let ok = ps(&cmd).0;+ for p in paths.iter().map(String::as_str).chain(procs.iter().copied()) {+ println!("{} exclude {p}", if ok { "done " } else { "FAILED" });+ }+ Ok(!ok as u32)+}++fn apply_dns(log: &mut Log) -> Result<u32, String> {+ let path = hosts_path();+ let text = fs::read_to_string(&path).unwrap_or_default();+ if text.contains(HOSTS_BEGIN) {+ println!("skip hosts: the block is already there");+ return Ok(0);+ }+ log.line("hosts|block")?;+ let new = format!("{}\r\n\r\n{}", text.trim_end_matches(['\r', '\n']), hosts_block());+ let ok = fs::write(&path, new.trim_start_matches(['\r', '\n'])).is_ok();+ let _ = run("ipconfig.exe", &["/flushdns"]);+ println!("{} hosts: {} domains blocked", if ok { "done " } else { "FAILED" }, BLOCK.len());+ Ok(!ok as u32)+}++fn apply(g: Group) -> Result<(), String> {+ let path = undo_path(g);+ let dir = path.parent().unwrap();+ fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e} (run as admin)", dir.display()))?;+ let f = OpenOptions::new().create(true).append(true).open(&path).map_err(|e| format!("{}: {e}", path.display()))?;+ let mut log = Log(f);+ let failed = match g {+ Group::Base => apply_services(SERVICES, &mut log)? + apply_regs(REGS, &mut log)?,+ Group::Updaters => apply_updaters(&mut log)?,+ Group::Defender => apply_defender(&mut log)?,+ Group::Ntfs => apply_regs(NTFS_REGS, &mut log)?,+ Group::Dns => apply_dns(&mut log)?,+ };+ drop(log);+ // nothing was changed (all skipped): no undo file, so the group does not show as applied+ if fs::metadata(&path).is_ok_and(|m| m.len() == 0) {+ let _ = fs::remove_file(&path);+ }println!("\nUndo information saved to {}. Some changes need a reboot or sign-out.", path.display());if failed > 0 { Err(format!("{failed} change(s) failed (run as administrator)")) } else { Ok(()) }}-fn undo() -> Result<(), String> {- let path = undo_path();+fn undo(g: Group) -> Result<(), String> {+ let path = undo_path(g);let Ok(text) = fs::read_to_string(&path) else {println!("nothing to undo (no undo file)");return Ok(());@@ -170,11 +526,21 @@ fn undo() -> Result<(), String> {let mut failed = 0;// the first line per item holds the ORIGINAL value (an earlier --apply may have logged the same item again)for line in text.lines().rev() {- let f: Vec<&str> = line.split('|').collect();+ let f: Vec<&str> = line.splitn(4, '|').collect();let ok = match f.as_slice() {["svc", name, mode] => run("sc.exe", &["config", name, "start=", mode]).0,["reg", key, value, "-"] => run("reg.exe", &["delete", key, "/v", value, "/f"]).0 || reg_val(key, value) == Val::Missing, // never written (the change itself failed): nothing to remove["reg", key, value, old] => run("reg.exe", &["add", key, "/v", value, "/t", "REG_DWORD", "/d", old, "/f"]).0,+ ["task", name] => run("schtasks.exe", &["/change", "/tn", name, "/enable"]).0 || task_enabled(name).is_none(), // uninstalled with its app meanwhile+ ["newtask", name] => run("schtasks.exe", &["/delete", "/tn", name, "/f"]).0 || task_enabled(name).is_none(),+ ["mpx", "path", p] => ps(&format!("Remove-MpPreference -ErrorAction Stop -ExclusionPath {}", psq(p))).0,+ ["mpx", "proc", p] => ps(&format!("Remove-MpPreference -ErrorAction Stop -ExclusionProcess {}", psq(p))).0,+ ["hosts", "block"] => {+ let p = hosts_path();+ let ok = fs::read_to_string(&p).is_ok_and(|t| fs::write(&p, strip_block(&t)).is_ok());+ let _ = run("ipconfig.exe", &["/flushdns"]);+ ok+ }_ => continue,};failed += !ok as u32;@@ -184,18 +550,33 @@ fn undo() -> Result<(), String> {return Err(format!("{failed} item(s) not restored; the undo file is kept at {}", path.display()));}fs::remove_file(&path).map_err(|e| e.to_string())?;- println!("\nServices were restored to their old start mode (start them manually or reboot).");+ println!("\nRestored (services start again after a reboot or by hand).");Ok(())}fn main() {let args: Vec<String> = env::args().skip(1).collect();- let r = if args.iter().any(|a| a == "--apply") {- apply()- } else if args.iter().any(|a| a == "--undo") {- undo()+ let group = match args.iter().find(|a| !a.starts_with("--")) {+ None => Group::Base,+ Some(g) => match Group::parse(g) {+ Some(g) => g,+ None => {+ eprintln!("unknown group '{g}' (updaters, defender, ntfs, dns)");+ std::process::exit(2);+ }+ },+ };+ let has = |f: &str| args.iter().any(|a| a == f);+ let r = if has("--status") {+ let on = undo_path(group).is_file();+ println!("{}", if on { "on" } else { "off" });+ std::process::exit(!on as i32);+ } else if has("--apply") {+ apply(group)+ } else if has("--undo") {+ undo(group)} else {- plan();+ plan(group);Ok(())};if let Err(e) = r {@@ -214,14 +595,58 @@ mod tests {assert_eq!(parse_val(true, dw), Val::Dword(1));assert_eq!(parse_val(true, " V REG_SZ hello\r\n"), Val::Other);assert_eq!(parse_val(false, "ERROR: The system was unable to find the specified registry key or value."), Val::Missing);+ assert_eq!(parse_val(true, " NtfsDisableLastAccessUpdate REG_DWORD 0x80000002\r\n"), Val::Dword(0x8000_0002));}#[test]fn every_registry_item_is_hkcu_or_hklm_and_unique() {let mut seen = std::collections::HashSet::new();- for (k, v, _, _) in REGS {+ for (k, v, _, _) in REGS.iter().chain(NTFS_REGS) {assert!(k.starts_with("HKLM\\") || k.starts_with("HKCU\\"), "{k}");assert!(seen.insert((k, v)), "duplicate {k} {v}");}}++ #[test]+ fn task_names_from_schtasks_csv() {+ let csv = "\r\n\"\\Adobe Acrobat Update Task\",\"21.11.2026 10:00:00\",\"Готово\"\r\n\"\\Mozilla\\Firefox Background Update 308046B0AF4A39CB\",\"N/A\",\"Ready\"\r\n\"\\Mozilla\\Firefox Background Update 308046B0AF4A39CB\",\"N/A\",\"Ready\"\r\nINFO: x\r\n";+ assert_eq!(parse_task_names(csv), vec![r"\Adobe Acrobat Update Task", r"\Mozilla\Firefox Background Update 308046B0AF4A39CB"]);+ }++ #[test]+ fn steam_library_paths() {+ let vdf = "\"libraryfolders\"\n{\n\t\"0\"\n\t{\n\t\t\"path\"\t\t\"C:\\\\Program Files (x86)\\\\Steam\"\n\t}\n\t\"1\"\n\t{\n\t\t\"path\"\t\t\"D:\\\\SteamLibrary\"\n\t}\n}";+ assert_eq!(parse_vdf_paths(vdf), vec![r"C:\Program Files (x86)\Steam", r"D:\SteamLibrary"]);+ }++ #[test]+ fn hosts_block_round_trips() {+ let orig = "# Copyright\r\n127.0.0.1 localhost\r\n";+ let with = format!("{}\r\n\r\n{}", orig.trim_end(), hosts_block());+ assert_eq!(strip_block(&with), "# Copyright\r\n127.0.0.1 localhost\r\n");+ let with_tail = format!("{with}10.0.0.1 nas\r\n");+ assert_eq!(strip_block(&with_tail), "# Copyright\r\n127.0.0.1 localhost\r\n10.0.0.1 nas\r\n");+ assert_eq!(strip_block(&hosts_block()), "");+ assert_eq!(strip_block(orig), orig);+ }++ #[test]+ fn block_list_is_clean() {+ let mut seen = std::collections::HashSet::new();+ for d in BLOCK {+ assert!(seen.insert(*d), "duplicate {d}");+ assert!(!d.contains(' ') && d.contains('.'), "{d}");+ for ms in ["microsoft", "windows", "msn.com", "live.com", "bing.com", "office", "skype", "xbox"] {+ assert!(!d.contains(ms), "Microsoft domain {d}: Defender flags it");+ }+ }+ }++ #[test]+ fn groups_parse_and_have_own_files() {+ let gs = ["updaters", "defender", "ntfs", "dns"].map(|g| Group::parse(g).unwrap());+ let files: std::collections::HashSet<_> = gs.iter().map(|g| g.file()).chain([Group::Base.file()]).collect();+ assert_eq!(files.len(), 5);+ assert_eq!(Group::parse("x"), None);+ }}diff --git a/plugins/rtaskmgr-win32/src/app.rs b/plugins/rtaskmgr-win32/src/app.rsindex cd06d79..9722646 100644--- a/plugins/rtaskmgr-win32/src/app.rs+++ b/plugins/rtaskmgr-win32/src/app.rs@@ -21,6 +21,8 @@ pub enum Btn {StartEnable,StartDisable,RuleDelete,+ BoostOn,+ BoostOff,}#[derive(Clone, Copy, PartialEq, Debug)]@@ -86,7 +88,7 @@ impl Ui {matches!(self.page, Page::Processes | Page::Users | Page::Details | Page::Services | Page::Startup | Page::History | Page::Rules)}pub fn has_table(&self) -> bool {- self.page_has_search()+ self.page_has_search() || self.page == Page::Boost}}@@ -108,6 +110,8 @@ pub enum Act {SvcStop,StartEnable,StartDisable,+ BoostOn,+ BoostOff,Export,SetTheme(u8),ToggleTray,@@ -165,6 +169,7 @@ fn page_buttons(p: Page) -> Vec<(Btn, &'static str, char)> {Page::Startup => vec![(Btn::StartEnable, t!("Включить", "Enable"), '\u{E73E}'), (Btn::StartDisable, t!("Отключить", "Disable"), '\u{E711}'), (Btn::More, "", '\u{E712}')],Page::Rules => vec![(Btn::RuleDelete, t!("Удалить правило", "Delete rule"), '\u{E74D}'), (Btn::More, "", '\u{E712}')],Page::History => vec![(Btn::More, "", '\u{E712}')],+ Page::Boost => vec![(Btn::BoostOn, t!("Включить", "Enable"), '\u{E73E}'), (Btn::BoostOff, t!("Выключить", "Disable"), '\u{E711}')],_ => vec![],}}@@ -382,7 +387,7 @@ impl App {let has_sel = ui.sel.is_some();match b {Btn::RunTask | Btn::More => true,- Btn::EndTask | Btn::Efficiency | Btn::SvcStart | Btn::SvcStop | Btn::StartEnable | Btn::StartDisable | Btn::RuleDelete => {+ Btn::EndTask | Btn::Efficiency | Btn::SvcStart | Btn::SvcStop | Btn::StartEnable | Btn::StartDisable | Btn::RuleDelete | Btn::BoostOn | Btn::BoostOff => {let _ = d;has_sel}@@ -702,7 +707,8 @@ impl App {let ui = self.ui.borrow();self.data.borrow_mut().want_gpu_temp = ui.page == Page::Performance && matches!(ui.perf_sel, PerfKind::Gpu(_));}- let notes = self.data.borrow_mut().refresh();+ let mut notes = self.data.borrow_mut().refresh();+ notes.extend(crate::boost::take_done()); // фоновые действия страницы «Ускорение»if !notes.is_empty() {let msg = notes.join("; ");self.toast(&msg);@@ -755,6 +761,8 @@ impl App {Btn::StartEnable => self.do_act(Act::StartEnable),Btn::StartDisable => self.do_act(Act::StartDisable),Btn::RuleDelete => self.do_act(Act::RuleDelete),+ Btn::BoostOn => self.do_act(Act::BoostOn),+ Btn::BoostOff => self.do_act(Act::BoostOff),Btn::More => {let items = self.more_menu();let r = self.ui.borrow().lay.as_ref().and_then(|l| l.buttons.iter().find(|x| x.1 == Btn::More).map(|x| x.0));@@ -821,6 +829,7 @@ impl App {Page::Services => vec![MI::Item(t!("Запустить службу", "Start service"), Act::SvcStart), MI::Item(t!("Остановить службу", "Stop service"), Act::SvcStop)],Page::Startup => vec![MI::Item(t!("Включить", "Enable"), Act::StartEnable), MI::Item(t!("Отключить", "Disable"), Act::StartDisable), MI::Sep, MI::Item(t!("Открыть расположение файла", "Open file location"), Act::OpenDir)],Page::Rules => vec![MI::Item(t!("Удалить правило", "Delete rule"), Act::RuleDelete)],+ Page::Boost => vec![MI::Item(t!("Включить", "Enable"), Act::BoostOn), MI::Item(t!("Выключить", "Disable"), Act::BoostOff)],_ => vec![],}}@@ -959,6 +968,7 @@ impl App {match page {Page::Services => return self.act_service(&row, act),Page::Startup => return self.act_startup(&row, act),+ Page::Boost => return self.act_boost(&row, act),Page::Rules => {if act == Act::RuleDelete {if let Ok(i) = row.key.parse::<usize>() {@@ -1128,6 +1138,25 @@ impl App {self.toast(&msg);}+ fn act_boost(&self, row: &Row, act: Act) {+ let on = match act {+ Act::BoostOn => true,+ Act::BoostOff => false,+ _ => return,+ };+ let Some(id) = crate::boost::Id::from_key(&row.key) else { return };+ if on && id == crate::boost::Id::Defender && !self.confirm(t!("Defender перестанет проверять кэши сборки и библиотеки игр (cargo, npm, pip, Steam, Epic…). Вредоносный файл в этих папках не будет найден при открытии. Включить?", "Defender will stop scanning build caches and game libraries (cargo, npm, pip, Steam, Epic…). A malicious file in those folders will not be caught when opened. Enable?")) {+ return;+ }+ // донор токена для программ, которые профиль запустит обратно: sihost.exe работает в каждом сеансе без повышения+ let donors: Vec<u32> = self.data.borrow().procs.iter().filter(|p| p.name.eq_ignore_ascii_case("sihost.exe")).map(|p| p.pid).collect();+ match crate::boost::start(id, on, donors) {+ Ok(()) => self.toast(&tf!("{}: выполняется…", "{}: running…", id.title())),+ Err(e) => self.toast(&format!("{}: {e}", id.title())),+ }+ self.rebuild();+ }+fn confirm(&self, text: &str) -> bool {let p = nwg::MessageParams { title: t!("Подтверждение", "Confirmation"), content: text, buttons: nwg::MessageButtons::YesNo, icons: nwg::MessageIcons::Warning };nwg::modal_message(&self.win, &p) == nwg::MessageChoice::Yesdiff --git a/plugins/rtaskmgr-win32/src/boost.rs b/plugins/rtaskmgr-win32/src/boost.rsnew file mode 100644index 0000000..947de06--- /dev/null+++ b/plugins/rtaskmgr-win32/src/boost.rs@@ -0,0 +1,437 @@+//! Страница «Ускорение»: профили «Игра»/«Работа», кэш памяти, лишние процессы оболочки и группы debloat+//! (апдейтеры, исключения Defender, NTFS, блокировка рекламы в hosts). Всё обратимо; долгие действия идут в фоновом потоке,+//! результат забирает такт окна (`take_done`).+use crate::sys;+use std::{+ fs,+ os::windows::process::CommandExt,+ path::PathBuf,+ process::Command,+ ptr::null_mut,+ sync::Mutex,+};+use winapi::shared::minwindef::HKEY;+use winapi::um::{winnt::{KEY_READ, REG_SZ}, winreg::*};++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Id {+ Game,+ Work,+ MemNow,+ MemAuto,+ Shell,+ Updaters,+ Defender,+ Ntfs,+ Dns,+}++pub const ALL: [Id; 9] = [Id::Game, Id::Work, Id::MemNow, Id::MemAuto, Id::Shell, Id::Updaters, Id::Defender, Id::Ntfs, Id::Dns];++impl Id {+ pub fn key(self) -> &'static str {+ match self {+ Id::Game => "game",+ Id::Work => "work",+ Id::MemNow => "memnow",+ Id::MemAuto => "memauto",+ Id::Shell => "shell",+ Id::Updaters => "updaters",+ Id::Defender => "defender",+ Id::Ntfs => "ntfs",+ Id::Dns => "dns",+ }+ }+ pub fn from_key(k: &str) -> Option<Id> {+ ALL.iter().copied().find(|i| i.key() == k)+ }+ pub fn title(self) -> &'static str {+ match self {+ Id::Game => t!("Профиль «Игра»", "'Game' profile"),+ Id::Work => t!("Профиль «Работа»", "'Work' profile"),+ Id::MemNow => t!("Очистить кэш памяти сейчас", "Clear memory cache now"),+ Id::MemAuto => t!("Очищать кэш памяти при нехватке", "Clear memory cache when it runs short"),+ Id::Shell => t!("Не запускать лишние процессы оболочки", "Block unneeded shell processes"),+ Id::Updaters => t!("Один обновлятор через winget", "One updater through winget"),+ Id::Defender => t!("Исключения Defender для сборок и игр", "Defender exclusions for builds and games"),+ Id::Ntfs => t!("Быстрее NTFS", "Faster NTFS"),+ Id::Dns => t!("Блокировать рекламу (hosts)", "Block ads (hosts)"),+ }+ }+ pub fn desc(self) -> &'static str {+ match self {+ Id::Game => t!("Останавливает Windows Update, BITS, оптимизацию доставки, печать, телеметрию; закрывает OneDrive, Teams, Dropbox, Google Drive, Phone Link, виджеты. «Выключить» всё запускает обратно.", "Stops Windows Update, BITS, Delivery Optimization, printing, telemetry; closes OneDrive, Teams, Dropbox, Google Drive, Phone Link, widgets. 'Disable' starts everything again."),+ Id::Work => t!("Закрывает Steam, Epic, Battle.net, EA, Ubisoft, GOG, Overwolf, Xbox и Game Bar, останавливает их службы. «Выключить» запускает лаунчеры обратно.", "Closes Steam, Epic, Battle.net, EA, Ubisoft, GOG, Overwolf, Xbox and Game Bar, stops their services. 'Disable' starts the launchers again."),+ Id::MemNow => t!("Сбрасывает список standby (кэш файлов, который никто не держит), как ISLC. Помогает от рывков в играх, когда свободной памяти нет.", "Drops the standby list (cached file data nobody holds), like ISLC. Helps against stutter in games when no memory is free."),+ Id::MemAuto => t!("Панель topbar каждые 10 с проверяет память и сбрасывает кэш, если свободно меньше 5% (не меньше 512 МБ), а кэш больше 1 ГБ; не чаще раза в минуту.", "The topbar checks memory every 10 s and drops the cache when less than 5% (at least 512 MB) is free and the cache holds over 1 GB; at most once a minute."),+ Id::Shell => t!("Меню «Пуск» Windows, виджеты и Связь с телефоном не запускаются (их заменяет topbar). Уведомления и ввод текста не трогаются.", "The Windows Start menu, widgets and Phone Link do not start (topbar replaces them). Notifications and text input are not touched."),+ Id::Updaters => t!("Отключает службы и задачи обновления Adobe, Mozilla, Dropbox, CCleaner, Opera, Apple, Zoom, OneDrive; раз в неделю winget обновляет все программы. Браузеры обновляются сами, как раньше.", "Disables updater services and tasks of Adobe, Mozilla, Dropbox, CCleaner, Opera, Apple, Zoom, OneDrive; winget updates every app once a week. Browsers keep updating themselves."),+ Id::Defender => t!("Defender перестаёт проверять кэши cargo, rustup, npm, pip, NuGet, Gradle и библиотеки Steam/Epic, а также cargo.exe и rustc.exe. Сборка и загрузка игр быстрее, но эти папки не сканируются.", "Defender stops scanning the caches of cargo, rustup, npm, pip, NuGet, Gradle and the Steam/Epic libraries, and cargo.exe and rustc.exe. Builds and game loading get faster, but those folders are not scanned."),+ Id::Ntfs => t!("NTFS не пишет время последнего доступа при каждом чтении и не создаёт короткие имена 8.3. Действует после перезагрузки.", "NTFS stops writing the last-access time on every read and creating 8.3 short names. Takes effect after a reboot."),+ Id::Dns => t!("Около 170 рекламных и следящих доменов ведут в никуда через файл hosts (домены Microsoft не трогаются).", "About 170 ad and tracker domains lead nowhere through the hosts file (Microsoft domains are left alone)."),+ }+ }+ fn debloat_group(self) -> Option<&'static str> {+ matches!(self, Id::Updaters | Id::Defender | Id::Ntfs | Id::Dns).then(|| self.key())+ }+}++#[derive(Clone, PartialEq, Debug)]+pub enum State {+ On,+ Off,+ Busy,+ Info(String), // разовое действие: что сейчас+ Unavailable(String), // почему нельзя+}++static BUSY: Mutex<Vec<Id>> = Mutex::new(vec![]);+static DONE: Mutex<Vec<String>> = Mutex::new(vec![]);++pub fn take_done() -> Vec<String> {+ std::mem::take(&mut *DONE.lock().unwrap())+}++fn program_files() -> PathBuf {+ PathBuf::from(std::env::var_os("ProgramFiles").unwrap_or_else(|| r"C:\Program Files".into()))+}++fn program_data() -> PathBuf {+ PathBuf::from(std::env::var_os("ProgramData").unwrap_or_else(|| r"C:\ProgramData".into()))+}++fn topbar_installed() -> bool {+ program_files().join(r"topbar\topbar.exe").is_file()+}++/// debloat.exe: установленный плагин или копия рядом с диспетчером (её кладёт установщик).+fn debloat_exe() -> Option<PathBuf> {+ let near = std::env::current_exe().ok().and_then(|e| Some(e.parent()?.join("debloat.exe")));+ [Some(program_files().join(r"debloat\debloat.exe")), near].into_iter().flatten().find(|p| p.is_file())+}++fn debloat_applied(group: &str) -> bool {+ program_data().join("winrust-debloat").join(format!("undo-{group}.txt")).is_file()+}++pub fn state(id: Id, is_admin: bool) -> State {+ if BUSY.lock().unwrap().contains(&id) {+ return State::Busy;+ }+ if !is_admin {+ return State::Unavailable(t!("нужен администратор", "administrator needed").into());+ }+ let on = |b: bool| if b { State::On } else { State::Off };+ match id {+ Id::Game | Id::Work => on(active_profile() == Some(id)),+ Id::MemNow => match winrust_common::mem::lists() {+ Some(l) => State::Info(tf!("свободно {}, кэш {}", "free {}, cache {}", crate::ui::fmt_mem(l.free), crate::ui::fmt_mem(l.standby))),+ None => State::Unavailable(t!("нет права SeProfileSingleProcess", "no SeProfileSingleProcess right").into()),+ },+ Id::MemAuto if !topbar_installed() => State::Unavailable(t!("нужна панель topbar", "needs the topbar").into()),+ Id::MemAuto => on(winrust_common::mem::auto_on()),+ Id::Shell if !topbar_installed() => State::Unavailable(t!("нужна панель topbar (без неё не будет меню «Пуск»)", "needs the topbar (no Start menu without it)").into()),+ Id::Shell => on(shell_blocked()),+ _ => match (id.debloat_group(), debloat_exe()) {+ (Some(g), Some(_)) => on(debloat_applied(g)),+ _ => State::Unavailable(t!("нет debloat.exe (переустановите диспетчер задач)", "no debloat.exe (reinstall the task manager)").into()),+ },+ }+}++/// Запускает включение/выключение в фоне. Err — сразу понятно, что нельзя (текст для подсказки).+pub fn start(id: Id, on: bool, donors: Vec<u32>) -> Result<(), String> {+ match state(id, true) {+ State::Busy => return Err(t!("уже выполняется", "already running").into()),+ State::Unavailable(why) => return Err(why),+ _ => {}+ }+ if id == Id::MemNow && !on {+ return Err(t!("это разовое действие: выключать нечего", "a one-time action: nothing to disable").into());+ }+ BUSY.lock().unwrap().push(id);+ std::thread::spawn(move || {+ let r = run(id, on, &donors);+ BUSY.lock().unwrap().retain(|&x| x != id);+ let head = id.title();+ DONE.lock().unwrap().push(match r {+ Ok(msg) => format!("{head}: {msg}"),+ Err(e) => tf!("{head}: ошибка — {e}", "{head}: error - {e}"),+ });+ });+ Ok(())+}++fn run(id: Id, on: bool, donors: &[u32]) -> Result<String, String> {+ match id {+ Id::Game | Id::Work if on => profile_on(id, donors),+ Id::Game | Id::Work => profile_off(donors),+ Id::MemNow => {+ let before = winrust_common::mem::lists();+ winrust_common::mem::purge_standby().map_err(|st| tf!("NTSTATUS 0x{:08X}", "NTSTATUS 0x{:08X}", st as u32))?;+ let freed = match (before, winrust_common::mem::lists()) {+ (Some(a), Some(b)) => b.free.saturating_sub(a.free),+ _ => 0,+ };+ Ok(tf!("освобождено {}", "{} freed", crate::ui::fmt_mem(freed)))+ }+ Id::MemAuto => {+ let f = winrust_common::mem::auto_file().ok_or("ProgramData?")?;+ if on {+ fs::create_dir_all(f.parent().unwrap()).and_then(|_| fs::write(&f, "1")).map_err(|e| e.to_string())?;+ Ok(t!("включено (работает, пока запущена панель)", "on (works while the bar runs)").into())+ } else {+ let _ = fs::remove_file(&f);+ Ok(t!("выключено", "off").into())+ }+ }+ Id::Shell => shell_set(on),+ _ => {+ let exe = debloat_exe().ok_or("debloat.exe")?;+ let g = id.debloat_group().unwrap();+ let o = Command::new(&exe).args([if on { "--apply" } else { "--undo" }, g]).creation_flags(0x0800_0000).output().map_err(|e| e.to_string())?;+ if o.status.success() {+ Ok(if on { t!("включено", "on") } else { t!("возвращено как было", "restored") }.into())+ } else {+ let err = String::from_utf8_lossy(&o.stderr);+ Err(err.lines().last().unwrap_or("debloat").to_string())+ }+ }+ }+}++/// Возвращает всё включённое здесь (удаление диспетчера). Синхронно; список ошибок.+pub fn undo_all() -> Vec<String> {+ let mut errs = vec![];+ for id in ALL {+ let applied = match id {+ Id::Game => active_profile().is_some(),+ Id::Work | Id::MemNow => false, // один файл профиля на оба; очистка — разовое действие+ Id::MemAuto => winrust_common::mem::auto_on(),+ Id::Shell => SHELL_EXES.iter().any(|e| debugger(e).is_some_and(|d| ours(&d))),+ _ => id.debloat_group().is_some_and(debloat_applied),+ };+ if applied && let Err(e) = run(id, false, &[]) {+ errs.push(format!("{}: {e}", id.title()));+ }+ }+ errs+}++// ---------- профили ----------++/// (имя процесса, аргументы для запуска обратно; None — не запускать: помощник или пакетное приложение, оно встанет само)+type ProcSpec = (&'static str, Option<&'static str>);++const GAME_SVCS: &[&str] = &["wuauserv", "BITS", "DoSvc", "UsoSvc", "Spooler", "WSearch", "DiagTrack", "MapsBroker", "WerSvc"];+const GAME_PROCS: &[ProcSpec] = &[+ ("onedrive.exe", Some("/background")),+ ("teams.exe", None),+ ("ms-teams.exe", None),+ ("dropbox.exe", Some("/systemstartup")),+ ("googledrivefs.exe", Some("")),+ ("phoneexperiencehost.exe", None),+ ("widgets.exe", None),+ ("adobecollabsync.exe", None),+ ("creative cloud.exe", None),+];+const WORK_SVCS: &[&str] = &["Steam Client Service", "XblAuthManager", "XblGameSave", "XboxNetApiSvc", "EABackgroundService", "EpicOnlineServices"];+const WORK_PROCS: &[ProcSpec] = &[+ ("steam.exe", Some("-silent")),+ ("steamwebhelper.exe", None),+ ("epicgameslauncher.exe", Some("-silent")),+ ("epicwebhelper.exe", None),+ ("battle.net.exe", Some("")),+ ("eadesktop.exe", Some("")),+ ("upc.exe", Some("")),+ ("galaxyclient.exe", Some("")),+ ("overwolf.exe", None),+ ("xboxpcapp.exe", None),+ ("gamebar.exe", None),+ ("gamebarftserver.exe", None),+];++fn profile_file() -> PathBuf {+ program_data().join(r"WinRust\profile.txt")+}++/// Файл профиля: первая строка game/work, дальше `svc|<имя>` (остановлено нами) и `run|<команда>` (закрыто нами).+pub fn parse_profile(text: &str) -> Option<(Id, Vec<String>, Vec<String>)> {+ let mut lines = text.lines();+ let id = match lines.next()?.trim() {+ "game" => Id::Game,+ "work" => Id::Work,+ _ => return None,+ };+ let (mut svcs, mut runs) = (vec![], vec![]);+ for l in lines {+ if let Some(s) = l.strip_prefix("svc|") {+ svcs.push(s.to_string());+ } else if let Some(r) = l.strip_prefix("run|") {+ runs.push(r.to_string());+ }+ }+ Some((id, svcs, runs))+}++fn active_profile() -> Option<Id> {+ fs::read_to_string(profile_file()).ok().and_then(|t| parse_profile(&t)).map(|p| p.0)+}++/// Все процессы: (PID, имя в нижнем регистре, путь к exe).+fn processes() -> Vec<(u32, String, Option<String>)> {+ use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};+ let Ok(mut s) = System::new() else { return vec![] };+ s.refresh_processes_specifics(ProcessesToUpdate::All, true, ProcessRefreshKind::nothing().with_exe(UpdateKind::Always));+ s.processes().iter().map(|(pid, p)| (pid.as_u32(), p.name().to_string_lossy().to_lowercase(), p.exe().map(|e| e.display().to_string()))).collect()+}++fn profile_on(id: Id, donors: &[u32]) -> Result<String, String> {+ if active_profile().is_some() {+ profile_off(donors)?;+ }+ let (svcs, procs) = if id == Id::Game { (GAME_SVCS, GAME_PROCS) } else { (WORK_SVCS, WORK_PROCS) };+ let mut text = format!("{}\n", id.key());+ let running: Vec<String> = sys::services().into_iter().filter(|s| s.running).map(|s| s.name).collect();+ let mut stopped = 0;+ for s in svcs {+ if running.iter().any(|r| r.eq_ignore_ascii_case(s)) && sys::service_ctl(s, false).is_ok() {+ text += &format!("svc|{s}\n");+ stopped += 1;+ }+ }+ let mut closed = 0;+ let mut runs: Vec<String> = vec![];+ for (pid, name, exe) in processes() {+ let Some((_, again)) = procs.iter().find(|p| p.0 == name) else { continue };+ if !sys::kill(pid) {+ continue;+ }+ closed += 1;+ if let (Some(args), Some(exe)) = (again, exe) {+ let cmd = if args.is_empty() { format!("\"{exe}\"") } else { format!("\"{exe}\" {args}") };+ if !runs.contains(&cmd) {+ runs.push(cmd);+ }+ }+ }+ for r in &runs {+ text += &format!("run|{r}\n");+ }+ let f = profile_file();+ fs::create_dir_all(f.parent().unwrap()).and_then(|_| fs::write(&f, text)).map_err(|e| e.to_string())?;+ Ok(tf!("остановлено служб: {stopped}, закрыто процессов: {closed}", "{stopped} services stopped, {closed} processes closed"))+}++fn profile_off(donors: &[u32]) -> Result<String, String> {+ let f = profile_file();+ let Some((_, svcs, runs)) = fs::read_to_string(&f).ok().and_then(|t| parse_profile(&t)) else {+ return Ok(t!("профиль не был включён", "no profile was on").into());+ };+ let started = svcs.iter().filter(|s| sys::service_ctl(s, true).is_ok()).count();+ let mut launched = 0;+ for r in &runs {+ if sys::run_unelevated(donors, r) {+ launched += 1;+ } else if let Some(exe) = r.strip_prefix('"').and_then(|x| x.split('"').next()) {+ // без донора: explorer.exe запускает программу с обычными правами, но без аргументов+ launched += Command::new("explorer.exe").arg(exe).spawn().is_ok() as usize;+ }+ }+ fs::remove_file(&f).map_err(|e| e.to_string())?;+ Ok(tf!("запущено служб: {started}, программ: {launched}", "{started} services and {launched} programs started again"))+}++// ---------- процессы оболочки ----------++const SHELL_EXES: [&str; 4] = ["StartMenuExperienceHost.exe", "Widgets.exe", "WidgetService.exe", "PhoneExperienceHost.exe"];+const IFEO: &str = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options";++/// Вместо процесса Windows запускает systray.exe: он ничего не показывает и сразу завершается.+fn noop_debugger() -> String {+ format!(r"{}\System32\systray.exe", std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into()))+}++fn w(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(Some(0)).collect()+}++fn debugger(exe: &str) -> Option<String> {+ let mut k: HKEY = null_mut();+ if unsafe { RegOpenKeyExW(HKEY_LOCAL_MACHINE, w(&format!(r"{IFEO}\{exe}")).as_ptr(), 0, KEY_READ, &mut k) } != 0 {+ return None;+ }+ let mut buf = [0u16; 1024];+ let mut len = (buf.len() * 2) as u32;+ let mut ty = 0u32;+ let rc = unsafe { RegQueryValueExW(k, w("Debugger").as_ptr(), null_mut(), &mut ty, buf.as_mut_ptr() as *mut u8, &mut len) };+ unsafe { RegCloseKey(k) };+ (rc == 0 && ty == REG_SZ).then(|| String::from_utf16_lossy(&buf[..len as usize / 2]).trim_end_matches('\0').to_string())+}++fn ours(v: &str) -> bool {+ v.to_lowercase().ends_with(r"\system32\systray.exe")+}++fn shell_blocked() -> bool {+ SHELL_EXES.iter().all(|e| debugger(e).is_some_and(|d| ours(&d)))+}++fn shell_set(on: bool) -> Result<String, String> {+ let mut n = 0;+ for exe in SHELL_EXES {+ let key = w(&format!(r"{IFEO}\{exe}"));+ let cur = debugger(exe);+ let rc = if on {+ if cur.as_deref().is_some_and(|d| !ours(d)) {+ continue; // чужой Debugger (отладчик, другая программа): не наш+ }+ let v = w(&noop_debugger());+ let rc = unsafe { RegSetKeyValueW(HKEY_LOCAL_MACHINE, key.as_ptr(), w("Debugger").as_ptr(), REG_SZ, v.as_ptr() as *const _, (v.len() * 2) as u32) };+ let _ = Command::new("taskkill.exe").args(["/f", "/im", exe]).creation_flags(0x0800_0000).output();+ rc+ } else if cur.as_deref().is_some_and(ours) {+ unsafe { RegDeleteKeyValueW(HKEY_LOCAL_MACHINE, key.as_ptr(), w("Debugger").as_ptr()) }+ } else {+ continue;+ };+ if rc != 0 {+ return Err(tf!("{exe}: ошибка реестра {rc}", "{exe}: registry error {rc}"));+ }+ n += 1;+ }+ Ok(if on { tf!("заблокировано процессов: {n}", "{n} processes blocked") } else { tf!("разблокировано процессов: {n}", "{n} processes unblocked") })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn profile_file_round_trip() {+ let t = "game\nsvc|wuauserv\nrun|\"C:\\Users\\a\\OneDrive.exe\" /background\nsvc|BITS\n";+ let (id, svcs, runs) = parse_profile(t).unwrap();+ assert_eq!(id, Id::Game);+ assert_eq!(svcs, ["wuauserv", "BITS"]);+ assert_eq!(runs, ["\"C:\\Users\\a\\OneDrive.exe\" /background"]);+ assert_eq!(parse_profile("junk\n"), None);+ assert_eq!(parse_profile(""), None);+ }++ #[test]+ fn keys_round_trip_and_lists_are_lower_case() {+ for id in ALL {+ assert_eq!(Id::from_key(id.key()), Some(id));+ assert!(!id.title().is_empty() && !id.desc().is_empty());+ }+ for (p, _) in GAME_PROCS.iter().chain(WORK_PROCS) {+ assert_eq!(*p, p.to_lowercase(), "имена процессов сравниваются в нижнем регистре");+ }+ assert!(ours(r"C:\WINDOWS\System32\systray.exe") && !ours("cmd.exe /c exit"));+ }++ #[test]+ fn needs_admin_without_it() {+ assert!(matches!(state(Id::Game, false), State::Unavailable(_)));+ }+}diff --git a/plugins/rtaskmgr-win32/src/data.rs b/plugins/rtaskmgr-win32/src/data.rsindex d3b04a9..f82a929 100644--- a/plugins/rtaskmgr-win32/src/data.rs+++ b/plugins/rtaskmgr-win32/src/data.rs@@ -146,6 +146,12 @@ pub struct Data {/// Температуру GPU читаем, пока открыта страница GPU (или всегда, если включено в параметрах):/// опрос драйвера может будить дискретную видеокарту ноутбука.pub want_gpu_temp: bool,+ cpu_times: Option<sys::CpuTimes>,+ /// Доля времени ЦП в DPC и прерываниях (работа драйверов), % за последний такт+ pub dpc_pct: f32,+ pub intr_pct: f32,+ /// Зависшие окна: (PID, заголовок)+ pub hung: Vec<(u32, String)>,}pub fn timestamp() -> String {@@ -208,6 +214,10 @@ impl Data {nvml_tried: false,user_cache: HashMap::new(),want_gpu_temp: false,+ cpu_times: None,+ dpc_pct: 0.0,+ intr_pct: 0.0,+ hung: vec![],}}@@ -251,6 +261,12 @@ impl Data {}self.sample = self.perf.as_mut().map(|p| p.sample()).unwrap_or_default();self.meminfo = perf::mem_info();+ let now = sys::cpu_times();+ if let (Some(a), Some(b)) = (self.cpu_times, now) {+ (self.dpc_pct, self.intr_pct) = sys::dpc_share(a, b);+ }+ self.cpu_times = now;+ self.hung = sys::hung_windows();if self.want_gpu_temp || self.cfg.gpu_temp_always {for g in self.gpus.iter_mut() {g.temp = gpu::temperature(g.adapter.luid).or_else(|| {@@ -537,13 +553,63 @@ impl Data {if self.cpu_total > 90.0 {out.push(t!("ЦП почти полностью занят — отсортируйте процессы по ЦП, чтобы увидеть виновника.", "CPU is almost fully used - sort processes by CPU to see the culprit.").into());}+ for (pid, title) in &self.hung {+ let name = self.procs.iter().find(|p| p.pid == *pid).map_or_else(|| format!("PID {pid}"), |p| p.name.clone());+ out.push(tf!("Не отвечает: «{title}» ({name}). Окно зависло: подождите или снимите задачу на странице «Процессы».", "Not responding: '{title}' ({name}). The window hangs: wait or end the task on the 'Processes' page."));+ }+ let drv = self.dpc_pct + self.intr_pct;+ if drv >= 5.0 {+ out.push(tf!("Драйверы заняли {:.1}% времени ЦП (DPC {:.1}%, прерывания {:.1}%; норма — до 2%). Так выглядит «драйвер тормозит систему»: трещит звук, дёргается мышь, проседают кадры. Чаще всего виноваты Wi-Fi/сеть, звук, видеодрайвер или USB: обновите их или отключайте по очереди в диспетчере устройств.", "Drivers took {:.1}% of CPU time (DPC {:.1}%, interrupts {:.1}%; normal is under 2%). This is what 'a driver slows the system down' looks like: crackling audio, jerky mouse, frame drops. Usually Wi-Fi/network, audio, graphics or USB drivers: update them or disable them one by one in Device Manager.", drv, self.dpc_pct, self.intr_pct));+ }+ if self.sample.disk_ms > 50.0 && self.sample.disk_active > 50.0 {+ out.push(tf!("Диск отвечает медленно: {:.0} мс на запрос при загрузке {:.0}% (у SSD норма — единицы мс). Если это HDD, программы и игры с него будут грузиться долго; если SSD — проверьте его здоровье и свободное место.", "The disk responds slowly: {:.0} ms per request at {:.0}% busy (an SSD normally takes a few ms). On an HDD apps and games load slowly; on an SSD check its health and free space.", self.sample.disk_ms, self.sample.disk_active));+ }+ let total = self.sys.total_memory();+ if total > 0 && self.sample.mem_free < total / 20 && self.sample.mem_standby > 1 << 30 {+ out.push(tf!("Свободной памяти почти нет ({}), а кэш (standby) занимает {}. В играх это даёт рывки: включите «Очистить кэш памяти» на странице «Ускорение».", "Almost no free memory ({}) while the standby cache holds {}. In games this shows as stutter: use 'Clear memory cache' on the 'Speed' page.", crate::ui::fmt_mem(self.sample.mem_free), crate::ui::fmt_mem(self.sample.mem_standby)));+ }if out.is_empty() {out.push(t!("Всё в порядке: ни один процесс не потребляет заметно больше обычного.", "All good: no process uses noticeably more than usual.").into());}+ if self.cpu_times.is_some() && drv < 5.0 {+ out.push(tf!("Драйверы в норме: DPC {:.1}%, прерывания {:.1}% времени ЦП.", "Drivers are fine: DPC {:.1}%, interrupts {:.1}% of CPU time.", self.dpc_pct, self.intr_pct));+ }+ if self.is_admin {+ out.extend(boot_hint(crate::startup::boot_log()));+ }out}}+/// Последние загрузки Windows и что их замедлило (журнал Diagnostics-Performance).+pub fn boot_hint(log: &crate::startup::BootLog) -> Option<String> {+ let s = |ms: u32| crate::model::dec(ms as f64 / 1000.0, 0);+ let first = log.boots.first()?;+ let times: Vec<String> = log.boots.iter().take(5).map(|b| s(b.1)).collect();+ let mut t = tf!("Загрузка Windows: последняя {} с ({}), до рабочего стола {} с. Предыдущие: {} с.", "Windows boot: last {} s ({}), {} s to the desktop. Before that: {} s.", s(first.1), first.0, s(first.2), times[1..].join(", "));+ if times.len() == 1 {+ t = tf!("Загрузка Windows: {} с ({}), до рабочего стола {} с.", "Windows boot: {} s ({}), {} s to the desktop.", s(first.1), first.0, s(first.2));+ }+ let slow: Vec<String> = log.slow.iter().take(5).map(|x| format!("{} (+{} с)", if x.1.is_empty() { &x.0 } else { &x.1 }, crate::model::dec(x.2 as f64 / 1000.0, 1))).collect();+ if !slow.is_empty() {+ t += &tf!(" Больше всего замедляли: {}. Отключить можно на странице «Автозагрузка» (колонка «Замедляет загрузку»).", " The worst slowdowns: {}. Disable them on the 'Startup' page ('Slows boot by' column).", slow.join(", "));+ }+ Some(t)+}++#[cfg(test)]+mod boot_tests {+ #[test]+ fn boot_hint_text() {+ let mut log = crate::startup::BootLog::default();+ assert_eq!(super::boot_hint(&log), None);+ log.boots = vec![("2026-11-20 08:15".into(), 41_000, 15_000), ("2026-11-19 09:00".into(), 52_400, 18_000)];+ log.slow = vec![("onedrive.exe".into(), "Microsoft OneDrive".into(), 2100)];+ let h = super::boot_hint(&log).unwrap();+ assert!(h.contains("последняя 41 с") && h.contains("Предыдущие: 52 с") && h.contains("Microsoft OneDrive (+2,1 с)"), "{h}");+ }+}+/// Размер системного диска, байт.fn disk_capacity() -> u64 {use sysinfo::Disks;diff --git a/plugins/rtaskmgr-win32/src/main.rs b/plugins/rtaskmgr-win32/src/main.rsindex 645e38e..845d97f 100644--- a/plugins/rtaskmgr-win32/src/main.rs+++ b/plugins/rtaskmgr-win32/src/main.rs@@ -2,6 +2,7 @@#[macro_use]extern crate winrust_common;mod app;+mod boost;mod data;mod draw;mod gpu;@@ -72,6 +73,14 @@ fn main() {return net_selftest(&out);}let args: Vec<String> = std::env::args().skip(1).collect();+ // установщик при удалении: вернуть всё, что включили на странице «Ускорение» (код выхода 1 = что-то не вернулось)+ if args.first().is_some_and(|a| a == "--undo-speed") {+ let errs = boost::undo_all();+ for e in &errs {+ eprintln!("{e}");+ }+ std::process::exit(!errs.is_empty() as i32);+ }// повторный вызов с правами администратора из start_real_taskmgr: только открыть системный диспетчерif args.first().is_some_and(|a| a == "--real-taskmgr") {sys::start_real_taskmgr(&args[1..].join(" "), false);diff --git a/plugins/rtaskmgr-win32/src/model.rs b/plugins/rtaskmgr-win32/src/model.rsindex 4720e10..cdf4006 100644--- a/plugins/rtaskmgr-win32/src/model.rs+++ b/plugins/rtaskmgr-win32/src/model.rs@@ -14,10 +14,11 @@ pub enum Page {Insights,Rules,Settings,+ Boost,}/// Пункты боковой панели: страница, символ значка, подпись.-pub static NAV: std::sync::LazyLock<[(Page, char, &'static str); 10]> = std::sync::LazyLock::new(|| [+pub static NAV: std::sync::LazyLock<[(Page, char, &'static str); 11]> = std::sync::LazyLock::new(|| [(Page::Processes, '\u{E9D9}', t!("Процессы", "Processes")),(Page::Performance, '\u{E9D2}', t!("Производительность", "Performance")),(Page::History, '\u{E81C}', t!("Журнал приложений", "App history")),@@ -28,6 +29,8 @@ pub static NAV: std::sync::LazyLock<[(Page, char, &'static str); 10]> = std::syn(Page::Insights, '\u{E946}', t!("Что тормозит", "What's slow")),(Page::Rules, '\u{E7BA}', t!("Правила", "Rules")),(Page::Settings, '\u{E713}', t!("Параметры", "Settings")),+ // последней: настройки хранят номер открытой страницы, вставка в середину сдвинула бы его+ (Page::Boost, '\u{E945}', t!("Ускорение", "Speed")),]);pub fn page_title(p: Page) -> &'static str {@@ -89,8 +92,9 @@ pub fn columns(p: Page) -> Vec<Col> {],Page::Details => vec![col(t!("Имя", "Name"), 220.0, Left), col("PID", 70.0, Right), col(t!("Состояние", "Status"), 100.0, Left), col(t!("ЦП", "CPU"), 70.0, Right), col(t!("Память", "Memory"), 110.0, Right), col(t!("Диск", "Disk"), 100.0, Right), col(t!("Командная строка", "Command line"), 0.0, Left)],Page::Services => vec![col(t!("Имя", "Name"), 200.0, Left), col("PID", 70.0, Right), col(t!("Описание", "Description"), 360.0, Left), col(t!("Состояние", "Status"), 110.0, Left)],- Page::Startup => vec![col(t!("Имя", "Name"), 240.0, Left), col(t!("Издатель", "Publisher"), 200.0, Left), col(t!("Состояние", "Status"), 110.0, Left), col(t!("Команда", "Command"), 0.0, Left)],+ Page::Startup => vec![col(t!("Имя", "Name"), 240.0, Left), col(t!("Издатель", "Publisher"), 180.0, Left), col(t!("Состояние", "Status"), 100.0, Left), col(t!("Замедляет загрузку", "Slows boot by"), 150.0, Right), col(t!("Команда", "Command"), 0.0, Left)],Page::History => vec![col(t!("Время", "Time"), 150.0, Left), col(t!("ЦП %", "CPU %"), 80.0, Right), col(t!("Память %", "Memory %"), 90.0, Right), col(t!("Ввод-вывод КБ/с", "I/O KB/s"), 130.0, Right), col(t!("Сеть КБ/с", "Network KB/s"), 110.0, Right), col(t!("Основной потребитель", "Top consumer"), 0.0, Left)],+ Page::Boost => vec![col(t!("Что", "What"), 320.0, Left), col(t!("Состояние", "Status"), 220.0, Left), col(t!("Что делает", "What it does"), 0.0, Left)],Page::Rules => vec![col(t!("Процесс", "Process"), 220.0, Left), col(t!("Условие", "Condition"), 280.0, Left), col(t!("Действие", "Action"), 200.0, Left), col(t!("Сработало, раз", "Times triggered"), 130.0, Right)],_ => vec![],}@@ -334,17 +338,46 @@ pub fn build_rows(d: &Data, c: &BuildCtx) -> Vec<Row> {.map(|s| {let exe = exe_from_command(&s.command);let company = exe.as_deref().and_then(|e| d.res.get(e)).map(|r| r.company).unwrap_or_default();+ // без администратора журнал загрузки не читается: «нет данных», а не «не замедляет»+ let impact = if d.is_admin { crate::startup::boot_impact(s, crate::startup::boot_log()) } else { None };+ let impact_txt = match impact {+ Some(ms) => tf!("+{} с", "+{} s", dec(ms as f64 / 1000.0, 1)),+ None if d.is_admin => "—".into(),+ None => t!("нужен администратор", "administrator needed").into(),+ };Row {key: s.key(),icon_path: exe,- cells: vec![s.name.clone(), company, (if s.enabled { t!("Включено", "Enabled") } else { t!("Отключено", "Disabled") }).into(), s.command.clone()],- sortv: vec![f64::NAN; 4],- heat: vec![None; 4],+ cells: vec![s.name.clone(), company, (if s.enabled { t!("Включено", "Enabled") } else { t!("Отключено", "Disabled") }).into(), impact_txt, s.command.clone()],+ sortv: vec![f64::NAN, f64::NAN, f64::NAN, impact.unwrap_or(0) as f64, f64::NAN],+ heat: vec![None; 5],tip: tf!("Источник: {}.{}", "Source: {}.{}", s.source_label(), if s.needs_admin() && !d.is_admin { t!(" Для изменения нужны права администратора.", " Administrator rights are needed to change it.") } else { "" }),..Default::default()}}).collect(),+ Page::Boost => crate::boost::ALL+ .iter()+ .map(|&id| {+ use crate::boost::State;+ let st = crate::boost::state(id, d.is_admin);+ let text = match &st {+ State::On => t!("Включено", "On").to_string(),+ State::Off => t!("Выключено", "Off").to_string(),+ State::Busy => t!("Выполняется…", "Running…").to_string(),+ State::Info(s) => s.clone(),+ State::Unavailable(s) => tf!("Недоступно: {s}", "Unavailable: {s}"),+ };+ Row {+ key: id.key().into(),+ cells: vec![id.title().into(), text, id.desc().into()],+ sortv: vec![f64::NAN; 3],+ heat: vec![None; 3],+ tip: id.desc().into(),+ ..Default::default()+ }+ })+ .collect(),Page::History => d.hist.iter()@@ -376,7 +409,7 @@ pub fn build_rows(d: &Data, c: &BuildCtx) -> Vec<Row> {.collect(),_ => vec![],};- if !matches!(c.page, Page::Processes | Page::Users) {+ if !matches!(c.page, Page::Processes | Page::Users | Page::Boost) {let (ci, desc) = c.sort;rows.sort_by(|a, b| {let o = cmp_cells(a, b, ci);diff --git a/plugins/rtaskmgr-win32/src/perf.rs b/plugins/rtaskmgr-win32/src/perf.rsindex ed93723..9ee6425 100644--- a/plugins/rtaskmgr-win32/src/perf.rs+++ b/plugins/rtaskmgr-win32/src/perf.rs@@ -72,7 +72,6 @@ pub struct Sample {pub disk_active: f32, // %pub disk_read: f64, // байт/сpub disk_write: f64,- #[cfg_attr(not(test), allow(dead_code))] // only the self-test prints itpub disk_ms: f32, // средний отклик, мсpub gpu_total: f32,pub gpu_types: HashMap<String, f32>, // загрузка по типам движков: 3D, Copy, VideoEncode, VideoDecode ...diff --git a/plugins/rtaskmgr-win32/src/startup.rs b/plugins/rtaskmgr-win32/src/startup.rsindex 0dc0568..2851621 100644--- a/plugins/rtaskmgr-win32/src/startup.rs+++ b/plugins/rtaskmgr-win32/src/startup.rs@@ -4,7 +4,7 @@ use std::{fs, path::PathBuf, ptr::null_mut};use winapi::shared::minwindef::HKEY;use winapi::um::{sysinfoapi::GetSystemTimeAsFileTime,- winnt::{KEY_READ, KEY_SET_VALUE, REG_BINARY, REG_EXPAND_SZ, REG_SZ},+ winnt::{KEY_READ, KEY_SET_VALUE, REG_BINARY, REG_DWORD, REG_EXPAND_SZ, REG_SZ},winreg::*,};@@ -28,19 +28,33 @@ static SOURCES: std::sync::LazyLock<[Source; 5]> = std::sync::LazyLock::new(|| []);pub struct Item {- pub name: String, // имя значения реестра или имя файла+ pub name: String, // имя значения реестра или имя файла; путь задачи; имя службыpub command: String,- pub source: usize,+ pub source: usize, // индекс в SOURCES, либо TASK / SERVICEpub enabled: bool,}+/// Задача планировщика, запускаемая при входе или загрузке (вне папки \Microsoft).+pub const TASK: usize = 5;+/// Сторонняя служба с автозапуском (не из папки Windows).+pub const SERVICE: usize = 6;+impl Item {pub fn source_label(&self) -> &'static str {- SOURCES[self.source].label+ match self.source {+ TASK => t!("Планировщик заданий (при входе или загрузке)", "Task Scheduler (at sign-in or boot)"),+ SERVICE => t!("Служба с автозапуском (отключение = запуск вручную)", "Auto-start service (disabling = manual start)"),+ i => SOURCES[i].label,+ }}- /// Для HKLM нужны права администратора.+ /// Для HKLM, задач и служб нужны права администратора.pub fn needs_admin(&self) -> bool {- SOURCES[self.source].hklm+ self.source >= TASK || SOURCES[self.source].hklm+ }+ /// Имя исполняемого файла в нижнем регистре (для сопоставления с журналом загрузки).+ pub fn exe_name(&self) -> Option<String> {+ let exe = crate::model::exe_from_command(&self.command)?;+ Some(exe.rsplit(['\\', '/']).next()?.to_lowercase())}pub fn key(&self) -> String {format!("{}|{}", self.source, self.name)@@ -103,7 +117,8 @@ fn startup_dir(hklm: bool) -> Option<PathBuf> {}pub fn list() -> Vec<Item> {- let mut out = vec![];+ let mut out = tasks();+ out.extend(services());for (i, s) in SOURCES.iter().enumerate() {match s.run {Some(path) => {@@ -140,6 +155,26 @@ fn approved_value(enabled: bool, filetime: u64) -> [u8; 12] {/// Err(код Win32) — например 5 (нет прав) для HKLM без администратора.pub fn set_enabled(it: &Item, on: bool) -> Result<(), u32> {+ match it.source {+ TASK => return cmd_ok("schtasks.exe", &["/change", "/tn", &it.name, if on { "/enable" } else { "/disable" }]),+ SERVICE => {+ cmd_ok("sc.exe", &["config", &it.name, "start=", if on { "auto" } else { "demand" }])?;+ // отключённая здесь служба остаётся в списке: иначе её не включить обратно+ if let Some(k) = create(HKEY_LOCAL_MACHINE, SVC_OFF) {+ unsafe {+ if on {+ RegDeleteValueW(k, w(&it.name).as_ptr());+ } else {+ let one = 1u32;+ RegSetValueExW(k, w(&it.name).as_ptr(), 0, REG_DWORD, &one as *const u32 as *const u8, 4);+ }+ RegCloseKey(k);+ }+ }+ return Ok(());+ }+ _ => {}+ }let s = &SOURCES[it.source];let mut ft = unsafe { std::mem::zeroed() };unsafe { GetSystemTimeAsFileTime(&mut ft) };@@ -157,6 +192,218 @@ pub fn set_enabled(it: &Item, on: bool) -> Result<(), u32> {if rc == 0 { Ok(()) } else { Err(rc as u32) }}+// ---------- задачи планировщика ----------++/// Код 5 (нет прав), если команда не удалась: schtasks и sc без администратора отказывают именно так.+fn cmd_ok(prog: &str, args: &[&str]) -> Result<(), u32> {+ use std::os::windows::process::CommandExt;+ match std::process::Command::new(prog).args(args).creation_flags(0x0800_0000 /*CREATE_NO_WINDOW*/).output() {+ Ok(o) if o.status.success() => Ok(()),+ Ok(_) => Err(5),+ Err(e) => Err(e.raw_os_error().unwrap_or(1) as u32),+ }+}++fn xml_unescape(s: &str) -> String {+ s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&")+}++/// Текст первого элемента `<tag>` внутри `xml`.+fn tag<'a>(xml: &'a str, tag: &str) -> Option<&'a str> {+ let open = format!("<{tag}>");+ let rest = &xml[xml.find(&open)? + open.len()..];+ Some(&rest[..rest.find(&format!("</{tag}>"))?])+}++/// (команда, включена) из XML задачи; None — задача не запускается при входе или загрузке, или не запускает программу.+pub fn parse_task(xml: &str) -> Option<(String, bool)> {+ let triggers = tag(xml, "Triggers")?;+ if !triggers.contains("<LogonTrigger") && !triggers.contains("<BootTrigger") {+ return None;+ }+ let exec = tag(xml, "Exec")?;+ let cmd = xml_unescape(tag(exec, "Command")?.trim());+ let args = tag(exec, "Arguments").map(|a| xml_unescape(a.trim())).unwrap_or_default();+ let quoted = if cmd.contains(' ') && !cmd.starts_with('"') { format!("\"{cmd}\"") } else { cmd };+ let enabled = !tag(xml, "Settings").is_some_and(|s| s.contains("<Enabled>false</Enabled>"));+ Some((if args.is_empty() { quoted } else { format!("{quoted} {args}") }, enabled))+}++fn decode_task_file(b: &[u8]) -> String {+ match b {+ [0xFF, 0xFE, rest @ ..] => from_utf16_bytes(rest),+ [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),+ _ => String::from_utf8_lossy(b).into_owned(),+ }+}++/// Файлы задач лежат в System32\Tasks (читает только администратор); папка \Microsoft — сама Windows, её не показываем.+fn tasks() -> Vec<Item> {+ let Some(root) = std::env::var_os("SystemRoot").map(|r| PathBuf::from(r).join(r"System32\Tasks")) else { return vec![] };+ let mut out = vec![];+ let mut stack = vec![root.clone()];+ while let Some(dir) = stack.pop() {+ for e in fs::read_dir(&dir).into_iter().flatten().flatten() {+ let p = e.path();+ if p.is_dir() {+ if dir != root || !e.file_name().eq_ignore_ascii_case("Microsoft") {+ stack.push(p);+ }+ } else if let Some((command, enabled)) = fs::read(&p).ok().and_then(|b| parse_task(&decode_task_file(&b))) {+ let rel = p.strip_prefix(&root).map(|r| format!("\\{}", r.display())).unwrap_or_default();+ out.push(Item { name: rel, command, source: TASK, enabled });+ }+ }+ }+ out+}++// ---------- службы ----------++const SERVICES_KEY: &str = r"SYSTEM\CurrentControlSet\Services";+/// Службы, отключённые здесь (Start 2 → 3): имя значения = имя службы.+const SVC_OFF: &str = r"SOFTWARE\WinRust\rtaskmgr\StartupSvc";++fn create(r: HKEY, path: &str) -> Option<HKEY> {+ let mut k: HKEY = null_mut();+ (unsafe { RegCreateKeyExW(r, w(path).as_ptr(), 0, null_mut(), 0, KEY_SET_VALUE, null_mut(), &mut k, null_mut()) } == 0).then_some(k)+}++fn dword(k: HKEY, name: &str) -> Option<u32> {+ let mut v = 0u32;+ let mut len = 4u32;+ let mut ty = 0u32;+ let rc = unsafe { RegQueryValueExW(k, w(name).as_ptr(), null_mut(), &mut ty, &mut v as *mut u32 as *mut u8, &mut len) };+ (rc == 0 && ty == REG_DWORD).then_some(v)+}++fn sz(k: HKEY, name: &str) -> Option<String> {+ let mut buf = vec![0u8; 4096];+ let mut len = buf.len() as u32;+ let mut ty = 0u32;+ let rc = unsafe { RegQueryValueExW(k, w(name).as_ptr(), null_mut(), &mut ty, buf.as_mut_ptr(), &mut len) };+ (rc == 0 && (ty == REG_SZ || ty == REG_EXPAND_SZ)).then(|| from_utf16_bytes(&buf[..len as usize]))+}++fn subkeys(r: HKEY, path: &str) -> Vec<String> {+ let Some(k) = open(r, path, KEY_READ) else { return vec![] };+ let mut out = vec![];+ for i in 0.. {+ let mut name = [0u16; 256];+ let mut n = name.len() as u32;+ if unsafe { RegEnumKeyExW(k, i, name.as_mut_ptr(), &mut n, null_mut(), null_mut(), null_mut(), null_mut()) } != 0 {+ break;+ }+ out.push(String::from_utf16_lossy(&name[..n as usize]));+ }+ unsafe { RegCloseKey(k) };+ out+}++/// Имена всех значений ключа (любого типа).+fn value_names(k: HKEY) -> Vec<String> {+ let mut out = vec![];+ for i in 0.. {+ let mut name = [0u16; 512];+ let mut n = name.len() as u32;+ if unsafe { RegEnumValueW(k, i, name.as_mut_ptr(), &mut n, null_mut(), null_mut(), null_mut(), null_mut()) } != 0 {+ break;+ }+ out.push(String::from_utf16_lossy(&name[..n as usize]));+ }+ out+}++/// Сторонняя ли служба: программа не из папки Windows и не svchost.+pub fn third_party_image(image: &str) -> bool {+ let i = image.to_lowercase();+ !(i.is_empty() || i.contains("\\windows\\") || i.starts_with("system32") || i.starts_with("\\systemroot") || i.starts_with("%systemroot%") || i.contains("svchost.exe"))+}++fn services() -> Vec<Item> {+ let ours = open(HKEY_LOCAL_MACHINE, SVC_OFF, KEY_READ).map_or(vec![], |k| {+ let v = value_names(k);+ unsafe { RegCloseKey(k) };+ v+ });+ let mut out = vec![];+ for name in subkeys(HKEY_LOCAL_MACHINE, SERVICES_KEY) {+ let Some(k) = open(HKEY_LOCAL_MACHINE, &format!(r"{SERVICES_KEY}\{name}"), KEY_READ) else { continue };+ let (start, ty, image) = (dword(k, "Start"), dword(k, "Type").unwrap_or(0), sz(k, "ImagePath").unwrap_or_default());+ unsafe { RegCloseKey(k) };+ let mine = ours.iter().any(|o| o.eq_ignore_ascii_case(&name));+ if ty & 0x30 == 0 || !third_party_image(&image) || !(start == Some(2) || mine && start == Some(3)) {+ continue;+ }+ out.push(Item { name, command: image, source: SERVICE, enabled: start == Some(2) });+ }+ out+}++// ---------- журнал загрузки ----------++/// Из журнала Microsoft-Windows-Diagnostics-Performance (его ведёт сама Windows, читает только администратор).+#[derive(Default, Debug, PartialEq)]+pub struct BootLog {+ /// (дата, полная загрузка мс, основная фаза до рабочего стола мс), новые первыми+ pub boots: Vec<(String, u32, u32)>,+ /// (имя файла или службы в нижнем регистре, понятное имя, на сколько замедлил загрузку мс): по одному на имя, худшее+ pub slow: Vec<(String, String, u32)>,+}++fn data_field<'a>(ev: &'a str, name: &str) -> Option<&'a str> {+ let key = format!("<Data Name='{name}'>");+ let rest = &ev[ev.find(&key)? + key.len()..];+ Some(&rest[..rest.find("</Data>")?])+}++pub fn parse_boot_log(xml: &str) -> BootLog {+ let mut log = BootLog::default();+ for ev in xml.split("<Event ").skip(1) {+ let id = tag(ev, "EventID").and_then(|s| s.trim().parse::<u32>().ok());+ let num = |n: &str| data_field(ev, n).and_then(|v| v.trim().parse::<u32>().ok());+ match id {+ Some(100) => {+ let date = ev.split("SystemTime='").nth(1).map(|s| s.chars().take(16).collect::<String>().replace('T', " ")).unwrap_or_default();+ if let Some(b) = num("BootTime") {+ log.boots.push((date, b, num("MainPathBootTime").unwrap_or(0)));+ }+ }+ Some(101 | 103) => {+ let (Some(name), Some(deg)) = (data_field(ev, "Name"), num("DegradationTime")) else { continue };+ let name = xml_unescape(name).to_lowercase();+ let friendly = data_field(ev, "FriendlyName").map(xml_unescape).unwrap_or_default();+ match log.slow.iter_mut().find(|s| s.0 == name) {+ Some(s) => s.2 = s.2.max(deg),+ None => log.slow.push((name, friendly, deg)),+ }+ }+ _ => {}+ }+ }+ log.slow.sort_by(|a, b| b.2.cmp(&a.2));+ log+}++/// Читается один раз за запуск программы: записи меняются только с новой загрузкой Windows.+pub fn boot_log() -> &'static BootLog {+ static LOG: std::sync::OnceLock<BootLog> = std::sync::OnceLock::new();+ LOG.get_or_init(|| {+ use std::os::windows::process::CommandExt;+ let out = std::process::Command::new("wevtutil.exe")+ .args(["qe", "Microsoft-Windows-Diagnostics-Performance/Operational", "/q:*[System[(EventID=100 or EventID=101 or EventID=103)]]", "/c:200", "/rd:true", "/f:xml"])+ .creation_flags(0x0800_0000)+ .output();+ out.map(|o| parse_boot_log(&String::from_utf8_lossy(&o.stdout))).unwrap_or_default()+ })+}++/// Насколько элемент автозагрузки замедлил загрузку (по журналу), мс.+pub fn boot_impact(it: &Item, log: &BootLog) -> Option<u32> {+ let key = if it.source == SERVICE { it.name.to_lowercase() } else { it.exe_name()? };+ log.slow.iter().find(|s| s.0 == key).map(|s| s.2)+}+const SELF_NAME: &str = "RTaskMgr";pub fn self_autostart() -> bool {@@ -214,6 +461,41 @@ mod tests {result.unwrap();}+ #[test]+ fn task_xml() {+ let xml = r#"<?xml version="1.0" encoding="UTF-16"?><Task><Triggers><LogonTrigger><Enabled>true</Enabled></LogonTrigger></Triggers>+ <Settings><Enabled>false</Enabled></Settings><Actions Context="Author"><Exec><Command>C:\Program Files\App\up.exe</Command><Arguments>/silent & /x</Arguments></Exec></Actions></Task>"#;+ assert_eq!(parse_task(xml), Some((r#""C:\Program Files\App\up.exe" /silent & /x"#.to_string(), false)));+ assert_eq!(parse_task(&xml.replace("LogonTrigger", "TimeTrigger")), None, "по расписанию — не автозагрузка");+ assert!(parse_task(&xml.replace("<Settings><Enabled>false</Enabled></Settings>", "<Settings></Settings>")).unwrap().1);+ let mut bytes = vec![0xFF, 0xFE];+ bytes.extend("<a>й</a>".encode_utf16().flat_map(|c| c.to_le_bytes()));+ assert_eq!(decode_task_file(&bytes), "<a>й</a>");+ }++ #[test]+ fn service_images() {+ assert!(third_party_image(r#""C:\Program Files\Steam\steamservice.exe" /RunAsService"#));+ assert!(!third_party_image(r"C:\WINDOWS\system32\svchost.exe -k netsvcs"));+ assert!(!third_party_image(r"system32\DRIVERS\x.sys"));+ assert!(!third_party_image(r"\SystemRoot\System32\drivers\y.sys"));+ assert!(!third_party_image(""));+ }++ #[test]+ fn boot_log_events() {+ let xml = "<Events><Event xmlns='x'><System><EventID>100</EventID><TimeCreated SystemTime='2026-11-20T08:15:01.1Z'/></System><EventData><Data Name='BootTime'>41234</Data><Data Name='MainPathBootTime'>15000</Data></EventData></Event>\+ <Event xmlns='x'><System><EventID>101</EventID></System><EventData><Data Name='Name'>OneDrive.exe</Data><Data Name='FriendlyName'>Microsoft OneDrive</Data><Data Name='TotalTime'>3000</Data><Data Name='DegradationTime'>2100</Data></EventData></Event>\+ <Event xmlns='x'><System><EventID>101</EventID></System><EventData><Data Name='Name'>onedrive.exe</Data><Data Name='DegradationTime'>900</Data></EventData></Event>\+ <Event xmlns='x'><System><EventID>103</EventID></System><EventData><Data Name='Name'>Steam Client Service</Data><Data Name='FriendlyName'>Steam</Data><Data Name='DegradationTime'>3000</Data></EventData></Event></Events>";+ let log = parse_boot_log(xml);+ assert_eq!(log.boots, vec![("2026-11-20 08:15".to_string(), 41234, 15000)]);+ assert_eq!(log.slow, vec![("steam client service".to_string(), "Steam".to_string(), 3000), ("onedrive.exe".to_string(), "Microsoft OneDrive".to_string(), 2100)]);+ let it = Item { name: "OneDrive".into(), command: r#""C:\Users\a\OneDrive.exe" /background"#.into(), source: 0, enabled: true };+ assert_eq!(boot_impact(&it, &log), Some(2100));+ assert_eq!(parse_boot_log(""), BootLog::default());+ }+#[test]fn utf16_bytes_decode() {assert_eq!(from_utf16_bytes(&[0x41, 0, 0x42, 0, 0, 0]), "AB");diff --git a/plugins/rtaskmgr-win32/src/sys.rs b/plugins/rtaskmgr-win32/src/sys.rsindex 4a1a0db..bd8dce8 100644--- a/plugins/rtaskmgr-win32/src/sys.rs+++ b/plugins/rtaskmgr-win32/src/sys.rs@@ -392,3 +392,137 @@ pub fn process_user(pid: u32) -> Option<String> {}).flatten()}++// ---------- диагностика ----------++/// Сумма по всем ядрам: (время ЦП всего, DPC, прерывания), в 100-нс единицах.+pub type CpuTimes = (i64, i64, i64);++pub fn cpu_times() -> Option<CpuTimes> {+ #[link(name = "ntdll")]+ unsafe extern "system" {+ fn NtQuerySystemInformation(class: u32, info: *mut std::ffi::c_void, len: u32, ret: *mut u32) -> i32;+ }+ #[repr(C)]+ #[derive(Clone, Copy, Default)]+ struct Spi {+ idle: i64,+ kernel: i64, // включает idle+ user: i64,+ dpc: i64,+ interrupt: i64,+ count: u32,+ }+ let mut buf = vec![Spi::default(); 1024];+ let mut ret = 0u32;+ let st = unsafe { NtQuerySystemInformation(8 /*SystemProcessorPerformanceInformation*/, buf.as_mut_ptr() as *mut _, (buf.len() * size_of::<Spi>()) as u32, &mut ret) };+ if st < 0 {+ return None;+ }+ let n = ret as usize / size_of::<Spi>();+ Some(buf[..n].iter().fold((0, 0, 0), |a, c| (a.0 + c.kernel + c.user, a.1 + c.dpc, a.2 + c.interrupt)))+}++/// (DPC %, прерывания %) между двумя замерами.+pub fn dpc_share(a: CpuTimes, b: CpuTimes) -> (f32, f32) {+ let total = (b.0 - a.0) as f64;+ if total <= 0.0 {+ return (0.0, 0.0);+ }+ (((b.1 - a.1) as f64 / total * 100.0) as f32, ((b.2 - a.2) as f64 / total * 100.0) as f32)+}++/// Видимые окна верхнего уровня, которые Windows считает зависшими (не обрабатывают сообщения 5 с).+pub fn hung_windows() -> Vec<(u32, String)> {+ use winapi::shared::{minwindef::{BOOL, LPARAM}, windef::HWND};+ use winapi::um::winuser::{EnumWindows, GetWindow, GetWindowTextW, GetWindowThreadProcessId, IsHungAppWindow, IsWindowVisible, GW_OWNER};+ unsafe extern "system" fn cb(h: HWND, l: LPARAM) -> BOOL {+ unsafe {+ let v = &mut *(l as *mut Vec<(u32, String)>);+ if IsWindowVisible(h) != 0 && GetWindow(h, GW_OWNER).is_null() && IsHungAppWindow(h) != 0 {+ let mut buf = [0u16; 256];+ let n = GetWindowTextW(h, buf.as_mut_ptr(), 256).max(0) as usize;+ let mut pid = 0u32;+ GetWindowThreadProcessId(h, &mut pid);+ if n > 0 && !v.iter().any(|x| x.0 == pid) {+ v.push((pid, String::from_utf16_lossy(&buf[..n])));+ }+ }+ }+ 1+ }+ let mut v: Vec<(u32, String)> = vec![];+ unsafe { EnumWindows(Some(cb), &mut v as *mut _ as LPARAM) };+ v+}++// ---------- запуск с обычными правами ----------++/// Запускает `cmdline` с токеном процесса-донора из нашего сеанса (sihost.exe: есть всегда и работает без повышения).+/// Иначе программа, закрытая профилем и запущенная обратно отсюда, унаследовала бы права администратора.+pub fn run_unelevated(donors: &[u32], cmdline: &str) -> bool {+ use winapi::um::{+ processthreadsapi::{OpenProcessToken, PROCESS_INFORMATION, ProcessIdToSessionId, STARTUPINFOW},+ securitybaseapi::DuplicateTokenEx,+ winnt::{SecurityImpersonation, TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TOKEN_QUERY, TokenPrimary, MAXIMUM_ALLOWED},+ };+ #[link(name = "advapi32")]+ unsafe extern "system" {+ fn CreateProcessWithTokenW(tok: HANDLE, logon: u32, app: *const u16, cmd: *mut u16, flags: u32, env: *mut std::ffi::c_void, dir: *const u16, si: *mut STARTUPINFOW, pi: *mut PROCESS_INFORMATION) -> i32;+ }+ let mut mine = 0u32;+ unsafe { ProcessIdToSessionId(std::process::id(), &mut mine) };+ for &pid in donors {+ let mut s = u32::MAX;+ if unsafe { ProcessIdToSessionId(pid, &mut s) } == 0 || s != mine {+ continue;+ }+ let ok = with_proc(pid, PROCESS_QUERY_LIMITED_INFORMATION, |h| unsafe {+ let mut tok: HANDLE = null_mut();+ if OpenProcessToken(h, TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY, &mut tok) == 0 {+ return false;+ }+ let mut prim: HANDLE = null_mut();+ let dup = DuplicateTokenEx(tok, MAXIMUM_ALLOWED, null_mut(), SecurityImpersonation, TokenPrimary, &mut prim) != 0;+ CloseHandle(tok);+ if !dup {+ return false;+ }+ let mut si: STARTUPINFOW = std::mem::zeroed();+ si.cb = size_of::<STARTUPINFOW>() as u32;+ let mut pi: PROCESS_INFORMATION = std::mem::zeroed();+ let mut cmd = wide(cmdline);+ let r = CreateProcessWithTokenW(prim, 0, std::ptr::null(), cmd.as_mut_ptr(), 0x0400 /*CREATE_UNICODE_ENVIRONMENT*/, null_mut(), std::ptr::null(), &mut si, &mut pi) != 0;+ if r {+ CloseHandle(pi.hProcess);+ CloseHandle(pi.hThread);+ }+ CloseHandle(prim);+ r+ });+ if ok == Some(true) {+ return true;+ }+ }+ false+}++#[cfg(test)]+mod diag_tests {+ use super::*;++ #[test]+ fn dpc_share_and_times() {+ assert_eq!(dpc_share((0, 0, 0), (1000, 20, 10)), (2.0, 1.0));+ assert_eq!(dpc_share((5, 0, 0), (5, 1, 1)), (0.0, 0.0));+ let t = cpu_times().expect("NtQuerySystemInformation(8)");+ assert!(t.0 > 0 && t.1 >= 0 && t.2 >= 0);+ let _ = hung_windows();+ }+}++/// Завершает процесс (TerminateProcess).+pub fn kill(pid: u32) -> bool {+ use winapi::um::{processthreadsapi::TerminateProcess, winnt::PROCESS_TERMINATE};+ with_proc(pid, PROCESS_TERMINATE, |h| unsafe { TerminateProcess(h, 1) != 0 }).unwrap_or(false)+}diff --git a/plugins/rust-explorer/Cargo.toml b/plugins/rust-explorer/Cargo.tomlindex 2cafcd4..fd0029a 100644--- a/plugins/rust-explorer/Cargo.toml+++ b/plugins/rust-explorer/Cargo.toml@@ -8,7 +8,13 @@ license = "MIT OR Apache-2.0"winrust-common = { path = "../../common" }windows = { version = "0.62.2", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_Com_StructuredStorage", "Win32_System_DataExchange", "Win32_System_Memory", "Win32_System_Ole", "Win32_System_SystemServices", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_UI_WindowsAndMessaging", "Win32_System_Com"] }windows-core = "0.62"-windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_Storage_FileSystem", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Time", "Win32_System_SystemInformation", "Win32_Graphics_Dwm", "Win32_Graphics_GdiPlus", "Win32_UI_Controls", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Time", "Win32_System_SystemInformation", "Win32_Graphics_Dwm", "Win32_Graphics_GdiPlus", "Win32_UI_Controls", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }+zip = { version = "9.8.1", default-features = false, features = ["deflate"] }+sevenz-rust2 = { version = "0.25.0", default-features = false, features = ["util", "ppmd", "bzip2", "deflate"] }[build-dependencies]embed-resource = "3"++[dev-dependencies]+# the tests make a real .7z to unpack (the exe itself only unpacks)+sevenz-rust2 = { version = "0.25.0", default-features = false, features = ["util", "compress"] }diff --git a/plugins/rust-explorer/src/jobs.rs b/plugins/rust-explorer/src/jobs.rsnew file mode 100644index 0000000..66272a1--- /dev/null+++ b/plugins/rust-explorer/src/jobs.rs@@ -0,0 +1,456 @@+//! Background file jobs, faster than the shell's: copying (several files at once on SSDs, unbuffered I/O for big files),+//! ZIP packing (files compressed on all cores) and unpacking ZIP / 7z. Progress shows in the status line (`status_text`),+//! the end comes to the window as WM_JOB.+use std::{+ fs,+ path::{Path, PathBuf},+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, AtomicU64, Ordering::Relaxed},+ },+ time::Instant,+};++pub struct Progress {+ pub what: String, // "Copying", "Packing x.zip"...+ pub files: AtomicU64,+ pub total_files: AtomicU64,+ pub bytes: AtomicU64,+ pub total_bytes: AtomicU64,+ started: Instant,+}++impl Progress {+ fn new(what: String) -> Arc<Progress> {+ Arc::new(Progress { what, files: 0.into(), total_files: 0.into(), bytes: 0.into(), total_bytes: 0.into(), started: Instant::now() })+ }+}++static JOB: Mutex<Option<Arc<Progress>>> = Mutex::new(None);+static RUNNING: AtomicBool = AtomicBool::new(false);++/// The status line text while a job runs.+pub fn status_text() -> Option<String> {+ let p = JOB.lock().unwrap().clone()?;+ let (b, tb, f, tf) = (p.bytes.load(Relaxed), p.total_bytes.load(Relaxed), p.files.load(Relaxed), p.total_files.load(Relaxed));+ let secs = p.started.elapsed().as_secs_f64().max(0.1);+ let mut s = p.what.clone();+ if tf > 0 {+ s += &format!(" \u{00B7} {f} of {tf} files");+ }+ if tb > 0 {+ s += &format!(" \u{00B7} {} of {} ({}%) \u{00B7} {}/s", super::size_text(b), super::size_text(tb), b * 100 / tb.max(1), super::size_text((b as f64 / secs) as u64));+ }+ Some(s + "\u{2026}")+}++pub fn busy() -> bool {+ RUNNING.load(Relaxed)+}++/// Runs `f` on a worker thread; its error (or None) is posted to `h` as WM_JOB (wp = Box<Option<String>>).+fn spawn(h: isize, what: String, f: impl FnOnce(&Progress) -> Result<(), String> + Send + 'static) -> bool {+ if RUNNING.swap(true, Relaxed) {+ return false;+ }+ let p = Progress::new(what);+ *JOB.lock().unwrap() = Some(p.clone());+ let ticker = std::thread::spawn({+ let p = p.clone();+ move || {+ // repaint the status line a few times a second while the job runs+ while RUNNING.load(Relaxed) {+ unsafe { super::ui::status_dirty(h as _) };+ std::thread::sleep(std::time::Duration::from_millis(200));+ }+ drop(p);+ }+ });+ std::thread::spawn(move || {+ let r = f(&p);+ *JOB.lock().unwrap() = None;+ RUNNING.store(false, Relaxed);+ let _ = ticker.join();+ let msg = Box::new(r.err());+ unsafe { windows_sys::Win32::UI::WindowsAndMessaging::PostMessageW(h as _, super::WM_JOB, Box::into_raw(msg) as usize, 0) };+ });+ true+}++// ---------- walking ----------++/// A file or folder to create: (source, path relative to the destination, size; None = folder).+type Entry = (PathBuf, PathBuf, Option<u64>);++/// Everything under `src`, folders before their contents. Links and junctions to folders are not followed (no loops).+fn walk(src: &Path, rel: PathBuf, out: &mut Vec<Entry>) -> std::io::Result<()> {+ let md = fs::symlink_metadata(src)?;+ if md.is_dir() {+ out.push((src.to_path_buf(), rel.clone(), None));+ for e in fs::read_dir(src)? {+ let e = e?;+ walk(&e.path(), rel.join(e.file_name()), out)?;+ }+ } else if md.file_type().is_symlink() && fs::metadata(src).is_ok_and(|m| m.is_dir()) {+ // a directory link: skipped on purpose+ } else {+ out.push((src.to_path_buf(), rel, Some(fs::metadata(src).map_or(md.len(), |m| m.len()))));+ }+ Ok(())+}++/// `name`, or "name (2).ext", "name (3).ext"... the first that does not exist in `dir`.+pub fn free_name(dir: &Path, name: &str, is_dir: bool) -> PathBuf {+ let (stem, ext) = match name.rsplit_once('.') {+ Some((s, e)) if !is_dir && !s.is_empty() => (s.to_string(), format!(".{e}")),+ _ => (name.to_string(), String::new()),+ };+ (1..).map(|n| dir.join(if n == 1 { name.to_string() } else { format!("{stem} ({n}){ext}") })).find(|p| fs::symlink_metadata(p).is_err()).unwrap()+}++/// Plain paths on a drive (not shell items like a phone or a library), and the destination not inside a source.+pub fn can_fast_copy(from: &[PathBuf], to: &Path) -> bool {+ to.is_dir() && to.has_root() && !from.is_empty() && from.iter().all(|p| p.has_root() && fs::symlink_metadata(p).is_ok() && !to.starts_with(p))+}++/// The destination accepts new files without elevation (otherwise the shell copy asks for it).+pub fn writable(dir: &Path) -> bool {+ let t = dir.join(format!(".winrust-{}.tmp", std::process::id()));+ let ok = fs::File::create(&t).is_ok();+ let _ = fs::remove_file(&t);+ ok+}++/// Same volume: a move is a rename there, the shell does that instantly.+pub fn same_volume(a: &Path, b: &Path) -> bool {+ let root = |p: &Path| p.components().next().map(|c| c.as_os_str().to_string_lossy().to_lowercase());+ root(a).is_some() && root(a) == root(b)+}++// ---------- copying ----------++/// Whether the volume of `p` is a spinning disk (seeking costs time: copy one file at a time there).+fn seek_penalty(p: &Path) -> bool {+ use windows_sys::Win32::{Foundation::*, Storage::FileSystem::*, System::{IO::DeviceIoControl, Ioctl::*}};+ let Some(letter) = p.to_string_lossy().chars().next().filter(|c| c.is_ascii_alphabetic()) else { return false };+ let dev: Vec<u16> = format!(r"\\.\{letter}:").encode_utf16().chain([0]).collect();+ unsafe {+ let h = CreateFileW(dev.as_ptr(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, std::ptr::null(), OPEN_EXISTING, 0, std::ptr::null_mut());+ if h == INVALID_HANDLE_VALUE {+ return false;+ }+ let q = STORAGE_PROPERTY_QUERY { PropertyId: StorageDeviceSeekPenaltyProperty, QueryType: PropertyStandardQuery, AdditionalParameters: [0] };+ let mut d: DEVICE_SEEK_PENALTY_DESCRIPTOR = std::mem::zeroed();+ let mut n = 0u32;+ let ok = DeviceIoControl(h, IOCTL_STORAGE_QUERY_PROPERTY, &q as *const _ as _, size_of::<STORAGE_PROPERTY_QUERY>() as u32, &mut d as *mut _ as _, size_of::<DEVICE_SEEK_PENALTY_DESCRIPTOR>() as u32, &mut n, std::ptr::null_mut()) != 0;+ CloseHandle(h);+ ok && d.IncursSeekPenalty+ }+}++const BIG: u64 = 256 << 20;++/// CopyFileExW; big files without the cache (faster for them, and they do not push everything else out of memory).+fn copy_file(src: &Path, dst: &Path, size: u64, p: &Progress) -> std::io::Result<()> {+ use windows_sys::Win32::Storage::FileSystem::{COPY_FILE_FAIL_IF_EXISTS, COPY_FILE_NO_BUFFERING, CopyFileExW};+ unsafe extern "system" fn cb(_total: i64, done: i64, _st: i64, _sd: i64, _id: u32, _r: u32, _s: *mut core::ffi::c_void, _d: *mut core::ffi::c_void, data: *const core::ffi::c_void) -> u32 {+ let (prog, last) = unsafe { &mut *(data as *mut (&Progress, u64)) };+ prog.bytes.fetch_add(done as u64 - *last, Relaxed);+ *last = done as u64;+ 0 // PROGRESS_CONTINUE+ }+ let w = |p: &Path| -> Vec<u16> { std::os::windows::ffi::OsStrExt::encode_wide(p.as_os_str()).chain([0]).collect() };+ let mut state: (&Progress, u64) = (p, 0);+ let flags = COPY_FILE_FAIL_IF_EXISTS | if size >= BIG { COPY_FILE_NO_BUFFERING } else { 0 };+ let ok = unsafe { CopyFileExW(w(src).as_ptr(), w(dst).as_ptr(), Some(cb), &mut state as *mut _ as _, std::ptr::null_mut(), flags) } != 0;+ p.bytes.fetch_add(size.saturating_sub(state.1), Relaxed); // empty files and anything the callback did not report+ if ok { Ok(()) } else { Err(std::io::Error::last_os_error()) }+}++/// Copies `from` into `to` (names that exist there get " (2)"); `then_delete` = a move across drives: the sources go away+/// only when every file arrived.+pub fn copy(h: isize, from: Vec<PathBuf>, to: PathBuf, then_delete: bool) -> bool {+ let what = if then_delete { "Moving" } else { "Copying" }.to_string();+ spawn(h, what, move |p| copy_now(&from, &to, then_delete, p))+}++fn copy_now(from: &[PathBuf], to: &Path, then_delete: bool, p: &Progress) -> Result<(), String> {+ let mut entries = vec![];+ for src in from {+ let name = src.file_name().ok_or_else(|| format!("{}: no name", src.display()))?.to_string_lossy().into_owned();+ let top = free_name(to, &name, src.is_dir());+ walk(src, PathBuf::from(top.file_name().unwrap()), &mut entries).map_err(|e| format!("{}: {e}", src.display()))?;+ }+ p.total_files.store(entries.iter().filter(|e| e.2.is_some()).count() as u64, Relaxed);+ p.total_bytes.store(entries.iter().filter_map(|e| e.2).sum(), Relaxed);+ for (_, rel, size) in &entries {+ if size.is_none() {+ fs::create_dir_all(to.join(rel)).map_err(|e| format!("{}: {e}", to.join(rel).display()))?;+ }+ }+ let mut files: Vec<&Entry> = entries.iter().filter(|e| e.2.is_some()).collect();+ files.sort_by_key(|e| std::cmp::Reverse(e.2)); // big ones first: the small ones fill the gaps at the end+ let threads = if seek_penalty(&from[0]) || seek_penalty(to) { 1 } else { std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(2, 8) };+ let next = AtomicU64::new(0);+ let errors: Mutex<Vec<String>> = Mutex::new(vec![]);+ std::thread::scope(|s| {+ for _ in 0..threads {+ s.spawn(|| {+ while let Some(e) = files.get(next.fetch_add(1, Relaxed) as usize) {+ let dst = to.join(&e.1);+ match copy_file(&e.0, &dst, e.2.unwrap(), p) {+ Ok(()) => _ = p.files.fetch_add(1, Relaxed),+ Err(err) => errors.lock().unwrap().push(format!("{}: {err}", e.0.display())),+ }+ }+ });+ }+ });+ let errors = errors.into_inner().unwrap();+ if !errors.is_empty() {+ let more = if errors.len() > 5 { format!("\n... and {} more", errors.len() - 5) } else { String::new() };+ let kept = if then_delete { "\nNothing was deleted from the source." } else { "" };+ return Err(format!("{} file(s) were not copied:\n{}{more}{kept}", errors.len(), errors[..errors.len().min(5)].join("\n")));+ }+ if then_delete {+ for src in from {+ let r = if fs::symlink_metadata(src).is_ok_and(|m| m.is_dir()) { fs::remove_dir_all(src) } else { fs::remove_file(src) };+ r.map_err(|e| format!("Copied, but {} could not be removed: {e}", src.display()))?;+ }+ }+ Ok(())+}++// ---------- ZIP / 7z ----------++/// Files at most this big are compressed on worker threads in memory; bigger ones are streamed by the writer itself.+const PAR_MAX: u64 = 64 << 20;++pub fn zip(h: isize, from: Vec<PathBuf>, dest: PathBuf) -> bool {+ let what = format!("Packing {}", dest.file_name().unwrap_or_default().to_string_lossy());+ spawn(h, what, move |p| zip_now(&from, &dest, p).inspect_err(|_| _ = fs::remove_file(&dest)))+}++/// Archive name of an entry: forward slashes, as ZIP wants.+fn zip_name(rel: &Path) -> String {+ rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/")+}++fn zip_now(from: &[PathBuf], dest: &Path, p: &Progress) -> Result<(), String> {+ use zip::{CompressionMethod, ZipWriter, write::{PreparedZipFile, SimpleFileOptions}};+ let mut entries = vec![];+ for src in from {+ let name = src.file_name().ok_or_else(|| format!("{}: no name", src.display()))?;+ walk(src, PathBuf::from(name), &mut entries).map_err(|e| format!("{}: {e}", src.display()))?;+ }+ entries.retain(|e| e.0 != dest); // packing the folder the archive is written into+ p.total_files.store(entries.iter().filter(|e| e.2.is_some()).count() as u64, Relaxed);+ p.total_bytes.store(entries.iter().filter_map(|e| e.2).sum(), Relaxed);+ let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true);+ let file = fs::File::create(dest).map_err(|e| format!("{}: {e}", dest.display()))?;+ let mut w = ZipWriter::new(std::io::BufWriter::with_capacity(1 << 20, file));+ let err = |e: &dyn std::fmt::Display, path: &Path| format!("{}: {e}", path.display());+ for (src, rel, size) in &entries {+ if size.is_none() {+ w.add_directory(format!("{}/", zip_name(rel)), opts).map_err(|e| err(&e, src))?;+ }+ }+ let small: Vec<&Entry> = entries.iter().filter(|e| e.2.is_some_and(|s| s <= PAR_MAX)).collect();+ let threads = std::thread::available_parallelism().map_or(4, |n| n.get());+ let next = AtomicU64::new(0);+ let (tx, rx) = std::sync::mpsc::sync_channel::<Result<PreparedZipFile, String>>(threads * 2); // bounded: memory stays small+ let written: Result<(), String> = std::thread::scope(|s| {+ for _ in 0..threads {+ let tx = tx.clone();+ let (small, next) = (&small, &next);+ s.spawn(move || {+ while let Some(e) = small.get(next.fetch_add(1, Relaxed) as usize) {+ let r = PreparedZipFile::from_path(zip_name(&e.1), &e.0, opts).map_err(|x| format!("{}: {x}", e.0.display()));+ if tx.send(r).is_err() {+ break; // the writer gave up+ }+ }+ });+ }+ drop(tx);+ for r in rx {+ let f = r?;+ let n = f.uncompressed_size();+ w.add_prepared_file(f).map_err(|e| e.to_string())?;+ p.bytes.fetch_add(n, Relaxed);+ p.files.fetch_add(1, Relaxed);+ }+ Ok(())+ });+ written?;+ for (src, rel, size) in entries.iter().filter(|e| e.2.is_some_and(|s| s > PAR_MAX)) {+ w.start_file(zip_name(rel), opts).map_err(|e| err(&e, src))?;+ let mut f = fs::File::open(src).map_err(|e| err(&e, src))?;+ std::io::copy(&mut f, &mut w).map_err(|e| err(&e, src))?;+ p.bytes.fetch_add(size.unwrap(), Relaxed);+ p.files.fetch_add(1, Relaxed);+ }+ w.finish().map_err(|e| err(&e, dest))?;+ Ok(())+}++pub fn is_archive(p: &Path) -> bool {+ p.extension().is_some_and(|e| e.eq_ignore_ascii_case("zip") || e.eq_ignore_ascii_case("7z"))+}++/// Unpacks each archive into a new folder named after it, next to it.+pub fn extract(h: isize, archives: Vec<PathBuf>, dir: PathBuf) -> bool {+ let what = format!("Extracting {}", archives.iter().map(|a| a.file_name().unwrap_or_default().to_string_lossy()).collect::<Vec<_>>().join(", "));+ spawn(h, what, move |p| {+ p.total_files.store(archives.len() as u64, Relaxed);+ for a in &archives {+ let stem = a.file_stem().unwrap_or_default().to_string_lossy().into_owned();+ let out = free_name(&dir, &stem, true);+ extract_one(a, &out).map_err(|e| format!("{}: {e}", a.display()))?;+ p.files.fetch_add(1, Relaxed);+ }+ Ok(())+ })+}++/// Entry names that would land outside `out` are refused by both libraries (zip-slip).+pub fn extract_one(archive: &Path, out: &Path) -> Result<(), String> {+ let is7z = archive.extension().is_some_and(|e| e.eq_ignore_ascii_case("7z"));+ if is7z {+ return sevenz_rust2::decompress_file(archive, out).map_err(|e| e.to_string());+ }+ let f = fs::File::open(archive).map_err(|e| e.to_string())?;+ let mut z = zip::ZipArchive::new(std::io::BufReader::new(f)).map_err(|e| e.to_string())?;+ fs::create_dir_all(out).map_err(|e| e.to_string())?;+ z.extract(out).map_err(|e| e.to_string())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn tmp(tag: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("rx-jobs-{tag}-{}", std::process::id()));+ let _ = fs::remove_dir_all(&d);+ fs::create_dir_all(&d).unwrap();+ d+ }++ fn tree(root: &Path) {+ fs::create_dir_all(root.join("src/a/b")).unwrap();+ fs::write(root.join("src/one.txt"), "hello").unwrap();+ fs::write(root.join("src/a/two.bin"), vec![7u8; 300_000]).unwrap();+ fs::write(root.join("src/a/b/empty"), "").unwrap();+ }++ #[test]+ fn free_names() {+ let d = tmp("names");+ fs::write(d.join("x.txt"), "").unwrap();+ fs::create_dir(d.join("dir.v2")).unwrap();+ assert_eq!(free_name(&d, "x.txt", false), d.join("x (2).txt"));+ assert_eq!(free_name(&d, "y.txt", false), d.join("y.txt"));+ assert_eq!(free_name(&d, "dir.v2", true), d.join("dir.v2 (2)"));+ assert_eq!(free_name(&d, ".gitignore", false), d.join(".gitignore"));+ let _ = fs::remove_dir_all(&d);+ }++ #[test]+ fn copies_a_tree_and_moves_it() {+ let d = tmp("copy");+ tree(&d);+ fs::create_dir(d.join("dst")).unwrap();+ let p = Progress::new(String::new());+ copy_now(&[d.join("src")], &d.join("dst"), false, &p).unwrap();+ assert_eq!(fs::read_to_string(d.join("dst/src/one.txt")).unwrap(), "hello");+ assert_eq!(fs::read(d.join("dst/src/a/two.bin")).unwrap().len(), 300_000);+ assert!(d.join("dst/src/a/b/empty").is_file());+ assert_eq!((p.files.load(Relaxed), p.total_files.load(Relaxed)), (3, 3));+ assert_eq!(p.bytes.load(Relaxed), p.total_bytes.load(Relaxed));+ // again: the existing name gets " (2)", and as a move the source goes away+ copy_now(&[d.join("src")], &d.join("dst"), true, &Progress::new(String::new())).unwrap();+ assert!(d.join("dst/src (2)/a/two.bin").is_file() && !d.join("src").exists());+ assert!(!can_fast_copy(&[d.join("dst")], &d.join("dst/src")), "into itself");+ let _ = fs::remove_dir_all(&d);+ }++ #[test]+ fn zip_round_trip() {+ let d = tmp("zip");+ tree(&d);+ let z = d.join("out.zip");+ zip_now(&[d.join("src")], &z, &Progress::new(String::new())).unwrap();+ extract_one(&z, &d.join("back")).unwrap();+ assert_eq!(fs::read_to_string(d.join("back/src/one.txt")).unwrap(), "hello");+ assert_eq!(fs::read(d.join("back/src/a/two.bin")).unwrap(), vec![7u8; 300_000]);+ assert!(d.join("back/src/a/b/empty").is_file());+ assert!(extract_one(&d.join("src/one.txt"), &d.join("bad")).is_err(), "not an archive");+ let _ = fs::remove_dir_all(&d);+ }++ #[test]+ fn unpacks_7z() {+ let d = tmp("7z");+ tree(&d);+ let a = d.join("t.7z");+ sevenz_rust2::compress_to_path(d.join("src"), &a).unwrap();+ extract_one(&a, &d.join("back")).unwrap();+ let found: Vec<PathBuf> = {+ let mut v = vec![];+ walk(&d.join("back"), PathBuf::new(), &mut v).unwrap();+ v.into_iter().filter(|e| e.2.is_some()).map(|e| e.1).collect()+ };+ assert_eq!(found.len(), 3, "{found:?}");+ let two = found.iter().find(|p| p.ends_with("two.bin")).unwrap();+ assert_eq!(fs::read(d.join("back").join(two)).unwrap(), vec![7u8; 300_000]);+ let _ = fs::remove_dir_all(&d);+ }++ /// Old path (IFileOperation, Explorer's engine) against ours on the same data. By hand:+ /// `set RX_BENCH=<empty dir on the disk to test>` and `cargo test -p rust-explorer --release bench -- --ignored --nocapture`+ #[test]+ #[ignore]+ fn bench() {+ let Some(root) = std::env::var_os("RX_BENCH").map(PathBuf::from) else { return };+ let small = root.join("small");+ fs::create_dir_all(&small).unwrap();+ for i in 0..5000 {+ fs::write(small.join(format!("f{i}.bin")), vec![(i % 251) as u8; 4096 + (i * 37) % 60_000]).unwrap();+ }+ let big = root.join("big");+ fs::create_dir_all(&big).unwrap();+ let chunk: Vec<u8> = (0..1u32 << 20).map(|i| (i.wrapping_mul(2654435761) >> 24) as u8).collect();+ let mut f = fs::File::create(big.join("1gb.bin")).unwrap();+ for _ in 0..1024 {+ std::io::Write::write_all(&mut f, &chunk).unwrap();+ }+ drop(f);+ super::super::sh::init();+ for src in [&small, &big] {+ let dst_old = root.join("out-old");+ let dst_new = root.join("out-new");+ let _ = fs::remove_dir_all(&dst_old);+ let _ = fs::remove_dir_all(&dst_new);+ fs::create_dir_all(&dst_old).unwrap();+ fs::create_dir_all(&dst_new).unwrap();+ let t = Instant::now();+ super::super::sh::fileop(std::ptr::null_mut(), super::super::sh::Op::Copy, &[src.clone()], &dst_old).unwrap();+ let old = t.elapsed();+ let t = Instant::now();+ copy_now(&[src.clone()], &dst_new, false, &Progress::new(String::new())).unwrap();+ let new = t.elapsed();+ println!("BENCH copy {}: IFileOperation {:.2} s, ours {:.2} s", src.file_name().unwrap().to_string_lossy(), old.as_secs_f64(), new.as_secs_f64());+ }+ let t = Instant::now();+ zip_now(&[small.clone()], &root.join("ours.zip"), &Progress::new(String::new())).unwrap();+ println!("BENCH zip small: ours {:.2} s", t.elapsed().as_secs_f64());+ }++ #[test]+ fn volumes_and_names() {+ assert!(same_volume(Path::new(r"C:\a"), Path::new(r"c:\b\c")));+ assert!(!same_volume(Path::new(r"C:\a"), Path::new(r"D:\a")));+ assert_eq!(zip_name(Path::new(r"a\b\c.txt")), "a/b/c.txt");+ assert!(is_archive(Path::new("x.ZIP")) && is_archive(Path::new("y.7z")) && !is_archive(Path::new("z.rar")));+ }+}diff --git a/plugins/rust-explorer/src/main.rs b/plugins/rust-explorer/src/main.rsindex ea7f2be..caca275 100644--- a/plugins/rust-explorer/src/main.rs+++ b/plugins/rust-explorer/src/main.rs@@ -20,6 +20,7 @@use std::{cell::RefCell, env, fs, os::windows::fs::MetadataExt, path::{Path, PathBuf}, ptr, sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed}};use windows_sys::Win32::{Foundation::*, Graphics::Gdi::{BLACK_BRUSH, GetStockObject, InvalidateRect}, System::LibraryLoader::GetModuleHandleW, UI::{Controls::*, Input::KeyboardAndMouse::{GetKeyState, SetFocus, VK_CONTROL}, Shell::*, WindowsAndMessaging::*}};+mod jobs; // our own copier, ZIP packer, ZIP/7z unpacker (background, progress in the status line)mod ui; // the look: palette, painted tabs / toolbar / address pill / status line, dark themestatic DESKTOP: AtomicBool = AtomicBool::new(false);@@ -73,6 +74,7 @@ static SORT_ASC: AtomicBool = AtomicBool::new(true);static SHOW_HIDDEN: AtomicBool = AtomicBool::new(false); // Ctrl+Hstatic NAV: AtomicBool = AtomicBool::new(false); // loading from the back / forward trail: do not record it againconst WM_NAV: u32 = WM_APP + 3; // wp: 1 back, 2 forward, 3 properties, 4 up (sent from the message loop for Alt+key)+const WM_JOB: u32 = WM_APP + 5; // jobs.rs worker finished: wp = Box<Option<String>> (the error, if any)fn row(name: String, m: Option<&fs::Metadata>) -> Row {Row { name, dir: m.is_some_and(|m| m.is_dir()), size: m.map_or(0, |m| m.len()), time: m.map_or(0, |m| m.last_write_time()), icon: -1, thumb: -2 }@@ -139,12 +141,40 @@ fn new_entry(dir: &PathBuf, base: &str, folder: bool) {}/// Pastes what is on the system clipboard (files copied or cut here or in any other file manager).+/// Copies and moves to another drive run in our own copier (jobs.rs: parallel on SSDs, unbuffered for big files); moves on the+/// same drive (a rename), shell items, and folders that need elevation go through the shell.fn paste(h: HWND, dir: &PathBuf) {let Some((paths, cut)) = sh::clip_get() else { return };- let _ = sh::fileop(h, if cut { sh::Op::Move } else { sh::Op::Copy }, &paths, dir);+ let fast = jobs::can_fast_copy(&paths, dir) && !(cut && paths.iter().all(|p| jobs::same_volume(p, dir))) && jobs::writable(dir);+ if fast && !jobs::busy() {+ jobs::copy(h as isize, paths, dir.clone(), cut);+ } else {+ let _ = sh::fileop(h, if cut { sh::Op::Move } else { sh::Op::Copy }, &paths, dir);+ }if cut { sh::clip_clear(); }}+const MENU_ZIP: u32 = 0x9001;+const MENU_EXTRACT: u32 = 0x9002;++/// The shell menu for the selection, with our "Compress to ZIP" / "Extract here" on top.+fn item_menu(h: HWND, dir: &Path, paths: &[PathBuf]) {+ let mut extra = vec![(MENU_ZIP, "Compress to ZIP")];+ if paths.iter().all(|p| p.is_file() && jobs::is_archive(p)) {+ extra.insert(0, (MENU_EXTRACT, "Extract here"));+ }+ let picked = sh::show(h, paths, if jobs::busy() { &[] } else { &extra }).ok().flatten();+ match picked {+ Some(MENU_ZIP) => {+ let base = if paths.len() == 1 { paths[0].file_stem().unwrap_or_default().to_string_lossy().into_owned() } else { dir.file_name().map_or("Archive".into(), |n| n.to_string_lossy().into_owned()) };+ let dest = jobs::free_name(dir, &format!("{base}.zip"), false);+ jobs::zip(h as isize, paths.to_vec(), dest);+ }+ Some(MENU_EXTRACT) => _ = jobs::extract(h as isize, paths.to_vec(), dir.to_path_buf()),+ _ => reload(h),+ }+}+/// Right click on empty space: the folder's own menu.#[allow(unsafe_op_in_unsafe_fn)]unsafe fn bg_menu(h: HWND) {@@ -593,23 +623,36 @@ mod sh {CM2.with_borrow(|c| c.as_ref().is_some_and(|c| unsafe { c.HandleMenuMsg(m, WPARAM(wp), LPARAM(lp)).is_ok() }))}- /// The real shell context menu for `paths`, so 7-Zip/Git/etc. entries show up.- pub fn show(h: *mut c_void, paths: &[PathBuf]) -> Result<()> {+ /// The real shell context menu for `paths`, so 7-Zip/Git/etc. entries show up. `extra` = our own items on top+ /// (ids above the shell's range); returns the one picked, None when the shell handled the pick or nothing was picked.+ pub fn show(h: *mut c_void, paths: &[PathBuf], extra: &[(u32, &str)]) -> Result<Option<u32>> {unsafe {let hwnd = HWND(h);let cm: IContextMenu = ui(hwnd, paths)?;let menu = CreatePopupMenu()?;cm.QueryContextMenu(menu, 0, 1, 0x7FFF, CMF_NORMAL).ok()?;+ if !extra.is_empty() {+ let _ = InsertMenuW(menu, 0, MF_BYPOSITION | MF_SEPARATOR, 0, PCWSTR::null());+ for (id, text) in extra.iter().rev() {+ let t: Vec<u16> = text.encode_utf16().chain([0]).collect();+ let _ = InsertMenuW(menu, 0, MF_BYPOSITION | MF_STRING, *id as usize, PCWSTR(t.as_ptr()));+ }+ }CM2.set(cm.cast::<IContextMenu2>().ok());let mut pt = POINT::default();GetCursorPos(&mut pt)?;let id = TrackPopupMenuEx(menu, TPM_RETURNCMD.0 | TPM_RIGHTBUTTON.0, pt.x, pt.y, hwnd, None).0;CM2.set(None);+ if extra.iter().any(|e| e.0 as i32 == id) {+ DestroyMenu(menu)?;+ return Ok(Some(id as u32));+ }if id > 0 {let ci = CMINVOKECOMMANDINFO { cbSize: size_of::<CMINVOKECOMMANDINFO>() as u32, hwnd, lpVerb: PCSTR((id - 1) as usize as *const u8), nShow: SW_SHOWNORMAL.0, ..Default::default() };cm.InvokeCommand(&ci)?;}- DestroyMenu(menu)+ DestroyMenu(menu)?;+ Ok(None)}}@@ -1097,8 +1140,8 @@ unsafe extern "system" fn proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESU}}NM_RCLICK if nm.hwndFrom == list => {- let (_, _, paths) = selected();- if !paths.is_empty() { let _ = sh::show(h, &paths); reload(h); } else { bg_menu(h); }+ let (_, dir, paths) = selected();+ if !paths.is_empty() { item_menu(h, &dir, &paths); } else { bg_menu(h); }}LVN_COLUMNCLICK => {let c = (*(lp as *const NMLISTVIEW)).iSubItem as usize;@@ -1147,7 +1190,7 @@ unsafe extern "system" fn proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESUput(edit, EM_SETSEL, 0, -1);return 0;}- 0x5D if !paths.is_empty() => { let _ = sh::show(h, &paths); }+ 0x5D if !paths.is_empty() => item_menu(h, &dir, &paths),0x43 | 0x58 if ctrl && !paths.is_empty() => { let _ = sh::clip_set(h, &paths, vk == 0x58); return 0; }0x56 if ctrl => paste(h, &dir),0x4E if ctrl => new_entry(&dir, "New folder", true),@@ -1182,6 +1225,13 @@ unsafe extern "system" fn proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESU}WM_SETFOCUS => { SetFocus(ST.with_borrow(|st| st.list)); 0 }WM_APP => { reload(h); 0 }+ WM_JOB => {+ let err = *Box::from_raw(wp as *mut Option<String>);+ reload(h);+ ui::status_dirty(h);+ if let Some(e) = err { MessageBoxW(h, w(&e).as_ptr(), w("WinRust Explorer").as_ptr(), MB_ICONWARNING); }+ 0+ }WM_NAV => {match wp {1 => nav(h, true),diff --git a/plugins/rust-explorer/src/ui.rs b/plugins/rust-explorer/src/ui.rsindex 6ea2ac8..1f1c5fe 100644--- a/plugins/rust-explorer/src/ui.rs+++ b/plugins/rust-explorer/src/ui.rs@@ -615,6 +615,7 @@ pub unsafe fn paint_status(h: HWND) {(s, 0) => format!("{} \u{00B7} {s} selected", items(n)),(s, b) => format!("{} \u{00B7} {s} selected \u{00B7} {}", items(n), size_text(b)),};+ let left = crate::jobs::status_text().unwrap_or(left); // a copy, packing or unpacking in progresslet by = ["Name", "Date", "Type", "Size"][SORT_COL.load(Relaxed).min(3)];let right = format!("{by} {}", if SORT_ASC.load(Relaxed) { "\u{2191}" } else { "\u{2193}" });let f = font(12, 400, ui_face()) as HFONT;diff --git a/plugins/rust-search/src/bin/rs-launcher.rs b/plugins/rust-search/src/bin/rs-launcher.rsindex e65d184..146a78e 100644--- a/plugins/rust-search/src/bin/rs-launcher.rs+++ b/plugins/rust-search/src/bin/rs-launcher.rs@@ -1393,6 +1393,7 @@ fn main() {#[cfg(test)]mod tests {use super::*;+ use std::os::windows::process::CommandExt;#[test]fn wipe_unlocks_read_only_and_never_follows_junctions() {@@ -1408,7 +1409,7 @@ mod tests {fs::set_permissions(&ro, perm).unwrap();fs::write(outside.join("keep.txt"), "keep").unwrap();let link = doomed.join("link");- assert!(std::process::Command::new("cmd").args(["/c", "mklink", "/J"]).arg(&link).arg(&outside).output().unwrap().status.success());+ assert!(std::process::Command::new("cmd").args(["/c", "mklink", "/J"]).arg(&link).arg(&outside).creation_flags(0x0800_0000).output().unwrap().status.success());assert_eq!(measure(&doomed), (2, 1), "ro.txt + the junction itself, target not counted");let mut failed = Vec::new();diff --git a/plugins/rust-search/src/regsweep.rs b/plugins/rust-search/src/regsweep.rsindex adb5301..d0f7db8 100644--- a/plugins/rust-search/src/regsweep.rs+++ b/plugins/rust-search/src/regsweep.rs@@ -255,11 +255,12 @@ pub fn delete(hits: &[Hit]) -> Report {#[cfg(test)]mod tests {use super::*;+ use std::os::windows::process::CommandExt; // no console window per reg.exe#[test]fn scan_backup_delete_restore_in_the_real_registry() {let p = "C:\\rs-sweep-test-9f3a\\App";- let reg = |args: &[&str]| std::process::Command::new("reg").args(args).output().unwrap().status.success();+ let reg = |args: &[&str]| std::process::Command::new("reg").args(args).creation_flags(0x0800_0000).output().unwrap().status.success();let base = "HKCU\\Software\\rs-sweep-test-9f3a";let _ = reg(&["delete", base, "/f"]);assert!(reg(&["add", &format!("{base}\\Run"), "/v", "x", "/d", &format!("\"{p}\\a.exe\" /s"), "/f"]));diff --git a/plugins/topbar/src/main.rs b/plugins/topbar/src/main.rsindex fa4e7bf..80d382f 100644--- a/plugins/topbar/src/main.rs+++ b/plugins/topbar/src/main.rs@@ -2652,6 +2652,7 @@ fn main() {load_pins();fly::init(GetModuleHandleW(null()));thread::spawn(fly::load_apps);+ thread::spawn(winrust_common::mem::auto_loop); // standby purge when memory runs short, switched on from the task manager's Speed pagelet hi = GetModuleHandleW(null());let class = wide("topbar");let wc = WNDCLASSW { lpfnWndProc: Some(wndproc), hInstance: hi, hCursor: LoadCursorW(null_mut(), IDC_ARROW), lpszClassName: class.as_ptr(), ..zeroed() };diff --git a/src/install/journal.rs b/src/install/journal.rsnew file mode 100644index 0000000..18be317--- /dev/null+++ b/src/install/journal.rs@@ -0,0 +1,78 @@+//! A plugin's change journal on disk (format and tests: common/src/journal.rs). Lives in Program Files (admin-only): the elevated+//! uninstall replays it, so a file a user could plant or edit would be a way to write any HKLM value.+use crate::*;+pub(crate) use i18n::journal::{Entry, svc_mode};++pub(crate) struct Journal(PathBuf);++pub(crate) fn svc_key(name: &str) -> String {+ format!(r"HKLM\SYSTEM\CurrentControlSet\Services\{name}")+}++/// A value as the journal stores it: (type, data), DWORD data in decimal. None = no such value.+pub(crate) fn reg_get(key: &str, name: &str) -> Option<(String, String)> {+ let o = out("reg", &["query", key, "/v", name]).ok()?;+ let (ty, d) = i18n::reg::value(&o)?;+ let d = if ty == "REG_DWORD" { i18n::reg::dword(&o)?.to_string() } else { d.to_string() };+ Some((ty.to_string(), d))+}++impl Journal {+ /// Opens `plugin`'s journal. A missing one starts with `legacy()`: what a launcher from before the journal changed.+ pub(crate) fn open(plugin: &str, legacy: impl FnOnce() -> Vec<Entry>) -> Result<Journal, String> {+ let j = Journal(program_files().join(r"WinRust\journal").join(format!("{plugin}.txt")));+ if !j.0.is_file() {+ fs::create_dir_all(j.0.parent().unwrap()).map_err(|e| e.to_string())?;+ let text: String = legacy().iter().filter_map(Entry::line).map(|l| l + "\n").collect();+ fs::write(&j.0, text).map_err(|e| format!("{}: {e}", j.0.display()))?;+ }+ Ok(j)+ }++ fn entries(&self) -> Vec<Entry> {+ fs::read_to_string(&self.0).map(|t| i18n::journal::parse_all(&t)).unwrap_or_default()+ }++ /// Writes `e` down before the change it describes; a value already in the journal keeps its original.+ fn record(&self, e: Entry) -> Result<(), String> {+ if self.entries().iter().any(|x| x.same(&e)) {+ return Ok(());+ }+ let line = e.line().ok_or(tf!("не могу сохранить старое значение: {e:?}", "cannot save the old value: {e:?}"))?;+ let mut f = fs::OpenOptions::new().append(true).open(&self.0).map_err(|e| format!("{}: {e}", self.0.display()))?;+ writeln!(f, "{line}").and_then(|_| f.sync_all()).map_err(|e| format!("{}: {e}", self.0.display()))+ }++ pub(crate) fn set_reg(&self, key: &str, name: &str, ty: &str, data: &str) -> Result<(), String> {+ self.record(Entry::Reg { key: key.into(), name: name.into(), old: reg_get(key, name) })?;+ run("reg", &["add", key, "/v", name, "/t", ty, "/d", data, "/f"])+ }++ pub(crate) fn set_svc(&self, name: &str, mode: &str) -> Result<(), String> {+ let k = svc_key(name);+ let old = svc_mode(reg_dword(&k, "Start"), reg_dword(&k, "DelayedAutostart")).ok_or(tf!("служба {name}: неизвестный тип запуска", "service {name}: unknown start type"))?;+ self.record(Entry::Svc { name: name.into(), mode: old.into() })?;+ run("sc.exe", &["config", name, "start=", mode])+ }++ /// Puts everything back, newest first. The journal is deleted only when every entry was restored, so a retry can finish.+ pub(crate) fn undo(&self) -> Result<(), String> {+ let errs: Vec<String> = self.entries().iter().rev().filter_map(|e| restore(e).err()).collect();+ if !errs.is_empty() {+ return Err(errs.join("; "));+ }+ let _ = fs::remove_file(&self.0);+ let _ = fs::remove_dir(self.0.parent().unwrap()); // only when empty+ Ok(())+ }+}++fn restore(e: &Entry) -> Result<(), String> {+ match e {+ // the change itself may have failed: a value that is not there is already restored+ Entry::Reg { key, name, old: None } => run("reg", &["delete", key, "/v", name, "/f"]).or_else(|e| if reg_get(key, name).is_none() { Ok(()) } else { Err(e) }),+ Entry::Reg { key, name, old: Some((ty, d)) } => run("reg", &["add", key, "/v", name, "/t", ty, "/d", d, "/f"]),+ // stripped builds may have lost the service since: nothing to restore+ Entry::Svc { name, mode } => run("sc.exe", &["config", name, "start=", mode]).or_else(|e| if run("sc.exe", &["query", name]).is_err() { Ok(()) } else { Err(e) }),+ }+}diff --git a/src/install/mod.rs b/src/install/mod.rsindex 690229a..ac3f77c 100644--- a/src/install/mod.rs+++ b/src/install/mod.rs@@ -2,12 +2,13 @@//! process/registry helpers, the embedded payload, and one file per plugin with its install/uninstall pair.use crate::*;mod explorer;+mod journal;mod search;mod session;mod taskmgr;mod tools;mod topbar;-pub(crate) use {explorer::*, search::*, session::*, taskmgr::*, tools::*, topbar::*};+pub(crate) use {explorer::*, journal::*, search::*, session::*, taskmgr::*, tools::*, topbar::*};pub(crate) fn out(prog: &str, args: &[&str]) -> Result<String, String> {// reg.exe: HKCU means the signed-in user's, not the elevated account's (see session.rs)diff --git a/src/install/search.rs b/src/install/search.rsindex aa19203..a14ca50 100644--- a/src/install/search.rs+++ b/src/install/search.rs@@ -1,26 +1,33 @@//! rust-search: NTFS search service + Alt+Space launcher; disables Windows Search (reversibly).use crate::*;-/// What the system looked like before the plugin touched it: HKLM\SOFTWARE\plugin-launcher\<plugin>. Written once-/// (an update must not overwrite the originals with our own values), read and deleted on uninstall.+/// Where launchers before the change journal kept the originals; turned into the journal's first lines, then deleted.pub(crate) const STATE: &str = r"HKLM\SOFTWARE\plugin-launcher\rust-search";-pub(crate) const WS_KEY: &str = r"HKLM\SYSTEM\CurrentControlSet\Services\WSearch";pub(crate) const SB_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Search";-pub(crate) fn save_dword(name: &str, v: Option<u32>) {- if let (Some(v), None) = (v, reg_dword(STATE, name)) {- let _ = run("reg", &["add", STATE, "/v", name, "/t", "REG_DWORD", "/d", &v.to_string(), "/f"]);- }-}-pub(crate) const SH_KEY: &str = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\SearchHost.exe";pub(crate) fn prog_dir() -> PathBuf {program_files().join("rs-search")}-pub(crate) fn taskbar_search(mode: u32) -> Result<(), String> {- run("reg", &["add", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Search", "/v", "SearchboxTaskbarMode", "/t", "REG_DWORD", "/d", &mode.to_string(), "/f"])+/// What this plugin changed in the system (journal.rs). An install by an older launcher is read from STATE: the Windows+/// defaults where it saved nothing.+pub(crate) fn journal() -> Result<Journal, String> {+ let j = Journal::open("rust-search", || {+ if run("reg", &["query", STATE]).is_err() && !prog_dir().join("rs.exe").is_file() {+ return vec![]; // never installed+ }+ let ws = svc_mode(reg_dword(STATE, "WSearchStart"), reg_dword(STATE, "WSearchDelayed")).unwrap_or("delayed-auto");+ let sb = reg_dword(STATE, "SearchboxMode").unwrap_or(2);+ vec![+ Entry::Svc { name: "WSearch".into(), mode: ws.into() },+ Entry::Reg { key: SH_KEY.into(), name: "Debugger".into(), old: None },+ Entry::Reg { key: SB_KEY.into(), name: "SearchboxTaskbarMode".into(), old: Some(("REG_DWORD".into(), sb.to_string())) },+ ]+ })?;+ let _ = run("reg", &["delete", STATE, "/f"]);+ Ok(j)}/// Stripped Windows builds (LTSC ISOs run through a debloater) have no WSearch service: nothing to switch off, not an error.@@ -29,10 +36,7 @@ pub(crate) fn has_wsearch() -> bool {}pub(crate) fn install() -> Result<(), String> {- // originals first: if anything below fails, the rollback restores exactly these- save_dword("WSearchStart", reg_dword(WS_KEY, "Start"));- save_dword("WSearchDelayed", Some(reg_dword(WS_KEY, "DelayedAutostart").unwrap_or(0)));- save_dword("SearchboxMode", reg_dword(SB_KEY, "SearchboxTaskbarMode"));+ let j = journal()?; // before anything changes: a failed install is rolled back from itwith_payload(&["rs.exe", "rs-launcher.exe"], |src| {run(src.join("rs.exe").to_str().unwrap(), &["--install"])?; // copies itself to Program Files, registers boot taskslet dst = prog_dir().join("rs-launcher.exe"); // must live somewhere stable: --autostart registers its own path@@ -43,15 +47,15 @@ pub(crate) fn install() -> Result<(), String> {// inherit admin rights, and every file opened from search would run elevated too.let _ = Command::new("explorer.exe").arg(&dst).spawn();if has_wsearch() {- run("sc.exe", &["config", "WSearch", "start=", "disabled"])?;+ j.set_svc("WSearch", "disabled")?;let _ = run("sc.exe", &["stop", "WSearch"]);} else {WARN.lock().unwrap().push(t!("службы Windows Search (WSearch) нет в этой системе: шаг пропущен", "the Windows Search service (WSearch) does not exist on this system: step skipped").into());}// SearchHost.exe (the Start/Win+S search UI) is not a service, so it gets the same IFEO trick as taskmgr: Windows runs `cmd /c exit` instead.- run("reg", &["add", SH_KEY, "/v", "Debugger", "/t", "REG_SZ", "/d", "cmd.exe /c exit", "/f"])?;+ j.set_reg(SH_KEY, "Debugger", "REG_SZ", "cmd.exe /c exit")?;let _ = run("taskkill", &["/f", "/im", "SearchHost.exe"]);- taskbar_search(0) // hide the taskbar search box+ j.set_reg(SB_KEY, "SearchboxTaskbarMode", "REG_DWORD", "0") // hide the taskbar search box})}@@ -59,22 +63,11 @@ pub(crate) fn uninstall() -> Result<(), String> {let _ = run("taskkill", &["/f", "/im", "rs-launcher.exe"]);let _ = run("reg", &["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "rs-launcher", "/f"]);// Windows Search back first: a failure removing our files below must not leave it switched off- let _ = run("reg", &["delete", SH_KEY, "/v", "Debugger", "/f"]);- // no saved values (installed by an older launcher): the Windows defaults- let mode = match (reg_dword(STATE, "WSearchStart"), reg_dword(STATE, "WSearchDelayed")) {- (Some(2), Some(0)) => "auto",- (Some(3), _) => "demand",- (Some(4), _) => "disabled",- _ => "delayed-auto",- };- let svc = if has_wsearch() { run("sc.exe", &["config", "WSearch", "start=", mode]) } else { Ok(()) }; // nothing to restore without the service- if svc.is_ok() && mode.ends_with("auto") && has_wsearch() {+ let r = journal().and_then(|j| j.undo());+ let k = svc_key("WSearch");+ if r.is_ok() && svc_mode(reg_dword(&k, "Start"), reg_dword(&k, "DelayedAutostart")).is_some_and(|m| m.ends_with("auto")) {let _ = run("sc.exe", &["start", "WSearch"]);}- let r = svc.and(taskbar_search(reg_dword(STATE, "SearchboxMode").unwrap_or(2)));- if r.is_ok() {- let _ = run("reg", &["delete", STATE, "/f"]);- }// run the unpacked copy: an exe cannot delete itself, so the installed one would leave its folder behindlet files = with_payload(&["rs.exe"], |src| run(src.join("rs.exe").to_str().unwrap(), &["--uninstall"]));let _ = fs::remove_dir_all(prog_dir());diff --git a/src/install/taskmgr.rs b/src/install/taskmgr.rsindex eb68a98..151eaf8 100644--- a/src/install/taskmgr.rs+++ b/src/install/taskmgr.rs@@ -20,12 +20,13 @@ pub(crate) fn tm_install() -> Result<(), String> {if let Some(old) = reg_str(TM_KEY, "Debugger").filter(|_| !tm_installed() && reg_str(TM_STATE, "Debugger").is_none()) {run("reg", &["add", TM_STATE, "/v", "Debugger", "/t", "REG_SZ", "/d", &old, "/f"])?;}- with_payload(&["Task manager.exe", "rs-du.exe"], |d| {+ with_payload(&["Task manager.exe", "rs-du.exe", "debloat.exe"], |d| {let dst = tm_dir().join("rtaskmgr-win32.exe");let _ = run("taskkill", &["/f", "/im", "rtaskmgr-win32.exe"]); // an update: a running exe cannot be overwrittenfs::create_dir_all(tm_dir()).map_err(|e| e.to_string())?;put(&d.join("Task manager.exe"), &dst)?;put(&d.join("rs-du.exe"), &tm_dir().join("rs-du.exe"))?;+ put(&d.join("debloat.exe"), &tm_dir().join("debloat.exe"))?; // the Speed page's optional groups (updaters, Defender, NTFS, hosts)// the search (and the bar's Start panel) lists Start Menu shortcuts only, so without one the task manager is invisible to themsoft(t!("ярлык в меню Пуск не создан, поиск не увидит диспетчер", "Start menu shortcut was not created, search will not find the task manager"), shortcut(&start_lnk("Task manager"), &dst, ""));// elevated start without a UAC prompt (the exe re-launches itself through this task), so it can end protected processes@@ -36,6 +37,14 @@ pub(crate) fn tm_install() -> Result<(), String> {}pub(crate) fn tm_uninstall() -> Result<(), String> {+ // first what the Speed page switched on (profile, shell blocks, debloat groups): it needs the exe and debloat.exe next to it.+ // On failure everything stays, so uninstalling again retries.+ let exe = tm_dir().join("rtaskmgr-win32.exe");+ if exe.is_file() {+ let _ = run("taskkill", &["/f", "/im", "rtaskmgr-win32.exe"]);+ out(&exe.display().to_string(), &["--undo-speed"])?;+ }+ let _ = fs::remove_file(tm_dir().join("debloat.exe"));let _ = fs::remove_file(start_lnk("Task manager"));let _ = run("schtasks", &["/delete", "/tn", "rtaskmgr", "/f"]);// registry first: with the exe gone, taskmgr.exe would not start at all. Only our value: the key may hold