Windows shell replacement in Rust: taskbar, file manager, NTFS search, task manager, disk cleaner. One installer exe.
Rust
v0.2.1: cargo workspace, shared winrust-common crate, payload.txt, installer split into modules, CI; Win+D/Win+I without Explorer; rs-shell ends Explorer on Windows 26300; one button installs and updates; docs rewritten
Lemxyce8f94759376
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlnew file mode 100644index 0000000..8798bc1--- /dev/null+++ b/.github/workflows/build.yml@@ -0,0 +1,28 @@+# Builds everything and runs the unit tests on every push and pull request. The built installer is kept as an artifact.+name: build+on:+ push:+ branches: [main]+ pull_request:++jobs:+ build:+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v4+ - uses: Swatinem/rust-cache@v2+ with:+ workspaces: |+ .+ plugins/rust-search+ - name: Build all (plugins, payload, installer)+ run: powershell -ExecutionPolicy Bypass -File scripts\build-all.ps1+ - name: Test workspace+ run: cargo test --workspace+ - name: Test rust-search+ run: cargo test+ working-directory: plugins/rust-search+ - uses: actions/upload-artifact@v4+ with:+ name: WinRust+ path: target/release/plugin-launcher.exediff --git a/CLAUDE.md b/CLAUDE.mdindex f95df2f..ac9b8d1 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,50 +1,70 @@-# plugin-launcher+# WinRust (plugin-launcher)-Windows-лаунчер (`src/main.rs`), который ставит плагины из `plugins/` (отдельные cargo-проекты) и `ReShell/`. Описание: `README.md`, планы: `ROADMAP.md`.+Установщик `plugin-launcher.exe` ставит и удаляет плагины, которые заменяют части Windows. Для пользователя: `README.md`, планы: `ROADMAP.md`.-## Как обновить плагин после правки его кода (без пересборки лаунчера)+## ⚠ Главная ловушка: MSIX и HKCU-Лаунчер берёт exe из `payload\` на диске раньше вшитых копий, поэтому после правки плагина:+Приложение Claude упаковано в MSIX. Всё, что запущено из его оболочки (даже через UAC), пишет HKCU в личную копию реестра пакета, которую настоящий сеанс не видит (так терялись Run-ключи, `ReplaceExplorer`, привязка папок). HKLM пишется по-настоящему.+- Установщик (`install`, `update`) запускай **только через explorer.exe** (ярлык или `explorer.exe <bat>`). `update-plugin.ps1` уже делает это сам.+- `reg query HKCU\...` из своей оболочки показывает копию пакета, а не правду. Настоящие значения смотри батником, запущенным через `explorer.exe <bat>`.++## Где что лежит++| Путь | Что |+|---|---|+| `src/main.rs` | таблица `PLUGINS` и общее состояние |+| `src/install/` | что каждый плагин меняет в системе и как откатывается (файл на плагин; `mod.rs`: общие хелперы, payload, `install_plugin`/`rollback`) |+| `src/cli.rs`, `src/ui.rs` | командная строка и окно |+| `common/` | `winrust-common`: `t!`/`tf!`/`en!` (язык) и `mft` (чтение MFT) для всех программ |+| `plugins/<имя>/`, `ReShell/` | исходники плагинов (это и есть оригиналы: копий на рабочем столе больше нет, правь здесь) |+| `payload.txt` | единственный список вшиваемых exe: из него читают `build.rs` и `scripts\build-plugins.ps1` |++Один cargo workspace, все exe в `target\release`. `plugins/rust-search` и `plugins/chrome-rs` вне workspace (им нужен `panic = "unwind"`), у них свой `target\`.++## Сборка и проверка++- Полная сборка: `powershell -ExecutionPolicy Bypass -File scripts\build-all.ps1` (плагины → `payload\` → установщик).+- Только плагины: `scripts\build-plugins.ps1`. Только установщик: `cargo build --release -p plugin-launcher` (нужен заполненный `payload\`).+- Тесты: `cargo test --workspace` и `cargo test` в `plugins\rust-search`. У самого установщика тестового exe нет (`test = false`: манифест требует админа).+- В юнит-тестах тексты всегда русские: в коде с тестами пиши `en!()`, а не `english()`.++## Обновить установленный плагин после правки (без пересборки установщика)```powershell-powershell -ExecutionPolicy Bypass -File scripts\update-plugin.ps1 <rust-search|rtaskmgr-win32|topbar>+powershell -ExecutionPolicy Bypass -File scripts\update-plugin.ps1 <rust-search|rtaskmgr-win32|topbar|rust-explorer|wiztree|photoview|debloat>```-Скрипт сам собирает плагин и то, что ставится вместе с ним (topbar → ещё `ReShell` и `rs-du`; rtaskmgr-win32 → ещё `rs-du`), кладёт exe в `payload\` и запускает `plugin-launcher update <плагин>`. Установка требует админа: из обычной оболочки появится окно UAC, **нажать «Да» должен пользователь**. Не пытайся обойти UAC и не меняй настройки UAC.--Лаунчер скрипт запускает **через explorer.exe** (ярлык), а не своим дочерним процессом. Приложение Claude упаковано в MSIX: всё, что запущено из его оболочки (даже через UAC), пишет HKCU в личную копию реестра пакета, которую настоящий сеанс не видит (так терялись Run-ключи, `ReplaceExplorer`, привязка папок). HKLM пишется по-настоящему. Поэтому `install` тоже запускай через explorer.exe, а `reg query HKCU\...` из своей оболочки показывает копию пакета, а не правду. Настоящие значения смотри батником, запущенным через `explorer.exe <bat>`.+Скрипт пересобирает плагины, обновляет `payload\` и запускает `plugin-launcher update <плагин>` через explorer.exe. Появится окно UAC: **«Да» нажимает пользователь**. Не обходи UAC и не меняй его настройки.После запуска:-1. Скрипт печатает последние строки `%ProgramData%\plugin-launcher\install.log`. Успех: строка `<плагин>: updated` (в русском режиме `обновлён`). Предупреждения идут после `|`. Ошибка: `ERROR ...` (`ОШИБКА ...`). Файл в UTF-8, читай с `-Encoding UTF8`.-2. Проверь, что процесс плагина запущен (`Get-Process topbar,reshell` и т. п.).-3. Не нашёл `updated`/`обновлён` или есть ошибка: покажи пользователю текст ошибки, сам ничего не удаляй и не чини реестр.+1. Скрипт печатает хвост `%ProgramData%\plugin-launcher\install.log` (UTF-8, читай с `-Encoding UTF8`). Успех: `<плагин>: updated` (`обновлён`), предупреждения после `|`. Ошибка: `ERROR ...` (`ОШИБКА ...`).+2. Проверь, что процесс запущен (`Get-Process topbar,reshell` и т. п.).+3. Нет `updated`/`обновлён` или есть ошибка: покажи пользователю текст ошибки, сам ничего не удаляй и не чини реестр.## Правила-- `update` только для уже установленного плагина. Новый плагин: `install <имя> --yes`, **только с разрешения пользователя** (rust-search отключает поиск Windows, topbar прячет панель задач).-- Не запускай `uninstall`, `rollback` и `install` без прямой просьбы пользователя.-- Правки в `src/main.rs` (сам лаунчер) требуют `cargo build --release` в корне. Для релиза со свежими вшитыми exe: `scripts\build-all.ps1`.-- Правки `src/main.rs` и код установки на живой системе ни разу не прогонялись целиком: тестируй осторожно, по одному плагину.-- `plugins/rust-search` и `plugins/rtaskmgr-win32` синхронизируются с оригиналами на рабочем столе (`scripts\sync.ps1`: оригиналы главнее). Правь оригиналы, а не копии в `plugins\`.+- `update` только для уже установленного плагина. `install <имя> --yes`, `uninstall`, `rollback` **только по прямой просьбе пользователя** (rust-search отключает поиск Windows, topbar прячет панель задач, rust-explorer отключает Проводник).+- Код установки (`src/install/`) ни разу не прогонялся целиком на живой системе: тестируй осторожно, по одному плагину.+- Новый плагин: crate в `plugins/` + `members` в `Cargo.toml`, строка в `payload.txt`, файл в `src/install/`, запись в `PLUGINS`. Перед изменением системы сохраняй исходные значения, чтобы uninstall их вернул.-## Публикация на GitHub (репозиторий `Lemxy/WinRust`, ветка `main`)+## Публикация на GitHub (`Lemxy/WinRust`, ветка `main`)-Папка уже подключена: `origin` = `https://github.com/Lemxy/WinRust.git`, аккаунт gh `Lemxy`.+`origin` = `https://github.com/Lemxy/WinRust.git`, аккаунт gh `Lemxy`.-**Автоматика.** Хук `Stop` (`.claude/settings.local.json`, в git не лежит) после каждого ответа запускает `scripts\publish.ps1 -Auto`: если есть изменения, коммитит и пушит в `main`. Скрипт сам отказывается пушить (и снимает индекс), если в изменениях `.exe/.dll/.pdb/.log/.reg/ключи`, `target/`, файлы больше 5 МБ или что-то похожее на токен. Вручную: `scripts\publish.ps1 [-Message "..."]`.+**Автоматика.** Хук `Stop` (`.claude/settings.local.json`, не в git) после каждого ответа запускает `scripts\publish.ps1 -Auto`: есть изменения → коммит и пуш в `main`. Значит, **код должен собираться и проходить тесты к концу каждого ответа**. Скрипт сам отказывается пушить (и снимает индекс), если в изменениях `.exe/.dll/.pdb/.log/.reg/ключи`, `target/`, файлы больше 5 МБ или похожее на токен. Вручную: `scripts\publish.ps1 [-Message "..."]`. CI (`.github/workflows/build.yml`) собирает и тестирует каждый пуш.-**Правила коммитов (требование владельца).**-- Никаких `Co-Authored-By` и упоминаний Claude в сообщениях коммитов, описаниях PR и релизов: Claude не должен появляться контрибьютором. Это важнее общих шаблонов атрибуции.-- Автор: `Lemxy <[email protected]>` (уже в локальном git config). Настоящую почту владельца в репозиторий не писать.+**Коммиты (требование владельца).**+- Никаких `Co-Authored-By` и упоминаний Claude в коммитах, PR и релизах: Claude не должен появляться контрибьютором. Это важнее общих шаблонов атрибуции.+- Автор: `Lemxy <[email protected]>` (уже в git config). Настоящую почту владельца в репозиторий не писать.- `git push --force`, удаление репозитория/тегов/релизов и смена видимости только по прямой просьбе.- Не коммитить `payload\*.exe`, `target\`, логи (они в `.gitignore`).-**Описания и документация.**-- `README.md` на английском, `README.ru.md` на русском: править оба одинаково. Так же `ROADMAP.md` / `ROADMAP.ru.md`.-- Бенчмарк в README обновлять только после реального нового замера (`scripts\bench.ps1`, на одной машине, одноразово), цифры не придумывать.-- В README есть оговорка про неподписанный exe и SmartScreen: не убирать, пока нет подписи.-- Описание, темы (topics) и главная страница репозитория меняются через `gh repo edit` только по просьбе владельца.+**Документация.**+- `README.md` (англ.) и `README.ru.md` (рус.) править одинаково. Так же `ROADMAP.md` / `ROADMAP.ru.md`.+- Бенчмарк в README обновлять только после реального нового замера (`scripts\bench.ps1`), цифры не придумывать.+- Оговорку про неподписанный exe и SmartScreen не убирать, пока нет подписи.+- Описание, темы и главная страница репозитория (`gh repo edit`) только по просьбе владельца.-**Релиз.** `scripts\release.ps1 v0.2.0 [-Notes "..."]`: собирает всё через `build-all.ps1` (с проверкой штампов), пушит, ставит тег, создаёт GitHub Release с `WinRust.exe`. Делать только когда владелец просит релиз. Перед релизом проверить, что в `ROADMAP.md` и README нет устаревшего.+**Релиз.** `scripts\release.ps1 v0.2.0 [-Notes "..."]`: `build-all.ps1`, пуш, тег, GitHub Release с `WinRust.exe`. Только когда владелец просит. Перед релизом проверить, что README и ROADMAP не устарели.-**Если пуш не прошёл:** показать текст ошибки владельцу. Не чинить принудительным пушем. Если `gh auth status` показывает активным не `Lemxy`, `gh auth switch -u Lemxy`.+**Если пуш не прошёл:** показать ошибку владельцу, не чинить принудительным пушем. Если в `gh auth status` активен не `Lemxy`: `gh auth switch -u Lemxy`.diff --git a/Cargo.lock b/Cargo.lockindex 51f8114..c3107a7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2,6 +2,18 @@# It is not intended for manual editing.version = 4+[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"+[[package]]name = "cc"version = "1.11.2"@@ -18,6 +30,10 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"+[[package]]+name = "debloat"+version = "0.1.0"+[[package]]name = "embed-resource"version = "3.0.12"@@ -60,6 +76,12 @@ dependencies = ["hashbrown",]+[[package]]+name = "lazy_static"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"+[[package]]name = "libc"version = "0.2.191"@@ -72,12 +94,68 @@ version = "2.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"+[[package]]+name = "muldiv"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0419348c027fa7be448d2ae7ea0e4e04c2334c31dc4e74ab29f00a2a7ca69204"++[[package]]+name = "native-windows-gui"+version = "1.0.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f7003a669f68deb6b7c57d74fff4f8e533c44a3f0b297492440ef4ff5a28454"+dependencies = [+ "bitflags 1.3.2",+ "lazy_static",+ "muldiv",+ "winapi",+ "winapi-build",+]++[[package]]+name = "ntapi"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"+dependencies = [+ "winapi",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "objc2-io-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"+dependencies = [+ "libc",+ "objc2-core-foundation",+]++[[package]]+name = "photoview"+version = "0.1.0"+dependencies = [+ "windows",+ "windows-sys",+]+[[package]]name = "plugin-launcher"-version = "0.2.0"+version = "0.2.1"dependencies = ["embed-resource","windows-sys",+ "winrust-common",][[package]]@@ -98,6 +176,52 @@ dependencies = ["proc-macro2",]+[[package]]+name = "reshell"+version = "0.1.0"+dependencies = [+ "windows-sys",+ "winrust-common",+]++[[package]]+name = "rs-du"+version = "0.1.0"+dependencies = [+ "windows-sys",+ "winrust-common",+]++[[package]]+name = "rs-shell"+version = "0.1.0"+dependencies = [+ "windows-sys",+ "winrust-common",+]++[[package]]+name = "rtaskmgr-win32"+version = "0.1.0"+dependencies = [+ "embed-resource",+ "native-windows-gui",+ "sysinfo",+ "winapi",+ "windows-sys",+ "winrust-common",+]++[[package]]+name = "rust-explorer"+version = "0.1.0"+dependencies = [+ "embed-resource",+ "windows",+ "windows-core",+ "windows-sys",+]+[[package]]name = "rustc_version"version = "0.4.1"@@ -130,7 +254,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"dependencies = ["proc-macro2","quote",- "syn",+ "syn 3.0.10",][[package]]@@ -148,6 +272,17 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"+[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]+[[package]]name = "syn"version = "3.0.10"@@ -159,6 +294,20 @@ dependencies = ["unicode-ident",]+[[package]]+name = "sysinfo"+version = "0.40.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a86bac2f7d06e6384984118ad727f5694110f0ec44d924d05c8fdec3d030bee6"+dependencies = [+ "libc",+ "memchr",+ "ntapi",+ "objc2-core-foundation",+ "objc2-io-kit",+ "windows",+]+[[package]]name = "toml"version = "1.2.1+spec-1.1.0"@@ -198,6 +347,15 @@ version = "1.2.0+spec-1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"+[[package]]+name = "topbar"+version = "0.1.0"+dependencies = [+ "windows",+ "windows-sys",+ "winrust-common",+]+[[package]]name = "unicode-ident"version = "1.0.27"@@ -224,12 +382,135 @@ dependencies = ["libc",]+[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-build"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc"++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"++[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core",+ "windows-link",+ "windows-threading",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "windows-link"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"+[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core",+ "windows-link",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]+[[package]]name = "windows-sys"version = "0.61.2"@@ -239,6 +520,15 @@ dependencies = ["windows-link",]+[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]+[[package]]name = "winnow"version = "1.0.5"@@ -254,3 +544,18 @@ dependencies = ["cfg-if","windows-sys",]++[[package]]+name = "winrust-common"+version = "0.1.0"+dependencies = [+ "windows-sys",+]++[[package]]+name = "wiztree"+version = "0.1.0"+dependencies = [+ "windows-sys",+ "winrust-common",+]diff --git a/Cargo.toml b/Cargo.tomlindex 1edb2b6..e8305d4 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,14 +1,38 @@[package]name = "plugin-launcher"-version = "0.2.0"+version = "0.2.1"edition = "2024"+[[bin]]+name = "plugin-launcher"+path = "src/main.rs"+test = false # the embedded manifest demands admin: a test exe could not start from a normal shell+[dependencies]+winrust-common = { path = "common" }windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_System_Console", "Win32_System_LibraryLoader", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }[build-dependencies]embed-resource = "3"+# One workspace: one Cargo.lock, one target\ (every exe lands in target\release), shared dependencies are built once.+[workspace]+members = [+ "common",+ "ReShell",+ "plugins/topbar",+ "plugins/rtaskmgr-win32",+ "plugins/rs-du",+ "plugins/rust-explorer",+ "plugins/rs-shell",+ "plugins/wiztree",+ "plugins/photoview",+ "plugins/debloat",+]+# Stay separate projects with their own target\ and Cargo.lock, because they need panic = "unwind" (the profile below is+# shared by every member): rust-search's service threads must not take the process down, chrome-rs catches panics per page.+exclude = ["plugins/rust-search", "plugins/chrome-rs"]+[profile.release]opt-level = "s"lto = true@@ -16,5 +40,5 @@ codegen-units = 1panic = "abort"strip = true-[workspace]-exclude = ["plugins"] # each plugin stays its own independent cargo project+[profile.release.package.rs-du]+opt-level = 3 # MFT parsing: speed over size, as before the workspacediff --git a/README.md b/README.mdindex 5e82eb5..26d930b 100644--- a/README.md+++ b/README.md@@ -2,12 +2,45 @@# WinRust-**A Windows shell written in Rust: faster and lighter than the stock one.** A set of small native programs (no .NET, no Electron) that replace parts of Windows: the taskbar, File Explorer, file search, Task Manager and a disk cleaner. One installer puts them in, one click takes them out.+**A Windows shell written in Rust: faster and lighter than the stock one.** Small native programs (no .NET, no Electron) that replace parts of Windows: the taskbar, File Explorer, file search, Task Manager, plus a disk cleaner, a disk map and a photo viewer. One installer puts them in, one button takes them all out.English | [Русский](README.ru.md)<p align="center"><img src="assets/th.jpg" alt="WinRust" width="480"></p>+> **Read this first.** WinRust turns off Windows Search, hides the taskbar and can turn off Explorer as the shell. The exe is not code-signed, so SmartScreen will warn you. A restore point is created before install, but try it on a spare machine or a VM first.++## Install++1. Download `WinRust.exe` from the [latest release](https://github.com/Lemxy/WinRust/releases/latest) (Windows 10/11, x64).+2. Run it as administrator.+3. Press **Install WinRust**. It installs every component, in the right order.++**Update:** download the new `WinRust.exe` from the releases page, run it as administrator and press **Update WinRust**. Installed plugins are updated, missing ones installed; your settings and the saved original Windows values stay.++The installer is in English. The **Русский** button in its corner (or "Language" in the bar's right-click menu) switches every WinRust program to Russian.++## Remove++- **Remove all** in the installer window undoes everything: Windows Search, the taskbar, Explorer and the services come back.+- One plugin at a time: `plugin-launcher uninstall <plugin>` (see [Command line](#command-line)).+- **If the screen is left without a taskbar or desktop:** press Ctrl+Alt+Del → Task Manager → Run new task → `explorer.exe`, then run the installer and press Remove all.++## What gets installed++| 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 |+| **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 DiagTrack, PcaSvc, InventorySvc, lfsvc, cbdhsvc, sets DoSvc to manual, merges svchost processes. 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) |+| **debloat** | Off: telemetry, Copilot, Recall, Start ads, Edge in the background | Services and registry policies; old values are saved and restored on uninstall. **Command line only:** `install debloat --yes` |+| chrome-rs | A browser | Not installable yet |++Every change is reversible: uninstall puts back the values that were there before.+## BenchmarkOne-off measurements on one machine (Windows 11 IoT Enterprise 10.0.26300, RTX 4060 Laptop, NTFS). Treat them as orders of magnitude, not lab numbers.@@ -25,66 +58,69 @@ One-off measurements on one machine (Windows 11 IoT Enterprise 10.0.26300, RTX 4In 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.-## Install+## Screenshots-Download `WinRust.exe` from the [latest release](https://github.com/Lemxy/WinRust/releases/latest), run it as administrator and press "Install WinRust" (the installer is in English by default; the **Русский** button in its corner, or "Language" in the bar's right-click menu, switches to Russian, and the other WinRust programs pick the choice up when they start). "Remove all" rolls everything back. Windows 10/11, x64.+**Taskbar**-> **Read this first.** WinRust disables Windows Search, replaces the taskbar and can replace the shell. The exe is not code-signed, so SmartScreen will warn. A restore point is created before install, but try it on a spare machine or a VM first.++-## What it is+**Task Manager** (Russian UI)-One exe (`plugin-launcher.exe`) that installs and removes our plugins on Windows. Administrator rights are required. In the window all plugins are grouped into one WinRust set: the "Install WinRust" button installs what is missing, in order (topbar before rust-explorer), and updates when everything is already there; "Remove all" rolls back. One plugin at a time: see the command line below.+-| Plugin | What it does |-|---|---|-| rust-search | file search over NTFS (Alt+Space); disables Windows Search |-| rtaskmgr-win32 | replaces Task Manager |-| topbar | a bottom bar in the Windows 11 style instead of the taskbar (smooth rounded corners, tooltips above buttons, volume on the mouse wheel with a level readout). It installs together with desktop hotkeys (reshell: Win+1/2/3, Win+`) and a block in the PowerShell profile (`src/profile.ps1`: zoxide, grep=rg, ll=eza, cat=bat; written to Windows PowerShell 5.1 and to pwsh 7 if present; silent without rg/eza/bat/zoxide). Uninstalling topbar removes the block. |-| rs-du | disk cleaner (MFT analysis, caches, `target`/`node_modules`, recycle bin). It has no card of its own: it is installed into the Task Manager folder together with rtaskmgr-win32 or topbar and starts from the bar menu (right-click an empty spot → "Disk cleaner"). Sources: `plugins/rs-du` |-| chrome-rs | placeholder |-| rs-shell | its own shell instead of explorer.exe for one user logon: wallpaper, autostart (Run and Startup), starts and restarts topbar, hands the session back to explorer.exe if topbar keeps crashing. Placed next to `topbar.exe`; `rs-shell --dry-run` shows what it would start; `--enable` / `--disable` turn it on and off (HKCU only, other users are untouched). Not installed by the launcher yet. Sources: `plugins/rs-shell` |-| rust-explorer | **A launcher plugin.** A Rust file manager in the Windows style instead of File Explorer: a left pane (quick access, drives), "Name / Date / Type / Size" columns, tabs, dark theme. Installing it makes folders and drives open in it (HKCU), starts `rs-shell --overlay` at logon and **turns off the regular explorer.exe** as the shell (AutoRestartShell=0; Explorer exits once topbar and the desktop are up; if topbar does not hold, Explorer comes back by itself). Needs topbar. Uninstall reverts everything. Features: virtual list, icons, tabs (Ctrl+T/W/Tab), copy/paste/delete via IFileOperation, the shell context menu, drag and drop. Not done: thumbnails, address bar, registering as the folder handler, stages 2-5 of the plan (index, shell, tray, Shell Launcher). |--## Layout+**File manager**++++---++## For developers++### Layout```-src/ the launcher (window + install logic)-payload/ built plugin exes, embedded into the launcher at build time (not in git)-plugins/ sources: rust-search, rtaskmgr-win32, topbar, rust-explorer, rs-shell, rs-du, ... (each is its own cargo project)-scripts/ build-all.ps1: syncs plugins/ with the originals, rebuilds, refreshes payload/ and STAMPS.txt; sync.ps1 -Check: drift check (run with -ExecutionPolicy Bypass)-ROADMAP.md plans+src/ the installer (plugin-launcher.exe)+ main.rs the plugin table PLUGINS: name, texts, install/uninstall pair, icon+ install/ what each plugin changes and how it is undone (one file per plugin)+ cli.rs, ui.rs the command line and the window; both call the same install functions+common/ winrust-common: language switch (t!/tf!) and the NTFS MFT reader, shared by the programs+plugins/ sources of every plugin, each its own crate+ReShell/ reshell (desktop hotkeys, topbar safety net), ships with topbar+payload.txt the exes embedded into the installer, and where the build puts them+payload/ those exes once built (not in git)+scripts/ build, update, release```+Everything is one cargo workspace (one `Cargo.lock`, every exe in `target\release`). `plugins/rust-search` and `plugins/chrome-rs` build separately because they need `panic = "unwind"` (see `Cargo.toml`).-## Build+### Build+Needs Windows x64, Rust stable (1.85+) with the MSVC toolchain.```powershell-.\scripts\build-all.ps1+powershell -ExecutionPolicy Bypass -File scripts\build-all.ps1```-Result: `target\release\plugin-launcher.exe`. Close a running launcher before building. Note: `build-all.ps1` currently syncs `rust-search` and `rtaskmgr-win32` from the author's own working folders (see `scripts\sync.ps1`), so a clean clone needs that step adapted.+Result: `target\release\plugin-launcher.exe`, with every plugin inside. Close a running installer first. Tests: `cargo test --workspace` (and `cargo test` in `plugins\rust-search`). CI runs the same on every push (`.github/workflows/build.yml`).-## Command line+| Script | What it does |+|---|---|+| `build-all.ps1` | everything: plugins → `payload\` → installer |+| `build-plugins.ps1` | plugins only → `payload\` (no installer rebuild) |+| `update-plugin.ps1 <plugin>` | rebuild and reinstall one installed plugin without rebuilding the installer (asks for admin via UAC) |+| `user-mode.ps1`, `dev-update.ps1` | developer mode: run topbar, rust-explorer, rs-shell and reshell from `%LOCALAPPDATA%` on top of Explorer, swap them without admin |+| `bench.ps1` | the search and Task Manager benchmark |+| `publish.ps1`, `release.ps1` | commit and push; GitHub release with `WinRust.exe` |++### Command lineFrom a terminal **with administrator rights**:```plugin-launcher listplugin-launcher install <plugin> --yes (without --yes it only prints the warning and changes nothing)-plugin-launcher update <plugin> (reinstall from payload\ next to the exe, no launcher rebuild; see scripts\update-plugin.ps1)+plugin-launcher update <plugin> (reinstall from payload\ next to the exe)plugin-launcher uninstall <plugin>-plugin-launcher rollback --yes+plugin-launcher rollback --yes (remove everything)```-Exit codes: 0 success, 1 error, 2 bad arguments or no `--yes`. With no arguments the window opens.--## New plugin-One entry in `PLUGINS` (`src/main.rs`): name, description, warning, `installed`, an install/uninstall function pair and a `glyph` icon. The window, the list height and the CLI pick it up on their own.--## Screenshots--**Taskbar (English)**-----**Task manager** (Russian UI)----**File explorer**+Exit codes: 0 success, 1 error, 2 bad arguments or no `--yes`. With no arguments the window opens. Install log: `%ProgramData%\plugin-launcher\install.log`.-+### Adding a plugin+1. A crate in `plugins/<name>`, added to `members` in the root `Cargo.toml`.+2. A line in `payload.txt`.+3. `src/install/<name>.rs` with an install/uninstall pair (and a `mod` line in `src/install/mod.rs`). Save the original values before changing anything, so uninstall can put them back.+4. An entry in `PLUGINS` (`src/main.rs`). The window, its height and the command line pick it up on their own.diff --git a/README.ru.md b/README.ru.mdindex 2e62526..03fb070 100644--- a/README.ru.md+++ b/README.ru.md@@ -1,15 +1,46 @@-[English](README.md) | **Русский**-<p align="center"><img src="assets/logo.svg" alt="WinRust" width="160"></p># WinRust-**Windows-оболочка на Rust: быстрее и легче стандартной.** Набор небольших нативных программ (без .NET, без Electron), которые заменяют части Windows: панель задач, Проводник, поиск файлов, диспетчер задач и чистильщик диска. Всё ставится и удаляется одним лаунчером, всё откатывается обратно.+**Windows-оболочка на Rust: быстрее и легче стандартной.** Небольшие нативные программы (без .NET, без Electron), которые заменяют части Windows: панель задач, Проводник, поиск файлов, диспетчер задач, а ещё чистильщик диска, карту диска и просмотрщик фото. Один установщик всё ставит, одна кнопка всё убирает.-Интерфейс по умолчанию английский; кнопка «Русский» в углу окна установщика (и пункт «Язык» в меню панели) переключает язык, остальные программы WinRust подхватывают выбор при запуске.+[English](README.md) | **Русский**<p align="center"><img src="assets/th.jpg" alt="WinRust" width="480"></p>+> **Сначала прочитайте.** WinRust отключает поиск Windows, прячет панель задач и может отключить Проводник как оболочку. Exe не подписан, поэтому SmartScreen покажет предупреждение. Перед установкой создаётся точка восстановления, но сначала попробуйте на запасной машине или в виртуалке.++## Установка++1. Скачайте `WinRust.exe` из [последнего релиза](https://github.com/Lemxy/WinRust/releases/latest) (Windows 10/11, x64).+2. Запустите от имени администратора.+3. Нажмите **Install WinRust**. Установщик поставит все компоненты в правильном порядке.++**Обновление:** скачайте новый `WinRust.exe` со страницы релизов, запустите от имени администратора и нажмите **Update WinRust** («Обновить WinRust» в русском режиме). Установленные плагины обновятся, недостающие поставятся; ваши настройки и сохранённые исходные значения Windows остаются.++Установщик открывается на английском. Кнопка **Русский** в его углу (или «Язык» в меню панели по правому клику) переключает на русский все программы WinRust.++## Удаление++- **Удалить всё** в окне установщика откатывает всё: возвращаются поиск Windows, панель задач, Проводник и службы.+- По одному плагину: `plugin-launcher uninstall <плагин>` (см. [Командная строка](#командная-строка)).+- **Если на экране не осталось панели или рабочего стола:** Ctrl+Alt+Del → Диспетчер задач → Запустить новую задачу → `explorer.exe`, затем откройте установщик и нажмите «Удалить всё».++## Что ставится++| Плагин | Что вы получаете | Что меняется в Windows |+|---|---|---|+| **rust-search** | Поиск файлов по всем NTFS-дискам, Alt+Space | Отключается служба поиска Windows, блокируется SearchHost.exe, прячется строка поиска на панели |+| **rtaskmgr-win32** | Диспетчер задач (Ctrl+Shift+Esc открывает его) | Запуск `taskmgr.exe` перенаправляется на него (системный файл не трогается). Заодно ставится чистильщик диска **rs-du** |+| **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 не работает). Отключаются DiagTrack, PcaSvc, InventorySvc, lfsvc, cbdhsvc, DoSvc ставится вручную, процессы svchost объединяются. Нужен topbar |+| **wiztree** | Карта занятого места на диске («WinRust Disk» в Пуске) | Ничего, кроме файла и ярлыка |+| **photoview** | Быстрый просмотр фото | Добавляется в «Открыть с помощью» (по умолчанию не назначается) |+| **debloat** | Отключает телеметрию, Copilot, Recall, рекламу в Пуске, фоновый Edge | Службы и политики реестра; старые значения сохраняются и возвращаются при удалении. **Только из командной строки:** `install debloat --yes` |+| chrome-rs | Браузер | Пока не ставится |++Все изменения обратимы: удаление возвращает те значения, что были до установки.+## БенчмаркОдноразовые замеры на одной машине (Windows 11 IoT Enterprise 10.0.26300, RTX 4060 Laptop, NTFS). Это порядок величин, а не лабораторные цифры.@@ -27,59 +58,69 @@В сумме: **в 85–99% случаев быстрее или меньше, по CPU в простое равны.** Оговорки: rs ищет по готовому индексу MFT (за это платит 53 МБ памяти), а `dir` и PowerShell обходят диск заново; explorer.exe при замере всё ещё работал и держал окна, поэтому выигрыш по памяти немного завышен; поиск Windows и диспетчер задач не сравнивались.-Один exe (`plugin-launcher.exe`), который ставит и удаляет наши плагины на Windows. Нужны права администратора. В окне все плагины собраны в один набор WinRust: кнопка «Установить WinRust» ставит недостающие по порядку (topbar раньше rust-explorer), когда всё стоит, она же обновляет; «Удалить всё» откатывает. По одному плагину: командная строка ниже.+## Снимки экрана-| Плагин | Что делает |-|---|---|-| rust-search | поиск файлов по NTFS (Alt+Space); отключает поиск Windows |-| rtaskmgr-win32 | заменяет диспетчер задач |-| topbar | нижняя панель в стиле Windows 11 вместо панели задач (сглаженные скругления, подсказки над кнопками, громкость колесом с показом уровня). Вместе с ним ставятся хоткеи рабочих столов (reshell: Win+1/2/3, Win+`) и блок в PowerShell-профиль (`src/profile.ps1`: zoxide, grep=rg, ll=eza, cat=bat; пишется в Windows PowerShell 5.1 и в pwsh 7, если он есть; без rg/eza/bat/zoxide блок молчит). При удалении topbar блок убирается. |-| rs-du | чистильщик диска (анализ MFT, кеши, `target`/`node_modules`, корзина). Отдельной карточки нет: ставится в папку диспетчера задач вместе с rtaskmgr-win32 или topbar и запускается из меню топбара (ПКМ по пустому месту → «Чистильщик диска»). Исходники: `plugins/rs-du` |-| chrome-rs | заглушка |-| rs-shell | своя оболочка вместо explorer.exe на один вход пользователя: обои, автозагрузка (Run и Startup), запуск и перезапуск topbar, при частых падениях topbar отдаёт сеанс explorer.exe. Кладётся рядом с `topbar.exe`; `rs-shell --dry-run` показывает, что запустит; `--enable` / `--disable` включают и выключают (только HKCU, остальные пользователи не затронуты). Лаунчером пока не ставится. Исходники: `plugins/rs-shell` |-| rust-explorer | **Плагин в лаунчере.** Файловый менеджер на Rust вместо Проводника в стиле Windows: панель слева (быстрый доступ, диски), колонки «Имя / Дата / Тип / Размер», вкладки, тёмная тема. Установка открывает в нём папки и диски (HKCU), запускает `rs-shell --overlay` при входе и **отключает обычный explorer.exe** как оболочку (AutoRestartShell=0, Explorer завершается, когда поднялись topbar и рабочий стол; если topbar не держится, Explorer возвращается сам). Нужен topbar. Удаление всё возвращает. Раньше было: замена окон Проводника на Rust (этап 1 плана: файловый менеджер). Пока не ставится лаунчером: запускается вручную `plugins/rust-explorer/target/release/rust-explorer.exe [папка]`. Есть: виртуальный список, иконки, вкладки (Ctrl+T/W/Tab), копирование/вставка/удаление через IFileOperation, контекстное меню оболочки, перетаскивание. Не сделано: миниатюры, адресная строка, регистрация обработчиком папок, этапы 2-5 (индекс, оболочка, трей, Shell Launcher). |--## Структура+**Панель задач**+++++**Диспетчер задач** (русский интерфейс)++++**Файловый менеджер**++++---++## Для разработчиков++### Структура```-src/ лаунчер (окно + логика установки)-payload/ готовые exe плагинов, вшиваются в лаунчер при сборке-plugins/ исходники: rust-search, rtaskmgr-win32, chrome-rs (каждый отдельный cargo-проект)-scripts/ build-all.ps1: синхронизирует plugins/ с оригиналами, пересобирает, обновляет payload/ и STAMPS.txt; sync.ps1 -Check: проверка на рассинхрон (запускать с -ExecutionPolicy Bypass)-ROADMAP.md планы+src/ установщик (plugin-launcher.exe)+ main.rs таблица плагинов PLUGINS: имя, тексты, пара install/uninstall, значок+ install/ что каждый плагин меняет в системе и как это откатывается (файл на плагин)+ cli.rs, ui.rs командная строка и окно; оба вызывают одни и те же функции установки+common/ winrust-common: переключатель языка (t!/tf!) и чтение MFT, общие для программ+plugins/ исходники всех плагинов, каждый отдельный crate+ReShell/ reshell (хоткеи рабочих столов, страховка topbar), ставится вместе с topbar+payload.txt какие exe вшиваются в установщик и где их кладёт сборка+payload/ эти exe после сборки (не в git)+scripts/ сборка, обновление, релиз```+Всё собрано в один cargo workspace (один `Cargo.lock`, все exe в `target\release`). `plugins/rust-search` и `plugins/chrome-rs` собираются отдельно: им нужен `panic = "unwind"` (см. `Cargo.toml`).-## Сборка+### Сборка+Нужны Windows x64 и Rust stable (1.85+) с MSVC.```powershell-.\scripts\build-all.ps1+powershell -ExecutionPolicy Bypass -File scripts\build-all.ps1```-Результат: `target\release\plugin-launcher.exe`. Закройте запущенный лаунчер перед сборкой.-+Результат: `target\release\plugin-launcher.exe`, внутри все плагины. Закройте запущенный установщик перед сборкой. Тесты: `cargo test --workspace` (и `cargo test` в `plugins\rust-search`). CI делает то же самое при каждом пуше (`.github/workflows/build.yml`).-## Командная строка+| Скрипт | Что делает |+|---|---|+| `build-all.ps1` | всё: плагины → `payload\` → установщик |+| `build-plugins.ps1` | только плагины → `payload\` (без пересборки установщика) |+| `update-plugin.ps1 <плагин>` | пересобрать и переустановить один установленный плагин без пересборки установщика (просит админа через UAC) |+| `user-mode.ps1`, `dev-update.ps1` | режим разработчика: topbar, rust-explorer, rs-shell и reshell запускаются из `%LOCALAPPDATA%` поверх Проводника и меняются без админа |+| `bench.ps1` | бенчмарк поиска и диспетчера задач |+| `publish.ps1`, `release.ps1` | коммит и пуш; релиз на GitHub с `WinRust.exe` |++### Командная строкаИз терминала **с правами администратора**:```plugin-launcher list-plugin-launcher install <плагин> --yes (без --yes только покажет предупреждение, ничего не меняет)-plugin-launcher update <плагин> (переустановить из payload\ рядом с exe: без пересборки лаунчера; см. scripts\update-plugin.ps1)+plugin-launcher install <плагин> --yes (без --yes только покажет предупреждение и ничего не изменит)+plugin-launcher update <плагин> (переустановить из payload\ рядом с exe)plugin-launcher uninstall <плагин>-plugin-launcher rollback --yes+plugin-launcher rollback --yes (удалить всё)```-Код выхода: 0 успех, 1 ошибка, 2 неверные аргументы или нет `--yes`. Без аргументов открывается окно.--## Новый плагин-Одна запись в `PLUGINS` (`src/main.rs`): имя, описание, предупреждение, `installed`, пара функций install/uninstall и значок `glyph`. Окно, высота списка и CLI подхватят её сами.--## Снимки экрана--**Панель задач (английский)**-----**Диспетчер задач** (русский интерфейс)----**Проводник**+Коды выхода: 0 успех, 1 ошибка, 2 неверные аргументы или нет `--yes`. Без аргументов открывается окно. Журнал установки: `%ProgramData%\plugin-launcher\install.log`.-+### Новый плагин+1. Crate в `plugins/<имя>`, добавить его в `members` корневого `Cargo.toml`.+2. Строка в `payload.txt`.+3. `src/install/<имя>.rs` с парой install/uninstall (и строка `mod` в `src/install/mod.rs`). Перед любым изменением сохраните исходные значения, чтобы удаление могло их вернуть.+4. Запись в `PLUGINS` (`src/main.rs`). Окно, его высота и командная строка подхватят её сами.diff --git a/ROADMAP.md b/ROADMAP.mdindex f3876ea..4adc143 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -1,40 +1,46 @@-# Plugin Launcher: Roadmap+# WinRust: Roadmap(Русская версия: [ROADMAP.ru.md](ROADMAP.ru.md))+Each item says how far it was checked: **tests** (unit tests), **built** (compiles, never run), **ran** (run by hand on a live system), **e2e** (full install/uninstall on a live system).+## Done-- **English by default + a language switch**: every program (installer, topbar, task manager, disk cleaner) is in English; a Русский/English button in the installer window and a "Language" item in the bar's menu switch it. The choice is stored in `%ProgramData%\WinRust\lang.txt` and read when a program starts. Texts are written as pairs in the code (`t!("русский", "english")`, `tf!` for format strings; `src/i18n.rs` is identical in each crate); unit tests run in Russian. Only built and unit-tested, the windows were not walked through by hand.-- A Win32/GDI window in the rtaskmgr-win32 style (dark theme, plugin cards).-- Plugins embedded into one `plugin-launcher.exe` (unpacked into Program Files, not %TEMP%), static CRT.-- **rust-search**: an NTFS search service + Alt+Space; disables WSearch and the taskbar search box.-- **rust-search, right-click on a result**: rename (inline, in the input line), move to recycle bin, "delete permanently + clean the registry". Deletion runs in three steps inside the card: scan (files, size, list of registry entries) → confirmation ("Cancel" by default) → delete files (clears read-only, never follows a junction/symlink); the registry is touched only if every file is gone, and is saved first to `%LOCALAPPDATA%\rs-search\registry-backups\*.reg`. An Uninstall/App Paths entry is removed whole only if the program itself lived inside the deleted folder. Sources: `rust-search/src/bin/rs-launcher.rs`, `src/regsweep.rs`; checked with tests and an end-to-end GUI run.-- **rtaskmgr-win32**: replaces Task Manager through an IFEO Debugger (`taskmgr.exe` itself is untouched). On a panic it writes `%APPDATA%\rtaskmgr\crash.log` and opens the real Taskmgr bypassing IFEO (started under a debugger that detaches at once; through UAC without admin rights). Understands `taskmgr /startup`, has "Restart as administrator". No clippy warnings.-- **topbar**: a bottom bar (AppBar) in the Windows 11 style instead of the taskbar: logo (opens Start), window buttons with icons (left click: minimize/activate, right/middle click: close), date and clock. It hides the native taskbar and sets it to auto-hide; uninstall brings it back (`topbar.exe --restore`). Was only built at that point, not run on a live system.-- **topbar + PowerShell profile**: installing topbar writes a block between the `# >>> topbar >>>` / `# <<< topbar <<<` markers into the profile (`src/profile.ps1`: zoxide, `grep`=rg, `ll`=eza, `cat`=bat). Written to Windows PowerShell 5.1 and to pwsh 7 if present; reinstalling does not duplicate the block, other profile lines are untouched, uninstalling topbar removes the block (and the file if nothing else was in it). Checked on a temporary profile; not checked in pwsh or by an end-to-end install.-- **Command line**: `plugin-launcher list | install <plugin> --yes | uninstall <plugin> | rollback --yes`. Without `--yes`, install only prints the warning. Exit codes 0/1/2. Needs an administrator terminal. The window and the CLI call the same functions. Only the commands that do not change the system were checked.-- **Plugins as data**: a `PLUGINS` entry includes the icon (`glyph`); a new plugin is added with one entry, and the window and CLI pick it up on their own.-- **topbar safety net**: `reshell` (always running with the bar) checks every 5 s that topbar is not running while the native taskbar is hidden; twice in a row (~10 s) it runs `topbar.exe --restore`. It does not restart the bar (to avoid a loop when it crashes on start). Covered by a unit test of the condition; the end-to-end scenario (kill topbar) was not checked.-- **More robust installer**: a failed install rolls its changes back (not when updating an existing copy); the previous WSearch and search-box values are kept in `HKLM\SOFTWARE\plugin-launcher\rust-search` and restored on uninstall; non-fatal errors (shortcut, scheduled task, restore point, profile) are counted and written to `%ProgramData%\plugin-launcher\install.log`; only what a plugin needs is unpacked. Only built, not run.-- **Update without rebuilding the launcher**: exes from `payload\` next to the launcher (or `..\..\payload` in the cargo layout) are read from disk instead of the embedded ones. `plugin-launcher update <plugin>` and `scripts\update-plugin.ps1 <plugin>` (build the plugin, put it into payload, update). The embedded copies stay as a fallback; releases still use `build-all.ps1`.-- A restore point before install, a "Roll everything back" button.-- Sources of all projects are collected in `plugins/`.++### Installer+- One `plugin-launcher.exe` with every plugin embedded (unpacked into Program Files, not %TEMP%), static CRT, dark Win32/GDI window. *ran*+- "Install WinRust" installs what is missing in order (topbar before rust-explorer), updates when everything is there; "Remove all" removes in reverse order. *built*+- A failed install undoes its own changes (not when updating a working copy); original values (WSearch, search box, Explorer settings, services) are saved under `HKLM\SOFTWARE\plugin-launcher\<plugin>` and put back on uninstall; non-fatal errors go to `%ProgramData%\plugin-launcher\install.log`. *built*+- Restore point before install. *built*+- One button installs what is missing **and** updates what is installed, so running a newer `WinRust.exe` brings its fixes to every plugin (v0.2.1). *built*+- Command line: `list | install <plugin> --yes | update <plugin> | uninstall <plugin> | rollback --yes`, exit codes 0/1/2; the window and the command line call the same functions. Only the read-only commands were run. *ran (partly)*+- `update` and `scripts\update-plugin.ps1`: reinstall from `payload\` on disk without rebuilding the installer. *ran*+- English by default, Русский/English switch in the installer and in the bar menu; the choice is stored in `%ProgramData%\WinRust\lang.txt`. *tests*+- Code layout: one cargo workspace; the installer split into `install/` (one file per plugin), `cli.rs`, `ui.rs`; shared `winrust-common` crate (language switch, MFT reader); one `payload.txt` list for the build and the scripts; CI on GitHub Actions. *tests*++### Plugins+- **rust-search**: NTFS search service + Alt+Space; disables WSearch, blocks SearchHost.exe, hides the taskbar search box. Right-click a result: rename, recycle bin, "delete permanently + clean the registry" (scan → confirm → delete; registry saved to `%LOCALAPPDATA%\rs-search\registry-backups\*.reg` first). *tests, ran*+- **rtaskmgr-win32**: replaces Task Manager through an IFEO Debugger (`taskmgr.exe` untouched); on a panic writes `%APPDATA%\rtaskmgr\crash.log` and opens the real Taskmgr. *tests, ran*+- **topbar**: Windows 11-style bottom bar instead of the taskbar; `topbar.exe --restore` brings the taskbar back. Installs with it: reshell hotkeys, rs-du, the PowerShell profile block (`src/install/profile.ps1`, Windows PowerShell 5.1 and pwsh 7). *ran; the profile block only on a temporary profile*+- **reshell safety net**: if topbar is not running while the taskbar is hidden, twice in a row (~10 s), it runs `topbar.exe --restore`. *tests; killing topbar was not tried*+- **reshell hotkeys**: Win+D (show desktop) and Win+I (Settings) work without Explorer, like Win+E (v0.2.1). *ran*+- **rust-explorer**: file manager (tabs, icons, IFileOperation copy/paste/delete, shell context menu, drag and drop), draws the desktop, turns off Explorer as the shell with `rs-shell --overlay` (90 s after sign-in at the latest: Windows 26300 no longer writes the autostart markers it used to wait for, v0.2.1), trims services. *tests, ran*+- **rs-du**: disk cleaner (MFT analysis, caches, `target`/`node_modules`, recycle bin, 30-day quarantine), started from the bar menu. *tests*+- **wiztree**: disk-usage treemap from the MFT. *tests (layout only); not run on a live disk*+- **photoview**: WIC photo viewer, EXIF rotation, "Open with" entry. *ran; EXIF orientations 5 and 7 not checked*+- **debloat**: services and policies (telemetry, Copilot, Recall, ads, Edge background), old values in `%ProgramData%\winrust-debloat\undo.txt`, `--undo`. *dry run ran; `--apply`/`--undo` not run*## Next (in order)-1. **Test on a clean Windows 11** (VM): install, uninstall, rollback, reboot. Nothing has been checked on another machine so far.-3. **chrome-rs**: a real install instead of the placeholder (once the browser is ready; see `plugins/chrome-rs/ROADMAP.md`).-4. **PowerShell profile**: optionally install rg/fd/bat/eza/zoxide through winget with a separate checkbox in the topbar settings (the block is silent without them today); check the pwsh 7 write on a machine that has it.-5. **Releases**: GitHub Releases (first one is out), SHA-256 next to it, version in the window, update check.-6. **Code signing** (removes SmartScreen and part of the antivirus false positives).-7. **Win+S / Start button**: open rust-search instead of Windows Search (risky, a separate decision).-8. **Non-NTFS drives** in rust-search (skipped today).-9. Tests for the install logic (sandbox/VM run), CI build. First check `install`/`uninstall`/`rollback` from the CLI on a VM: they were not run in the original session.+1. **Test on a clean Windows 11 VM**: install, uninstall, rollback, reboot, for each plugin. Nothing has been checked on another machine yet.+2. **One undo journal for every plugin**: each change (registry value, service, file) written as "before → after" before it is made; uninstall and rollback replay it backwards. Replaces the hand-written uninstall of each plugin. Needs step 1 first, and a migration for installs made by the current version.+3. **Registry through the Win32 API** (`RegGetValueW`/`RegSetValueExW`) instead of running `reg.exe` and parsing its output.+4. **Releases**: SHA-256 next to the exe, version in the window, update check.+5. **Code signing** (removes the SmartScreen warning and part of the antivirus false positives).+6. **PowerShell profile**: optionally install rg/fd/bat/eza/zoxide through winget (a checkbox in the topbar settings).+7. **chrome-rs**: a real install once the browser is ready (see `plugins/chrome-rs/ROADMAP.md`).+8. **Win+S / Start button** open rust-search instead of Windows Search (risky, a separate decision).+9. **Non-NTFS drives** in rust-search (skipped today).## Known limitations-- System components are not removed but disabled or bypassed (reversibly). Fully deleting `taskmgr.exe` and Windows Search is not possible without breaking system protection.+- System components are disabled or bypassed (reversibly), not removed: deleting `taskmgr.exe` or Windows Search outright would break system protection.- Administrator rights are required.- Win+S and Start still open Windows Search.--- **wiztree / photoview / debloat** (new, separate cargo projects; wiztree and photoview are in the launcher window, debloat only from the command line: `install debloat --yes`, `uninstall debloat`).- - **wiztree**: a disk-usage treemap from the MFT, a GDI window; reads the MFT with the same code as rs-du (`plugins/rs-du/src/mft.rs`, wiztree pulls it in through `#[path]`). Click a folder: go in, right-click/Backspace: up, click a file: show in Explorer, Tab: next drive, F5: rescan. Restarts itself with UAC. Only the treemap layout is tested; not run on a live disk.- - **photoview**: a WIC photo viewer (jpg/png/bmp/gif/tiff/webp/heic/avif if the codec is present), EXIF rotation, folder browsing, wheel zoom, Del to the recycle bin. Install adds "Open with" and an entry in "Default apps"; it does not become the default. Checked by launching on a system image; EXIF orientations 5 and 7 were not checked.- - **debloat**: services (DiagTrack, maps, error reporting, etc.) and registry policies (Copilot, Recall, ads, Edge background). The old value of each change is written to `%ProgramData%\winrust-debloat\undo.txt` before the change, `--undo` reverts. The dry run (without `--apply`) was checked on a live system, `--apply`/`--undo` were not.diff --git a/ROADMAP.ru.md b/ROADMAP.ru.mdindex 15c7738..9e70971 100644--- a/ROADMAP.ru.md+++ b/ROADMAP.ru.md@@ -1,38 +1,46 @@-# Plugin Launcher: Roadmap+# WinRust: планы++(English version: [ROADMAP.md](ROADMAP.md))++У каждого пункта указано, насколько он проверен: **тесты** (юнит-тесты), **собрано** (компилируется, не запускалось), **запускалось** (руками на живой системе), **сквозная** (полная установка/удаление на живой системе).## Сделано-- **Английский по умолчанию и переключатель языка**: все программы (установщик, topbar, диспетчер задач, чистильщик диска) по умолчанию на английском; кнопка «Русский/English» в окне установщика и пункт «Язык» в меню панели переключают язык. Выбор лежит в `%ProgramData%\WinRust\lang.txt` и читается при запуске программы. Тексты в коде парами (`t!("русский", "english")`, `tf!` для форматных строк; `src/i18n.rs` одинаковый в каждом проекте); юнит-тесты идут на русском. Только собрано и прогнано юнит-тестами, окна руками не проходились.-- Окно на Win32/GDI в стиле rtaskmgr-win32 (тёмная тема, карточки плагинов).-- Плагины вшиты в один `plugin-launcher.exe` (распаковка в Program Files, не в %TEMP%), статический CRT.-- **rust-search**: служба поиска по NTFS + Alt+Space; отключает WSearch и строку поиска на панели задач.-- **rust-search, правый клик по результату**: переименовать (прямо в строке ввода), в корзину, «удалить навсегда + почистить реестр». Удаление идёт в три шага в самой карточке: сканирование (файлы, размер, список записей реестра) → подтверждение (по умолчанию «Cancel») → удаление файлов (снимает read-only, junction/symlink не проходит насквозь); реестр трогается только если все файлы ушли, и сначала сохраняется в `%LOCALAPPDATA%\rs-search\registry-backups\*.reg`. Запись Uninstall/App Paths удаляется целиком, только если сама программа лежала внутри удалённого. Исходники: `rust-search/src/bin/rs-launcher.rs`, `src/regsweep.rs`; проверено тестами и сквозным прогоном в GUI.-- **rtaskmgr-win32**: заменяет диспетчер задач через IFEO-Debugger (`taskmgr.exe` не трогается). При панике пишет `%APPDATA%\rtaskmgr\crash.log` и открывает настоящий Taskmgr в обход IFEO (запуск под отладкой с мгновенным отсоединением; без прав админа через UAC). Понимает `taskmgr /startup`, есть «Перезапустить от имени администратора». Без предупреждений clippy.-- **topbar**: нижняя панель (AppBar) в стиле Windows 11 вместо панели задач: логотип (открывает Пуск), кнопки окон с иконками (ЛКМ — свернуть/активировать, ПКМ/СКМ — закрыть), дата и часы. Родную панель скрывает и ставит в автоскрытие; удаление возвращает её (`topbar.exe --restore`). Не запускалась на живой системе, только собрана.-- **topbar + профиль PowerShell**: при установке topbar в профиль пишется блок между маркерами `# >>> topbar >>>` / `# <<< topbar <<<` (`src/profile.ps1`: zoxide, `grep`=rg, `ll`=eza, `cat`=bat). Пишется в Windows PowerShell 5.1 и в pwsh 7, если он есть; повторная установка не дублирует блок, чужие строки профиля не трогаются, удаление topbar убирает блок (и файл, если в нём больше ничего не было). Проверено на временном профиле; в pwsh и сквозной установкой не проверялось.-- **Командная строка**: `plugin-launcher list | install <плагин> --yes | uninstall <плагин> | rollback --yes`. Без `--yes` install только печатает предупреждение. Коды выхода 0/1/2. Нужен терминал с правами администратора. Окно и CLI вызывают одни и те же функции. Проверены только команды без изменений системы.-- **Плагины как данные**: запись в `PLUGINS` включает значок (`glyph`); новый плагин добавляется одной записью, окно и CLI подхватывают её сами.-- **Страховка topbar**: `reshell` (всегда запущен вместе с панелью) раз в 5 с проверяет, что topbar не работает, а родная панель задач скрыта; два раза подряд (~10 с) — запускает `topbar.exe --restore`. Панель не перезапускает (чтобы не крутиться в цикле при падении на старте). Покрыто unit-тестом условия; сквозной сценарий (убить topbar) не проверялся.-- **Установщик надёжнее**: сбой установки откатывает изменения (при обновлении уже стоящей копии не откатывает); прежние значения WSearch и строки поиска сохраняются в `HKLM\SOFTWARE\plugin-launcher\rust-search` и возвращаются при удалении; несмертельные ошибки (ярлык, задача планировщика, точка восстановления, профиль) считаются и пишутся в `%ProgramData%\plugin-launcher\install.log`; распаковывается только нужное плагину. Только собрано, не запускалось.-- **Обновление без пересборки лаунчера**: exe из `payload\` рядом с лаунчером (или `..\..\payload` в cargo-раскладке) берутся с диска вместо вшитых. `plugin-launcher update <плагин>` и `scripts\update-plugin.ps1 <плагин>` (собрать плагин, положить в payload, обновить). Вшитые копии остаются запасными; для релиза по-прежнему `build-all.ps1`.-- Точка восстановления перед установкой, кнопка «Откатить всё».-- Исходники всех проектов собраны в `plugins/`.++### Установщик+- Один `plugin-launcher.exe`, в который вшиты все плагины (распаковка в Program Files, не в %TEMP%), статический CRT, тёмное окно на Win32/GDI. *запускалось*+- «Install WinRust» ставит недостающее по порядку (topbar раньше rust-explorer), когда всё стоит, обновляет; «Удалить всё» удаляет в обратном порядке. *собрано*+- Сбой установки откатывает свои изменения (кроме обновления рабочей копии); исходные значения (WSearch, строка поиска, настройки Проводника, службы) сохраняются в `HKLM\SOFTWARE\plugin-launcher\<плагин>` и возвращаются при удалении; несмертельные ошибки пишутся в `%ProgramData%\plugin-launcher\install.log`. *собрано*+- Точка восстановления перед установкой. *собрано*+- Одна кнопка ставит недостающее **и** обновляет установленное: запуск нового `WinRust.exe` доносит исправления до всех плагинов (v0.2.1). *собрано*+- Командная строка: `list | install <плагин> --yes | update <плагин> | uninstall <плагин> | rollback --yes`, коды выхода 0/1/2; окно и командная строка вызывают одни и те же функции. Запускались только команды, которые ничего не меняют. *запускалось (частично)*+- `update` и `scripts\update-plugin.ps1`: переустановка из `payload\` на диске без пересборки установщика. *запускалось*+- Английский по умолчанию, переключатель Русский/English в установщике и в меню панели; выбор хранится в `%ProgramData%\WinRust\lang.txt`. *тесты*+- Устройство кода: один cargo workspace; установщик разделён на `install/` (файл на плагин), `cli.rs`, `ui.rs`; общий crate `winrust-common` (переключатель языка, чтение MFT); один список `payload.txt` для сборки и скриптов; CI на GitHub Actions. *тесты*++### Плагины+- **rust-search**: служба поиска по NTFS + Alt+Space; отключает WSearch, блокирует SearchHost.exe, прячет строку поиска. Правый клик по результату: переименовать, в корзину, «удалить навсегда + почистить реестр» (сканирование → подтверждение → удаление; реестр сначала сохраняется в `%LOCALAPPDATA%\rs-search\registry-backups\*.reg`). *тесты, запускалось*+- **rtaskmgr-win32**: заменяет диспетчер задач через IFEO-Debugger (`taskmgr.exe` не трогается); при панике пишет `%APPDATA%\rtaskmgr\crash.log` и открывает настоящий Taskmgr. *тесты, запускалось*+- **topbar**: нижняя панель в стиле Windows 11 вместо панели задач; `topbar.exe --restore` возвращает панель задач. Вместе с ним ставятся хоткеи reshell, rs-du, блок профиля PowerShell (`src/install/profile.ps1`, Windows PowerShell 5.1 и pwsh 7). *запускалось; блок профиля только на временном профиле*+- **Страховка reshell**: если topbar не запущен, а панель задач скрыта, два раза подряд (~10 с), запускает `topbar.exe --restore`. *тесты; сценарий «убить topbar» не проверялся*+- **Хоткеи reshell**: Win+D (показать рабочий стол) и Win+I (Параметры) работают без Проводника, как Win+E (v0.2.1). *запускалось*+- **rust-explorer**: файловый менеджер (вкладки, иконки, копирование/вставка/удаление через IFileOperation, контекстное меню, перетаскивание), рисует рабочий стол, отключает Проводник как оболочку через `rs-shell --overlay` (не позже 90 с после входа: Windows 26300 больше не пишет отметки автозагрузки, которых он ждал, v0.2.1), урезает службы. *тесты, запускалось*+- **rs-du**: чистильщик диска (анализ MFT, кеши, `target`/`node_modules`, корзина, карантин на 30 дней), запускается из меню панели. *тесты*+- **wiztree**: карта занятого места по MFT. *тесты (только раскладка); на живом диске не запускался*+- **photoview**: просмотр фото на WIC, поворот по EXIF, пункт «Открыть с помощью». *запускалось; EXIF-ориентации 5 и 7 не проверялись*+- **debloat**: службы и политики (телеметрия, Copilot, Recall, реклама, фоновый Edge), старые значения в `%ProgramData%\winrust-debloat\undo.txt`, `--undo`. *сухой прогон запускался; `--apply`/`--undo` нет*## Дальше (по порядку)-1. **Проверка на чистой Windows 11** (виртуалка): установка, удаление, откат, перезагрузка. Сейчас на другой машине ничего не проверялось.-3. **chrome-rs**: реальная установка вместо заглушки (после готовности браузера; см. `plugins/chrome-rs/ROADMAP.md`).-4. **Профиль PowerShell**: по желанию ставить rg/fd/bat/eza/zoxide через winget отдельной галочкой в настройках topbar (сейчас блок молчит, если их нет); проверить запись в pwsh 7 на машине, где он стоит.-5. **Релизы**: GitHub Releases, SHA-256 рядом, версия в окне, проверка обновлений.-6. **Подпись кода** (убирает SmartScreen и часть ложных срабатываний антивирусов).-7. **Win+S / кнопка «Пуск»**: открывать rust-search вместо поиска Windows (рискованно, отдельное решение).-8. **Не-NTFS диски** в rust-search (сейчас они пропускаются).-9. Тесты на установочную логику (запуск в песочнице/VM), CI-сборка. Сначала проверить `install`/`uninstall`/`rollback` из CLI на VM: в этой сессии они не запускались.+1. **Проверка на чистой Windows 11 в виртуалке**: установка, удаление, откат, перезагрузка, по каждому плагину. На другой машине пока ничего не проверялось.+2. **Один журнал отката для всех плагинов**: каждое изменение (значение реестра, служба, файл) записывается как «было → стало» до того, как сделано; удаление и откат проигрывают журнал назад. Заменяет ручной uninstall каждого плагина. Сначала нужен шаг 1 и миграция для установок текущей версии.+3. **Реестр через Win32 API** (`RegGetValueW`/`RegSetValueExW`) вместо запуска `reg.exe` и разбора его вывода.+4. **Релизы**: SHA-256 рядом с exe, версия в окне, проверка обновлений.+5. **Подпись кода** (убирает предупреждение SmartScreen и часть ложных срабатываний антивирусов).+6. **Профиль PowerShell**: по желанию ставить rg/fd/bat/eza/zoxide через winget (галочка в настройках topbar).+7. **chrome-rs**: настоящая установка, когда браузер будет готов (см. `plugins/chrome-rs/ROADMAP.md`).+8. **Win+S / кнопка «Пуск»** открывают rust-search вместо поиска Windows (рискованно, отдельное решение).+9. **Не-NTFS диски** в rust-search (сейчас пропускаются).## Известные ограничения-- Системные компоненты не удаляются, а отключаются или обходятся (обратимо). Полное удаление `taskmgr.exe` и поиска Windows невозможно без взлома защиты системы.+- Системные компоненты отключаются или обходятся (обратимо), а не удаляются: удаление `taskmgr.exe` или поиска Windows сломало бы защиту системы.- Нужны права администратора.- Win+S и «Пуск» по-прежнему открывают поиск Windows.--- **wiztree / photoview / debloat** (новые, отдельные cargo-проекты; в окне лаунчера wiztree и photoview, debloat только из командной строки: `install debloat --yes`, `uninstall debloat`).- - **wiztree**: карта занятого места (treemap) по MFT, окно на GDI; читает MFT тем же кодом, что rs-du (`plugins/rs-du/src/mft.rs`, wiztree подключает его через `#[path]`). Клик по папке: войти, ПКМ/Backspace: вверх, клик по файлу: показать в Проводнике, Tab: следующий диск, F5: заново. Сам перезапускается с UAC. Тест только на раскладку treemap; на живом диске не запускался.- - **photoview**: просмотр фото на WIC (jpg/png/bmp/gif/tiff/webp/heic/avif при наличии кодека), поворот по EXIF, листание папки, зум колесом, Del в корзину. Установка добавляет «Открыть с помощью» и запись в «Приложения по умолчанию», значением по умолчанию не становится. Проверено запуском на системной картинке; EXIF-ориентации 5 и 7 не проверялись.- - **debloat**: службы (DiagTrack, карты, отчёты об ошибках и т. п.) и политики реестра (Copilot, Recall, реклама, фон Edge). Старое значение каждой правки пишется в `%ProgramData%\winrust-debloat\undo.txt` до изменения, `--undo` возвращает. Сухой прогон (без `--apply`) проверен на живой системе, `--apply`/`--undo` нет.diff --git a/ReShell/Cargo.lock b/ReShell/Cargo.lockdeleted file mode 100644index 87e2bcb..0000000--- a/ReShell/Cargo.lock+++ /dev/null@@ -1,25 +0,0 @@-# This file is automatically @generated by Cargo.-# It is not intended for manual editing.-version = 4--[[package]]-name = "reshell"-version = "0.1.0"-dependencies = [- "windows-sys",-]--[[package]]-name = "windows-link"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"--[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]diff --git a/ReShell/Cargo.toml b/ReShell/Cargo.tomlindex 8c9749f..3a79b84 100644--- a/ReShell/Cargo.toml+++ b/ReShell/Cargo.toml@@ -4,13 +4,5 @@ version = "0.1.0"edition = "2024"[dependencies]-windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_Console", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_Security", "Win32_System_LibraryLoader", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse"] }--[profile.release]-opt-level = "s"-lto = true-codegen-units = 1-panic = "abort"-strip = true--[workspace]+winrust-common = { path = "../common" }+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Console", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_Security", "Win32_System_LibraryLoader", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse"] }diff --git a/ReShell/ROADMAP.md b/ReShell/ROADMAP.mdindex 3bf9032..34d9a15 100644--- a/ReShell/ROADMAP.md+++ b/ReShell/ROADMAP.md@@ -12,7 +12,7 @@1. Cargo-проект `ReShell/` (статический CRT, `opt-level=3`, `lto`, `panic=abort`, как у остальных плагинов). Один бинарник `reshell.exe` с подкомандами: `reshell <команда> [аргументы]`.2. Общий модуль: Win32 через крейт `windows` (без `Add-Type`), логирование в `%LOCALAPPDATA%\reshell\log.txt`, сохранение прежнего состояния перед любым изменением системы (для отката).3. Замер: `scripts/bench.ps1` гоняет `hyperfine` (или 20 прогонов `Measure-Command`) по старому скрипту и новому exe, пишет таблицу в `BENCH.md`.-4. Запись в `plugin-launcher`: карточка «ReShell», install/uninstall, добавление в `build-all.ps1` и `sync.ps1`.+4. Запись в `plugin-launcher`: карточка «ReShell», install/uninstall, добавление в `payload.txt`.## Фаза 1. Первые замены (уже есть готовые скрипты)1. **`SuperSaver.ps1` → `reshell saver on|off`**: план питания, частота экрана (`EnumDisplaySettings`/`ChangeDisplaySettings`), яркость (WMI). Прежняя частота сохраняется в `%LOCALAPPDATA%\reshell\`, а не в `%TEMP%`. Сейчас скрипт при каждом запуске компилирует C# через `Add-Type`, это самый явный выигрыш.@@ -50,8 +50,8 @@- Скрипты, которые в основном ждут сеть или внешнюю программу, переписывать бессмысленно: выигрыш только на старте.## Статус-- **Фаза 0** (частично): Cargo-проект `ReShell/` собирается (330 КБ), подкоманды в `src/`. Не сделано: общий модуль логов, `bench.ps1`, карточка в plugin-launcher, `build-all.ps1`/`sync.ps1`.+- **Фаза 0** (частично): Cargo-проект `ReShell/` собирается (330 КБ), подкоманды в `src/`. Не сделано: общий модуль логов, `bench.ps1`, карточка в plugin-launcher.- **Фаза 1.1** `reshell saver on|off`: написано, юнит-тест на разбор GUID проходит. **На живой системе не запускалось** (kill лаунчеров, смена плана питания и частоты экрана). Замер старта: `reshell` ~19 мс против ~340 мс у `powershell -NoProfile` + `Add-Type` (15 прогонов, 2026-11-15); это старт, не вся работа скрипта (`powercfg` вызывается как внешний процесс).- Отличия от `SuperSaver.ps1`: яркость задаётся в плане питания (powercfg), а не через WMI; `off` больше не выставляет яркость 70, а просто возвращает план «Сбалансированная»; прежняя частота хранится в `%LOCALAPPDATA%\reshell\saver_hz.txt`, а не в `%TEMP%`.- **Фаза 1.2** `reshell hotkeys`: написано, собирается, тест разбора реестра проходит; **на живой системе не запускалось**. Отличие от плана: без COM `IVirtualDesktopManagerInternal`. Текущий стол и их число берутся из реестра (`...\Explorer\VirtualDesktops`), переключение шлёт Ctrl+Win+←/→ нужное число раз (Win пользователь уже держит). Плюс: не ломается между сборками Windows. Минус: идёт через анимацию переключения, нужны включённые системные сочетания. Перед проверкой остановить старый `desktop-hotkeys.ps1`, иначе два хука сработают дважды.-- **Вшит в plugin-launcher** (2026-11-15): payload\reshell.exe; установка topbar кладёт eshell.exe в Program Files\topbar, пишет HKCU\...\Run\reshell и запускает его; удаление topbar убирает всё. Без аргументов eshell = hotkeys. Установка из лаунчера не проверялась.+- **Вшит в plugin-launcher** (2026-11-15): payload\reshell.exe; установка topbar кладёт eshell.exe в Program Files\topbar, пишет HKCU\...\Run\reshell и запускает его; удаление topbar убирает всё. Без аргументов eshell = hotkeys. Установка из лаунчера не проверялась.diff --git a/ReShell/src/hotkeys.rs b/ReShell/src/hotkeys.rsindex 2f6d42f..c7d29e1 100644--- a/ReShell/src/hotkeys.rs+++ b/ReShell/src/hotkeys.rs@@ -1,11 +1,14 @@-//! Replacement for desktop-hotkeys.ps1: Win+1/2/3 -> desktop 1/2/3, Win+` -> previous desktop, Win+E -> our file manager.+//! Replacement for desktop-hotkeys.ps1: Win+1/2/3 -> desktop 1/2/3, Win+` -> previous desktop, Win+E -> our file manager,+//! Win+D -> show desktop, Win+I -> Settings. Win+E/D/I are done here, not left to Explorer: with topbar (and rust-explorer)+//! Explorer's taskbar is hidden or gone and it stops answering them although it still holds the hotkeys.//! No undocumented COM: the current desktop comes from the registry, switching sends Ctrl+Win+Left/Right//! (Win is already held by the user). shortcut: relies on the system shortcuts being enabled.-use std::sync::atomic::{AtomicIsize, AtomicUsize, Ordering::Relaxed};-use windows_sys::Win32::{Foundation::*, System::{LibraryLoader::GetModuleHandleW, Registry::*}, UI::{Input::KeyboardAndMouse::*, WindowsAndMessaging::*}};+use std::sync::atomic::{AtomicIsize, AtomicU32, AtomicUsize, Ordering::Relaxed};+use windows_sys::Win32::{Foundation::*, System::{Com::{COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE, CoInitializeEx}, LibraryLoader::GetModuleHandleW, Registry::*}, UI::{Input::KeyboardAndMouse::*, Shell::ShellExecuteW, WindowsAndMessaging::*}};static PREV: AtomicUsize = AtomicUsize::new(usize::MAX);static HOOK: AtomicIsize = AtomicIsize::new(0);+static HELD: AtomicU32 = AtomicU32::new(0); // the Win+letter key still down: auto-repeat must not toggle the desktop again and again/// (current index, desktop count) from the registry.fn desktops() -> Option<(usize, usize)> {@@ -46,6 +49,25 @@ fn open_files() {let _ = Command::new(exe).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn();}+/// Win+I: the Settings app through its protocol (no Explorer needed).+fn open_settings() {+ let (verb, uri): (Vec<u16>, Vec<u16>) = ("open\0".encode_utf16().collect(), "ms-settings:\0".encode_utf16().collect());+ unsafe {+ CoInitializeEx(std::ptr::null(), (COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) as u32); // ShellExecute may activate COM handlers+ ShellExecuteW(std::ptr::null_mut(), verb.as_ptr(), uri.as_ptr(), std::ptr::null(), std::ptr::null(), SW_SHOWNORMAL);+ }+}++/// What Win+<key> does here instead of in Explorer.+fn win_action(vk: u32) -> Option<fn()> {+ match vk {+ 0x45 => Some(open_files), // E+ 0x44 => Some(winrust_common::desktop::toggle), // D+ 0x49 => Some(open_settings), // I+ _ => None,+ }+}+fn go(target: usize) {let Some((cur, count)) = desktops() else { return };if target == cur || target >= count { return }@@ -60,11 +82,14 @@ unsafe extern "system" fn hook(n: i32, w: WPARAM, l: LPARAM) -> LRESULT {if n >= 0 {let k = unsafe { &*(l as *const KBDLLHOOKSTRUCT) };let win = unsafe { (GetAsyncKeyState(VK_LWIN as i32) | GetAsyncKeyState(VK_RWIN as i32)) as u16 & 0x8000 != 0 };- if k.vkCode == 0x45 && win && k.flags & LLKHF_INJECTED == 0 {- // Win+E: swallow it so Explorer's own handler does not open a window as well- if w == WM_KEYDOWN as usize {+ if (w == WM_KEYUP as usize || w == WM_SYSKEYUP as usize) && HELD.load(Relaxed) == k.vkCode {+ HELD.store(0, Relaxed); // also when Win was let go first+ }+ if let (Some(act), true) = (win_action(k.vkCode), win && k.flags & LLKHF_INJECTED == 0) {+ // swallow it so Explorer's own handler (if it still answers) does not act as well+ if w == WM_KEYDOWN as usize && HELD.swap(k.vkCode, Relaxed) != k.vkCode {send(&[tap(0xE8, false), tap(0xE8, true)]); // Win release must not open Start- std::thread::spawn(open_files);+ std::thread::spawn(act);}return 1;}diff --git a/build.rs b/build.rsindex bc185be..5ce3700 100644--- a/build.rs+++ b/build.rs@@ -1,6 +1,21 @@+use std::{env, fs, path::Path};+fn main() {println!("cargo:rerun-if-changed=app.rc");println!("cargo:rerun-if-changed=app.manifest");- println!("cargo:rerun-if-changed=payload");+ println!("cargo:rerun-if-changed=payload.txt");embed_resource::compile("app.rc", embed_resource::NONE).manifest_required().unwrap();++ // payload.txt -> `const PAYLOAD: [(&str, &[u8]); N]` with every listed exe from payload\ embedded.+ let root = env::var("CARGO_MANIFEST_DIR").unwrap();+ let list = fs::read_to_string(Path::new(&root).join("payload.txt")).expect("payload.txt");+ let names: Vec<&str> = list.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).map(|l| l.split('=').next().unwrap().trim()).collect();+ let mut code = format!("const PAYLOAD: [(&str, &[u8]); {}] = [\n", names.len());+ for n in &names {+ let p = Path::new(&root).join("payload").join(n);+ assert!(p.is_file(), r"payload\{n} is missing: run scripts\build-all.ps1 (or scripts\build-plugins.ps1) first");+ println!("cargo:rerun-if-changed={}", p.display());+ code += &format!(" ({n:?}, include_bytes!({:?})),\n", p.display().to_string());+ }+ fs::write(Path::new(&env::var("OUT_DIR").unwrap()).join("payload.rs"), code + "];\n").unwrap();}diff --git a/common/Cargo.toml b/common/Cargo.tomlnew file mode 100644index 0000000..34fcca8--- /dev/null+++ b/common/Cargo.toml@@ -0,0 +1,7 @@+[package]+name = "winrust-common"+version = "0.1.0"+edition = "2024"++[dependencies]+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_UI_WindowsAndMessaging"] }diff --git a/common/src/desktop.rs b/common/src/desktop.rsnew file mode 100644index 0000000..c5ae935--- /dev/null+++ b/common/src/desktop.rs@@ -0,0 +1,58 @@+//! Win+D without Explorer: minimize every app window, press again to bring the same windows back.+//! Used by reshell (keyboard hook) and rs-shell (when it is the shell).+use std::sync::Mutex;+use windows_sys::{+ core::BOOL,+ Win32::{Foundation::{HWND, LPARAM}, Graphics::Dwm::DwmGetWindowAttribute, UI::WindowsAndMessaging::*},+};++static HIDDEN: Mutex<Vec<isize>> = Mutex::new(Vec::new());++/// Anything open on screen means "minimize": after a window was brought back by hand the old list must not turn the next+/// press into a silent "restore".+pub fn toggle() {+ let mut hid = HIDDEN.lock().unwrap();+ unsafe {+ let mut v: Vec<isize> = vec![];+ EnumWindows(Some(collect), &mut v as *mut _ as LPARAM);+ if !v.is_empty() {+ v.iter().for_each(|&h| { ShowWindow(h as HWND, SW_MINIMIZE); });+ *hid = v;+ } else {+ hid.iter().for_each(|&h| { if IsWindow(h as HWND) != 0 { ShowWindow(h as HWND, SW_RESTORE); } });+ hid.clear();+ }+ }+}++unsafe extern "system" fn collect(h: HWND, lp: LPARAM) -> BOOL {+ unsafe {+ let mut cloaked = 0u32; // DWMWA_CLOAKED: UWP ghosts that are "visible" but not on screen+ DwmGetWindowAttribute(h, 14, &mut cloaked as *mut _ as _, 4);+ let tool = GetWindowLongW(h, GWL_EXSTYLE) as u32 & WS_EX_TOOLWINDOW != 0; // topbar, desktop, tray hosts+ if IsWindowVisible(h) != 0 && IsIconic(h) == 0 && !tool && cloaked == 0 && GetWindow(h, GW_OWNER).is_null() && GetWindowTextLengthW(h) > 0 && !is_desktop(h) {+ (*(lp as *mut Vec<isize>)).push(h as isize);+ }+ 1+ }+}++/// The desktop itself (Explorer's, or the rust-explorer one, which also registers as "Progman") must never be minimized.+fn is_desktop(h: HWND) -> bool {+ let mut cls = [0u16; 32];+ let n = unsafe { GetClassNameW(h, cls.as_mut_ptr(), cls.len() as i32) } as usize;+ is_desktop_class(&String::from_utf16_lossy(&cls[..n]))+}++fn is_desktop_class(c: &str) -> bool {+ matches!(c, "Progman" | "WorkerW")+}++#[cfg(test)]+mod tests {+ #[test]+ fn desktop_classes() {+ assert!(super::is_desktop_class("Progman"));+ assert!(!super::is_desktop_class("Notepad"));+ }+}diff --git a/plugins/rs-du/src/i18n.rs b/common/src/lib.rssimilarity index 55%rename from plugins/rs-du/src/i18n.rsrename to common/src/lib.rsindex 707cc46..ea39770 100644--- a/plugins/rs-du/src/i18n.rs+++ b/common/src/lib.rs@@ -1,25 +1,29 @@-// Language switch shared by every WinRust program (an identical copy of this file lives in each crate).-// English by default; Russian when %ProgramData%\WinRust\lang.txt contains "ru" (the installer's EN/RU button writes it).-// Programs read the file once at start; the one that flips the switch updates its own texts at once.+//! Code shared by the WinRust programs: the language switch (`t!`, `tf!`, `en!`), the NTFS MFT reader, Win+D.+//! Use it with `#[macro_use] extern crate winrust_common;` at the crate root.+//!+//! English by default; Russian when %ProgramData%\WinRust\lang.txt contains "ru" (the installer's EN/RU button writes it).+//! Programs read the file once at start; the one that flips the switch updates its own texts at once.use std::{path::PathBuf,sync::atomic::{AtomicU8, Ordering::Relaxed},};+pub mod desktop;+pub mod mft;+static LANG: AtomicU8 = AtomicU8::new(0); // 0 = not read yet, 1 = English, 2 = Russianfn file() -> Option<PathBuf> {std::env::var_os("ProgramData").map(|p| PathBuf::from(p).join("WinRust").join("lang.txt"))}-#[allow(dead_code)]+/// The current language at run time. In code that has unit tests use `en!()` instead: it is always Russian under `cargo test`.pub fn english() -> bool {match LANG.load(Relaxed) {1 => true,2 => false,_ => {- // unit tests keep their Russian expectations- let ru = cfg!(test) || file().and_then(|f| std::fs::read_to_string(f).ok()).is_some_and(|s| s.trim().eq_ignore_ascii_case("ru"));+ let ru = file().and_then(|f| std::fs::read_to_string(f).ok()).is_some_and(|s| s.trim().eq_ignore_ascii_case("ru"));LANG.store(if ru { 2 } else { 1 }, Relaxed);!ru}@@ -27,7 +31,6 @@ pub fn english() -> bool {}/// Switches this process and writes the choice for the other programs (they pick it up when they start).-#[allow(dead_code)]pub fn set_english(en: bool) {LANG.store(if en { 1 } else { 2 }, Relaxed);if let Some(f) = file() {@@ -36,19 +39,27 @@ pub fn set_english(en: bool) {}}+/// `en!()`: true for English. `cfg!(test)` is checked in the calling crate, so its unit tests keep their Russian expectations.+#[macro_export]+macro_rules! en {+ () => {+ !cfg!(test) && $crate::english()+ };+}+/// `t!("русский", "english")`: a text in the current language.-#[allow(unused_macros)]+#[macro_export]macro_rules! t {($ru:expr, $en:expr) => {- if $crate::i18n::english() { $en } else { $ru }+ if $crate::en!() { $en } else { $ru }};}/// `tf!("русский {}", "english {}", args...)`: format! in the current language (both templates are checked at compile time).-#[allow(unused_macros)]+#[macro_export]macro_rules! tf {($ru:literal, $en:literal $(, $a:expr)* $(,)?) => {- if $crate::i18n::english() { format!($en $(, $a)*) } else { format!($ru $(, $a)*) }+ if $crate::en!() { format!($en $(, $a)*) } else { format!($ru $(, $a)*) }};}diff --git a/plugins/rs-du/src/mft.rs b/common/src/mft.rssimilarity index 98%rename from plugins/rs-du/src/mft.rsrename to common/src/mft.rsindex 5eb1541..d479dc5 100644--- a/plugins/rs-du/src/mft.rs+++ b/common/src/mft.rs@@ -1,4 +1,4 @@-// NTFS MFT reader shared by rs-du (console) and wiztree (GUI, includes this file by #[path]).+// NTFS MFT reader shared by rs-du (console) and wiztree (GUI).use std::{collections::HashMap, mem::size_of, ptr};use windows_sys::Win32::{Foundation::*, Storage::FileSystem::*, System::{IO::DeviceIoControl, Ioctl::*}};diff --git a/payload.txt b/payload.txtnew file mode 100644index 0000000..f259e63--- /dev/null+++ b/payload.txt@@ -0,0 +1,13 @@+# The exes embedded into plugin-launcher.exe: <name in payload\> = <where the build puts it>.+# The one list for build.rs (what gets embedded) and scripts\build-plugins.ps1 (what gets copied into payload\).+rs.exe = plugins/rust-search/target/release/rs.exe+rs-launcher.exe = plugins/rust-search/target/release/rs-launcher.exe+Task manager.exe = target/release/rtaskmgr-win32.exe+rs-du.exe = target/release/rs-du.exe+topbar.exe = target/release/topbar.exe+reshell.exe = target/release/reshell.exe+rust-explorer.exe = target/release/rust-explorer.exe+rs-shell.exe = target/release/rs-shell.exe+wiztree.exe = target/release/wiztree.exe+photoview.exe = target/release/photoview.exe+debloat.exe = target/release/debloat.exediff --git a/payload/STAMPS.txt b/payload/STAMPS.txtdeleted file mode 100644index ef02a41..0000000--- a/payload/STAMPS.txt+++ /dev/null@@ -1,2 +0,0 @@-rtaskmgr-win32 327a035def48-rust-search e2eb11ba9295diff --git a/plugins/debloat/Cargo.lock b/plugins/debloat/Cargo.lockdeleted file mode 100644index a5e5dbb..0000000--- a/plugins/debloat/Cargo.lock+++ /dev/null@@ -1,7 +0,0 @@-# This file is automatically @generated by Cargo.-# It is not intended for manual editing.-version = 4--[[package]]-name = "debloat"-version = "0.1.0"diff --git a/plugins/debloat/Cargo.toml b/plugins/debloat/Cargo.tomlindex e6592c1..e1fee24 100644--- a/plugins/debloat/Cargo.toml+++ b/plugins/debloat/Cargo.toml@@ -2,10 +2,3 @@name = "debloat"version = "0.1.0"edition = "2024"--[profile.release]-opt-level = "s"-lto = true-codegen-units = 1-panic = "abort"-strip = truediff --git a/plugins/photoview/Cargo.lock b/plugins/photoview/Cargo.lockdeleted file mode 100644index eb12e90..0000000--- a/plugins/photoview/Cargo.lock+++ /dev/null@@ -1,165 +0,0 @@-# This file is automatically @generated by Cargo.-# It is not intended for manual editing.-version = 4--[[package]]-name = "photoview"-version = "0.1.0"-dependencies = [- "windows",- "windows-sys",-]--[[package]]-name = "proc-macro2"-version = "1.0.107"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"-dependencies = [- "unicode-ident",-]--[[package]]-name = "quote"-version = "1.0.47"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"-dependencies = [- "proc-macro2",-]--[[package]]-name = "syn"-version = "2.0.119"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"-dependencies = [- "proc-macro2",- "quote",- "unicode-ident",-]--[[package]]-name = "unicode-ident"-version = "1.0.27"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"--[[package]]-name = "windows"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"-dependencies = [- "windows-collections",- "windows-core",- "windows-future",- "windows-numerics",-]--[[package]]-name = "windows-collections"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"-dependencies = [- "windows-core",-]--[[package]]-name = "windows-core"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"-dependencies = [- "windows-implement",- "windows-interface",- "windows-link",- "windows-result",- "windows-strings",-]--[[package]]-name = "windows-future"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"-dependencies = [- "windows-core",- "windows-link",- "windows-threading",-]--[[package]]-name = "windows-implement"-version = "0.60.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"-dependencies = [- "proc-macro2",- "quote",- "syn",-]--[[package]]-name = "windows-interface"-version = "0.59.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"-dependencies = [- "proc-macro2",- "quote",- "syn",-]--[[package]]-name = "windows-link"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"--[[package]]-name = "windows-numerics"-version = "0.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"-dependencies = [- "windows-core",- "windows-link",-]--[[package]]-name = "windows-result"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-strings"-version = "0.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-threading"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"-dependencies = [- "windows-link",-]diff --git a/plugins/photoview/Cargo.toml b/plugins/photoview/Cargo.tomlindex 5868bb4..f5bdb2f 100644--- a/plugins/photoview/Cargo.toml+++ b/plugins/photoview/Cargo.toml@@ -7,10 +7,3 @@ edition = "2024"windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_UI_HiDpi", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }# COM only for the image decoder (WIC): JPEG/PNG/GIF/BMP/TIFF, WebP/HEIC/AVIF when the Windows codec is installedwindows = { version = "0.62", features = ["Win32_Foundation", "Win32_Graphics_Imaging", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Variant"] }--[profile.release]-opt-level = "s"-lto = true-codegen-units = 1-panic = "abort"-strip = truediff --git a/plugins/rs-du/Cargo.lock b/plugins/rs-du/Cargo.lockdeleted file mode 100644index c6f4764..0000000--- a/plugins/rs-du/Cargo.lock+++ /dev/null@@ -1,25 +0,0 @@-# This file is automatically @generated by Cargo.-# It is not intended for manual editing.-version = 4--[[package]]-name = "rs-du"-version = "0.1.0"-dependencies = [- "windows-sys",-]--[[package]]-name = "windows-link"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"--[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]diff --git a/plugins/rs-du/Cargo.toml b/plugins/rs-du/Cargo.tomlindex d9fb4da..c5c5506 100644--- a/plugins/rs-du/Cargo.toml+++ b/plugins/rs-du/Cargo.toml@@ -4,10 +4,5 @@ version = "0.1.0"edition = "2024"[dependencies]+winrust-common = { path = "../../common" }windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_IO", "Win32_System_Ioctl"] }--[profile.release]-opt-level = 3-lto = true-panic = "abort"-codegen-units = 1diff --git a/plugins/rs-du/README.md b/plugins/rs-du/README.mdindex 404e1de..f80e61d 100644--- a/plugins/rs-du/README.md+++ b/plugins/rs-du/README.md@@ -53,4 +53,4 @@2. Замер на реальном диске, запись результата здесь.3. Чистильщик.4. Дубликаты.-5. Запись в `plugin-launcher` (карточка, `build-all.ps1`, `sync.ps1`).+5. Запись в `plugin-launcher` (карточка, `payload.txt`).diff --git a/plugins/rs-du/src/main.rs b/plugins/rs-du/src/main.rsindex 69cf152..88986e3 100644--- a/plugins/rs-du/src/main.rs+++ b/plugins/rs-du/src/main.rs@@ -3,10 +3,9 @@// rs-du [X:] --clean [--apply [--all|--safe]] list (or delete: default = green+yellow, --all = everything, --safe = green only)// rs-du [X:] --restore | --purge bring quarantined files back | empty the quarantine now (it also empties itself after 30 days)#[macro_use]-mod i18n;+extern crate winrust_common;mod clean;-mod mft;-use mft::*;+use winrust_common::mft::*;// Reads the NTFS MFT (see mft.rs), sums sizes up the parent chain, prints the biggest folders and files. Needs admin (raw volume handle).// shortcuts: attribute lists / extension records are ignored (very fragmented files are undercounted),// folder index sizes are not counted; upgrade if numbers drift from Explorer.diff --git a/plugins/rs-shell/Cargo.lock b/plugins/rs-shell/Cargo.lockdeleted file mode 100644index 9d40e91..0000000--- a/plugins/rs-shell/Cargo.lock+++ /dev/null@@ -1,25 +0,0 @@-# This file is automatically @generated by Cargo.-# It is not intended for manual editing.-version = 4--[[package]]-name = "rs-shell"-version = "0.1.0"-dependencies = [- "windows-sys",-]--[[package]]-name = "windows-link"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"--[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]diff --git a/plugins/rs-shell/Cargo.toml b/plugins/rs-shell/Cargo.tomlindex 2d31ec5..9029316 100644--- a/plugins/rs-shell/Cargo.toml+++ b/plugins/rs-shell/Cargo.toml@@ -4,13 +4,5 @@ version = "0.1.0"edition = "2024"[dependencies]+winrust-common = { path = "../../common" }windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_System_Console", "Win32_System_RemoteDesktop", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }--[profile.release]-opt-level = "s"-lto = true-codegen-units = 1-panic = "abort"-strip = true--[workspace]diff --git a/plugins/rs-shell/src/main.rs b/plugins/rs-shell/src/main.rsindex 0f9723f..f6e98bd 100644--- a/plugins/rs-shell/src/main.rs+++ b/plugins/rs-shell/src/main.rs@@ -6,13 +6,13 @@// rs-shell --overlay run NEXT TO explorer.exe (it stays the shell): topbar + desktop + keep the bar alive. Started at logon by the "rs-overlay" scheduled task (HKCU Run as the fallback).// Put it next to topbar.exe. Recovery from a black screen: Ctrl+Alt+Del -> Task Manager -> run explorer.exe,// then `rs-shell --disable`; or sign in as another admin and run `reg delete` on the key printed by --enable.-// Also: starts `rust-explorer.exe --desktop` (desktop icons), Win+D = show desktop / bring the windows back,+// Also: starts `rust-explorer.exe --desktop` (desktop icons), Win+D = show desktop / bring the windows back (winrust-common),// Win+E = file manager (rust-explorer.exe if next to us). Put rust-explorer.exe next to rs-shell.exe.// shortcuts: Win+D only minimizes ordinary top-level windows (no per-monitor / virtual-desktop logic),// Run/Startup entries are started through `cmd /c start` (no RunOnce, no startup-delay rules, no disabled-list in// StartupApproved), topbar's "open" still shells out to explorer.exe for /select; upgrade when those matter.-use std::{os::windows::process::CommandExt, path::PathBuf, process::Command, ptr, sync::Mutex, thread, time::{Duration, Instant}};-use windows_sys::{core::BOOL, Win32::{Foundation::{HWND, LPARAM, RECT}, Graphics::Dwm::DwmGetWindowAttribute, UI::{Input::KeyboardAndMouse::{MOD_NOREPEAT, MOD_WIN, RegisterHotKey}, WindowsAndMessaging::*}}};+use std::{os::windows::process::CommandExt, path::PathBuf, process::Command, ptr, thread, time::{Duration, Instant}};+use windows_sys::{core::BOOL, Win32::{Foundation::{HWND, LPARAM, RECT}, UI::{Input::KeyboardAndMouse::{MOD_NOREPEAT, MOD_WIN, RegisterHotKey}, WindowsAndMessaging::*}}};const WINLOGON: &str = r"HKCU\Software\Microsoft\Windows NT\CurrentVersion\Winlogon";const NO_WINDOW: u32 = 0x0800_0000;@@ -87,20 +87,6 @@ fn find_exe(name: &str) -> PathBuf {fn bar_up() -> bool { unsafe { !FindWindowW(wide("topbar").as_ptr(), std::ptr::null()).is_null() } }-static HIDDEN: Mutex<Vec<isize>> = Mutex::new(Vec::new());--unsafe extern "system" fn collect(h: HWND, lp: LPARAM) -> BOOL {- unsafe {- let mut cloaked = 0u32; // DWMWA_CLOAKED: UWP ghosts that are "visible" but not on screen- DwmGetWindowAttribute(h, 14, &mut cloaked as *mut _ as _, 4);- let tool = GetWindowLongW(h, GWL_EXSTYLE) as u32 & WS_EX_TOOLWINDOW != 0; // topbar, desktop, tray hosts- if IsWindowVisible(h) != 0 && IsIconic(h) == 0 && !tool && cloaked == 0 && GetWindow(h, GW_OWNER).is_null() && GetWindowTextLengthW(h) > 0 {- (*(lp as *mut Vec<isize>)).push(h as isize);- }- 1- }-}-/// A minimized window left on screen (or minimized before the hide setting was applied) shows as a caption stub on/// the desktop: park it where Windows itself parks hidden minimized windows.unsafe extern "system" fn park(h: HWND, _: LPARAM) -> BOOL {@@ -114,23 +100,6 @@ unsafe extern "system" fn park(h: HWND, _: LPARAM) -> BOOL {}}-/// Win+D: minimize everything, press again to bring the same windows back. Anything open on screen means "minimize":-/// after a window was brought back by hand the old list must not turn the next press into a silent "restore".-fn toggle_desktop() {- let mut hid = HIDDEN.lock().unwrap();- unsafe {- let mut v: Vec<isize> = vec![];- EnumWindows(Some(collect), &mut v as *mut _ as LPARAM);- if !v.is_empty() {- v.iter().for_each(|&h| { ShowWindow(h as HWND, SW_MINIMIZE); });- *hid = v;- } else {- hid.iter().for_each(|&h| { if IsWindow(h as HWND) != 0 { ShowWindow(h as HWND, SW_RESTORE); } });- hid.clear();- }- }-}-fn set_wallpaper() {let Some(src) = reg(&["query", r"HKCU\Control Panel\Desktop", "/v", "WallPaper"]).map(|o| parse_run(&o)).and_then(|v| v.into_iter().next()) else { return };let mut path = PathBuf::from(&src);@@ -198,7 +167,7 @@ fn hotkey_loop() {let mut m: MSG = std::mem::zeroed();while GetMessageW(&mut m, ptr::null_mut(), 0, 0) > 0 {match (m.message == WM_HOTKEY).then_some(m.wParam) {- Some(1) => toggle_desktop(),+ Some(1) => winrust_common::desktop::toggle(),Some(2) => { let fm = dir().join("rust-explorer.exe"); let _ = quiet(if fm.exists() { fm } else { "explorer.exe".into() }).spawn(); }_ => {}}@@ -243,6 +212,10 @@ fn kill_shell_explorer() {log(&format!("explorer shell stopped -> {:?}", r.map(|s| s.success())));}+/// How long after the overlay starts Explorer may be ended even without the markers below: newer Windows builds (26300)+/// no longer write them, and the overlay then waited forever. Explorer gets through the autostart well within this.+const AUTOSTART_GRACE: Duration = Duration::from_secs(90);+/// True once Explorer has started this session's Run keys and Startup folder. The overlay starts at logon (a scheduled task),/// before Explorer gets to them: ending Explorer earlier would lose the user's autostart apps.fn startup_run() -> bool {@@ -252,6 +225,10 @@ fn startup_run() -> bool {["RunStuffHasBeenRun", "StartupHasBeenRun"].iter().all(|n| reg(&["query", &format!(r"{k}\{n}")]).is_some())}+fn may_end_explorer(markers: bool, since_start: Duration) -> bool {+ markers || since_start >= AUTOSTART_GRACE+}+/// Gives the user Explorer back (with a normal, not elevated, token: the shell must never run elevated).fn start_shell_explorer() {let r = quiet("runas").args(["/trustlevel:0x20000", r"C:\Windows\explorer.exe"]).creation_flags(NO_WINDOW).spawn();@@ -281,12 +258,17 @@ fn overlay() {/// (so the user is never left without a shell) if the bar will not stay up.fn overlay_watch(replace: bool, desktop: PathBuf, up: impl Fn() -> bool) {let (mut starts, mut misses, mut dmiss, mut stable, mut killed) = (0, 0, 0, 0, false);+ let began = Instant::now();loop {thread::sleep(Duration::from_secs(3));if replace && !killed {// both our surfaces must be on screen before the system's one goes awaystable = if bar_up() && up() { stable + 1 } else { 0 };- if stable >= 3 && startup_run() { kill_shell_explorer(); killed = true; }+ if stable >= 3 && may_end_explorer(startup_run(), began.elapsed()) {+ log(&format!("autostart done (markers: {}, after {} s)", startup_run(), began.elapsed().as_secs()));+ kill_shell_explorer();+ killed = true;+ }}dmiss = if desktop.exists() && !up() { dmiss + 1 } else { 0 };if dmiss >= 2 { log(&format!("desktop respawn -> {:?}", quiet(&desktop).arg("--desktop").spawn().map(|_| ()))); dmiss = 0; }@@ -365,7 +347,14 @@ fn main() {#[cfg(test)]mod tests {- use super::{exe_path, parse_run};+ use super::{exe_path, may_end_explorer, parse_run};+ use std::time::Duration;+ #[test]+ fn ends_explorer_on_markers_or_after_grace() {+ assert!(may_end_explorer(true, Duration::ZERO));+ assert!(!may_end_explorer(false, Duration::from_secs(30)));+ assert!(may_end_explorer(false, Duration::from_secs(90)));+ }#[test]fn finds_the_exe_in_run_commands() {assert_eq!(exe_path(r#""C:\a b\x.exe" --hidden"#).as_deref(), Some(r"C:\a b\x.exe"));diff --git a/plugins/rtaskmgr-win32/Cargo.lock b/plugins/rtaskmgr-win32/Cargo.lockdeleted file mode 100644index e9382ad..0000000--- a/plugins/rtaskmgr-win32/Cargo.lock+++ /dev/null@@ -1,481 +0,0 @@-# This file is automatically @generated by Cargo.-# It is not intended for manual editing.-version = 4--[[package]]-name = "bitflags"-version = "1.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"--[[package]]-name = "bitflags"-version = "2.13.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"--[[package]]-name = "cc"-version = "1.11.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"-dependencies = [- "find-msvc-tools",- "shlex",-]--[[package]]-name = "cfg-if"-version = "1.0.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"--[[package]]-name = "embed-resource"-version = "3.0.12"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f"-dependencies = [- "cc",- "memchr",- "rustc_version",- "toml",- "vswhom",- "winreg",-]--[[package]]-name = "equivalent"-version = "1.0.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"--[[package]]-name = "find-msvc-tools"-version = "0.1.15"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"--[[package]]-name = "hashbrown"-version = "0.17.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"--[[package]]-name = "indexmap"-version = "2.14.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"-dependencies = [- "equivalent",- "hashbrown",-]--[[package]]-name = "lazy_static"-version = "1.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"--[[package]]-name = "libc"-version = "0.2.191"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"--[[package]]-name = "memchr"-version = "2.8.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"--[[package]]-name = "muldiv"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0419348c027fa7be448d2ae7ea0e4e04c2334c31dc4e74ab29f00a2a7ca69204"--[[package]]-name = "native-windows-gui"-version = "1.0.13"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4f7003a669f68deb6b7c57d74fff4f8e533c44a3f0b297492440ef4ff5a28454"-dependencies = [- "bitflags 1.3.2",- "lazy_static",- "muldiv",- "winapi",- "winapi-build",-]--[[package]]-name = "ntapi"-version = "0.4.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"-dependencies = [- "winapi",-]--[[package]]-name = "objc2-core-foundation"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"-dependencies = [- "bitflags 2.13.2",-]--[[package]]-name = "objc2-io-kit"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"-dependencies = [- "libc",- "objc2-core-foundation",-]--[[package]]-name = "proc-macro2"-version = "1.0.107"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"-dependencies = [- "unicode-ident",-]--[[package]]-name = "quote"-version = "1.0.47"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"-dependencies = [- "proc-macro2",-]--[[package]]-name = "rtaskmgr-win32"-version = "0.1.0"-dependencies = [- "embed-resource",- "native-windows-gui",- "sysinfo",- "winapi",- "windows-sys",-]--[[package]]-name = "rustc_version"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"-dependencies = [- "semver",-]--[[package]]-name = "semver"-version = "1.0.28"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"--[[package]]-name = "serde_core"-version = "1.0.229"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"-dependencies = [- "serde_derive",-]--[[package]]-name = "serde_derive"-version = "1.0.229"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"-dependencies = [- "proc-macro2",- "quote",- "syn 3.0.10",-]--[[package]]-name = "serde_spanned"-version = "1.1.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"-dependencies = [- "serde_core",-]--[[package]]-name = "shlex"-version = "2.0.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"--[[package]]-name = "syn"-version = "2.0.119"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"-dependencies = [- "proc-macro2",- "quote",- "unicode-ident",-]--[[package]]-name = "syn"-version = "3.0.10"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"-dependencies = [- "proc-macro2",- "quote",- "unicode-ident",-]--[[package]]-name = "sysinfo"-version = "0.40.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a86bac2f7d06e6384984118ad727f5694110f0ec44d924d05c8fdec3d030bee6"-dependencies = [- "libc",- "memchr",- "ntapi",- "objc2-core-foundation",- "objc2-io-kit",- "windows",-]--[[package]]-name = "toml"-version = "1.2.1+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"-dependencies = [- "indexmap",- "serde_core",- "serde_spanned",- "toml_datetime",- "toml_parser",- "toml_writer",- "winnow",-]--[[package]]-name = "toml_datetime"-version = "1.1.3+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"-dependencies = [- "serde_core",-]--[[package]]-name = "toml_parser"-version = "1.1.5+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"-dependencies = [- "winnow",-]--[[package]]-name = "toml_writer"-version = "1.2.0+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"--[[package]]-name = "unicode-ident"-version = "1.0.27"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"--[[package]]-name = "vswhom"-version = "0.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"-dependencies = [- "libc",- "vswhom-sys",-]--[[package]]-name = "vswhom-sys"-version = "0.1.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"-dependencies = [- "cc",- "libc",-]--[[package]]-name = "winapi"-version = "0.3.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"-dependencies = [- "winapi-i686-pc-windows-gnu",- "winapi-x86_64-pc-windows-gnu",-]--[[package]]-name = "winapi-build"-version = "0.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc"--[[package]]-name = "winapi-i686-pc-windows-gnu"-version = "0.4.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"--[[package]]-name = "winapi-x86_64-pc-windows-gnu"-version = "0.4.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"--[[package]]-name = "windows"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"-dependencies = [- "windows-collections",- "windows-core",- "windows-future",- "windows-numerics",-]--[[package]]-name = "windows-collections"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"-dependencies = [- "windows-core",-]--[[package]]-name = "windows-core"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"-dependencies = [- "windows-implement",- "windows-interface",- "windows-link",- "windows-result",- "windows-strings",-]--[[package]]-name = "windows-future"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"-dependencies = [- "windows-core",- "windows-link",- "windows-threading",-]--[[package]]-name = "windows-implement"-version = "0.60.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.119",-]--[[package]]-name = "windows-interface"-version = "0.59.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.119",-]--[[package]]-name = "windows-link"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"--[[package]]-name = "windows-numerics"-version = "0.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"-dependencies = [- "windows-core",- "windows-link",-]--[[package]]-name = "windows-result"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-strings"-version = "0.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-threading"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"-dependencies = [- "windows-link",-]--[[package]]-name = "winnow"-version = "1.0.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"--[[package]]-name = "winreg"-version = "0.56.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"-dependencies = [- "cfg-if",- "windows-sys",-]diff --git a/plugins/rtaskmgr-win32/Cargo.toml b/plugins/rtaskmgr-win32/Cargo.tomlindex fc65307..ddb3da5 100644--- a/plugins/rtaskmgr-win32/Cargo.toml+++ b/plugins/rtaskmgr-win32/Cargo.toml@@ -4,17 +4,11 @@ version = "0.1.0"edition = "2024"[dependencies]+winrust-common = { path = "../../common" }native-windows-gui = { version = "1.0.13", default-features = false, features = ["timer", "clipboard", "cursor", "tray-notification", "high-dpi", "embed-resource"] }sysinfo = { version = "0.40.3", default-features = false, features = ["system", "network", "disk"] }winapi = { version = "0.3", features = ["debugapi", "winsvc", "processthreadsapi", "winbase", "winnt", "handleapi", "shellapi", "errhandlingapi", "minwindef", "winuser", "wingdi", "winreg", "winerror", "sysinfoapi", "minwinbase", "windef", "commctrl", "winver", "psapi", "libloaderapi", "fileapi", "ioapiset", "ntdef", "setupapi", "guiddef", "securitybaseapi", "synchapi"] }windows-sys = { version = "0.61.2", features = ["Win32_System_Diagnostics_Etw", "Win32_Foundation", "Win32_System_Time", "Win32_Security_WinTrust", "Win32_Security_Cryptography", "Win32_System_Performance"] }-[profile.release]-opt-level = "s"-lto = true-codegen-units = 1-panic = "abort"-strip = true-[build-dependencies]embed-resource = "3"diff --git a/plugins/rtaskmgr-win32/src/i18n.rs b/plugins/rtaskmgr-win32/src/i18n.rsdeleted file mode 100644index 707cc46..0000000--- a/plugins/rtaskmgr-win32/src/i18n.rs+++ /dev/null@@ -1,62 +0,0 @@-// Language switch shared by every WinRust program (an identical copy of this file lives in each crate).-// English by default; Russian when %ProgramData%\WinRust\lang.txt contains "ru" (the installer's EN/RU button writes it).-// Programs read the file once at start; the one that flips the switch updates its own texts at once.-use std::{- path::PathBuf,- sync::atomic::{AtomicU8, Ordering::Relaxed},-};--static LANG: AtomicU8 = AtomicU8::new(0); // 0 = not read yet, 1 = English, 2 = Russian--fn file() -> Option<PathBuf> {- std::env::var_os("ProgramData").map(|p| PathBuf::from(p).join("WinRust").join("lang.txt"))-}--#[allow(dead_code)]-pub fn english() -> bool {- match LANG.load(Relaxed) {- 1 => true,- 2 => false,- _ => {- // unit tests keep their Russian expectations- let ru = cfg!(test) || file().and_then(|f| std::fs::read_to_string(f).ok()).is_some_and(|s| s.trim().eq_ignore_ascii_case("ru"));- LANG.store(if ru { 2 } else { 1 }, Relaxed);- !ru- }- }-}--/// Switches this process and writes the choice for the other programs (they pick it up when they start).-#[allow(dead_code)]-pub fn set_english(en: bool) {- LANG.store(if en { 1 } else { 2 }, Relaxed);- if let Some(f) = file() {- let _ = std::fs::create_dir_all(f.parent().unwrap());- let _ = std::fs::write(f, if en { "en" } else { "ru" });- }-}--/// `t!("русский", "english")`: a text in the current language.-#[allow(unused_macros)]-macro_rules! t {- ($ru:expr, $en:expr) => {- if $crate::i18n::english() { $en } else { $ru }- };-}--/// `tf!("русский {}", "english {}", args...)`: format! in the current language (both templates are checked at compile time).-#[allow(unused_macros)]-macro_rules! tf {- ($ru:literal, $en:literal $(, $a:expr)* $(,)?) => {- if $crate::i18n::english() { format!($en $(, $a)*) } else { format!($ru $(, $a)*) }- };-}--#[cfg(test)]-mod tests {- #[test]- fn tests_run_in_russian() {- assert_eq!(t!("да", "yes"), "да");- assert_eq!(tf!("{} шт", "{} pcs", 3), "3 шт");- }-}diff --git a/plugins/rtaskmgr-win32/src/main.rs b/plugins/rtaskmgr-win32/src/main.rsindex 178d60c..645e38e 100644--- a/plugins/rtaskmgr-win32/src/main.rs+++ b/plugins/rtaskmgr-win32/src/main.rs@@ -1,6 +1,6 @@#![windows_subsystem = "windows"]#[macro_use]-mod i18n;+extern crate winrust_common;mod app;mod data;mod draw;diff --git a/plugins/rtaskmgr-win32/src/model.rs b/plugins/rtaskmgr-win32/src/model.rsindex 3f8a5e6..4720e10 100644--- a/plugins/rtaskmgr-win32/src/model.rs+++ b/plugins/rtaskmgr-win32/src/model.rs@@ -124,7 +124,7 @@ pub struct Row {pub fn dec(v: f64, digits: usize) -> String {let s = format!("{:.*}", digits, v);- if crate::i18n::english() { s } else { s.replace('.', ",") }+ if en!() { s } else { s.replace('.', ",") }}pub fn fmt_cpu(v: f32) -> String {@@ -133,7 +133,7 @@ pub fn fmt_cpu(v: f32) -> String {pub fn fmt_mem_ru(b: u64) -> String {let mb = b as f64 / 1_048_576.0;- if mb >= 1000.0 { tf!("{} МБ", "{} MB", { let g = group_thousands(mb as u64); if crate::i18n::english() { g } else { g.replace(',', " ") } }) } else if mb >= 100.0 { tf!("{} МБ", "{} MB", dec(mb, 0)) } else { tf!("{} МБ", "{} MB", dec(mb, 1)) }+ if mb >= 1000.0 { tf!("{} МБ", "{} MB", { let g = group_thousands(mb as u64); if en!() { g } else { g.replace(',', " ") } }) } else if mb >= 100.0 { tf!("{} МБ", "{} MB", dec(mb, 0)) } else { tf!("{} МБ", "{} MB", dec(mb, 1)) }}pub fn fmt_disk_ru(bps: f64) -> String {diff --git a/plugins/rtaskmgr-win32/src/sys.rs b/plugins/rtaskmgr-win32/src/sys.rsindex 7e4beb6..d6f0b8c 100644--- a/plugins/rtaskmgr-win32/src/sys.rs+++ b/plugins/rtaskmgr-win32/src/sys.rs@@ -365,9 +365,9 @@ pub fn process_user(pid: u32) -> Option<String> {if OpenProcessToken(h, TOKEN_QUERY, &mut tok) == 0 {return None;}- let mut buf = [0u8; 512];+ let mut buf = [0u64; 64]; // u64: TOKEN_USER holds pointers, a byte array is not aligned for itlet mut need = 0u32;- let ok = GetTokenInformation(tok, 1 /*TokenUser*/, buf.as_mut_ptr() as *mut _, buf.len() as u32, &mut need) != 0;+ let ok = GetTokenInformation(tok, 1 /*TokenUser*/, buf.as_mut_ptr() as *mut _, size_of_val(&buf) as u32, &mut need) != 0;CloseHandle(tok);if !ok {return None;diff --git a/plugins/rust-explorer/Cargo.lock b/plugins/rust-explorer/Cargo.lockdeleted file mode 100644index 86aa1e7..0000000--- a/plugins/rust-explorer/Cargo.lock+++ /dev/null@@ -1,373 +0,0 @@-# This file is automatically @generated by Cargo.-# It is not intended for manual editing.-version = 4--[[package]]-name = "cc"-version = "1.11.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"-dependencies = [- "find-msvc-tools",- "shlex",-]--[[package]]-name = "cfg-if"-version = "1.0.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"--[[package]]-name = "embed-resource"-version = "3.0.12"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f"-dependencies = [- "cc",- "memchr",- "rustc_version",- "toml",- "vswhom",- "winreg",-]--[[package]]-name = "equivalent"-version = "1.0.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"--[[package]]-name = "find-msvc-tools"-version = "0.1.15"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"--[[package]]-name = "hashbrown"-version = "0.17.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"--[[package]]-name = "indexmap"-version = "2.14.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"-dependencies = [- "equivalent",- "hashbrown",-]--[[package]]-name = "libc"-version = "0.2.191"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"--[[package]]-name = "memchr"-version = "2.8.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"--[[package]]-name = "proc-macro2"-version = "1.0.107"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"-dependencies = [- "unicode-ident",-]--[[package]]-name = "quote"-version = "1.0.47"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"-dependencies = [- "proc-macro2",-]--[[package]]-name = "rust-explorer"-version = "0.1.0"-dependencies = [- "embed-resource",- "windows",- "windows-core",- "windows-sys",-]--[[package]]-name = "rustc_version"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"-dependencies = [- "semver",-]--[[package]]-name = "semver"-version = "1.0.28"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"--[[package]]-name = "serde_core"-version = "1.0.229"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"-dependencies = [- "serde_derive",-]--[[package]]-name = "serde_derive"-version = "1.0.229"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"-dependencies = [- "proc-macro2",- "quote",- "syn 3.0.10",-]--[[package]]-name = "serde_spanned"-version = "1.1.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"-dependencies = [- "serde_core",-]--[[package]]-name = "shlex"-version = "2.0.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"--[[package]]-name = "syn"-version = "2.0.119"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"-dependencies = [- "proc-macro2",- "quote",- "unicode-ident",-]--[[package]]-name = "syn"-version = "3.0.10"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"-dependencies = [- "proc-macro2",- "quote",- "unicode-ident",-]--[[package]]-name = "toml"-version = "1.2.1+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"-dependencies = [- "indexmap",- "serde_core",- "serde_spanned",- "toml_datetime",- "toml_parser",- "toml_writer",- "winnow",-]--[[package]]-name = "toml_datetime"-version = "1.1.3+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"-dependencies = [- "serde_core",-]--[[package]]-name = "toml_parser"-version = "1.1.5+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"-dependencies = [- "winnow",-]--[[package]]-name = "toml_writer"-version = "1.2.0+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"--[[package]]-name = "unicode-ident"-version = "1.0.27"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"--[[package]]-name = "vswhom"-version = "0.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"-dependencies = [- "libc",- "vswhom-sys",-]--[[package]]-name = "vswhom-sys"-version = "0.1.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"-dependencies = [- "cc",- "libc",-]--[[package]]-name = "windows"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"-dependencies = [- "windows-collections",- "windows-core",- "windows-future",- "windows-numerics",-]--[[package]]-name = "windows-collections"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"-dependencies = [- "windows-core",-]--[[package]]-name = "windows-core"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"-dependencies = [- "windows-implement",- "windows-interface",- "windows-link",- "windows-result",- "windows-strings",-]--[[package]]-name = "windows-future"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"-dependencies = [- "windows-core",- "windows-link",- "windows-threading",-]--[[package]]-name = "windows-implement"-version = "0.60.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.119",-]--[[package]]-name = "windows-interface"-version = "0.59.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.119",-]--[[package]]-name = "windows-link"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"--[[package]]-name = "windows-numerics"-version = "0.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"-dependencies = [- "windows-core",- "windows-link",-]--[[package]]-name = "windows-result"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-strings"-version = "0.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-threading"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"-dependencies = [- "windows-link",-]--[[package]]-name = "winnow"-version = "1.0.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"--[[package]]-name = "winreg"-version = "0.56.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"-dependencies = [- "cfg-if",- "windows-sys",-]diff --git a/plugins/rust-explorer/Cargo.toml b/plugins/rust-explorer/Cargo.tomlindex b4bc99d..bd852c6 100644--- a/plugins/rust-explorer/Cargo.toml+++ b/plugins/rust-explorer/Cargo.toml@@ -10,10 +10,3 @@ windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graph[build-dependencies]embed-resource = "3"--[profile.release]-opt-level = "s"-lto = true-panic = "abort"-codegen-units = 1-strip = truediff --git a/plugins/topbar/.cargo/config.toml b/plugins/topbar/.cargo/config.tomldeleted file mode 100644index fac678a..0000000--- a/plugins/topbar/.cargo/config.toml+++ /dev/null@@ -1,2 +0,0 @@-[build]-rustflags = ["-C", "target-feature=+crt-static"]diff --git a/plugins/topbar/Cargo.lock b/plugins/topbar/Cargo.lockdeleted file mode 100644index 1963b08..0000000--- a/plugins/topbar/Cargo.lock+++ /dev/null@@ -1,165 +0,0 @@-# This file is automatically @generated by Cargo.-# It is not intended for manual editing.-version = 4--[[package]]-name = "proc-macro2"-version = "1.0.107"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"-dependencies = [- "unicode-ident",-]--[[package]]-name = "quote"-version = "1.0.47"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"-dependencies = [- "proc-macro2",-]--[[package]]-name = "syn"-version = "2.0.119"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"-dependencies = [- "proc-macro2",- "quote",- "unicode-ident",-]--[[package]]-name = "topbar"-version = "0.1.0"-dependencies = [- "windows",- "windows-sys",-]--[[package]]-name = "unicode-ident"-version = "1.0.27"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"--[[package]]-name = "windows"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"-dependencies = [- "windows-collections",- "windows-core",- "windows-future",- "windows-numerics",-]--[[package]]-name = "windows-collections"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"-dependencies = [- "windows-core",-]--[[package]]-name = "windows-core"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"-dependencies = [- "windows-implement",- "windows-interface",- "windows-link",- "windows-result",- "windows-strings",-]--[[package]]-name = "windows-future"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"-dependencies = [- "windows-core",- "windows-link",- "windows-threading",-]--[[package]]-name = "windows-implement"-version = "0.60.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"-dependencies = [- "proc-macro2",- "quote",- "syn",-]--[[package]]-name = "windows-interface"-version = "0.59.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"-dependencies = [- "proc-macro2",- "quote",- "syn",-]--[[package]]-name = "windows-link"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"--[[package]]-name = "windows-numerics"-version = "0.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"-dependencies = [- "windows-core",- "windows-link",-]--[[package]]-name = "windows-result"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-strings"-version = "0.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-threading"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"-dependencies = [- "windows-link",-]diff --git a/plugins/topbar/Cargo.toml b/plugins/topbar/Cargo.tomlindex 70c156a..439522c 100644--- a/plugins/topbar/Cargo.toml+++ b/plugins/topbar/Cargo.toml@@ -4,13 +4,7 @@ version = "0.1.0"edition = "2024"[dependencies]+winrust-common = { path = "../../common" }windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_NetworkManagement_WiFi", "Win32_NetworkManagement_Ndis", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_DataExchange", "Win32_System_Diagnostics_ToolHelp", "Win32_System_LibraryLoader", "Win32_System_Power", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }# COM only where raw vtables would be long: master volume and .lnk targetswindows = { version = "0.62", features = ["Win32_Media_Audio", "Win32_Media_Audio_Endpoints", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Variant", "Win32_Graphics_Gdi", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_Storage_FileSystem"] }--[profile.release]-opt-level = "s"-lto = true-codegen-units = 1-panic = "abort"-strip = truediff --git a/plugins/topbar/src/i18n.rs b/plugins/topbar/src/i18n.rsdeleted file mode 100644index 707cc46..0000000--- a/plugins/topbar/src/i18n.rs+++ /dev/null@@ -1,62 +0,0 @@-// Language switch shared by every WinRust program (an identical copy of this file lives in each crate).-// English by default; Russian when %ProgramData%\WinRust\lang.txt contains "ru" (the installer's EN/RU button writes it).-// Programs read the file once at start; the one that flips the switch updates its own texts at once.-use std::{- path::PathBuf,- sync::atomic::{AtomicU8, Ordering::Relaxed},-};--static LANG: AtomicU8 = AtomicU8::new(0); // 0 = not read yet, 1 = English, 2 = Russian--fn file() -> Option<PathBuf> {- std::env::var_os("ProgramData").map(|p| PathBuf::from(p).join("WinRust").join("lang.txt"))-}--#[allow(dead_code)]-pub fn english() -> bool {- match LANG.load(Relaxed) {- 1 => true,- 2 => false,- _ => {- // unit tests keep their Russian expectations- let ru = cfg!(test) || file().and_then(|f| std::fs::read_to_string(f).ok()).is_some_and(|s| s.trim().eq_ignore_ascii_case("ru"));- LANG.store(if ru { 2 } else { 1 }, Relaxed);- !ru- }- }-}--/// Switches this process and writes the choice for the other programs (they pick it up when they start).-#[allow(dead_code)]-pub fn set_english(en: bool) {- LANG.store(if en { 1 } else { 2 }, Relaxed);- if let Some(f) = file() {- let _ = std::fs::create_dir_all(f.parent().unwrap());- let _ = std::fs::write(f, if en { "en" } else { "ru" });- }-}--/// `t!("русский", "english")`: a text in the current language.-#[allow(unused_macros)]-macro_rules! t {- ($ru:expr, $en:expr) => {- if $crate::i18n::english() { $en } else { $ru }- };-}--/// `tf!("русский {}", "english {}", args...)`: format! in the current language (both templates are checked at compile time).-#[allow(unused_macros)]-macro_rules! tf {- ($ru:literal, $en:literal $(, $a:expr)* $(,)?) => {- if $crate::i18n::english() { format!($en $(, $a)*) } else { format!($ru $(, $a)*) }- };-}--#[cfg(test)]-mod tests {- #[test]- fn tests_run_in_russian() {- assert_eq!(t!("да", "yes"), "да");- assert_eq!(tf!("{} шт", "{} pcs", 3), "3 шт");- }-}diff --git a/plugins/topbar/src/main.rs b/plugins/topbar/src/main.rsindex d6e23c4..7e9f452 100644--- a/plugins/topbar/src/main.rs+++ b/plugins/topbar/src/main.rs@@ -16,7 +16,8 @@ use std::{sync::atomic::{AtomicBool, AtomicIsize, Ordering::Relaxed},};#[macro_use]-mod i18n;+extern crate winrust_common;+use winrust_common as i18n;mod fly;use windows::{Win32::{@@ -1683,7 +1684,7 @@ fn wstr_of(w: &[u16]) -> String {/// "1 окно", "3 окна", "5 окон".fn windows_ru(n: usize) -> String {- if crate::i18n::english() {+ if en!() {return format!("{n} {}", if n == 1 { "window" } else { "windows" });}let w = match (n % 10, n % 100) {diff --git a/plugins/wiztree/Cargo.lock b/plugins/wiztree/Cargo.lockdeleted file mode 100644index 635844c..0000000--- a/plugins/wiztree/Cargo.lock+++ /dev/null@@ -1,25 +0,0 @@-# This file is automatically @generated by Cargo.-# It is not intended for manual editing.-version = 4--[[package]]-name = "windows-link"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"--[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]--[[package]]-name = "wiztree"-version = "0.1.0"-dependencies = [- "windows-sys",-]diff --git a/plugins/wiztree/Cargo.toml b/plugins/wiztree/Cargo.tomlindex 7922a21..a1d2948 100644--- a/plugins/wiztree/Cargo.toml+++ b/plugins/wiztree/Cargo.toml@@ -4,11 +4,5 @@ version = "0.1.0"edition = "2024"[dependencies]+winrust-common = { path = "../../common" }windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_LibraryLoader", "Win32_UI_HiDpi", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }--[profile.release]-opt-level = "s"-lto = true-codegen-units = 1-panic = "abort"-strip = truediff --git a/plugins/wiztree/src/main.rs b/plugins/wiztree/src/main.rsindex 45befad..ff5682a 100644--- a/plugins/wiztree/src/main.rs+++ b/plugins/wiztree/src/main.rs@@ -1,11 +1,9 @@#![windows_subsystem = "windows"]-// wiztree [X:] Disk usage treemap on the NTFS MFT (the same reader as rs-du, shared through mft.rs).+// wiztree [X:] Disk usage treemap on the NTFS MFT (the same reader as rs-du, from winrust-common).// Click a folder: go in. Right click / Backspace: up. Click a file: show it in Explorer. Tab: next drive. F5: rescan. Esc: quit.// Needs admin (raw volume); starts itself elevated (UAC) when it is not.-// shortcuts: one level of the tree at a time, the 300 biggest items; a folder's own index size is not counted (see mft.rs).-#[path = "../../rs-du/src/mft.rs"]-mod mft;-use mft::*;+// shortcuts: one level of the tree at a time, the 300 biggest items; a folder's own index size is not counted (see common/src/mft.rs).+use winrust_common::mft::*;use std::{cell::RefCell, collections::HashMap, ptr::{null, null_mut}};use windows_sys::Win32::{Foundation::*,diff --git a/scripts/build-all.ps1 b/scripts/build-all.ps1index 90401dc..1c8df7d 100644--- a/scripts/build-all.ps1+++ b/scripts/build-all.ps1@@ -1,27 +1,9 @@-# Syncs plugins\ from the original project folders, rebuilds every plugin, refreshes payload\ (+ STAMPS.txt),-# then rebuilds the launcher (one self-contained exe). Ends with a stamp check: any mismatch fails the script.+# Full build: every plugin into payload\, then the launcher with all of them embedded (one self-contained exe).+# powershell -ExecutionPolicy Bypass -File scripts\build-all.ps1+# Close a running plugin-launcher.exe first.$ErrorActionPreference = 'Stop'$root = Split-Path $PSScriptRoot-$sync = "$PSScriptRoot\sync.ps1"-& $sync | Out-Null-function Build($dir) { Push-Location "$root\plugins\$dir"; cargo build --release; if ($LASTEXITCODE) { throw "build failed: $dir" }; Pop-Location }-Build 'rust-search'-Build 'rtaskmgr-win32'-Build 'topbar'-Build 'rs-du'-Build 'rust-explorer'-Build 'rs-shell'-foreach ($t in 'wiztree', 'photoview', 'debloat') { Build $t; Copy-Item "$root\plugins\$t\target\release\$t.exe" "$root\payload" -Force }-Push-Location "$root\ReShell"; cargo build --release; if ($LASTEXITCODE) { throw 'build failed: ReShell' }; Pop-Location-Copy-Item "$root\ReShell\target\release\reshell.exe" "$root\payload" -Force-Copy-Item "$root\plugins\topbar\target\release\topbar.exe" "$root\payload" -Force-Copy-Item "$root\plugins\rs-du\target\release\rs-du.exe" "$root\payload" -Force-Copy-Item "$root\plugins\rust-explorer\target\release\rust-explorer.exe", "$root\plugins\rs-shell\target\release\rs-shell.exe" "$root\payload" -Force-$rs = "$root\plugins\rust-search\target\release"-Copy-Item "$rs\rs.exe", "$rs\rs-launcher.exe" "$root\payload" -Force-Copy-Item "$root\plugins\rtaskmgr-win32\target\release\rtaskmgr-win32.exe" "$root\payload\Task manager.exe" -Force-& $sync -Stamp | Out-Null-Push-Location $root; cargo build --release; if ($LASTEXITCODE) { throw 'launcher build failed' }; Pop-Location-& $sync -Check-if ($LASTEXITCODE) { throw 'stamp mismatch' }+& "$PSScriptRoot\build-plugins.ps1"+Push-Location $root+try { cargo build --release -p plugin-launcher; if ($LASTEXITCODE) { throw 'launcher build failed' } } finally { Pop-Location }Write-Host "done: $root\target\release\plugin-launcher.exe"diff --git a/scripts/build-plugins.ps1 b/scripts/build-plugins.ps1new file mode 100644index 0000000..d687dfc--- /dev/null+++ b/scripts/build-plugins.ps1@@ -0,0 +1,18 @@+# Builds every plugin and copies the exes listed in payload.txt into payload\. No admin needed.+# powershell -ExecutionPolicy Bypass -File scripts\build-plugins.ps1+# cargo only rebuilds what changed, so this is also the fast path after editing one plugin.+$ErrorActionPreference = 'Stop'+$root = Split-Path $PSScriptRoot+function Build([string]$dir, [string[]]$a) {+ Push-Location $dir+ try { cargo build --release @a; if ($LASTEXITCODE) { throw "cargo build failed in $dir" } } finally { Pop-Location }+}+Build $root '--workspace', '--exclude', 'plugin-launcher' # the launcher embeds payload\, so it is built after the copy+Build "$root\plugins\rust-search" @() # outside the workspace (needs panic = unwind, see Cargo.toml)+New-Item -ItemType Directory -Force "$root\payload" | Out-Null+foreach ($l in Get-Content "$root\payload.txt") {+ if ($l -match '^\s*(#|$)') { continue }+ $name, $src = $l -split '=', 2+ Copy-Item (Join-Path $root $src.Trim()) (Join-Path "$root\payload" $name.Trim()) -Force+}+Write-Host "payload\ refreshed"diff --git a/scripts/dev-update.ps1 b/scripts/dev-update.ps1index b21dd37..f6769e4 100644--- a/scripts/dev-update.ps1+++ b/scripts/dev-update.ps1@@ -6,14 +6,13 @@ param([Parameter(Mandatory)][ValidateSet('topbar', 'rs-shell', 'rust-explorer',$ErrorActionPreference = 'Stop'$root = Split-Path $PSScriptRoot$bin = "$env:LOCALAPPDATA\plugin-launcher\bin"-$dir = @{ 'topbar' = "$root\plugins\topbar"; 'rs-shell' = "$root\plugins\rs-shell"; 'rust-explorer' = "$root\plugins\rust-explorer"; 'reshell' = "$root\ReShell" }[$Name]$exe = "$Name.exe"if (-not (Test-Path "$bin\rs-shell.exe")) { throw "run scripts\user-mode.ps1 first" }-Push-Location $dir; cargo build --release; $rc = $LASTEXITCODE; Pop-Location+Push-Location $root; cargo build --release -p $Name; $rc = $LASTEXITCODE; Pop-Locationif ($rc -ne 0) { throw "cargo build failed" }$to = "$bin\$exe"if (Test-Path $to) { Rename-Item $to ("$exe." + (Get-Date -Format HHmmssfff) + '.old') -Force }-Copy-Item "$dir\target\release\$exe" $to -Force+Copy-Item "$root\target\release\$exe" $to -ForceGet-ChildItem $bin -Filter "$exe.*.old" | ForEach-Object { Remove-Item $_.FullName -Force -ErrorAction SilentlyContinue }switch ($Name) {'topbar' { Stop-Process -Name topbar -Force -ErrorAction SilentlyContinue; "topbar stopped: rs-shell starts the new one in a few seconds" }diff --git a/scripts/release.ps1 b/scripts/release.ps1index 953ad7d..b8a5c89 100644--- a/scripts/release.ps1+++ b/scripts/release.ps1@@ -1,6 +1,6 @@# Publishes a GitHub release with a fresh WinRust.exe.# release.ps1 v0.2.0 [-Notes "text"]-# Rebuilds everything (build-all.ps1, ends with the stamp check), pushes pending changes, tags, uploads the exe.+# Rebuilds everything (build-all.ps1), pushes pending changes, tags, uploads the exe.param([Parameter(Mandatory)][string]$Version, [string]$Notes)$ErrorActionPreference = 'Stop'$root = Split-Path $PSScriptRootdiff --git a/scripts/sync.ps1 b/scripts/sync.ps1deleted file mode 100644index 0233d1f..0000000--- a/scripts/sync.ps1+++ /dev/null@@ -1,37 +0,0 @@-# Keeps plugins\<name> identical to the original project folder and stamps what the payload exes were built from.-# sync.ps1 copy originals -> plugins\ (originals win), then report-# sync.ps1 -Check only report; exit 1 on any mismatch-# A stamp = short SHA-256 over every source file (path + content), target\ and .git\ excluded.-# sync.ps1 -Stamp (used by build-all.ps1) record what the payload exes were just built from-param([switch]$Check, [switch]$Stamp)-$ErrorActionPreference = 'Stop'-$root = Split-Path $PSScriptRoot-$desk = Split-Path $root-$orig = @{ 'rust-search' = "$desk\rust-search"; 'rtaskmgr-win32' = "$desk\rtaskmgr-win32" }-$stampFile = "$root\payload\STAMPS.txt"--function Stamp($dir) {- $parts = Get-ChildItem $dir -Recurse -File | Where-Object { $_.FullName -notmatch '\\(target|dist|backup-v1|\.git)\\' } | Sort-Object FullName |- ForEach-Object { $_.FullName.Substring($dir.Length) + ':' + (Get-FileHash $_.FullName -Algorithm SHA256).Hash }- $sha = [Security.Cryptography.SHA256]::Create()- -join ($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($parts -join "`n")) | Select-Object -First 6 | ForEach-Object { $_.ToString('x2') })-}-function Built($name) {- if (Test-Path $stampFile) { foreach ($l in Get-Content $stampFile) { $n, $s = $l -split ' '; if ($n -eq $name) { return $s } } }- '-'-}--if (-not $Check) {- foreach ($n in $orig.Keys) {- robocopy $orig[$n] "$root\plugins\$n" /MIR /XD target dist backup-v1 .git /NFL /NDL /NJH /NJS /NP | Out-Null- if ($LASTEXITCODE -ge 8) { throw "robocopy failed for $n ($LASTEXITCODE)" }- }-}-if ($Stamp) { ($orig.Keys | ForEach-Object { "$_ $(Stamp "$root\plugins\$_")" }) | Set-Content $stampFile }-$bad = 0-foreach ($n in $orig.Keys) {- $o = Stamp $orig[$n]; $c = Stamp "$root\plugins\$n"; $b = Built $n- $state = if ($o -ne $c) { $bad++; 'COPY STALE: run scripts\sync.ps1' } elseif ($c -ne $b) { $bad++; 'PAYLOAD STALE: run scripts\build-all.ps1' } else { 'ok' }- '{0,-15} original {1} plugins\ {2} payload built from {3} {4}' -f $n, $o, $c, $b, $state-}-if ($Check -and $bad) { exit 1 }diff --git a/scripts/update-plugin.ps1 b/scripts/update-plugin.ps1index d9a95a5..e3be7f8 100644--- a/scripts/update-plugin.ps1+++ b/scripts/update-plugin.ps1@@ -1,38 +1,11 @@-# Rebuilds ONE plugin (and what ships with it), copies the exes to payload\ and runs `plugin-launcher update`: no launcher rebuild.-# scripts\update-plugin.ps1 rust-search|rtaskmgr-win32|topbar|rust-explorer+# Rebuilds the plugins (cargo only recompiles what changed), refreshes payload\ and runs `plugin-launcher update`: no launcher rebuild.+# scripts\update-plugin.ps1 rust-search|rtaskmgr-win32|topbar|rust-explorer|wiztree|photoview|debloat# Build + copy need no admin. The update step does: from a normal shell this script asks for it via a UAC prompt (the user clicks Yes),# then prints the last lines of %ProgramData%\plugin-launcher\install.log (the elevated window's own output is lost).param([Parameter(Mandatory)][ValidateSet('rust-search', 'rtaskmgr-win32', 'topbar', 'rust-explorer', 'wiztree', 'photoview', 'debloat')][string]$name)$ErrorActionPreference = 'Stop'$root = Split-Path $PSScriptRoot-function Build($dir) { Push-Location $dir; cargo build --release; if ($LASTEXITCODE) { throw "build failed: $dir" }; Pop-Location }-$p = "$root\payload"-if ($name -in 'rust-search', 'rtaskmgr-win32') { & "$PSScriptRoot\sync.ps1" | Out-Null } # these two are edited in their original folders on the desktop-switch ($name) {- 'rust-search' {- Build "$root\plugins\rust-search"; $r = "$root\plugins\rust-search\target\release"- Copy-Item "$r\rs.exe", "$r\rs-launcher.exe" $p -Force- }- 'rtaskmgr-win32' {- Build "$root\plugins\rtaskmgr-win32"; Build "$root\plugins\rs-du"- Copy-Item "$root\plugins\rtaskmgr-win32\target\release\rtaskmgr-win32.exe" "$p\Task manager.exe" -Force- Copy-Item "$root\plugins\rs-du\target\release\rs-du.exe" $p -Force- }- 'topbar' { # reshell and rs-du are installed together with topbar- Build "$root\plugins\topbar"; Build "$root\plugins\rs-du"; Build "$root\ReShell"- Copy-Item "$root\plugins\topbar\target\release\topbar.exe" $p -Force- Copy-Item "$root\plugins\rs-du\target\release\rs-du.exe" $p -Force- Copy-Item "$root\ReShell\target\release\reshell.exe" $p -Force- }- { $_ -in 'wiztree', 'photoview', 'debloat' } { # stand-alone: one exe each (wiztree reads the MFT through rs-du\src\mft.rs)- Build "$root\plugins\$name"- Copy-Item "$root\plugins\$name\target\release\$name.exe" $p -Force- }- 'rust-explorer' { # rs-shell --overlay starts topbar and the desktop at logon- Build "$root\plugins\rust-explorer"; Build "$root\plugins\rs-shell"- Copy-Item "$root\plugins\rust-explorer\target\release\rust-explorer.exe", "$root\plugins\rs-shell\target\release\rs-shell.exe" $p -Force- }-}+& "$PSScriptRoot\build-plugins.ps1" # rebuilds what changed (and what ships with the plugin), refreshes payload\$exe = "$root\target\release\plugin-launcher.exe"if (-not (Test-Path $exe)) { throw "build the launcher once first: cargo build --release in $root" }# Started through explorer.exe, never as our child: from a packaged app (the Claude desktop app is MSIX) every child process,diff --git a/scripts/user-mode.ps1 b/scripts/user-mode.ps1index 0391311..0a8855c 100644--- a/scripts/user-mode.ps1+++ b/scripts/user-mode.ps1@@ -25,12 +25,12 @@ if ($Undo) {}$src = @{- 'rs-shell.exe' = "$root\plugins\rs-shell\target\release\rs-shell.exe"- 'rust-explorer.exe' = "$root\plugins\rust-explorer\target\release\rust-explorer.exe"- 'topbar.exe' = "$root\plugins\topbar\target\release\topbar.exe"- 'reshell.exe' = "$root\ReShell\target\release\reshell.exe"+ 'rs-shell.exe' = "$root\target\release\rs-shell.exe"+ 'rust-explorer.exe' = "$root\target\release\rust-explorer.exe"+ 'topbar.exe' = "$root\target\release\topbar.exe"+ 'reshell.exe' = "$root\target\release\reshell.exe"}-foreach ($k in $src.Keys) { if (-not (Test-Path $src[$k])) { throw "missing $($src[$k]): build it first (cargo build --release in that folder)" } }+foreach ($k in $src.Keys) { if (-not (Test-Path $src[$k])) { throw "missing $($src[$k]): build it first (scripts\build-plugins.ps1)" } }New-Item -ItemType Directory $bin -Force | Out-Nullforeach ($k in $src.Keys) {$to = "$bin\$k"diff --git a/src/cli.rs b/src/cli.rsnew file mode 100644index 0000000..990d233--- /dev/null+++ b/src/cli.rs@@ -0,0 +1,61 @@+//! Command line: list / install / update / uninstall / rollback (see README).+use crate::*;++// ---------- command line ----------+//+// plugin-launcher list+// plugin-launcher install <plugin> --yes (without --yes it only prints the warning: nothing is changed)+// plugin-launcher uninstall <plugin>+// plugin-launcher rollback --yes+// Exit code 0 = done, 1 = failed, 2 = bad arguments or --yes missing. Run it from an elevated terminal: the manifest+// demands admin, and from a normal one Windows opens a separate elevated console whose output is lost.++pub(crate) fn cli(args: &[String]) -> i32 {+ // A windows-subsystem exe has no console of its own: use stdout if the caller redirected it (pipe, file),+ // else attach to the parent's console and write to it directly.+ let redirected = unsafe { !GetStdHandle(STD_OUTPUT_HANDLE).is_null() && GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE };+ let mut out: Box<dyn Write> = if redirected {+ Box::new(std::io::stdout())+ } else {+ unsafe { AttachConsole(ATTACH_PARENT_PROCESS) };+ fs::OpenOptions::new().write(true).open("CONOUT$").map_or_else(|_| Box::new(std::io::sink()) as Box<dyn Write>, |f| Box::new(f))+ };+ let mut say = |s: &str| {+ let _ = writeln!(out, "{s}");+ };+ let yes = args.iter().any(|a| a == "--yes");+ let words: Vec<&str> = args.iter().map(String::as_str).filter(|a| *a != "--yes").collect();+ let find = |n: &str| PLUGINS.iter().position(|p| p.name == n);+ let usage = "usage: plugin-launcher list | install <plugin> --yes | update <plugin> | uninstall <plugin> | rollback --yes";+ let result = match words.as_slice() {+ ["list"] => {+ for p in PLUGINS {+ say(&format!("{:<16}{}", p.name, if p.actions.is_none() { "stub" } else if (p.installed)() { "installed" } else { "not installed" }));+ }+ return 0;+ }+ ["install", n] => match find(n) {+ None => return { say(&format!("unknown plugin: {n}")); 2 },+ Some(i) if !yes => return { say(&format!("{}\nNothing changed. Repeat with --yes to install {n}.", PLUGINS[i].warn.get())); 2 },+ Some(i) if (PLUGINS[i].installed)() => return { say(&format!("{n} is already installed")); 0 },+ Some(i) => install_plugin(i),+ },+ ["update", n] => match find(n) {+ None => return { say(&format!("unknown plugin: {n}")); 2 },+ Some(i) if !(PLUGINS[i].installed)() => return { say(&format!("{n} is not installed (use install)")); 2 },+ Some(i) => install_plugin(i),+ },+ ["uninstall", n] => match find(n) {+ None => return { say(&format!("unknown plugin: {n}")); 2 },+ Some(i) if !(PLUGINS[i].installed)() => return { say(&format!("{n} is not installed")); 0 },+ Some(i) => uninstall_plugin(i),+ },+ ["rollback"] if yes => rollback(),+ ["rollback"] => return { say("Removes every installed plugin. Repeat with --yes."); 2 },+ _ => return { say(usage); 2 },+ };+ match result {+ Ok(m) => { say(&m); 0 }+ Err(e) => { say(&format!("error: {e}")); 1 }+ }+}diff --git a/src/i18n.rs b/src/i18n.rsdeleted file mode 100644index 707cc46..0000000--- a/src/i18n.rs+++ /dev/null@@ -1,62 +0,0 @@-// Language switch shared by every WinRust program (an identical copy of this file lives in each crate).-// English by default; Russian when %ProgramData%\WinRust\lang.txt contains "ru" (the installer's EN/RU button writes it).-// Programs read the file once at start; the one that flips the switch updates its own texts at once.-use std::{- path::PathBuf,- sync::atomic::{AtomicU8, Ordering::Relaxed},-};--static LANG: AtomicU8 = AtomicU8::new(0); // 0 = not read yet, 1 = English, 2 = Russian--fn file() -> Option<PathBuf> {- std::env::var_os("ProgramData").map(|p| PathBuf::from(p).join("WinRust").join("lang.txt"))-}--#[allow(dead_code)]-pub fn english() -> bool {- match LANG.load(Relaxed) {- 1 => true,- 2 => false,- _ => {- // unit tests keep their Russian expectations- let ru = cfg!(test) || file().and_then(|f| std::fs::read_to_string(f).ok()).is_some_and(|s| s.trim().eq_ignore_ascii_case("ru"));- LANG.store(if ru { 2 } else { 1 }, Relaxed);- !ru- }- }-}--/// Switches this process and writes the choice for the other programs (they pick it up when they start).-#[allow(dead_code)]-pub fn set_english(en: bool) {- LANG.store(if en { 1 } else { 2 }, Relaxed);- if let Some(f) = file() {- let _ = std::fs::create_dir_all(f.parent().unwrap());- let _ = std::fs::write(f, if en { "en" } else { "ru" });- }-}--/// `t!("русский", "english")`: a text in the current language.-#[allow(unused_macros)]-macro_rules! t {- ($ru:expr, $en:expr) => {- if $crate::i18n::english() { $en } else { $ru }- };-}--/// `tf!("русский {}", "english {}", args...)`: format! in the current language (both templates are checked at compile time).-#[allow(unused_macros)]-macro_rules! tf {- ($ru:literal, $en:literal $(, $a:expr)* $(,)?) => {- if $crate::i18n::english() { format!($en $(, $a)*) } else { format!($ru $(, $a)*) }- };-}--#[cfg(test)]-mod tests {- #[test]- fn tests_run_in_russian() {- assert_eq!(t!("да", "yes"), "да");- assert_eq!(tf!("{} шт", "{} pcs", 3), "3 шт");- }-}diff --git a/src/install/explorer.rs b/src/install/explorer.rsnew file mode 100644index 0000000..9d083f4--- /dev/null+++ b/src/install/explorer.rs@@ -0,0 +1,108 @@+//! rust-explorer: the file manager that replaces Explorer as folder handler and (with rs-shell) as the shell.+use crate::*;++pub(crate) fn rx_dir() -> PathBuf {+ program_files().join("rust-explorer")+}++// ---------- rust-explorer: file manager + Explorer replacement ----------+//+// Install: our files in Program Files, folders / drives opened from any program go to rust-explorer (HKCU class verbs of the+// installing user), rs-shell --overlay starts at sign-in and, with the ReplaceExplorer switch, ends the shell Explorer once topbar+// and the rust-explorer desktop are on screen. AutoRestartShell is set to 0 so Windows does not bring Explorer back.+// Uninstall puts everything back and starts Explorer again. rs-shell itself hands the session back to Explorer if topbar dies.+pub(crate) const RX_STATE: &str = r"HKLM\SOFTWARE\plugin-launcher\rust-explorer";+pub(crate) const WINLOGON_KEY: &str = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon";+pub(crate) const RX_SWITCH: &str = r"HKCU\Software\rs-shell";+pub(crate) const RX_FOLDERS: [&str; 3] = [r"HKCU\Software\Classes\Directory\shell\open", r"HKCU\Software\Classes\Folder\shell\open", r"HKCU\Software\Classes\Drive\shell\open"];++// svchost RAM trim, done with rust-explorer: (service, Start we set, Windows default). Uninstall puts back the Windows defaults,+// not the values found at install: they may already be our own (the same tweak was first run by hand).+// DoSvc's key is ACL-protected on some builds, so every step is soft: a refused one is only a warning.+pub(crate) const RX_SVCS: [(&str, u32, u32); 6] = [("DiagTrack", 4, 2), ("PcaSvc", 4, 2), ("InventorySvc", 4, 2), ("lfsvc", 4, 3), ("cbdhsvc", 4, 2), ("DoSvc", 3, 2)];+pub(crate) const SPLIT_KEY: &str = r"HKLM\SYSTEM\CurrentControlSet\Control";+pub(crate) const SPLIT_DEFAULT: u32 = 3670016; // 3.5 GB: above it Windows gives every service its own svchost++pub(crate) fn rx_trim(on: bool) {+ for (s, off, def) in RX_SVCS {+ let v = if on { off } else { def };+ soft(&tf!("служба {s}", "service {s}"), run("reg", &["add", &format!(r"HKLM\SYSTEM\CurrentControlSet\Services\{s}"), "/v", "Start", "/t", "REG_DWORD", "/d", &v.to_string(), "/f"]));+ if on && off == 4 {+ let _ = run("sc.exe", &["stop", s]); // the per-user cbdhsvc_xxxx instance stops at the next sign-in+ }+ }+ let t = if on { 0x4000000 } else { SPLIT_DEFAULT };+ soft("SvcHostSplitThresholdInKB", run("reg", &["add", SPLIT_KEY, "/v", "SvcHostSplitThresholdInKB", "/t", "REG_DWORD", "/d", &t.to_string(), "/f"]));+}++pub(crate) fn rx_lnk() -> PathBuf {+ PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join(r"plugin-launcher\rs-overlay.lnk")+}++pub(crate) fn rx_install() -> Result<(), String> {+ if !bar_dir().join("topbar.exe").is_file() {+ return Err(t!("сначала установите topbar: без него после отключения Explorer не будет панели", "install topbar first: without it there will be no bar after Explorer is disabled").into());+ }+ with_payload(&["rust-explorer.exe", "rs-shell.exe"], |d| {+ for n in ["rs-shell.exe", "rust-explorer.exe"] {+ let _ = run("taskkill", &["/f", "/im", n]); // an update: a running exe cannot be overwritten+ }+ fs::create_dir_all(rx_dir()).map_err(|e| e.to_string())?;+ let (fm, sh) = (rx_dir().join("rust-explorer.exe"), rx_dir().join("rs-shell.exe"));+ put(&d.join("rust-explorer.exe"), &fm)?;+ put(&d.join("rs-shell.exe"), &sh)?;+ // what Windows had, saved once (an update must not overwrite it with our own 0)+ if reg_dword(RX_STATE, "AutoRestartShell").is_none() {+ let v = reg_dword(WINLOGON_KEY, "AutoRestartShell").unwrap_or(1);+ run("reg", &["add", RX_STATE, "/v", "AutoRestartShell", "/t", "REG_DWORD", "/d", &v.to_string(), "/f"])?;+ }+ // folders and drives opened by other programs, the desktop, Win+R: rust-explorer. DelegateExecute is emptied on purpose:+ // while it is set, Windows ignores the command and uses Explorer's built-in handler.+ for k in RX_FOLDERS {+ let c = format!(r"{k}\command");+ run("reg", &["add", &c, "/ve", "/t", "REG_SZ", "/d", &format!("\"{}\" \"%1\"", fm.display()), "/f"])?;+ run("reg", &["add", &c, "/v", "DelegateExecute", "/t", "REG_SZ", "/d", "", "/f"])?;+ }+ // A logon task starts the overlay right at sign-in; Explorer runs the Run key only after its own startup delay (~20 s of+ // plain Windows on screen). Limited run level: the shell side must never run elevated. Fallback: the Run key.+ let task = format!("$u=[Security.Principal.WindowsIdentity]::GetCurrent().Name; Register-ScheduledTask -TaskName rs-overlay -Force -Action (New-ScheduledTaskAction -Execute '{}' -Argument '--overlay') -Trigger (New-ScheduledTaskTrigger -AtLogOn -User $u) -Principal (New-ScheduledTaskPrincipal -UserId $u -LogonType Interactive -RunLevel Limited) -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)) | Out-Null", sh.display());+ if run("powershell", &["-NoProfile", "-Command", &task]).is_ok() {+ let _ = run("reg", &["delete", RUN_KEY, "/v", "rs-overlay", "/f"]);+ } else {+ WARN.lock().unwrap().push(t!("задача rs-overlay не создана: запуск через Run, с задержкой Windows", "rs-overlay task was not created: it starts via Run, with a Windows startup delay").into());+ run("reg", &["add", RUN_KEY, "/v", "rs-overlay", "/t", "REG_SZ", "/d", &format!("\"{}\" --overlay", sh.display()), "/f"])?;+ }+ run("reg", &["add", RX_SWITCH, "/v", "ReplaceExplorer", "/t", "REG_DWORD", "/d", "1", "/f"])?;+ run("reg", &["add", WINLOGON_KEY, "/v", "AutoRestartShell", "/t", "REG_DWORD", "/d", "0", "/f"])?;+ rx_trim(true);+ // Start it now, with the user's normal token: explorer.exe opens a shortcut unelevated, and the shortcut carries --overlay.+ let lnk = rx_lnk();+ let _ = fs::create_dir_all(lnk.parent().unwrap());+ soft(t!("overlay не запущен сейчас: он стартует при следующем входе", "overlay is not running now: it starts at the next logon"), run("powershell", &["-NoProfile", "-Command", &format!("$s=(New-Object -ComObject WScript.Shell).CreateShortcut('{}'); $s.TargetPath='{}'; $s.Arguments='--overlay'; $s.Save()", lnk.display(), sh.display())]));+ let _ = Command::new("explorer.exe").arg(&lnk).spawn();+ Ok(())+ })+}++pub(crate) fn rx_uninstall() -> Result<(), String> {+ // Windows may restart its shell again; our hooks off; then the shell back, unelevated, only if none is running+ let back = reg_dword(RX_STATE, "AutoRestartShell").unwrap_or(1);+ let r = run("reg", &["add", WINLOGON_KEY, "/v", "AutoRestartShell", "/t", "REG_DWORD", "/d", &back.to_string(), "/f"]);+ let _ = run("reg", &["delete", RUN_KEY, "/v", "rs-overlay", "/f"]);+ let _ = run("schtasks", &["/delete", "/tn", "rs-overlay", "/f"]);+ let _ = run("reg", &["delete", RX_SWITCH, "/f"]);+ rx_trim(false);+ for k in RX_FOLDERS {+ let _ = run("reg", &["delete", k, "/f"]); // only our HKCU override; the system's verbs under HKLM stay+ }+ for n in ["rs-shell.exe", "rust-explorer.exe"] {+ let _ = run("taskkill", &["/f", "/im", n]);+ }+ let _ = run("powershell", &["-NoProfile", "-Command", r#"if (-not (Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object { $_.CommandLine -match '(?i)explorer\.exe"?\s*$' })) { runas /trustlevel:0x20000 C:\Windows\explorer.exe }"#]);+ let _ = fs::remove_file(rx_lnk());+ let _ = fs::remove_dir_all(rx_dir());+ if r.is_ok() {+ let _ = run("reg", &["delete", RX_STATE, "/f"]);+ }+ r+}diff --git a/src/install/mod.rs b/src/install/mod.rsnew file mode 100644index 0000000..420e075--- /dev/null+++ b/src/install/mod.rs@@ -0,0 +1,135 @@+//! Install logic, shared by the window and the command line so both do exactly the same thing:+//! process/registry helpers, the embedded payload, and one file per plugin with its install/uninstall pair.+use crate::*;+mod explorer;+mod search;+mod taskmgr;+mod tools;+mod topbar;+pub(crate) use {explorer::*, search::*, taskmgr::*, tools::*, topbar::*};++pub(crate) fn out(prog: &str, args: &[&str]) -> Result<String, String> {+ let o = Command::new(prog).args(args).creation_flags(0x0800_0000).output().map_err(|e| format!("{prog}: {e}"))?;+ if o.status.success() {+ Ok(String::from_utf8_lossy(&o.stdout).into_owned())+ } else {+ Err(format!("{prog} {}: {}{}", args.join(" "), String::from_utf8_lossy(&o.stdout).trim(), String::from_utf8_lossy(&o.stderr).trim()))+ }+}++pub(crate) fn run(prog: &str, args: &[&str]) -> Result<(), String> {+ out(prog, args).map(|_| ())+}++// Non-fatal failures of one install: shown as a count in the status line, spelled out in install.log.+pub(crate) static WARN: Mutex<Vec<String>> = Mutex::new(Vec::new());++pub(crate) fn soft(what: &str, r: Result<(), String>) {+ if let Err(e) = r {+ WARN.lock().unwrap().push(format!("{what}: {e}"));+ }+}++pub(crate) fn log(s: &str) {+ let d = PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join("plugin-launcher");+ let _ = fs::create_dir_all(&d);+ if let Ok(mut f) = fs::OpenOptions::new().create(true).append(true).open(d.join("install.log")) {+ let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());+ let _ = writeln!(f, "[{t}] {s}"); // shortcut: unix seconds, no date formatting; upgrade if the log gets read by humans a lot+ }+}++/// Copies over an exe that was just killed: taskkill returns before Windows (or an antivirus scan) releases the file, so retry ~6 s.+pub(crate) fn put(src: &Path, dst: &Path) -> Result<(), String> {+ let mut r = fs::copy(src, dst).map(|_| ());+ for _ in 0..30 {+ if !matches!(&r, Err(e) if e.raw_os_error() == Some(32) || e.raw_os_error() == Some(5)) {+ break;+ }+ thread::sleep(std::time::Duration::from_millis(200));+ r = fs::copy(src, dst).map(|_| ());+ }+ r.map_err(|e| format!("{}: {e}", dst.display()))+}++pub(crate) fn reg_dword(key: &str, name: &str) -> Option<u32> {+ let o = out("reg", &["query", key, "/v", name]).ok()?;+ let t = o.lines().find(|l| l.contains("REG_DWORD"))?.split_whitespace().last()?;+ u32::from_str_radix(t.trim_start_matches("0x"), 16).ok()+}++include!(concat!(env!("OUT_DIR"), "/payload.rs")); // PAYLOAD: the exes listed in payload.txt, embedded by build.rs++/// Update without rebuilding the launcher: an exe in `payload\` next to this one (or two levels up, the cargo+/// target\release layout) wins over the embedded copy. Trust level = the launcher exe's own folder.+pub(crate) fn disk_payload() -> Option<PathBuf> {+ let exe = env::current_exe().ok()?;+ let d = exe.parent()?;+ [d.join("payload"), d.join(r"..\..\payload")].into_iter().find(|p| p.is_dir())+}++/// Unpacks the `need`ed bundled plugins, runs `f` on them, deletes them. The folder is under Program Files (admin-only writable),+/// not %TEMP%: a user-level process must not be able to swap an exe that is about to be installed as a SYSTEM task.+pub(crate) fn with_payload<T>(need: &[&str], f: impl FnOnce(&Path) -> Result<T, String>) -> Result<T, String> {+ let d = program_files().join(format!("plugin-launcher-tmp-{}", std::process::id()));+ fs::create_dir_all(&d).map_err(|e| format!("{}: {e}", d.display()))?;+ let disk = disk_payload();+ let unpack = |n: &&str| -> Result<(), String> {+ let bytes = PAYLOAD.iter().find(|(m, _)| m == n).ok_or(tf!("нет {n} в сборке", "{n} is missing from the build"))?.1;+ match disk.as_ref().map(|p| p.join(n)).filter(|p| p.is_file()) {+ Some(src) => {+ log(&tf!("{n}: из {}", "{n}: from {}", src.display()));+ fs::copy(src, d.join(n)).map(|_| ())+ }+ None => fs::write(d.join(n), bytes),+ }+ .map_err(|e| tf!("распаковка {n}: {e}", "unpacking {n}: {e}"))+ };+ let r = need.iter().try_for_each(unpack).and_then(|_| f(&d));+ let _ = fs::remove_dir_all(&d);+ r+}++pub(crate) fn program_files() -> PathBuf {+ PathBuf::from(env::var("ProgramFiles").unwrap_or(r"C:\Program Files".into()))+}++// shortcut: Windows makes at most one restore point per 24 h and it needs System Protection on; failures are ignored.+pub(crate) fn checkpoint() -> Result<(), String> {+ run("powershell", &["-NoProfile", "-Command", "Checkpoint-Computer -Description 'Plugin Launcher' -RestorePointType MODIFY_SETTINGS"])+}++// Shared by the window and the command line, so both do exactly the same thing.+pub(crate) fn install_plugin(i: usize) -> Result<String, String> {+ let p = &PLUGINS[i];+ let (inst, uninst) = p.actions.ok_or(t!("установка недоступна", "installation is not available"))?;+ let was = (p.installed)(); // already installed = an update: a failure must not remove the working copy+ WARN.lock().unwrap().clear();+ soft(t!("точка восстановления не создана", "restore point was not created"), checkpoint());+ if let Err(e) = inst() {+ log(&tf!("{}: ОШИБКА {e}", "{}: ERROR {e}", p.name));+ if was {+ return Err(e);+ }+ let back = uninst().err().map_or(String::new(), |u| tf!("; откат: {u}", "; rollback: {u}"));+ return Err(tf!("{e} (установка отменена, изменения возвращены{back})", "{e} (installation cancelled, changes reverted{back})"));+ }+ let w = WARN.lock().unwrap().clone();+ log(&format!("{}: {} {}", p.name, if was { t!("обновлён", "updated") } else { t!("установлен", "installed") }, w.join(" | ")));+ let note = if w.is_empty() { String::new() } else { tf!(" Предупреждений: {} (см. %ProgramData%\\plugin-launcher\\install.log).", " Warnings: {} (see %ProgramData%\\plugin-launcher\\install.log).", w.len()) };+ Ok(format!("{} {}.{note}", p.name, if was { t!("обновлён", "updated") } else { t!("установлен", "installed") }))+}++pub(crate) fn uninstall_plugin(i: usize) -> Result<String, String> {+ let p = &PLUGINS[i];+ let (_, uninst) = p.actions.ok_or(t!("удаление недоступно", "uninstall is not available"))?;+ uninst().inspect_err(|e| log(&tf!("{}: ОШИБКА удаления {e}", "{}: uninstall ERROR {e}", p.name)))?;+ log(&tf!("{}: удалён", "{}: removed", p.name));+ Ok(tf!("{} удалён, система восстановлена.", "{} removed, system restored.", p.name))+}++pub(crate) fn rollback() -> Result<String, String> {+ // reverse install order: rust-explorer (which switched Explorer off) goes before topbar, else the session is left with no panel and no shell+ let errs: Vec<String> = PLUGINS.iter().rev().filter(|p| (p.installed)()).filter_map(|p| p.actions.and_then(|a| a.1().err().map(|e| format!("{}: {e}", p.name)))).collect();+ if errs.is_empty() { Ok(t!("Все плагины удалены, система восстановлена.", "All plugins removed, system restored.").into()) } else { Err(errs.join("; ")) }+}diff --git a/src/profile.ps1 b/src/install/profile.ps1similarity index 100%rename from src/profile.ps1rename to src/install/profile.ps1diff --git a/src/install/search.rs b/src/install/search.rsnew file mode 100644index 0000000..203efe7--- /dev/null+++ b/src/install/search.rs@@ -0,0 +1,74 @@+//! 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.+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"])+}++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"));+ with_payload(&["rs.exe", "rs-launcher.exe"], |src| {+ run(src.join("rs.exe").to_str().unwrap(), &["--install"])?; // copies itself to Program Files, registers boot tasks+ let dst = prog_dir().join("rs-launcher.exe"); // must live somewhere stable: --autostart registers its own path+ let _ = run("taskkill", &["/f", "/im", "rs-launcher.exe"]);+ put(&src.join("rs-launcher.exe"), &dst)?;+ run(dst.to_str().unwrap(), &["--autostart"])?;+ // via explorer: it starts the launcher with the desktop user's normal token. Started from here it would+ // inherit admin rights, and every file opened from search would run elevated too.+ let _ = Command::new("explorer.exe").arg(&dst).spawn();+ run("sc.exe", &["config", "WSearch", "start=", "disabled"])?;+ let _ = run("sc.exe", &["stop", "WSearch"]);+ // 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"])?;+ let _ = run("taskkill", &["/f", "/im", "SearchHost.exe"]);+ taskbar_search(0) // hide the taskbar search box+ })+}++pub(crate) fn uninstall() -> Result<(), String> {+ with_payload(&["rs.exe"], |src| {+ let _ = run("taskkill", &["/f", "/im", "rs-launcher.exe"]);+ let _ = run("reg", &["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "rs-launcher", "/f"]);+ // run the unpacked copy: an exe cannot delete itself, so the installed one would leave its folder behind+ run(src.join("rs.exe").to_str().unwrap(), &["--uninstall"])?;+ let _ = fs::remove_dir_all(prog_dir());+ 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",+ };+ run("sc.exe", &["config", "WSearch", "start=", mode])?;+ if mode.ends_with("auto") {+ let _ = run("sc.exe", &["start", "WSearch"]);+ }+ let r = taskbar_search(reg_dword(STATE, "SearchboxMode").unwrap_or(2));+ if r.is_ok() {+ let _ = run("reg", &["delete", STATE, "/f"]);+ }+ r+ })+}diff --git a/src/install/taskmgr.rs b/src/install/taskmgr.rsnew file mode 100644index 0000000..164e9a6--- /dev/null+++ b/src/install/taskmgr.rs@@ -0,0 +1,50 @@+//! rtaskmgr-win32: replaces Task Manager through an IFEO Debugger; ships rs-du (disk cleaner) next to it.+use crate::*;++pub(crate) const TM_KEY: &str = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe";++pub(crate) fn tm_dir() -> PathBuf {+ program_files().join("rtaskmgr")+}++// Image File Execution Options "Debugger": Windows starts our exe instead of taskmgr.exe (the system file stays untouched, so this is fully reversible).+pub(crate) fn tm_install() -> Result<(), String> {+ with_payload(&["Task manager.exe", "rs-du.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 overwritten+ fs::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"))?;+ // the search (and the bar's Start panel) lists Start Menu shortcuts only, so without one the task manager is invisible to them+ soft(t!("ярлык в меню Пуск не создан, поиск не увидит диспетчер", "Start menu shortcut was not created, search will not find the task manager"), run("powershell", &["-NoProfile", "-Command", &format!("$s=(New-Object -ComObject WScript.Shell).CreateShortcut('{}'); $s.TargetPath='{}'; $s.Save()", tm_lnk().display(), dst.display())]));+ // elevated start without a UAC prompt (the exe re-launches itself through this task), so it can end protected processes+ let task = format!("$u=[Security.Principal.WindowsIdentity]::GetCurrent().Name; Register-ScheduledTask -TaskName rtaskmgr -Force -Action (New-ScheduledTaskAction -Execute '{}') -Principal (New-ScheduledTaskPrincipal -UserId $u -LogonType Interactive -RunLevel Highest) -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances Parallel) | Out-Null", dst.display());+ soft(t!("задача rtaskmgr не создана, запуск от администратора будет через UAC", "rtaskmgr task was not created, launching as administrator will go through UAC"), run("powershell", &["-NoProfile", "-Command", &task]));+ run("reg", &["add", TM_KEY, "/v", "Debugger", "/t", "REG_SZ", "/d", &format!("\"{}\"", dst.display()), "/f"])+ })+}++pub(crate) fn tm_lnk() -> PathBuf {+ PathBuf::from(std::env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join(r"Microsoft\Windows\Start Menu\Programs\Task manager.lnk")+}++pub(crate) fn tm_uninstall() -> Result<(), String> {+ let _ = fs::remove_file(tm_lnk());+ 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+ // other IFEO settings (e.g. mitigation policies) that are not ours to remove.+ run("reg", &["delete", TM_KEY, "/v", "Debugger", "/f"])?;+ let _ = run("taskkill", &["/f", "/im", "rtaskmgr-win32.exe"]);+ let _ = fs::remove_file(tm_dir().join("rtaskmgr-win32.exe"));+ cleaner_release(bar_dir().join("topbar.exe").is_file());+ Ok(())+}++/// rs-du (disk cleaner) lives in the task manager folder and is shared by rtaskmgr-win32 and the topbar menu:+/// it goes away only when the other plugin is gone too.+pub(crate) fn cleaner_release(other_installed: bool) {+ if !other_installed {+ let _ = fs::remove_file(tm_dir().join("rs-du.exe"));+ }+ let _ = fs::remove_dir(tm_dir()); // only succeeds when empty+}diff --git a/src/install/tools.rs b/src/install/tools.rsnew file mode 100644index 0000000..5308d57--- /dev/null+++ b/src/install/tools.rs@@ -0,0 +1,105 @@+//! wiztree, photoview, debloat: small stand-alone tools, one exe each in its own Program Files folder.+use crate::*;++// ---------- wiztree, photoview, debloat: small stand-alone tools, one exe each in its own Program Files folder ----------++pub(crate) fn wz_dir() -> PathBuf {+ program_files().join("wiztree")+}++pub(crate) fn pv_dir() -> PathBuf {+ program_files().join("photoview")+}++pub(crate) fn db_dir() -> PathBuf {+ program_files().join("debloat")+}++/// Start Menu shortcut: search and the bar's Start panel list Start Menu shortcuts only.+pub(crate) fn start_lnk(name: &str) -> PathBuf {+ PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join(format!(r"Microsoft\Windows\Start Menu\Programs\{name}.lnk"))+}++/// Copies `exe` out of the payload into `dir` (an update: the running copy is killed first) and adds the Start Menu shortcut `lnk`.+pub(crate) fn tool_install(exe: &str, dir: &Path, lnk: Option<&str>) -> Result<(), String> {+ with_payload(&[exe], |d| {+ let _ = run("taskkill", &["/f", "/im", exe]);+ fs::create_dir_all(dir).map_err(|e| e.to_string())?;+ let dst = dir.join(exe);+ put(&d.join(exe), &dst)?;+ if let Some(n) = lnk {+ soft(&tf!("ярлык «{n}» в меню Пуск не создан, поиск его не увидит", "Start menu shortcut '{n}' was not created, search will not find it"), run("powershell", &["-NoProfile", "-Command", &format!("$s=(New-Object -ComObject WScript.Shell).CreateShortcut('{}'); $s.TargetPath='{}'; $s.Save()", start_lnk(n).display(), dst.display())]));+ }+ Ok(())+ })+}++pub(crate) fn tool_remove(exe: &str, dir: &Path, lnk: Option<&str>) {+ if let Some(n) = lnk {+ let _ = fs::remove_file(start_lnk(n));+ }+ let _ = run("taskkill", &["/f", "/im", exe]);+ let _ = fs::remove_dir_all(dir);+}++pub(crate) fn wz_install() -> Result<(), String> {+ tool_install("wiztree.exe", &wz_dir(), Some("WinRust Disk"))+}++pub(crate) fn wz_uninstall() -> Result<(), String> {+ tool_remove("wiztree.exe", &wz_dir(), Some("WinRust Disk"));+ Ok(())+}++pub(crate) const PV_EXTS: [&str; 11] = ["jpg", "jpeg", "jfif", "png", "bmp", "gif", "tif", "tiff", "webp", "heic", "avif"]; // keep in step with photoview's EXTS+pub(crate) const PV_PROG: &str = "WinRustPhoto";+pub(crate) const PV_APP: &str = "WinRust Photo Viewer";++/// "Open with" entry and a Default apps entry; the default itself stays the user's choice (Windows does not allow setting it from code).+pub(crate) fn pv_install() -> Result<(), String> {+ tool_install("photoview.exe", &pv_dir(), Some("Photo viewer"))?;+ let exe = pv_dir().join("photoview.exe").display().to_string().replace('\\', r"\\");+ let mut reg = format!(+ "Windows Registry Editor Version 5.00\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\{PV_PROG}]\r\n@=\"Picture\"\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\{PV_PROG}\\shell\\open\\command]\r\n@=\"\\\"{exe}\\\" \\\"%1\\\"\"\r\n\r\n\+ [HKEY_LOCAL_MACHINE\\SOFTWARE\\WinRust\\PhotoView\\Capabilities]\r\n\"ApplicationName\"=\"{PV_APP}\"\r\n\"ApplicationDescription\"=\"Fast picture viewer\"\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\WinRust\\PhotoView\\Capabilities\\FileAssociations]\r\n"+ );+ for e in PV_EXTS {+ reg += &format!("\".{e}\"=\"{PV_PROG}\"\r\n");+ }+ reg += &format!("\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\RegisteredApplications]\r\n\"{PV_APP}\"=\"SOFTWARE\\\\WinRust\\\\PhotoView\\\\Capabilities\"\r\n");+ for e in PV_EXTS {+ reg += &format!("\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\.{e}\\OpenWithProgids]\r\n\"{PV_PROG}\"=hex(0):\r\n");+ }+ // the .reg lives in Program Files (admin-only), not %TEMP%+ let f = pv_dir().join("register.reg");+ fs::write(&f, reg).map_err(|e| format!("{}: {e}", f.display()))?;+ let r = run("reg", &["import", &f.display().to_string()]);+ let _ = fs::remove_file(&f);+ r+}++pub(crate) fn pv_uninstall() -> Result<(), String> {+ for e in PV_EXTS {+ let _ = run("reg", &["delete", &format!(r"HKLM\SOFTWARE\Classes\.{e}\OpenWithProgids"), "/v", PV_PROG, "/f"]);+ }+ let _ = run("reg", &["delete", r"HKLM\SOFTWARE\RegisteredApplications", "/v", PV_APP, "/f"]);+ let _ = run("reg", &["delete", &format!(r"HKLM\SOFTWARE\Classes\{PV_PROG}"), "/f"]);+ let _ = run("reg", &["delete", r"HKLM\SOFTWARE\WinRust\PhotoView", "/f"]);+ tool_remove("photoview.exe", &pv_dir(), Some("Photo viewer"));+ Ok(())+}++/// Installing = applying: debloat.exe --apply writes an undo file first, uninstalling plays it back.+pub(crate) fn db_install() -> Result<(), String> {+ tool_install("debloat.exe", &db_dir(), None)?;+ out(&db_dir().join("debloat.exe").display().to_string(), &["--apply"]).map(|_| ())+}++pub(crate) fn db_uninstall() -> Result<(), String> {+ let exe = db_dir().join("debloat.exe");+ if exe.is_file() {+ out(&exe.display().to_string(), &["--undo"])?; // on failure the exe and the undo file stay, so it can be repeated+ }+ tool_remove("debloat.exe", &db_dir(), None);+ Ok(())+}diff --git a/src/install/topbar.rs b/src/install/topbar.rsnew file mode 100644index 0000000..ffbd28d--- /dev/null+++ b/src/install/topbar.rs@@ -0,0 +1,87 @@+//! topbar: the bottom bar instead of the taskbar, plus reshell hotkeys and the PowerShell profile block.+use crate::*;++pub(crate) fn bar_dir() -> PathBuf {+ program_files().join("topbar")+}++pub(crate) const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";++// topbar.cfg next to topbar.exe (the bar re-reads it every few seconds). Missing file = OneDrive hidden.+pub(crate) fn cfg_path() -> PathBuf {+ bar_dir().join("topbar.cfg")+}++pub(crate) fn od_hidden() -> bool {+ fs::read_to_string(cfg_path()).map_or(true, |c| !c.contains("hide_onedrive=0"))+}++pub(crate) fn set_od_hidden(v: bool) -> Result<(), String> {+ fs::create_dir_all(bar_dir()).and_then(|_| fs::write(cfg_path(), format!("hide_onedrive={}\n", v as u8))).map_err(|e| e.to_string())+}++// PowerShell profile block (profile.ps1 next to this file: zoxide, grep->rg, ll->eza, cat->bat) that lives exactly as long as topbar is installed.+// Written to Windows PowerShell 5.1 and, if installed, pwsh 7 (each has its own $PROFILE).+// shortcut: the elevated user's profile, which is the same account unless UAC asks for a different admin; upgrade if that matters.+pub(crate) const PS_STRIP: &str = r"$p=$PROFILE; $t=[string]$(if(Test-Path $p){Get-Content $p -Raw}); $t=[regex]::Replace($t,'(?s)# >>> topbar >>>.*?# <<< topbar <<<\r?\n?','');";+pub(crate) const PS_BLOCK: &str = include_str!("profile.ps1");+pub(crate) const SHELLS: [&str; 2] = ["powershell", "pwsh"];++pub(crate) fn profile_install() -> Result<(), String> {+ shells_run(&format!("{PS_STRIP}$b=@'\n{PS_BLOCK}'@; New-Item -Force -ItemType Directory (Split-Path $p) | Out-Null; Set-Content $p ($t.TrimEnd() + [Environment]::NewLine + $b) -Encoding utf8"))+}++pub(crate) fn profile_uninstall() -> Result<(), String> {+ // delete the file if nothing but our block was in it+ shells_run(&format!("{PS_STRIP} if($t.Trim()){{Set-Content $p $t -Encoding utf8}}elseif(Test-Path $p){{Remove-Item $p}}"))+}++/// Runs `script` in every shell. Only the first (always present) can fail the call: a missing pwsh is not an error.+pub(crate) fn shells_run(script: &str) -> Result<(), String> {+ let r = run(SHELLS[0], &["-NoProfile", "-Command", script]);+ let _ = run(SHELLS[1], &["-NoProfile", "-Command", script]);+ r+}++pub(crate) fn bar_install() -> Result<(), String> {+ with_payload(&["topbar.exe", "rs-du.exe", "reshell.exe"], |d| {+ let dst = bar_dir().join("topbar.exe");+ let _ = run("taskkill", &["/f", "/im", "topbar.exe"]);+ fs::create_dir_all(bar_dir()).map_err(|e| e.to_string())?;+ put(&d.join("topbar.exe"), &dst)?;+ fs::create_dir_all(tm_dir()).map_err(|e| e.to_string())?;+ put(&d.join("rs-du.exe"), &tm_dir().join("rs-du.exe"))?; // topbar menu "Чистильщик диска"+ let rsh = bar_dir().join("reshell.exe"); // Win+1/2/3 desktop hotkeys, no args = hotkeys+ let _ = run("taskkill", &["/f", "/im", "reshell.exe"]);+ put(&d.join("reshell.exe"), &rsh)?;+ run("reg", &["add", RUN_KEY, "/v", "reshell", "/t", "REG_SZ", "/d", &format!("\"{}\"", rsh.display()), "/f"])?;+ let _ = Command::new("explorer.exe").arg(&rsh).spawn();+ run(dst.to_str().unwrap(), &["--restore"])?; // clean state in case a killed instance left the taskbar hidden+ // The bar runs elevated (a task with the highest run level starts it at logon without a UAC prompt): that lets it close+ // elevated windows and click elevated apps' tray icons. It starts everything else through explorer, i.e. unelevated.+ // Fallback when the task cannot be made: the plain Run key and a normal-rights bar.+ let task = format!("$u=[Security.Principal.WindowsIdentity]::GetCurrent().Name; Register-ScheduledTask -TaskName topbar -Force -Action (New-ScheduledTaskAction -Execute '{}') -Trigger (New-ScheduledTaskTrigger -AtLogOn -User $u) -Principal (New-ScheduledTaskPrincipal -UserId $u -LogonType Interactive -RunLevel Highest) -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)) | Out-Null", dst.display());+ if run("powershell", &["-NoProfile", "-Command", &task]).is_ok() && run("schtasks", &["/run", "/tn", "topbar"]).is_ok() {+ let _ = run("reg", &["delete", RUN_KEY, "/v", "topbar", "/f"]);+ } else {+ WARN.lock().unwrap().push(t!("задача topbar не создана: запуск через Run, без прав администратора", "topbar task was not created: it starts via Run, without administrator rights").into());+ run("reg", &["add", RUN_KEY, "/v", "topbar", "/t", "REG_SZ", "/d", &format!("\"{}\"", dst.display()), "/f"])?;+ let _ = Command::new("explorer.exe").arg(&dst).spawn(); // normal user token, like rs-launcher+ }+ soft(t!("профиль PowerShell не записан", "PowerShell profile was not written"), profile_install()); // a shell nicety, must not fail the bar install+ Ok(())+ })+}++pub(crate) fn bar_uninstall() -> Result<(), String> {+ let _ = run("reg", &["delete", RUN_KEY, "/v", "topbar", "/f"]);+ let _ = run("schtasks", &["/delete", "/tn", "topbar", "/f"]);+ let _ = run("reg", &["delete", RUN_KEY, "/v", "reshell", "/f"]);+ let _ = run("taskkill", &["/f", "/im", "reshell.exe"]);+ let _ = run("taskkill", &["/f", "/im", "topbar.exe"]);+ let _ = profile_uninstall();+ let r = run(bar_dir().join("topbar.exe").to_str().unwrap(), &["--restore"]); // a killed bar cannot restore the taskbar itself+ let _ = fs::remove_dir_all(bar_dir());+ cleaner_release(tm_dir().join("rtaskmgr-win32.exe").is_file());+ r+}diff --git a/src/main.rs b/src/main.rsindex 50a3f5f..84c4354 100644--- a/src/main.rs+++ b/src/main.rs@@ -1,9 +1,17 @@-// Plugin Launcher: a small dark Win32 window that installs / removes plugins (rust-search; chrome-rs is a stub).-// Binaries come from next to this exe, else ..\rust-search\target\release. Needs admin (see app.manifest).+// WinRust installer (plugin-launcher.exe): a small dark Win32 window and a command line that install / remove the plugins.+// The plugin exes are embedded (payload.txt, build.rs); payload\ next to this exe wins over them. Needs admin (see app.manifest).+// main.rs the plugin table (PLUGINS) and shared state+// install/ what each plugin changes in the system and how it is undone+// cli.rs the command line; ui.rs the window#![windows_subsystem = "windows"]#![allow(unsafe_op_in_unsafe_fn)]#[macro_use]-mod i18n;+extern crate winrust_common;+use winrust_common as i18n;+mod cli;+mod install;+mod ui;+use {cli::*, install::*, ui::*};use std::{cell::Cell,env, fs,@@ -153,1201 +161,6 @@ static MSG: Mutex<(String, bool)> = Mutex::new((String::new(), true));thread_local! { static SETTINGS: Cell<Option<usize>> = const { Cell::new(None) }; } // plugin whose settings panel is openthread_local! { static HOVER: Cell<Option<usize>> = const { Cell::new(None) }; }-// ---------- install logic ------------fn out(prog: &str, args: &[&str]) -> Result<String, String> {- let o = Command::new(prog).args(args).creation_flags(0x0800_0000).output().map_err(|e| format!("{prog}: {e}"))?;- if o.status.success() {- Ok(String::from_utf8_lossy(&o.stdout).into_owned())- } else {- Err(format!("{prog} {}: {}{}", args.join(" "), String::from_utf8_lossy(&o.stdout).trim(), String::from_utf8_lossy(&o.stderr).trim()))- }-}--fn run(prog: &str, args: &[&str]) -> Result<(), String> {- out(prog, args).map(|_| ())-}--// Non-fatal failures of one install: shown as a count in the status line, spelled out in install.log.-static WARN: Mutex<Vec<String>> = Mutex::new(Vec::new());--fn soft(what: &str, r: Result<(), String>) {- if let Err(e) = r {- WARN.lock().unwrap().push(format!("{what}: {e}"));- }-}--fn log(s: &str) {- let d = PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join("plugin-launcher");- let _ = fs::create_dir_all(&d);- if let Ok(mut f) = fs::OpenOptions::new().create(true).append(true).open(d.join("install.log")) {- let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());- let _ = writeln!(f, "[{t}] {s}"); // shortcut: unix seconds, no date formatting; upgrade if the log gets read by humans a lot- }-}--/// Copies over an exe that was just killed: taskkill returns before Windows (or an antivirus scan) releases the file, so retry ~6 s.-fn put(src: &Path, dst: &Path) -> Result<(), String> {- let mut r = fs::copy(src, dst).map(|_| ());- for _ in 0..30 {- if !matches!(&r, Err(e) if e.raw_os_error() == Some(32) || e.raw_os_error() == Some(5)) {- break;- }- thread::sleep(std::time::Duration::from_millis(200));- r = fs::copy(src, dst).map(|_| ());- }- r.map_err(|e| format!("{}: {e}", dst.display()))-}--fn reg_dword(key: &str, name: &str) -> Option<u32> {- let o = out("reg", &["query", key, "/v", name]).ok()?;- let t = o.lines().find(|l| l.contains("REG_DWORD"))?.split_whitespace().last()?;- u32::from_str_radix(t.trim_start_matches("0x"), 16).ok()-}--/// 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.-const STATE: &str = r"HKLM\SOFTWARE\plugin-launcher\rust-search";-const WS_KEY: &str = r"HKLM\SYSTEM\CurrentControlSet\Services\WSearch";-const SB_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Search";--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"]);- }-}--const SH_KEY: &str = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\SearchHost.exe";-const TM_KEY: &str = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe";--const PAYLOAD: [(&str, &[u8]); 11] = [- ("wiztree.exe", include_bytes!("../payload/wiztree.exe")),- ("photoview.exe", include_bytes!("../payload/photoview.exe")),- ("debloat.exe", include_bytes!("../payload/debloat.exe")),- ("rust-explorer.exe", include_bytes!("../payload/rust-explorer.exe")),- ("rs-shell.exe", include_bytes!("../payload/rs-shell.exe")),- ("reshell.exe", include_bytes!("../payload/reshell.exe")),- ("topbar.exe", include_bytes!("../payload/topbar.exe")),- ("rs.exe", include_bytes!("../payload/rs.exe")),- ("rs-launcher.exe", include_bytes!("../payload/rs-launcher.exe")),- ("Task manager.exe", include_bytes!("../payload/Task manager.exe")),- ("rs-du.exe", include_bytes!("../payload/rs-du.exe")),-];--/// Update without rebuilding the launcher: an exe in `payload\` next to this one (or two levels up, the cargo-/// target\release layout) wins over the embedded copy. Trust level = the launcher exe's own folder.-fn disk_payload() -> Option<PathBuf> {- let exe = env::current_exe().ok()?;- let d = exe.parent()?;- [d.join("payload"), d.join(r"..\..\payload")].into_iter().find(|p| p.is_dir())-}--/// Unpacks the `need`ed bundled plugins, runs `f` on them, deletes them. The folder is under Program Files (admin-only writable),-/// not %TEMP%: a user-level process must not be able to swap an exe that is about to be installed as a SYSTEM task.-fn with_payload<T>(need: &[&str], f: impl FnOnce(&Path) -> Result<T, String>) -> Result<T, String> {- let d = program_files().join(format!("plugin-launcher-tmp-{}", std::process::id()));- fs::create_dir_all(&d).map_err(|e| format!("{}: {e}", d.display()))?;- let disk = disk_payload();- let unpack = |n: &&str| -> Result<(), String> {- let bytes = PAYLOAD.iter().find(|(m, _)| m == n).ok_or(tf!("нет {n} в сборке", "{n} is missing from the build"))?.1;- match disk.as_ref().map(|p| p.join(n)).filter(|p| p.is_file()) {- Some(src) => {- log(&tf!("{n}: из {}", "{n}: from {}", src.display()));- fs::copy(src, d.join(n)).map(|_| ())- }- None => fs::write(d.join(n), bytes),- }- .map_err(|e| tf!("распаковка {n}: {e}", "unpacking {n}: {e}"))- };- let r = need.iter().try_for_each(unpack).and_then(|_| f(&d));- let _ = fs::remove_dir_all(&d);- r-}--fn program_files() -> PathBuf {- PathBuf::from(env::var("ProgramFiles").unwrap_or(r"C:\Program Files".into()))-}--fn tm_dir() -> PathBuf {- program_files().join("rtaskmgr")-}--fn bar_dir() -> PathBuf {- program_files().join("topbar")-}--fn rx_dir() -> PathBuf {- program_files().join("rust-explorer")-}--fn prog_dir() -> PathBuf {- program_files().join("rs-search")-}--// shortcut: Windows makes at most one restore point per 24 h and it needs System Protection on; failures are ignored.-fn checkpoint() -> Result<(), String> {- run("powershell", &["-NoProfile", "-Command", "Checkpoint-Computer -Description 'Plugin Launcher' -RestorePointType MODIFY_SETTINGS"])-}--// Image File Execution Options "Debugger": Windows starts our exe instead of taskmgr.exe (the system file stays untouched, so this is fully reversible).-fn tm_install() -> Result<(), String> {- with_payload(&["Task manager.exe", "rs-du.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 overwritten- fs::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"))?;- // the search (and the bar's Start panel) lists Start Menu shortcuts only, so without one the task manager is invisible to them- soft(t!("ярлык в меню Пуск не создан, поиск не увидит диспетчер", "Start menu shortcut was not created, search will not find the task manager"), run("powershell", &["-NoProfile", "-Command", &format!("$s=(New-Object -ComObject WScript.Shell).CreateShortcut('{}'); $s.TargetPath='{}'; $s.Save()", tm_lnk().display(), dst.display())]));- // elevated start without a UAC prompt (the exe re-launches itself through this task), so it can end protected processes- let task = format!("$u=[Security.Principal.WindowsIdentity]::GetCurrent().Name; Register-ScheduledTask -TaskName rtaskmgr -Force -Action (New-ScheduledTaskAction -Execute '{}') -Principal (New-ScheduledTaskPrincipal -UserId $u -LogonType Interactive -RunLevel Highest) -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances Parallel) | Out-Null", dst.display());- soft(t!("задача rtaskmgr не создана, запуск от администратора будет через UAC", "rtaskmgr task was not created, launching as administrator will go through UAC"), run("powershell", &["-NoProfile", "-Command", &task]));- run("reg", &["add", TM_KEY, "/v", "Debugger", "/t", "REG_SZ", "/d", &format!("\"{}\"", dst.display()), "/f"])- })-}--fn tm_lnk() -> PathBuf {- PathBuf::from(std::env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join(r"Microsoft\Windows\Start Menu\Programs\Task manager.lnk")-}--fn tm_uninstall() -> Result<(), String> {- let _ = fs::remove_file(tm_lnk());- 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- // other IFEO settings (e.g. mitigation policies) that are not ours to remove.- run("reg", &["delete", TM_KEY, "/v", "Debugger", "/f"])?;- let _ = run("taskkill", &["/f", "/im", "rtaskmgr-win32.exe"]);- let _ = fs::remove_file(tm_dir().join("rtaskmgr-win32.exe"));- cleaner_release(bar_dir().join("topbar.exe").is_file());- Ok(())-}--/// rs-du (disk cleaner) lives in the task manager folder and is shared by rtaskmgr-win32 and the topbar menu:-/// it goes away only when the other plugin is gone too.-fn cleaner_release(other_installed: bool) {- if !other_installed {- let _ = fs::remove_file(tm_dir().join("rs-du.exe"));- }- let _ = fs::remove_dir(tm_dir()); // only succeeds when empty-}--const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";--// topbar.cfg next to topbar.exe (the bar re-reads it every few seconds). Missing file = OneDrive hidden.-fn cfg_path() -> PathBuf {- bar_dir().join("topbar.cfg")-}--fn od_hidden() -> bool {- fs::read_to_string(cfg_path()).map_or(true, |c| !c.contains("hide_onedrive=0"))-}--fn set_od_hidden(v: bool) -> Result<(), String> {- fs::create_dir_all(bar_dir()).and_then(|_| fs::write(cfg_path(), format!("hide_onedrive={}\n", v as u8))).map_err(|e| e.to_string())-}--// PowerShell profile block (src/profile.ps1: zoxide, grep->rg, ll->eza, cat->bat) that lives exactly as long as topbar is installed.-// Written to Windows PowerShell 5.1 and, if installed, pwsh 7 (each has its own $PROFILE).-// shortcut: the elevated user's profile, which is the same account unless UAC asks for a different admin; upgrade if that matters.-const PS_STRIP: &str = r"$p=$PROFILE; $t=[string]$(if(Test-Path $p){Get-Content $p -Raw}); $t=[regex]::Replace($t,'(?s)# >>> topbar >>>.*?# <<< topbar <<<\r?\n?','');";-const PS_BLOCK: &str = include_str!("profile.ps1");-const SHELLS: [&str; 2] = ["powershell", "pwsh"];--fn profile_install() -> Result<(), String> {- shells_run(&format!("{PS_STRIP}$b=@'\n{PS_BLOCK}'@; New-Item -Force -ItemType Directory (Split-Path $p) | Out-Null; Set-Content $p ($t.TrimEnd() + [Environment]::NewLine + $b) -Encoding utf8"))-}--fn profile_uninstall() -> Result<(), String> {- // delete the file if nothing but our block was in it- shells_run(&format!("{PS_STRIP} if($t.Trim()){{Set-Content $p $t -Encoding utf8}}elseif(Test-Path $p){{Remove-Item $p}}"))-}--/// Runs `script` in every shell. Only the first (always present) can fail the call: a missing pwsh is not an error.-fn shells_run(script: &str) -> Result<(), String> {- let r = run(SHELLS[0], &["-NoProfile", "-Command", script]);- let _ = run(SHELLS[1], &["-NoProfile", "-Command", script]);- r-}--fn bar_install() -> Result<(), String> {- with_payload(&["topbar.exe", "rs-du.exe", "reshell.exe"], |d| {- let dst = bar_dir().join("topbar.exe");- let _ = run("taskkill", &["/f", "/im", "topbar.exe"]);- fs::create_dir_all(bar_dir()).map_err(|e| e.to_string())?;- put(&d.join("topbar.exe"), &dst)?;- fs::create_dir_all(tm_dir()).map_err(|e| e.to_string())?;- put(&d.join("rs-du.exe"), &tm_dir().join("rs-du.exe"))?; // topbar menu "Чистильщик диска"- let rsh = bar_dir().join("reshell.exe"); // Win+1/2/3 desktop hotkeys, no args = hotkeys- let _ = run("taskkill", &["/f", "/im", "reshell.exe"]);- put(&d.join("reshell.exe"), &rsh)?;- run("reg", &["add", RUN_KEY, "/v", "reshell", "/t", "REG_SZ", "/d", &format!("\"{}\"", rsh.display()), "/f"])?;- let _ = Command::new("explorer.exe").arg(&rsh).spawn();- run(dst.to_str().unwrap(), &["--restore"])?; // clean state in case a killed instance left the taskbar hidden- // The bar runs elevated (a task with the highest run level starts it at logon without a UAC prompt): that lets it close- // elevated windows and click elevated apps' tray icons. It starts everything else through explorer, i.e. unelevated.- // Fallback when the task cannot be made: the plain Run key and a normal-rights bar.- let task = format!("$u=[Security.Principal.WindowsIdentity]::GetCurrent().Name; Register-ScheduledTask -TaskName topbar -Force -Action (New-ScheduledTaskAction -Execute '{}') -Trigger (New-ScheduledTaskTrigger -AtLogOn -User $u) -Principal (New-ScheduledTaskPrincipal -UserId $u -LogonType Interactive -RunLevel Highest) -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)) | Out-Null", dst.display());- if run("powershell", &["-NoProfile", "-Command", &task]).is_ok() && run("schtasks", &["/run", "/tn", "topbar"]).is_ok() {- let _ = run("reg", &["delete", RUN_KEY, "/v", "topbar", "/f"]);- } else {- WARN.lock().unwrap().push(t!("задача topbar не создана: запуск через Run, без прав администратора", "topbar task was not created: it starts via Run, without administrator rights").into());- run("reg", &["add", RUN_KEY, "/v", "topbar", "/t", "REG_SZ", "/d", &format!("\"{}\"", dst.display()), "/f"])?;- let _ = Command::new("explorer.exe").arg(&dst).spawn(); // normal user token, like rs-launcher- }- soft(t!("профиль PowerShell не записан", "PowerShell profile was not written"), profile_install()); // a shell nicety, must not fail the bar install- Ok(())- })-}--fn bar_uninstall() -> Result<(), String> {- let _ = run("reg", &["delete", RUN_KEY, "/v", "topbar", "/f"]);- let _ = run("schtasks", &["/delete", "/tn", "topbar", "/f"]);- let _ = run("reg", &["delete", RUN_KEY, "/v", "reshell", "/f"]);- let _ = run("taskkill", &["/f", "/im", "reshell.exe"]);- let _ = run("taskkill", &["/f", "/im", "topbar.exe"]);- let _ = profile_uninstall();- let r = run(bar_dir().join("topbar.exe").to_str().unwrap(), &["--restore"]); // a killed bar cannot restore the taskbar itself- let _ = fs::remove_dir_all(bar_dir());- cleaner_release(tm_dir().join("rtaskmgr-win32.exe").is_file());- r-}--// ---------- rust-explorer: file manager + Explorer replacement -----------//-// Install: our files in Program Files, folders / drives opened from any program go to rust-explorer (HKCU class verbs of the-// installing user), rs-shell --overlay starts at sign-in and, with the ReplaceExplorer switch, ends the shell Explorer once topbar-// and the rust-explorer desktop are on screen. AutoRestartShell is set to 0 so Windows does not bring Explorer back.-// Uninstall puts everything back and starts Explorer again. rs-shell itself hands the session back to Explorer if topbar dies.-const RX_STATE: &str = r"HKLM\SOFTWARE\plugin-launcher\rust-explorer";-const WINLOGON_KEY: &str = r"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon";-const RX_SWITCH: &str = r"HKCU\Software\rs-shell";-const RX_FOLDERS: [&str; 3] = [r"HKCU\Software\Classes\Directory\shell\open", r"HKCU\Software\Classes\Folder\shell\open", r"HKCU\Software\Classes\Drive\shell\open"];--// svchost RAM trim, done with rust-explorer: (service, Start we set, Windows default). Uninstall puts back the Windows defaults,-// not the values found at install: they may already be our own (the same tweak was first run by hand).-// DoSvc's key is ACL-protected on some builds, so every step is soft: a refused one is only a warning.-const RX_SVCS: [(&str, u32, u32); 6] = [("DiagTrack", 4, 2), ("PcaSvc", 4, 2), ("InventorySvc", 4, 2), ("lfsvc", 4, 3), ("cbdhsvc", 4, 2), ("DoSvc", 3, 2)];-const SPLIT_KEY: &str = r"HKLM\SYSTEM\CurrentControlSet\Control";-const SPLIT_DEFAULT: u32 = 3670016; // 3.5 GB: above it Windows gives every service its own svchost--fn rx_trim(on: bool) {- for (s, off, def) in RX_SVCS {- let v = if on { off } else { def };- soft(&tf!("служба {s}", "service {s}"), run("reg", &["add", &format!(r"HKLM\SYSTEM\CurrentControlSet\Services\{s}"), "/v", "Start", "/t", "REG_DWORD", "/d", &v.to_string(), "/f"]));- if on && off == 4 {- let _ = run("sc.exe", &["stop", s]); // the per-user cbdhsvc_xxxx instance stops at the next sign-in- }- }- let t = if on { 0x4000000 } else { SPLIT_DEFAULT };- soft("SvcHostSplitThresholdInKB", run("reg", &["add", SPLIT_KEY, "/v", "SvcHostSplitThresholdInKB", "/t", "REG_DWORD", "/d", &t.to_string(), "/f"]));-}--fn rx_lnk() -> PathBuf {- PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join(r"plugin-launcher\rs-overlay.lnk")-}--fn rx_install() -> Result<(), String> {- if !bar_dir().join("topbar.exe").is_file() {- return Err(t!("сначала установите topbar: без него после отключения Explorer не будет панели", "install topbar first: without it there will be no bar after Explorer is disabled").into());- }- with_payload(&["rust-explorer.exe", "rs-shell.exe"], |d| {- for n in ["rs-shell.exe", "rust-explorer.exe"] {- let _ = run("taskkill", &["/f", "/im", n]); // an update: a running exe cannot be overwritten- }- fs::create_dir_all(rx_dir()).map_err(|e| e.to_string())?;- let (fm, sh) = (rx_dir().join("rust-explorer.exe"), rx_dir().join("rs-shell.exe"));- put(&d.join("rust-explorer.exe"), &fm)?;- put(&d.join("rs-shell.exe"), &sh)?;- // what Windows had, saved once (an update must not overwrite it with our own 0)- if reg_dword(RX_STATE, "AutoRestartShell").is_none() {- let v = reg_dword(WINLOGON_KEY, "AutoRestartShell").unwrap_or(1);- run("reg", &["add", RX_STATE, "/v", "AutoRestartShell", "/t", "REG_DWORD", "/d", &v.to_string(), "/f"])?;- }- // folders and drives opened by other programs, the desktop, Win+R: rust-explorer. DelegateExecute is emptied on purpose:- // while it is set, Windows ignores the command and uses Explorer's built-in handler.- for k in RX_FOLDERS {- let c = format!(r"{k}\command");- run("reg", &["add", &c, "/ve", "/t", "REG_SZ", "/d", &format!("\"{}\" \"%1\"", fm.display()), "/f"])?;- run("reg", &["add", &c, "/v", "DelegateExecute", "/t", "REG_SZ", "/d", "", "/f"])?;- }- // A logon task starts the overlay right at sign-in; Explorer runs the Run key only after its own startup delay (~20 s of- // plain Windows on screen). Limited run level: the shell side must never run elevated. Fallback: the Run key.- let task = format!("$u=[Security.Principal.WindowsIdentity]::GetCurrent().Name; Register-ScheduledTask -TaskName rs-overlay -Force -Action (New-ScheduledTaskAction -Execute '{}' -Argument '--overlay') -Trigger (New-ScheduledTaskTrigger -AtLogOn -User $u) -Principal (New-ScheduledTaskPrincipal -UserId $u -LogonType Interactive -RunLevel Limited) -Settings (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero)) | Out-Null", sh.display());- if run("powershell", &["-NoProfile", "-Command", &task]).is_ok() {- let _ = run("reg", &["delete", RUN_KEY, "/v", "rs-overlay", "/f"]);- } else {- WARN.lock().unwrap().push(t!("задача rs-overlay не создана: запуск через Run, с задержкой Windows", "rs-overlay task was not created: it starts via Run, with a Windows startup delay").into());- run("reg", &["add", RUN_KEY, "/v", "rs-overlay", "/t", "REG_SZ", "/d", &format!("\"{}\" --overlay", sh.display()), "/f"])?;- }- run("reg", &["add", RX_SWITCH, "/v", "ReplaceExplorer", "/t", "REG_DWORD", "/d", "1", "/f"])?;- run("reg", &["add", WINLOGON_KEY, "/v", "AutoRestartShell", "/t", "REG_DWORD", "/d", "0", "/f"])?;- rx_trim(true);- // Start it now, with the user's normal token: explorer.exe opens a shortcut unelevated, and the shortcut carries --overlay.- let lnk = rx_lnk();- let _ = fs::create_dir_all(lnk.parent().unwrap());- soft(t!("overlay не запущен сейчас: он стартует при следующем входе", "overlay is not running now: it starts at the next logon"), run("powershell", &["-NoProfile", "-Command", &format!("$s=(New-Object -ComObject WScript.Shell).CreateShortcut('{}'); $s.TargetPath='{}'; $s.Arguments='--overlay'; $s.Save()", lnk.display(), sh.display())]));- let _ = Command::new("explorer.exe").arg(&lnk).spawn();- Ok(())- })-}--fn rx_uninstall() -> Result<(), String> {- // Windows may restart its shell again; our hooks off; then the shell back, unelevated, only if none is running- let back = reg_dword(RX_STATE, "AutoRestartShell").unwrap_or(1);- let r = run("reg", &["add", WINLOGON_KEY, "/v", "AutoRestartShell", "/t", "REG_DWORD", "/d", &back.to_string(), "/f"]);- let _ = run("reg", &["delete", RUN_KEY, "/v", "rs-overlay", "/f"]);- let _ = run("schtasks", &["/delete", "/tn", "rs-overlay", "/f"]);- let _ = run("reg", &["delete", RX_SWITCH, "/f"]);- rx_trim(false);- for k in RX_FOLDERS {- let _ = run("reg", &["delete", k, "/f"]); // only our HKCU override; the system's verbs under HKLM stay- }- for n in ["rs-shell.exe", "rust-explorer.exe"] {- let _ = run("taskkill", &["/f", "/im", n]);- }- let _ = run("powershell", &["-NoProfile", "-Command", r#"if (-not (Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object { $_.CommandLine -match '(?i)explorer\.exe"?\s*$' })) { runas /trustlevel:0x20000 C:\Windows\explorer.exe }"#]);- let _ = fs::remove_file(rx_lnk());- let _ = fs::remove_dir_all(rx_dir());- if r.is_ok() {- let _ = run("reg", &["delete", RX_STATE, "/f"]);- }- r-}--// ---------- wiztree, photoview, debloat: small stand-alone tools, one exe each in its own Program Files folder ------------fn wz_dir() -> PathBuf {- program_files().join("wiztree")-}--fn pv_dir() -> PathBuf {- program_files().join("photoview")-}--fn db_dir() -> PathBuf {- program_files().join("debloat")-}--/// Start Menu shortcut: search and the bar's Start panel list Start Menu shortcuts only.-fn start_lnk(name: &str) -> PathBuf {- PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join(format!(r"Microsoft\Windows\Start Menu\Programs\{name}.lnk"))-}--/// Copies `exe` out of the payload into `dir` (an update: the running copy is killed first) and adds the Start Menu shortcut `lnk`.-fn tool_install(exe: &str, dir: &Path, lnk: Option<&str>) -> Result<(), String> {- with_payload(&[exe], |d| {- let _ = run("taskkill", &["/f", "/im", exe]);- fs::create_dir_all(dir).map_err(|e| e.to_string())?;- let dst = dir.join(exe);- put(&d.join(exe), &dst)?;- if let Some(n) = lnk {- soft(&tf!("ярлык «{n}» в меню Пуск не создан, поиск его не увидит", "Start menu shortcut '{n}' was not created, search will not find it"), run("powershell", &["-NoProfile", "-Command", &format!("$s=(New-Object -ComObject WScript.Shell).CreateShortcut('{}'); $s.TargetPath='{}'; $s.Save()", start_lnk(n).display(), dst.display())]));- }- Ok(())- })-}--fn tool_remove(exe: &str, dir: &Path, lnk: Option<&str>) {- if let Some(n) = lnk {- let _ = fs::remove_file(start_lnk(n));- }- let _ = run("taskkill", &["/f", "/im", exe]);- let _ = fs::remove_dir_all(dir);-}--fn wz_install() -> Result<(), String> {- tool_install("wiztree.exe", &wz_dir(), Some("WinRust Disk"))-}--fn wz_uninstall() -> Result<(), String> {- tool_remove("wiztree.exe", &wz_dir(), Some("WinRust Disk"));- Ok(())-}--const PV_EXTS: [&str; 11] = ["jpg", "jpeg", "jfif", "png", "bmp", "gif", "tif", "tiff", "webp", "heic", "avif"]; // keep in step with photoview's EXTS-const PV_PROG: &str = "WinRustPhoto";-const PV_APP: &str = "WinRust Photo Viewer";--/// "Open with" entry and a Default apps entry; the default itself stays the user's choice (Windows does not allow setting it from code).-fn pv_install() -> Result<(), String> {- tool_install("photoview.exe", &pv_dir(), Some("Photo viewer"))?;- let exe = pv_dir().join("photoview.exe").display().to_string().replace('\\', r"\\");- let mut reg = format!(- "Windows Registry Editor Version 5.00\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\{PV_PROG}]\r\n@=\"Picture\"\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\{PV_PROG}\\shell\\open\\command]\r\n@=\"\\\"{exe}\\\" \\\"%1\\\"\"\r\n\r\n\- [HKEY_LOCAL_MACHINE\\SOFTWARE\\WinRust\\PhotoView\\Capabilities]\r\n\"ApplicationName\"=\"{PV_APP}\"\r\n\"ApplicationDescription\"=\"Fast picture viewer\"\r\n\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\WinRust\\PhotoView\\Capabilities\\FileAssociations]\r\n"- );- for e in PV_EXTS {- reg += &format!("\".{e}\"=\"{PV_PROG}\"\r\n");- }- reg += &format!("\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\RegisteredApplications]\r\n\"{PV_APP}\"=\"SOFTWARE\\\\WinRust\\\\PhotoView\\\\Capabilities\"\r\n");- for e in PV_EXTS {- reg += &format!("\r\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\.{e}\\OpenWithProgids]\r\n\"{PV_PROG}\"=hex(0):\r\n");- }- // the .reg lives in Program Files (admin-only), not %TEMP%- let f = pv_dir().join("register.reg");- fs::write(&f, reg).map_err(|e| format!("{}: {e}", f.display()))?;- let r = run("reg", &["import", &f.display().to_string()]);- let _ = fs::remove_file(&f);- r-}--fn pv_uninstall() -> Result<(), String> {- for e in PV_EXTS {- let _ = run("reg", &["delete", &format!(r"HKLM\SOFTWARE\Classes\.{e}\OpenWithProgids"), "/v", PV_PROG, "/f"]);- }- let _ = run("reg", &["delete", r"HKLM\SOFTWARE\RegisteredApplications", "/v", PV_APP, "/f"]);- let _ = run("reg", &["delete", &format!(r"HKLM\SOFTWARE\Classes\{PV_PROG}"), "/f"]);- let _ = run("reg", &["delete", r"HKLM\SOFTWARE\WinRust\PhotoView", "/f"]);- tool_remove("photoview.exe", &pv_dir(), Some("Photo viewer"));- Ok(())-}--/// Installing = applying: debloat.exe --apply writes an undo file first, uninstalling plays it back.-fn db_install() -> Result<(), String> {- tool_install("debloat.exe", &db_dir(), None)?;- out(&db_dir().join("debloat.exe").display().to_string(), &["--apply"]).map(|_| ())-}--fn db_uninstall() -> Result<(), String> {- let exe = db_dir().join("debloat.exe");- if exe.is_file() {- out(&exe.display().to_string(), &["--undo"])?; // on failure the exe and the undo file stay, so it can be repeated- }- tool_remove("debloat.exe", &db_dir(), None);- Ok(())-}--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"])-}--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"));- with_payload(&["rs.exe", "rs-launcher.exe"], |src| {- run(src.join("rs.exe").to_str().unwrap(), &["--install"])?; // copies itself to Program Files, registers boot tasks- let dst = prog_dir().join("rs-launcher.exe"); // must live somewhere stable: --autostart registers its own path- let _ = run("taskkill", &["/f", "/im", "rs-launcher.exe"]);- put(&src.join("rs-launcher.exe"), &dst)?;- run(dst.to_str().unwrap(), &["--autostart"])?;- // via explorer: it starts the launcher with the desktop user's normal token. Started from here it would- // inherit admin rights, and every file opened from search would run elevated too.- let _ = Command::new("explorer.exe").arg(&dst).spawn();- run("sc.exe", &["config", "WSearch", "start=", "disabled"])?;- let _ = run("sc.exe", &["stop", "WSearch"]);- // 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"])?;- let _ = run("taskkill", &["/f", "/im", "SearchHost.exe"]);- taskbar_search(0) // hide the taskbar search box- })-}--fn uninstall() -> Result<(), String> {- with_payload(&["rs.exe"], |src| {- let _ = run("taskkill", &["/f", "/im", "rs-launcher.exe"]);- let _ = run("reg", &["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "rs-launcher", "/f"]);- // run the unpacked copy: an exe cannot delete itself, so the installed one would leave its folder behind- run(src.join("rs.exe").to_str().unwrap(), &["--uninstall"])?;- let _ = fs::remove_dir_all(prog_dir());- 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",- };- run("sc.exe", &["config", "WSearch", "start=", mode])?;- if mode.ends_with("auto") {- let _ = run("sc.exe", &["start", "WSearch"]);- }- let r = taskbar_search(reg_dword(STATE, "SearchboxMode").unwrap_or(2));- if r.is_ok() {- let _ = run("reg", &["delete", STATE, "/f"]);- }- r- })-}--// Shared by the window and the command line, so both do exactly the same thing.-fn install_plugin(i: usize) -> Result<String, String> {- let p = &PLUGINS[i];- let (inst, uninst) = p.actions.ok_or(t!("установка недоступна", "installation is not available"))?;- let was = (p.installed)(); // already installed = an update: a failure must not remove the working copy- WARN.lock().unwrap().clear();- soft(t!("точка восстановления не создана", "restore point was not created"), checkpoint());- if let Err(e) = inst() {- log(&tf!("{}: ОШИБКА {e}", "{}: ERROR {e}", p.name));- if was {- return Err(e);- }- let back = uninst().err().map_or(String::new(), |u| tf!("; откат: {u}", "; rollback: {u}"));- return Err(tf!("{e} (установка отменена, изменения возвращены{back})", "{e} (installation cancelled, changes reverted{back})"));- }- let w = WARN.lock().unwrap().clone();- log(&format!("{}: {} {}", p.name, if was { t!("обновлён", "updated") } else { t!("установлен", "installed") }, w.join(" | ")));- let note = if w.is_empty() { String::new() } else { tf!(" Предупреждений: {} (см. %ProgramData%\\plugin-launcher\\install.log).", " Warnings: {} (see %ProgramData%\\plugin-launcher\\install.log).", w.len()) };- Ok(format!("{} {}.{note}", p.name, if was { t!("обновлён", "updated") } else { t!("установлен", "installed") }))-}--fn uninstall_plugin(i: usize) -> Result<String, String> {- let p = &PLUGINS[i];- let (_, uninst) = p.actions.ok_or(t!("удаление недоступно", "uninstall is not available"))?;- uninst().inspect_err(|e| log(&tf!("{}: ОШИБКА удаления {e}", "{}: uninstall ERROR {e}", p.name)))?;- log(&tf!("{}: удалён", "{}: removed", p.name));- Ok(tf!("{} удалён, система восстановлена.", "{} removed, system restored.", p.name))-}--fn rollback() -> Result<String, String> {- // reverse install order: rust-explorer (which switched Explorer off) goes before topbar, else the session is left with no panel and no shell- let errs: Vec<String> = PLUGINS.iter().rev().filter(|p| (p.installed)()).filter_map(|p| p.actions.and_then(|a| a.1().err().map(|e| format!("{}: {e}", p.name)))).collect();- if errs.is_empty() { Ok(t!("Все плагины удалены, система восстановлена.", "All plugins removed, system restored.").into()) } else { Err(errs.join("; ")) }-}--// ---------- command line -----------//-// plugin-launcher list-// plugin-launcher install <plugin> --yes (without --yes it only prints the warning: nothing is changed)-// plugin-launcher uninstall <plugin>-// plugin-launcher rollback --yes-// Exit code 0 = done, 1 = failed, 2 = bad arguments or --yes missing. Run it from an elevated terminal: the manifest-// demands admin, and from a normal one Windows opens a separate elevated console whose output is lost.--fn cli(args: &[String]) -> i32 {- // A windows-subsystem exe has no console of its own: use stdout if the caller redirected it (pipe, file),- // else attach to the parent's console and write to it directly.- let redirected = unsafe { !GetStdHandle(STD_OUTPUT_HANDLE).is_null() && GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE };- let mut out: Box<dyn Write> = if redirected {- Box::new(std::io::stdout())- } else {- unsafe { AttachConsole(ATTACH_PARENT_PROCESS) };- fs::OpenOptions::new().write(true).open("CONOUT$").map_or_else(|_| Box::new(std::io::sink()) as Box<dyn Write>, |f| Box::new(f))- };- let mut say = |s: &str| {- let _ = writeln!(out, "{s}");- };- let yes = args.iter().any(|a| a == "--yes");- let words: Vec<&str> = args.iter().map(String::as_str).filter(|a| *a != "--yes").collect();- let find = |n: &str| PLUGINS.iter().position(|p| p.name == n);- let usage = "usage: plugin-launcher list | install <plugin> --yes | update <plugin> | uninstall <plugin> | rollback --yes";- let result = match words.as_slice() {- ["list"] => {- for p in PLUGINS {- say(&format!("{:<16}{}", p.name, if p.actions.is_none() { "stub" } else if (p.installed)() { "installed" } else { "not installed" }));- }- return 0;- }- ["install", n] => match find(n) {- None => return { say(&format!("unknown plugin: {n}")); 2 },- Some(i) if !yes => return { say(&format!("{}\nNothing changed. Repeat with --yes to install {n}.", PLUGINS[i].warn.get())); 2 },- Some(i) if (PLUGINS[i].installed)() => return { say(&format!("{n} is already installed")); 0 },- Some(i) => install_plugin(i),- },- ["update", n] => match find(n) {- None => return { say(&format!("unknown plugin: {n}")); 2 },- Some(i) if !(PLUGINS[i].installed)() => return { say(&format!("{n} is not installed (use install)")); 2 },- Some(i) => install_plugin(i),- },- ["uninstall", n] => match find(n) {- None => return { say(&format!("unknown plugin: {n}")); 2 },- Some(i) if !(PLUGINS[i].installed)() => return { say(&format!("{n} is not installed")); 0 },- Some(i) => uninstall_plugin(i),- },- ["rollback"] if yes => rollback(),- ["rollback"] => return { say("Removes every installed plugin. Repeat with --yes."); 2 },- _ => return { say(usage); 2 },- };- match result {- Ok(m) => { say(&m); 0 }- Err(e) => { say(&format!("error: {e}")); 1 }- }-}--// ---------- drawing -----------//-// One back buffer per paint: GDI+ for the anti-aliased shapes, then GDI (ClearType) for text on top.--fn wide(s: &str) -> Vec<u16> {- s.encode_utf16().chain([0]).collect()-}--/// COLORREF (0x00BBGGRR) + alpha -> GDI+ ARGB.-const fn argb(c: u32, a: u8) -> u32 {- (a as u32) << 24 | (c & 255) << 16 | (c >> 8 & 255) << 8 | (c >> 16 & 255)-}--fn lerp(a: u32, b: u32, t: f32) -> u32 {- let m = |sh: u32| (((a >> sh & 255) as f32) * (1.0 - t) + ((b >> sh & 255) as f32) * t) as u32;- m(0) | m(8) << 8 | m(16) << 16-}--type Box4 = [f32; 4]; // left, top, right, bottom in logical px--struct Ui {- dc: HDC,- g: *mut GpGraphics,- s: f32,-}-impl Ui {- fn px(&self, v: f32) -> i32 {- (v * self.s).round() as i32- }- unsafe fn shape(&self, b: Box4, rad: f32, color: u32) {- let (s, mut path) = (self.s, null_mut::<GpPath>());- let (x, y, w, h) = (b[0] * s, b[1] * s, (b[2] - b[0]) * s, (b[3] - b[1]) * s);- let d = (rad * 2.0 * s).min(h).min(w).max(0.01);- GdipCreatePath(FillModeAlternate, &mut path);- GdipAddPathArc(path, x, y, d, d, 180.0, 90.0);- GdipAddPathArc(path, x + w - d, y, d, d, 270.0, 90.0);- GdipAddPathArc(path, x + w - d, y + h - d, d, d, 0.0, 90.0);- GdipAddPathArc(path, x, y + h - d, d, d, 90.0, 90.0);- GdipClosePathFigure(path);- let mut br = null_mut::<GpSolidFill>();- GdipCreateSolidFill(color, &mut br);- GdipFillPath(self.g, br as *mut GpBrush, path);- GdipDeleteBrush(br as *mut GpBrush);- GdipDeletePath(path);- }- /// Rounded box with a 1 px outline (`line` == `fill` for none).- unsafe fn round(&self, b: Box4, rad: f32, fill: u32, line: u32) {- if line != fill {- self.shape(b, rad, argb(line, 255));- let i = 1.0 / self.s;- self.shape([b[0] + i, b[1] + i, b[2] - i, b[3] - i], rad - i, argb(fill, 255));- } else {- self.shape(b, rad, argb(fill, 255));- }- }- unsafe fn font(&self, size: f32, weight: i32, face: &str) -> HFONT {- CreateFontW(-self.px(size), 0, 0, 0, weight, 0, 0, 0, 1, 0, 0, 5, 0, wide(face).as_ptr())- }- unsafe fn text_in(&self, s: &str, b: Box4, size: f32, weight: i32, color: u32, flags: u32, face: &str) {- let f = self.font(size, weight, face);- let of = SelectObject(self.dc, f);- SetTextColor(self.dc, color);- SetBkMode(self.dc, TRANSPARENT as i32);- let mut r = RECT { left: self.px(b[0]), top: self.px(b[1]), right: self.px(b[2]), bottom: self.px(b[3]) };- DrawTextW(self.dc, wide(s).as_ptr(), -1, &mut r, flags | DT_NOPREFIX);- SelectObject(self.dc, of);- DeleteObject(f);- }- unsafe fn text(&self, s: &str, b: Box4, size: f32, weight: i32, color: u32, flags: u32) {- self.text_in(s, b, size, weight, color, flags, "Segoe UI");- }- /// Width of a single line of text, logical px.- unsafe fn width(&self, s: &str, size: f32, weight: i32) -> f32 {- let f = self.font(size, weight, "Segoe UI");- let of = SelectObject(self.dc, f);- let mut r: RECT = zeroed();- DrawTextW(self.dc, wide(s).as_ptr(), -1, &mut r, DT_CALCRECT | DT_SINGLELINE | DT_NOPREFIX);- SelectObject(self.dc, of);- DeleteObject(f);- r.right as f32 / self.s- }-}--// layout, logical px-const WIN_W: f32 = 600.0;-const M: f32 = 24.0; // outer margin-const N_READY: usize = {- let (mut n, mut i) = (0, 0);- while i < PLUGINS.len() {- if PLUGINS[i].actions.is_some() && PLUGINS[i].bulk {- n += 1;- }- i += 1;- }- n-};-const LIST_TOP: f32 = 136.0;-const ROW_H: f32 = 62.0;-const LIST_H: f32 = N_READY as f32 * ROW_H + 12.0;-const MAIN_TOP: f32 = LIST_TOP + LIST_H + 20.0;-const MAIN_H: f32 = 54.0;-const FOOT_H: f32 = 72.0;-const WIN_H: f32 = MAIN_TOP + MAIN_H + 16.0 + FOOT_H;-const BTN_W: f32 = 136.0;-const BTN_H: f32 = 36.0;-// clickable things-const ID_MAIN: usize = 0;-const ID_ROLLBACK: usize = 1;-const ID_OK: usize = 2;-const ID_CANCEL: usize = 3;-const ID_SWITCH: usize = 4;-const ID_GEAR: usize = 5;-const ID_LANG: usize = 6; // EN / RU switch-const STARTING: usize = usize::MAX - 1; // JOB before install_all picks its first component--/// Installable components, in install order (topbar comes before rust-explorer, which needs it).-fn ready() -> impl Iterator<Item = usize> {- (0..PLUGINS.len()).filter(|&i| PLUGINS[i].actions.is_some() && PLUGINS[i].bulk)-}--fn row_box(k: usize, w: f32) -> Box4 {- let t = LIST_TOP + 6.0 + k as f32 * ROW_H;- [M + 6.0, t, w - M - 6.0, t + ROW_H]-}--/// Settings gear at the right end of the row of the plugin that has settings (topbar): (plugin index, box).-fn gear_box(w: f32) -> Option<(usize, Box4)> {- let (k, i) = ready().enumerate().find(|&(_, i)| PLUGINS[i].settings)?;- let r = row_box(k, w);- let t = r[1] + (ROW_H - 32.0) / 2.0;- Some((i, [r[2] - 14.0 - 32.0, t, r[2] - 14.0, t + 32.0]))-}--fn main_box(w: f32) -> Box4 {- [M, MAIN_TOP, w - M, MAIN_TOP + MAIN_H]-}--/// On/off switch inside the settings panel row.-fn switch_box(w: f32) -> Box4 {- let (d, _, _) = dialog_boxes(w);- [d[2] - 24.0 - 16.0 - 44.0, d[1] + 78.0 + 23.0, d[2] - 24.0 - 16.0, d[1] + 78.0 + 47.0]-}--/// The EN / RU switch in the top right corner of the header.-fn lang_box(w: f32) -> Box4 {- [w - M - 96.0, 18.0, w - M, 18.0 + 30.0]-}--fn rollback_box(w: f32) -> Box4 {- let t = WIN_H - FOOT_H + (FOOT_H - BTN_H) / 2.0;- [w - M - 150.0, t, w - M, t + BTN_H]-}--/// Dialog panel and its (cancel, ok) buttons.-fn dialog_boxes(w: f32) -> (Box4, Box4, Box4) {- let (dw, dh) = (528.0, 352.0);- let (l, t) = ((w - dw) / 2.0, (WIN_H - dh) / 2.0);- let (bt, r) = (t + dh - 24.0 - BTN_H, l + dw - 24.0);- ([l, t, l + dw, t + dh], [r - BTN_W - 10.0 - 120.0, bt, r - BTN_W - 10.0, bt + BTN_H], [r - BTN_W, bt, r, bt + BTN_H])-}--/// A button: `kind` 0 = primary (accent), 1 = secondary (outline), 2 = danger (outline, red text), 3 = disabled.-unsafe fn button(ui: &Ui, b: Box4, label: &str, kind: u8, hot: bool) {- let (fill, line, fg) = match kind {- 0 => (ACCENT, ACCENT, rgb(255, 255, 255)),- 1 => (PANEL, BORDER, TEXT),- 2 => (PANEL, BORDER, BAD),- _ => (PANEL, lerp(PANEL, BORDER, 0.6), lerp(DIM, PANEL, 0.35)),- };- let fill = if hot && kind != 3 { lerp(fill, TEXT, if kind == 0 { 0.14 } else { 0.07 }) } else { fill };- let line = if hot && kind == 2 { BAD } else if kind == 0 { fill } else { line };- ui.round(b, 8.0, fill, line);- ui.text(label, b, 13.5, 600, fg, DT_CENTER | DT_VCENTER | DT_SINGLELINE);-}--unsafe fn paint(hwnd: HWND) {- let mut ps: PAINTSTRUCT = zeroed();- let hdc = BeginPaint(hwnd, &mut ps);- let mut rc: RECT = zeroed();- GetClientRect(hwnd, &mut rc);- let (cw, ch) = (rc.right, rc.bottom);- let mem = CreateCompatibleDC(hdc);- let bmp = CreateCompatibleBitmap(hdc, cw, ch);- let ob = SelectObject(mem, bmp);- let s = GetDeviceCaps(hdc, LOGPIXELSX as i32) as f32 / 96.0;- let bgb = CreateSolidBrush(BG);- FillRect(mem, &rc, bgb);- DeleteObject(bgb);- let mut g = null_mut::<GpGraphics>();- GdipCreateFromHDC(mem, &mut g);- GdipSetSmoothingMode(g, SmoothingModeAntiAlias);- let ui = Ui { dc: mem, g, s };- let w = cw as f32 / s;- let hover = HOVER.get();- let dialog = DIALOG.with_borrow(|d| d.as_ref().map(|d| (d.title.clone(), d.text.clone(), d.ok.clone(), d.danger)));- let hot = |id: usize| hover == Some(id);- let busy = BUSY.load(Relaxed);- let job = JOB.load(Relaxed);- let n = PLUGINS.len();- let n_inst = ready().filter(|&i| INSTALLED[i].load(Relaxed)).count();-- // header: logo + name- ui.shape([0.0, 0.0, w, 3.0], 0.0, argb(ACCENT, 255));- let logo = [M, 30.0, M + 60.0, 90.0];- ui.round(logo, 16.0, ACCENT, ACCENT);- let inner = lerp(ACCENT, BG, 0.12);- ui.round([logo[0] + 4.0, logo[1] + 4.0, logo[2] - 4.0, logo[3] - 4.0], 13.0, inner, inner);- ui.text("W", [logo[0], logo[1] - 2.0, logo[2], logo[3]], 32.0, 900, rgb(255, 255, 255), DT_CENTER | DT_VCENTER | DT_SINGLELINE);- let tx = logo[2] + 18.0;- ui.text("WinRust", [tx, 28.0, w - M, 64.0], 30.0, 700, TEXT, DT_LEFT | DT_SINGLELINE | DT_VCENTER);- ui.text(&tf!("Оболочка Windows на Rust \u{00B7} установлено {n_inst} из {N_READY}", "A Windows shell in Rust \u{00B7} {n_inst} of {N_READY} installed"), [tx, 64.0, w - M, 88.0], 13.0, 400, DIM, DT_LEFT | DT_SINGLELINE | DT_VCENTER);- ui.text(t!("ВХОДИТ В СОСТАВ", "INCLUDED"), [M + 4.0, LIST_TOP - 26.0, w - M, LIST_TOP - 6.0], 11.0, 700, DIM, DT_LEFT | DT_SINGLELINE | DT_VCENTER);-- // component list- ui.round([M, LIST_TOP, w - M, LIST_TOP + LIST_H], 12.0, PANEL, BORDER);- let pos = ready().position(|i| i == job); // where install_all is now- let gear = gear_box(w);- for (k, i) in ready().enumerate() {- let p = &PLUGINS[i];- let r = row_box(k, w);- let installed = INSTALLED[i].load(Relaxed);- let working = busy && (job == i || (job == n && installed));- let queued = busy && !installed && (job == STARTING || pos.is_some_and(|q| k > q));- if k > 0 {- ui.shape([r[0] + 12.0, r[1], r[2] - 12.0, r[1] + 1.0 / s], 0.0, argb(BORDER, 255));- }- if working {- let t = lerp(PANEL, ACCENT, 0.10);- ui.round([r[0], r[1] + 3.0, r[2], r[3] - 3.0], 9.0, t, t);- }- let tile = [r[0] + 10.0, r[1] + 13.0, r[0] + 46.0, r[1] + 49.0];- let lit = installed || working;- let tint = if lit { lerp(PANEL, ACCENT, 0.20) } else { lerp(PANEL, TEXT, 0.06) };- ui.round(tile, 9.0, tint, tint);- ui.text_in(p.glyph, tile, 16.0, 400, if lit { ACCENT } else { TEXT }, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");-- let (pill, pc) = if working {- (if job == n { t!("Удаление…", "Removing…") } else { t!("Установка…", "Installing…") }, ACCENT)- } else if installed {- (t!("Установлен", "Installed"), GOOD)- } else if queued {- (t!("В очереди", "Queued"), DIM)- } else {- (t!("Не установлен", "Not installed"), DIM)- };- let pr = r[2] - 14.0 - 32.0 - 10.0;- let pw = ui.width(pill, 11.5, 600) + 18.0;- let pb = [pr - pw, r[1] + 21.0, pr, r[1] + 41.0];- let ptint = lerp(PANEL, pc, 0.16);- ui.round(pb, 10.0, ptint, ptint);- ui.text(pill, pb, 11.5, 600, pc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);-- let nx = tile[2] + 14.0;- ui.text(p.name, [nx, r[1] + 11.0, pb[0] - 10.0, r[1] + 32.0], 14.5, 600, TEXT, DT_LEFT | DT_SINGLELINE | DT_VCENTER);- let desc = p.desc.get();- let short = desc.split(". ").next().unwrap_or(desc).trim_end_matches('.');- ui.text(short, [nx, r[1] + 32.0, pb[0] - 10.0, r[3] - 10.0], 12.0, 400, DIM, DT_LEFT | DT_SINGLELINE | DT_END_ELLIPSIS);-- if let Some((_, gb)) = gear.filter(|&(gi, _)| gi == i && installed) {- let h = hot(ID_GEAR) && !busy;- ui.round(gb, 8.0, if h { lerp(PANEL, TEXT, 0.08) } else { PANEL }, BORDER);- ui.text_in("\u{E713}", gb, 14.0, 400, if busy { DIM } else { TEXT }, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");- }- }-- // the one button: installs everything that is missing (or updates all when nothing is)- let mb = main_box(w);- if busy {- let base = lerp(PANEL, ACCENT, 0.22);- ui.round(mb, 12.0, base, base);- let done = if job == n { 0.0 } else { pos.map_or(0.0, |q| (q as f32 + 0.5) / N_READY as f32) };- if done > 0.0 {- ui.shape([mb[0], mb[1], mb[0] + (mb[2] - mb[0]) * done, mb[3]], 12.0, argb(ACCENT, 255));- }- let label = if job == n {- t!("Удаление WinRust…", "Removing WinRust…").to_string()- } else {- pos.map_or(t!("Подготовка…", "Preparing…").into(), |q| tf!("Устанавливается {} ({} из {N_READY})", "Installing {} ({} of {N_READY})", PLUGINS[job].name, q + 1))- };- ui.text(&label, mb, 15.5, 700, TEXT, DT_CENTER | DT_VCENTER | DT_SINGLELINE);- } else {- let all = n_inst == N_READY;- let label = if all {- t!("Обновить WinRust", "Update WinRust").to_string()- } else if n_inst == 0 {- t!("Установить WinRust", "Install WinRust").into()- } else {- tf!("Доустановить WinRust ({} из {N_READY})", "Finish installing WinRust ({} of {N_READY})", N_READY - n_inst)- };- let (fill, fg) = if all { (PANEL, TEXT) } else { (ACCENT, rgb(255, 255, 255)) };- let fill = if hot(ID_MAIN) { lerp(fill, TEXT, if all { 0.07 } else { 0.14 }) } else { fill };- ui.round(mb, 12.0, fill, if all { BORDER } else { fill });- let tw = ui.width(&label, 16.0, 700);- let cx = (mb[0] + mb[2]) / 2.0 + 13.0;- ui.text_in(if all { "\u{E72C}" } else { "\u{E896}" }, [cx - tw / 2.0 - 30.0, mb[1], cx - tw / 2.0 - 6.0, mb[3]], 15.0, 400, fg, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");- ui.text(&label, [cx - tw / 2.0, mb[1], cx + tw / 2.0 + 4.0, mb[3]], 16.0, 700, fg, DT_LEFT | DT_VCENTER | DT_SINGLELINE);- }-- // footer: status on the left, remove-all on the right- let ft = WIN_H - FOOT_H;- ui.shape([M, ft, w - M, ft + 1.0 / s], 0.0, argb(BORDER, 255));- let (m, ok) = MSG.lock().unwrap().clone();- let (m, dot, fg) = if busy {- (t!("Выполняется, не закрывайте окно…", "Working, do not close the window…").to_string(), ACCENT, DIM)- } else if m.is_empty() {- (t!("Перед установкой создаётся точка восстановления.", "A restore point is created before installing.").into(), DIM, DIM)- } else if ok {- (m, GOOD, TEXT)- } else {- (m, BAD, BAD)- };- let rb = rollback_box(w);- ui.shape([M, ft + FOOT_H / 2.0 - 4.0, M + 8.0, ft + FOOT_H / 2.0 + 4.0], 4.0, argb(dot, 255));- let one_line = ui.width(&m, 12.5, 400) < rb[0] - 16.0 - M - 18.0;- let tb = [M + 18.0, ft + if one_line { 0.0 } else { 12.0 }, rb[0] - 16.0, WIN_H - if one_line { 0.0 } else { 8.0 }];- ui.text(&m, tb, 12.5, 400, fg, DT_LEFT | DT_END_ELLIPSIS | if one_line { DT_SINGLELINE | DT_VCENTER } else { DT_WORDBREAK });- button(&ui, rb, t!("Удалить всё", "Remove all"), if n_inst > 0 && !busy { 2 } else { 3 }, hot(ID_ROLLBACK));- // shows the language you would switch to; the other WinRust programs pick the choice up when they start- button(&ui, lang_box(w), if i18n::english() { "Русский" } else { "English" }, 1, hot(ID_LANG));-- // confirmation dialog over the dimmed window- if let Some((title, text, ok_label, danger)) = dialog {- ui.shape([0.0, 0.0, w, WIN_H + 1.0], 0.0, argb(0, 160));- let (d, cancel, okb) = dialog_boxes(w);- ui.round(d, 14.0, lerp(PANEL, BG, 0.25), BORDER);- let accent = if danger { BAD } else { ACCENT };- let icon = [d[0] + 24.0, d[1] + 24.0, d[0] + 60.0, d[1] + 60.0];- let tint = lerp(PANEL, accent, 0.18);- ui.round(icon, 18.0, tint, tint);- ui.text_in(if danger { "\u{E7BA}" } else { "\u{E946}" }, icon, 16.0, 400, accent, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");- ui.text(&title, [icon[2] + 14.0, d[1] + 24.0, d[2] - 24.0, d[1] + 60.0], 17.0, 600, TEXT, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);- ui.text(&text, [d[0] + 24.0, d[1] + 76.0, d[2] - 24.0, cancel[1] - 12.0], 12.5, 400, DIM, DT_LEFT | DT_WORDBREAK | DT_END_ELLIPSIS);- button(&ui, cancel, t!("Отмена", "Cancel"), 1, hot(ID_CANCEL));- let okfill = if hot(ID_OK) { lerp(accent, TEXT, 0.14) } else { accent };- ui.round(okb, 8.0, okfill, okfill);- ui.text(&ok_label, okb, 13.5, 600, rgb(255, 255, 255), DT_CENTER | DT_VCENTER | DT_SINGLELINE);- }-- // settings panel of a plugin (topbar: OneDrive switch)- if let Some(i) = SETTINGS.get() {- ui.shape([0.0, 0.0, w, WIN_H + 1.0], 0.0, argb(0, 160));- let (d, _, closeb) = dialog_boxes(w);- ui.round(d, 14.0, lerp(PANEL, BG, 0.25), BORDER);- let icon = [d[0] + 24.0, d[1] + 24.0, d[0] + 60.0, d[1] + 60.0];- let tint = lerp(PANEL, ACCENT, 0.18);- ui.round(icon, 18.0, tint, tint);- ui.text_in("\u{E713}", icon, 16.0, 400, ACCENT, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");- ui.text(&tf!("Настройки {}", "{} settings", PLUGINS[i].name), [icon[2] + 14.0, d[1] + 24.0, d[2] - 24.0, d[1] + 60.0], 17.0, 600, TEXT, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);- let row = [d[0] + 24.0, d[1] + 78.0, d[2] - 24.0, d[1] + 148.0];- let hid = od_hidden();- ui.round(row, 10.0, PANEL, BORDER);- ui.text(t!("Отключение OneDrive", "Disable OneDrive"), [row[0] + 16.0, row[1] + 10.0, row[2] - 80.0, row[1] + 32.0], 14.0, 600, TEXT, DT_LEFT | DT_SINGLELINE | DT_VCENTER);- ui.text(t!("Значок OneDrive не показывается в топбаре (по умолчанию). Синхронизация продолжает работать.", "The OneDrive icon is not shown in the bar (default). Sync keeps working."), [row[0] + 16.0, row[1] + 32.0, row[2] - 80.0, row[3] - 6.0], 12.0, 400, DIM, DT_LEFT | DT_WORDBREAK);- let sw = switch_box(w);- let off = lerp(PANEL, TEXT, 0.25);- let track = if hid { ACCENT } else { off };- ui.round(sw, 12.0, track, track);- let kx = if hid { sw[2] - 12.0 } else { sw[0] + 12.0 };- ui.round([kx - 8.0, sw[1] + 4.0, kx + 8.0, sw[3] - 4.0], 8.0, TEXT, TEXT);- button(&ui, closeb, t!("Закрыть", "Close"), 1, hot(ID_CANCEL));- }-- GdipDeleteGraphics(g);- BitBlt(hdc, 0, 0, cw, ch, mem, 0, 0, SRCCOPY);- SelectObject(mem, ob);- DeleteObject(bmp);- DeleteDC(mem);- EndPaint(hwnd, &ps);-}--// ---------- window ------------/// What a confirmed dialog runs.-#[derive(Clone, Copy)]-enum Act {- InstallAll,- Rollback,-}-struct Dialog {- title: String,- text: String,- ok: String,- danger: bool,- act: Act,-}-thread_local! { static DIALOG: std::cell::RefCell<Option<Dialog>> = const { std::cell::RefCell::new(None) }; }--/// Clickable thing under the cursor (ID_*). While a panel is up only its buttons count; while a job runs nothing does.-unsafe fn hit(hwnd: HWND, lp: isize) -> Option<usize> {- let (x, y) = ((lp & 0xFFFF) as i16 as f32, ((lp >> 16) & 0xFFFF) as i16 as f32);- let (mut rc, dc): (RECT, _) = (zeroed(), GetDC(hwnd));- let s = GetDeviceCaps(dc, LOGPIXELSX as i32) as f32 / 96.0;- ReleaseDC(hwnd, dc);- GetClientRect(hwnd, &mut rc);- let w = rc.right as f32 / s;- let inside = |b: Box4| x >= b[0] * s && x <= b[2] * s && y >= b[1] * s && y <= b[3] * s;- if SETTINGS.get().is_some() {- let (_, _, closeb) = dialog_boxes(w);- return if inside(switch_box(w)) { Some(ID_SWITCH) } else if inside(closeb) { Some(ID_CANCEL) } else { None };- }- if DIALOG.with_borrow(|d| d.is_some()) {- let (_, cancel, ok) = dialog_boxes(w);- return if inside(ok) { Some(ID_OK) } else if inside(cancel) { Some(ID_CANCEL) } else { None };- }- if BUSY.load(Relaxed) {- return None;- }- if gear_box(w).is_some_and(|(i, b)| INSTALLED[i].load(Relaxed) && inside(b)) {- return Some(ID_GEAR);- }- if inside(lang_box(w)) {- return Some(ID_LANG);- }- if inside(main_box(w)) {- return Some(ID_MAIN);- }- (INSTALLED.iter().any(|f| f.load(Relaxed)) && inside(rollback_box(w))).then_some(ID_ROLLBACK)-}--/// Runs `job` off the UI thread; its Ok/Err text becomes the status line. `which` = plugin index, n = rollback.-fn start(hwnd: HWND, which: usize, job: impl FnOnce() -> Result<String, String> + Send + 'static) {- JOB.store(which, Relaxed);- BUSY.store(true, Relaxed);- HOVER.set(None);- unsafe { InvalidateRect(hwnd, null(), 0) };- let h = hwnd as isize;- thread::spawn(move || {- *MSG.lock().unwrap() = match job() {- Ok(m) => (m, true),- Err(e) => (tf!("Ошибка: {e}", "Error: {e}"), false),- };- refresh();- BUSY.store(false, Relaxed);- unsafe { PostMessageW(h as HWND, WM_DONE, 0, 0) };- });-}--/// One click: every component that is missing, in order (all of them again = update when nothing is missing).-/// Stops at the first failure: rust-explorer must not go on without topbar. `h` = window to repaint between steps.-fn install_all(h: isize) -> Result<String, String> {- let all = ready().all(|i| (PLUGINS[i].installed)());- let (mut done, mut warned) = (Vec::new(), false);- for i in ready() {- if !all && (PLUGINS[i].installed)() {- continue;- }- JOB.store(i, Relaxed);- unsafe { InvalidateRect(h as HWND, null(), 0) };- if let Err(e) = install_plugin(i) {- let ok = if done.is_empty() { String::new() } else { tf!(" Уже готово: {}.", " Already done: {}.", done.join(", ")) };- return Err(format!("{}: {e}.{ok}", PLUGINS[i].name));- }- warned |= !WARN.lock().unwrap().is_empty(); // install_plugin clears the list for each component- done.push(PLUGINS[i].name);- refresh();- }- let note = if warned { t!(" Есть предупреждения (см. %ProgramData%\\plugin-launcher\\install.log).", " There are warnings (see %ProgramData%\\plugin-launcher\\install.log).") } else { "" };- Ok(format!("WinRust {}: {}.{note}", if all { t!("обновлён", "updated") } else { t!("установлен", "installed") }, done.join(", ")))-}--unsafe fn ask(hwnd: HWND, d: Dialog) {- DIALOG.set(Some(d));- HOVER.set(None);- InvalidateRect(hwnd, null(), 0);-}--unsafe fn close_dialog(hwnd: HWND, run: bool) {- let Some(d) = DIALOG.take() else { return };- HOVER.set(None);- InvalidateRect(hwnd, null(), 0);- if !run {- return;- }- match d.act {- Act::Rollback => start(hwnd, PLUGINS.len(), rollback),- Act::InstallAll => {- let h = hwnd as isize;- start(hwnd, STARTING, move || install_all(h))- }- }-}--unsafe fn click(hwnd: HWND, id: usize) {- if SETTINGS.get().is_some() {- if id == ID_SWITCH {- if let Err(e) = set_od_hidden(!od_hidden()) {- *MSG.lock().unwrap() = (tf!("Ошибка: {e}", "Error: {e}"), false);- }- } else if id == ID_CANCEL {- SETTINGS.set(None);- }- HOVER.set(None);- InvalidateRect(hwnd, null(), 0);- return;- }- if id == ID_OK || id == ID_CANCEL {- return close_dialog(hwnd, id == ID_OK);- }- if BUSY.load(Relaxed) {- return;- }- match id {- ID_LANG => {- i18n::set_english(!i18n::english());- HOVER.set(None);- InvalidateRect(hwnd, null(), 0);- }- ID_GEAR => {- SETTINGS.set(PLUGINS.iter().position(|p| p.settings));- HOVER.set(None);- InvalidateRect(hwnd, null(), 0);- }- ID_ROLLBACK => ask(hwnd, Dialog {- title: t!("Удалить WinRust?", "Remove WinRust?").into(),- text: t!("Все компоненты будут удалены. Вернутся поиск Windows, стандартный диспетчер задач, панель задач и обычный Проводник.", "All components will be removed. Windows Search, the stock Task Manager, the taskbar and regular Explorer come back.").into(),- ok: t!("Удалить всё", "Remove all").into(),- danger: true,- act: Act::Rollback,- }),- ID_MAIN if ready().all(|i| INSTALLED[i].load(Relaxed)) => ask(hwnd, Dialog {- title: t!("Обновить WinRust?", "Update WinRust?").into(),- text: t!("Все компоненты будут переустановлены из этой версии установщика. Настройки сохранятся.", "All components will be reinstalled from this version of the installer. Settings are kept.").into(),- ok: t!("Обновить", "Update").into(),- danger: false,- act: Act::InstallAll,- }),- ID_MAIN => ask(hwnd, Dialog {- title: t!("Установить WinRust?", "Install WinRust?").into(),- text: t!("Компоненты Windows будут заменены:\n\u{2022} поиск Windows отключается, вместо него rust-search (Alt+Space);\n\u{2022} диспетчер задач заменяется на rtaskmgr;\n\u{2022} панель задач заменяется на topbar (внизу экрана);\n\u{2022} Проводник как оболочка отключается: папки и рабочий стол открывает rust-explorer, отключаются службы телеметрии.\n\nСоздаётся точка восстановления, «Удалить всё» вернёт систему. Если экран останется пустым: Ctrl+Alt+Del \u{2192} Диспетчер задач \u{2192} Запустить explorer.exe.", "Windows components will be replaced:\n\u{2022} Windows Search is disabled, rust-search (Alt+Space) takes its place;\n\u{2022} Task Manager is replaced by rtaskmgr;\n\u{2022} the taskbar is replaced by topbar (at the bottom of the screen);\n\u{2022} Explorer as the shell is disabled: rust-explorer opens folders and the desktop, telemetry services are disabled.\n\nA restore point is created, 'Remove all' restores the system. If the screen stays empty: Ctrl+Alt+Del \u{2192} Task Manager \u{2192} Run explorer.exe.").into(),- ok: t!("Установить", "Install").into(),- danger: false,- act: Act::InstallAll,- }),- _ => {}- }-}--unsafe extern "system" fn proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {- match msg {- WM_PAINT => paint(hwnd),- WM_ERASEBKGND => return 1,- WM_MOUSEMOVE => {- let h = hit(hwnd, lp);- if h != HOVER.get() {- HOVER.set(h);- InvalidateRect(hwnd, null(), 0);- }- let mut t = TRACKMOUSEEVENT { cbSize: size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 };- TrackMouseEvent(&mut t);- }- WM_SETCURSOR if (lp & 0xFFFF) as u32 == HTCLIENT => {- SetCursor(LoadCursorW(null_mut(), if HOVER.get().is_some() { IDC_HAND } else { IDC_ARROW }));- return 1;- }- WM_MOUSELEAVE => {- HOVER.set(None);- InvalidateRect(hwnd, null(), 0);- }- WM_LBUTTONUP => {- if let Some(i) = hit(hwnd, lp) {- click(hwnd, i);- }- }- WM_KEYDOWN if SETTINGS.get().is_some() && wp as u16 == VK_ESCAPE => {- SETTINGS.set(None);- InvalidateRect(hwnd, null(), 0);- }- WM_KEYDOWN if DIALOG.with_borrow(|d| d.is_some()) => match wp as u16 {- VK_ESCAPE => close_dialog(hwnd, false),- VK_RETURN if DIALOG.with_borrow(|d| d.as_ref().is_some_and(|d| !d.danger)) => close_dialog(hwnd, true), // a dangerous one needs the click-- _ => {}- },- WM_DONE => {- InvalidateRect(hwnd, null(), 0);- }- WM_CLOSE if BUSY.load(Relaxed) => {} // closing mid-install would leave the system half-changed- WM_DESTROY => PostQuitMessage(0),- _ => return DefWindowProcW(hwnd, msg, wp, lp),- }- 0-}-fn main() {let args: Vec<String> = env::args().skip(1).collect();if !args.is_empty() {diff --git a/src/ui.rs b/src/ui.rsnew file mode 100644index 0000000..0df75b3--- /dev/null+++ b/src/ui.rs@@ -0,0 +1,583 @@+//! The window: drawing (GDI+ shapes, GDI text), layout, dialogs and the message loop handler.+use crate::*;++// ---------- drawing ----------+//+// One back buffer per paint: GDI+ for the anti-aliased shapes, then GDI (ClearType) for text on top.++pub(crate) fn wide(s: &str) -> Vec<u16> {+ s.encode_utf16().chain([0]).collect()+}++/// COLORREF (0x00BBGGRR) + alpha -> GDI+ ARGB.+pub(crate) const fn argb(c: u32, a: u8) -> u32 {+ (a as u32) << 24 | (c & 255) << 16 | (c >> 8 & 255) << 8 | (c >> 16 & 255)+}++pub(crate) fn lerp(a: u32, b: u32, t: f32) -> u32 {+ let m = |sh: u32| (((a >> sh & 255) as f32) * (1.0 - t) + ((b >> sh & 255) as f32) * t) as u32;+ m(0) | m(8) << 8 | m(16) << 16+}++pub(crate) type Box4 = [f32; 4]; // left, top, right, bottom in logical px++pub(crate) struct Ui {+ dc: HDC,+ g: *mut GpGraphics,+ s: f32,+}+impl Ui {+ fn px(&self, v: f32) -> i32 {+ (v * self.s).round() as i32+ }+ unsafe fn shape(&self, b: Box4, rad: f32, color: u32) {+ let (s, mut path) = (self.s, null_mut::<GpPath>());+ let (x, y, w, h) = (b[0] * s, b[1] * s, (b[2] - b[0]) * s, (b[3] - b[1]) * s);+ let d = (rad * 2.0 * s).min(h).min(w).max(0.01);+ GdipCreatePath(FillModeAlternate, &mut path);+ GdipAddPathArc(path, x, y, d, d, 180.0, 90.0);+ GdipAddPathArc(path, x + w - d, y, d, d, 270.0, 90.0);+ GdipAddPathArc(path, x + w - d, y + h - d, d, d, 0.0, 90.0);+ GdipAddPathArc(path, x, y + h - d, d, d, 90.0, 90.0);+ GdipClosePathFigure(path);+ let mut br = null_mut::<GpSolidFill>();+ GdipCreateSolidFill(color, &mut br);+ GdipFillPath(self.g, br as *mut GpBrush, path);+ GdipDeleteBrush(br as *mut GpBrush);+ GdipDeletePath(path);+ }+ /// Rounded box with a 1 px outline (`line` == `fill` for none).+ unsafe fn round(&self, b: Box4, rad: f32, fill: u32, line: u32) {+ if line != fill {+ self.shape(b, rad, argb(line, 255));+ let i = 1.0 / self.s;+ self.shape([b[0] + i, b[1] + i, b[2] - i, b[3] - i], rad - i, argb(fill, 255));+ } else {+ self.shape(b, rad, argb(fill, 255));+ }+ }+ unsafe fn font(&self, size: f32, weight: i32, face: &str) -> HFONT {+ CreateFontW(-self.px(size), 0, 0, 0, weight, 0, 0, 0, 1, 0, 0, 5, 0, wide(face).as_ptr())+ }+ unsafe fn text_in(&self, s: &str, b: Box4, size: f32, weight: i32, color: u32, flags: u32, face: &str) {+ let f = self.font(size, weight, face);+ let of = SelectObject(self.dc, f);+ SetTextColor(self.dc, color);+ SetBkMode(self.dc, TRANSPARENT as i32);+ let mut r = RECT { left: self.px(b[0]), top: self.px(b[1]), right: self.px(b[2]), bottom: self.px(b[3]) };+ DrawTextW(self.dc, wide(s).as_ptr(), -1, &mut r, flags | DT_NOPREFIX);+ SelectObject(self.dc, of);+ DeleteObject(f);+ }+ unsafe fn text(&self, s: &str, b: Box4, size: f32, weight: i32, color: u32, flags: u32) {+ self.text_in(s, b, size, weight, color, flags, "Segoe UI");+ }+ /// Width of a single line of text, logical px.+ unsafe fn width(&self, s: &str, size: f32, weight: i32) -> f32 {+ let f = self.font(size, weight, "Segoe UI");+ let of = SelectObject(self.dc, f);+ let mut r: RECT = zeroed();+ DrawTextW(self.dc, wide(s).as_ptr(), -1, &mut r, DT_CALCRECT | DT_SINGLELINE | DT_NOPREFIX);+ SelectObject(self.dc, of);+ DeleteObject(f);+ r.right as f32 / self.s+ }+}++// layout, logical px+pub(crate) const WIN_W: f32 = 600.0;+pub(crate) const M: f32 = 24.0; // outer margin+pub(crate) const N_READY: usize = {+ let (mut n, mut i) = (0, 0);+ while i < PLUGINS.len() {+ if PLUGINS[i].actions.is_some() && PLUGINS[i].bulk {+ n += 1;+ }+ i += 1;+ }+ n+};+pub(crate) const LIST_TOP: f32 = 136.0;+pub(crate) const ROW_H: f32 = 62.0;+pub(crate) const LIST_H: f32 = N_READY as f32 * ROW_H + 12.0;+pub(crate) const MAIN_TOP: f32 = LIST_TOP + LIST_H + 20.0;+pub(crate) const MAIN_H: f32 = 54.0;+pub(crate) const FOOT_H: f32 = 72.0;+pub(crate) const WIN_H: f32 = MAIN_TOP + MAIN_H + 16.0 + FOOT_H;+pub(crate) const BTN_W: f32 = 136.0;+pub(crate) const BTN_H: f32 = 36.0;+// clickable things+pub(crate) const ID_MAIN: usize = 0;+pub(crate) const ID_ROLLBACK: usize = 1;+pub(crate) const ID_OK: usize = 2;+pub(crate) const ID_CANCEL: usize = 3;+pub(crate) const ID_SWITCH: usize = 4;+pub(crate) const ID_GEAR: usize = 5;+pub(crate) const ID_LANG: usize = 6; // EN / RU switch+pub(crate) const STARTING: usize = usize::MAX - 1; // JOB before install_all picks its first component++/// Installable components, in install order (topbar comes before rust-explorer, which needs it).+pub(crate) fn ready() -> impl Iterator<Item = usize> {+ (0..PLUGINS.len()).filter(|&i| PLUGINS[i].actions.is_some() && PLUGINS[i].bulk)+}++pub(crate) fn row_box(k: usize, w: f32) -> Box4 {+ let t = LIST_TOP + 6.0 + k as f32 * ROW_H;+ [M + 6.0, t, w - M - 6.0, t + ROW_H]+}++/// Settings gear at the right end of the row of the plugin that has settings (topbar): (plugin index, box).+pub(crate) fn gear_box(w: f32) -> Option<(usize, Box4)> {+ let (k, i) = ready().enumerate().find(|&(_, i)| PLUGINS[i].settings)?;+ let r = row_box(k, w);+ let t = r[1] + (ROW_H - 32.0) / 2.0;+ Some((i, [r[2] - 14.0 - 32.0, t, r[2] - 14.0, t + 32.0]))+}++pub(crate) fn main_box(w: f32) -> Box4 {+ [M, MAIN_TOP, w - M, MAIN_TOP + MAIN_H]+}++/// On/off switch inside the settings panel row.+pub(crate) fn switch_box(w: f32) -> Box4 {+ let (d, _, _) = dialog_boxes(w);+ [d[2] - 24.0 - 16.0 - 44.0, d[1] + 78.0 + 23.0, d[2] - 24.0 - 16.0, d[1] + 78.0 + 47.0]+}++/// The EN / RU switch in the top right corner of the header.+pub(crate) fn lang_box(w: f32) -> Box4 {+ [w - M - 96.0, 18.0, w - M, 18.0 + 30.0]+}++pub(crate) fn rollback_box(w: f32) -> Box4 {+ let t = WIN_H - FOOT_H + (FOOT_H - BTN_H) / 2.0;+ [w - M - 150.0, t, w - M, t + BTN_H]+}++/// Dialog panel and its (cancel, ok) buttons.+pub(crate) fn dialog_boxes(w: f32) -> (Box4, Box4, Box4) {+ let (dw, dh) = (528.0, 352.0);+ let (l, t) = ((w - dw) / 2.0, (WIN_H - dh) / 2.0);+ let (bt, r) = (t + dh - 24.0 - BTN_H, l + dw - 24.0);+ ([l, t, l + dw, t + dh], [r - BTN_W - 10.0 - 120.0, bt, r - BTN_W - 10.0, bt + BTN_H], [r - BTN_W, bt, r, bt + BTN_H])+}++/// A button: `kind` 0 = primary (accent), 1 = secondary (outline), 2 = danger (outline, red text), 3 = disabled.+pub(crate) unsafe fn button(ui: &Ui, b: Box4, label: &str, kind: u8, hot: bool) {+ let (fill, line, fg) = match kind {+ 0 => (ACCENT, ACCENT, rgb(255, 255, 255)),+ 1 => (PANEL, BORDER, TEXT),+ 2 => (PANEL, BORDER, BAD),+ _ => (PANEL, lerp(PANEL, BORDER, 0.6), lerp(DIM, PANEL, 0.35)),+ };+ let fill = if hot && kind != 3 { lerp(fill, TEXT, if kind == 0 { 0.14 } else { 0.07 }) } else { fill };+ let line = if hot && kind == 2 { BAD } else if kind == 0 { fill } else { line };+ ui.round(b, 8.0, fill, line);+ ui.text(label, b, 13.5, 600, fg, DT_CENTER | DT_VCENTER | DT_SINGLELINE);+}++pub(crate) unsafe fn paint(hwnd: HWND) {+ let mut ps: PAINTSTRUCT = zeroed();+ let hdc = BeginPaint(hwnd, &mut ps);+ let mut rc: RECT = zeroed();+ GetClientRect(hwnd, &mut rc);+ let (cw, ch) = (rc.right, rc.bottom);+ let mem = CreateCompatibleDC(hdc);+ let bmp = CreateCompatibleBitmap(hdc, cw, ch);+ let ob = SelectObject(mem, bmp);+ let s = GetDeviceCaps(hdc, LOGPIXELSX as i32) as f32 / 96.0;+ let bgb = CreateSolidBrush(BG);+ FillRect(mem, &rc, bgb);+ DeleteObject(bgb);+ let mut g = null_mut::<GpGraphics>();+ GdipCreateFromHDC(mem, &mut g);+ GdipSetSmoothingMode(g, SmoothingModeAntiAlias);+ let ui = Ui { dc: mem, g, s };+ let w = cw as f32 / s;+ let hover = HOVER.get();+ let dialog = DIALOG.with_borrow(|d| d.as_ref().map(|d| (d.title.clone(), d.text.clone(), d.ok.clone(), d.danger)));+ let hot = |id: usize| hover == Some(id);+ let busy = BUSY.load(Relaxed);+ let job = JOB.load(Relaxed);+ let n = PLUGINS.len();+ let n_inst = ready().filter(|&i| INSTALLED[i].load(Relaxed)).count();++ // header: logo + name+ ui.shape([0.0, 0.0, w, 3.0], 0.0, argb(ACCENT, 255));+ let logo = [M, 30.0, M + 60.0, 90.0];+ ui.round(logo, 16.0, ACCENT, ACCENT);+ let inner = lerp(ACCENT, BG, 0.12);+ ui.round([logo[0] + 4.0, logo[1] + 4.0, logo[2] - 4.0, logo[3] - 4.0], 13.0, inner, inner);+ ui.text("W", [logo[0], logo[1] - 2.0, logo[2], logo[3]], 32.0, 900, rgb(255, 255, 255), DT_CENTER | DT_VCENTER | DT_SINGLELINE);+ let tx = logo[2] + 18.0;+ ui.text("WinRust", [tx, 28.0, w - M, 64.0], 30.0, 700, TEXT, DT_LEFT | DT_SINGLELINE | DT_VCENTER);+ ui.text(&tf!("Оболочка Windows на Rust \u{00B7} установлено {n_inst} из {N_READY}", "A Windows shell in Rust \u{00B7} {n_inst} of {N_READY} installed"), [tx, 64.0, w - M, 88.0], 13.0, 400, DIM, DT_LEFT | DT_SINGLELINE | DT_VCENTER);+ ui.text(t!("ВХОДИТ В СОСТАВ", "INCLUDED"), [M + 4.0, LIST_TOP - 26.0, w - M, LIST_TOP - 6.0], 11.0, 700, DIM, DT_LEFT | DT_SINGLELINE | DT_VCENTER);++ // component list+ ui.round([M, LIST_TOP, w - M, LIST_TOP + LIST_H], 12.0, PANEL, BORDER);+ let pos = ready().position(|i| i == job); // where install_all is now+ let gear = gear_box(w);+ for (k, i) in ready().enumerate() {+ let p = &PLUGINS[i];+ let r = row_box(k, w);+ let installed = INSTALLED[i].load(Relaxed);+ let working = busy && (job == i || (job == n && installed));+ let queued = busy && !installed && (job == STARTING || pos.is_some_and(|q| k > q));+ if k > 0 {+ ui.shape([r[0] + 12.0, r[1], r[2] - 12.0, r[1] + 1.0 / s], 0.0, argb(BORDER, 255));+ }+ if working {+ let t = lerp(PANEL, ACCENT, 0.10);+ ui.round([r[0], r[1] + 3.0, r[2], r[3] - 3.0], 9.0, t, t);+ }+ let tile = [r[0] + 10.0, r[1] + 13.0, r[0] + 46.0, r[1] + 49.0];+ let lit = installed || working;+ let tint = if lit { lerp(PANEL, ACCENT, 0.20) } else { lerp(PANEL, TEXT, 0.06) };+ ui.round(tile, 9.0, tint, tint);+ ui.text_in(p.glyph, tile, 16.0, 400, if lit { ACCENT } else { TEXT }, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");++ let (pill, pc) = if working {+ (if job == n { t!("Удаление…", "Removing…") } else { t!("Установка…", "Installing…") }, ACCENT)+ } else if installed {+ (t!("Установлен", "Installed"), GOOD)+ } else if queued {+ (t!("В очереди", "Queued"), DIM)+ } else {+ (t!("Не установлен", "Not installed"), DIM)+ };+ let pr = r[2] - 14.0 - 32.0 - 10.0;+ let pw = ui.width(pill, 11.5, 600) + 18.0;+ let pb = [pr - pw, r[1] + 21.0, pr, r[1] + 41.0];+ let ptint = lerp(PANEL, pc, 0.16);+ ui.round(pb, 10.0, ptint, ptint);+ ui.text(pill, pb, 11.5, 600, pc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);++ let nx = tile[2] + 14.0;+ ui.text(p.name, [nx, r[1] + 11.0, pb[0] - 10.0, r[1] + 32.0], 14.5, 600, TEXT, DT_LEFT | DT_SINGLELINE | DT_VCENTER);+ let desc = p.desc.get();+ let short = desc.split(". ").next().unwrap_or(desc).trim_end_matches('.');+ ui.text(short, [nx, r[1] + 32.0, pb[0] - 10.0, r[3] - 10.0], 12.0, 400, DIM, DT_LEFT | DT_SINGLELINE | DT_END_ELLIPSIS);++ if let Some((_, gb)) = gear.filter(|&(gi, _)| gi == i && installed) {+ let h = hot(ID_GEAR) && !busy;+ ui.round(gb, 8.0, if h { lerp(PANEL, TEXT, 0.08) } else { PANEL }, BORDER);+ ui.text_in("\u{E713}", gb, 14.0, 400, if busy { DIM } else { TEXT }, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");+ }+ }++ // the one button: installs everything that is missing (or updates all when nothing is)+ let mb = main_box(w);+ if busy {+ let base = lerp(PANEL, ACCENT, 0.22);+ ui.round(mb, 12.0, base, base);+ let done = if job == n { 0.0 } else { pos.map_or(0.0, |q| (q as f32 + 0.5) / N_READY as f32) };+ if done > 0.0 {+ ui.shape([mb[0], mb[1], mb[0] + (mb[2] - mb[0]) * done, mb[3]], 12.0, argb(ACCENT, 255));+ }+ let label = if job == n {+ t!("Удаление WinRust…", "Removing WinRust…").to_string()+ } else {+ pos.map_or(t!("Подготовка…", "Preparing…").into(), |q| tf!("Устанавливается {} ({} из {N_READY})", "Installing {} ({} of {N_READY})", PLUGINS[job].name, q + 1))+ };+ ui.text(&label, mb, 15.5, 700, TEXT, DT_CENTER | DT_VCENTER | DT_SINGLELINE);+ } else {+ let all = n_inst == N_READY;+ let label = if all {+ t!("Обновить WinRust", "Update WinRust").to_string()+ } else if n_inst == 0 {+ t!("Установить WinRust", "Install WinRust").into()+ } else {+ tf!("Доустановить и обновить WinRust (новых: {})", "Install and update WinRust ({} new)", N_READY - n_inst)+ };+ let (fill, fg) = if all { (PANEL, TEXT) } else { (ACCENT, rgb(255, 255, 255)) };+ let fill = if hot(ID_MAIN) { lerp(fill, TEXT, if all { 0.07 } else { 0.14 }) } else { fill };+ ui.round(mb, 12.0, fill, if all { BORDER } else { fill });+ let tw = ui.width(&label, 16.0, 700);+ let cx = (mb[0] + mb[2]) / 2.0 + 13.0;+ ui.text_in(if all { "\u{E72C}" } else { "\u{E896}" }, [cx - tw / 2.0 - 30.0, mb[1], cx - tw / 2.0 - 6.0, mb[3]], 15.0, 400, fg, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");+ ui.text(&label, [cx - tw / 2.0, mb[1], cx + tw / 2.0 + 4.0, mb[3]], 16.0, 700, fg, DT_LEFT | DT_VCENTER | DT_SINGLELINE);+ }++ // footer: status on the left, remove-all on the right+ let ft = WIN_H - FOOT_H;+ ui.shape([M, ft, w - M, ft + 1.0 / s], 0.0, argb(BORDER, 255));+ let (m, ok) = MSG.lock().unwrap().clone();+ let (m, dot, fg) = if busy {+ (t!("Выполняется, не закрывайте окно…", "Working, do not close the window…").to_string(), ACCENT, DIM)+ } else if m.is_empty() {+ (t!("Перед установкой создаётся точка восстановления.", "A restore point is created before installing.").into(), DIM, DIM)+ } else if ok {+ (m, GOOD, TEXT)+ } else {+ (m, BAD, BAD)+ };+ let rb = rollback_box(w);+ ui.shape([M, ft + FOOT_H / 2.0 - 4.0, M + 8.0, ft + FOOT_H / 2.0 + 4.0], 4.0, argb(dot, 255));+ let one_line = ui.width(&m, 12.5, 400) < rb[0] - 16.0 - M - 18.0;+ let tb = [M + 18.0, ft + if one_line { 0.0 } else { 12.0 }, rb[0] - 16.0, WIN_H - if one_line { 0.0 } else { 8.0 }];+ ui.text(&m, tb, 12.5, 400, fg, DT_LEFT | DT_END_ELLIPSIS | if one_line { DT_SINGLELINE | DT_VCENTER } else { DT_WORDBREAK });+ button(&ui, rb, t!("Удалить всё", "Remove all"), if n_inst > 0 && !busy { 2 } else { 3 }, hot(ID_ROLLBACK));+ // shows the language you would switch to; the other WinRust programs pick the choice up when they start+ button(&ui, lang_box(w), if en!() { "Русский" } else { "English" }, 1, hot(ID_LANG));++ // confirmation dialog over the dimmed window+ if let Some((title, text, ok_label, danger)) = dialog {+ ui.shape([0.0, 0.0, w, WIN_H + 1.0], 0.0, argb(0, 160));+ let (d, cancel, okb) = dialog_boxes(w);+ ui.round(d, 14.0, lerp(PANEL, BG, 0.25), BORDER);+ let accent = if danger { BAD } else { ACCENT };+ let icon = [d[0] + 24.0, d[1] + 24.0, d[0] + 60.0, d[1] + 60.0];+ let tint = lerp(PANEL, accent, 0.18);+ ui.round(icon, 18.0, tint, tint);+ ui.text_in(if danger { "\u{E7BA}" } else { "\u{E946}" }, icon, 16.0, 400, accent, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");+ ui.text(&title, [icon[2] + 14.0, d[1] + 24.0, d[2] - 24.0, d[1] + 60.0], 17.0, 600, TEXT, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);+ ui.text(&text, [d[0] + 24.0, d[1] + 76.0, d[2] - 24.0, cancel[1] - 12.0], 12.5, 400, DIM, DT_LEFT | DT_WORDBREAK | DT_END_ELLIPSIS);+ button(&ui, cancel, t!("Отмена", "Cancel"), 1, hot(ID_CANCEL));+ let okfill = if hot(ID_OK) { lerp(accent, TEXT, 0.14) } else { accent };+ ui.round(okb, 8.0, okfill, okfill);+ ui.text(&ok_label, okb, 13.5, 600, rgb(255, 255, 255), DT_CENTER | DT_VCENTER | DT_SINGLELINE);+ }++ // settings panel of a plugin (topbar: OneDrive switch)+ if let Some(i) = SETTINGS.get() {+ ui.shape([0.0, 0.0, w, WIN_H + 1.0], 0.0, argb(0, 160));+ let (d, _, closeb) = dialog_boxes(w);+ ui.round(d, 14.0, lerp(PANEL, BG, 0.25), BORDER);+ let icon = [d[0] + 24.0, d[1] + 24.0, d[0] + 60.0, d[1] + 60.0];+ let tint = lerp(PANEL, ACCENT, 0.18);+ ui.round(icon, 18.0, tint, tint);+ ui.text_in("\u{E713}", icon, 16.0, 400, ACCENT, DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");+ ui.text(&tf!("Настройки {}", "{} settings", PLUGINS[i].name), [icon[2] + 14.0, d[1] + 24.0, d[2] - 24.0, d[1] + 60.0], 17.0, 600, TEXT, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);+ let row = [d[0] + 24.0, d[1] + 78.0, d[2] - 24.0, d[1] + 148.0];+ let hid = od_hidden();+ ui.round(row, 10.0, PANEL, BORDER);+ ui.text(t!("Отключение OneDrive", "Disable OneDrive"), [row[0] + 16.0, row[1] + 10.0, row[2] - 80.0, row[1] + 32.0], 14.0, 600, TEXT, DT_LEFT | DT_SINGLELINE | DT_VCENTER);+ ui.text(t!("Значок OneDrive не показывается в топбаре (по умолчанию). Синхронизация продолжает работать.", "The OneDrive icon is not shown in the bar (default). Sync keeps working."), [row[0] + 16.0, row[1] + 32.0, row[2] - 80.0, row[3] - 6.0], 12.0, 400, DIM, DT_LEFT | DT_WORDBREAK);+ let sw = switch_box(w);+ let off = lerp(PANEL, TEXT, 0.25);+ let track = if hid { ACCENT } else { off };+ ui.round(sw, 12.0, track, track);+ let kx = if hid { sw[2] - 12.0 } else { sw[0] + 12.0 };+ ui.round([kx - 8.0, sw[1] + 4.0, kx + 8.0, sw[3] - 4.0], 8.0, TEXT, TEXT);+ button(&ui, closeb, t!("Закрыть", "Close"), 1, hot(ID_CANCEL));+ }++ GdipDeleteGraphics(g);+ BitBlt(hdc, 0, 0, cw, ch, mem, 0, 0, SRCCOPY);+ SelectObject(mem, ob);+ DeleteObject(bmp);+ DeleteDC(mem);+ EndPaint(hwnd, &ps);+}++// ---------- window ----------++/// What a confirmed dialog runs.+#[derive(Clone, Copy)]+pub(crate) enum Act {+ InstallAll,+ Rollback,+}+pub(crate) struct Dialog {+ title: String,+ text: String,+ ok: String,+ danger: bool,+ act: Act,+}+thread_local! { pub(crate) static DIALOG: std::cell::RefCell<Option<Dialog>> = const { std::cell::RefCell::new(None) }; }++/// Clickable thing under the cursor (ID_*). While a panel is up only its buttons count; while a job runs nothing does.+pub(crate) unsafe fn hit(hwnd: HWND, lp: isize) -> Option<usize> {+ let (x, y) = ((lp & 0xFFFF) as i16 as f32, ((lp >> 16) & 0xFFFF) as i16 as f32);+ let (mut rc, dc): (RECT, _) = (zeroed(), GetDC(hwnd));+ let s = GetDeviceCaps(dc, LOGPIXELSX as i32) as f32 / 96.0;+ ReleaseDC(hwnd, dc);+ GetClientRect(hwnd, &mut rc);+ let w = rc.right as f32 / s;+ let inside = |b: Box4| x >= b[0] * s && x <= b[2] * s && y >= b[1] * s && y <= b[3] * s;+ if SETTINGS.get().is_some() {+ let (_, _, closeb) = dialog_boxes(w);+ return if inside(switch_box(w)) { Some(ID_SWITCH) } else if inside(closeb) { Some(ID_CANCEL) } else { None };+ }+ if DIALOG.with_borrow(|d| d.is_some()) {+ let (_, cancel, ok) = dialog_boxes(w);+ return if inside(ok) { Some(ID_OK) } else if inside(cancel) { Some(ID_CANCEL) } else { None };+ }+ if BUSY.load(Relaxed) {+ return None;+ }+ if gear_box(w).is_some_and(|(i, b)| INSTALLED[i].load(Relaxed) && inside(b)) {+ return Some(ID_GEAR);+ }+ if inside(lang_box(w)) {+ return Some(ID_LANG);+ }+ if inside(main_box(w)) {+ return Some(ID_MAIN);+ }+ (INSTALLED.iter().any(|f| f.load(Relaxed)) && inside(rollback_box(w))).then_some(ID_ROLLBACK)+}++/// Runs `job` off the UI thread; its Ok/Err text becomes the status line. `which` = plugin index, n = rollback.+pub(crate) fn start(hwnd: HWND, which: usize, job: impl FnOnce() -> Result<String, String> + Send + 'static) {+ JOB.store(which, Relaxed);+ BUSY.store(true, Relaxed);+ HOVER.set(None);+ unsafe { InvalidateRect(hwnd, null(), 0) };+ let h = hwnd as isize;+ thread::spawn(move || {+ *MSG.lock().unwrap() = match job() {+ Ok(m) => (m, true),+ Err(e) => (tf!("Ошибка: {e}", "Error: {e}"), false),+ };+ refresh();+ BUSY.store(false, Relaxed);+ unsafe { PostMessageW(h as HWND, WM_DONE, 0, 0) };+ });+}++/// One click: every component in order; missing ones are installed, installed ones updated from this installer.+/// Stops at the first failure: rust-explorer must not go on without topbar. `h` = window to repaint between steps.+pub(crate) fn install_all(h: isize) -> Result<String, String> {+ let all = ready().all(|i| (PLUGINS[i].installed)());+ let (mut done, mut warned) = (Vec::new(), false);+ for i in ready() {+ // installed ones are updated too: a newer installer must bring its fixes to them, not only add what is missing+ JOB.store(i, Relaxed);+ unsafe { InvalidateRect(h as HWND, null(), 0) };+ if let Err(e) = install_plugin(i) {+ let ok = if done.is_empty() { String::new() } else { tf!(" Уже готово: {}.", " Already done: {}.", done.join(", ")) };+ return Err(format!("{}: {e}.{ok}", PLUGINS[i].name));+ }+ warned |= !WARN.lock().unwrap().is_empty(); // install_plugin clears the list for each component+ done.push(PLUGINS[i].name);+ refresh();+ }+ let note = if warned { t!(" Есть предупреждения (см. %ProgramData%\\plugin-launcher\\install.log).", " There are warnings (see %ProgramData%\\plugin-launcher\\install.log).") } else { "" };+ Ok(format!("WinRust {}: {}.{note}", if all { t!("обновлён", "updated") } else { t!("установлен", "installed") }, done.join(", ")))+}++pub(crate) unsafe fn ask(hwnd: HWND, d: Dialog) {+ DIALOG.set(Some(d));+ HOVER.set(None);+ InvalidateRect(hwnd, null(), 0);+}++pub(crate) unsafe fn close_dialog(hwnd: HWND, run: bool) {+ let Some(d) = DIALOG.take() else { return };+ HOVER.set(None);+ InvalidateRect(hwnd, null(), 0);+ if !run {+ return;+ }+ match d.act {+ Act::Rollback => start(hwnd, PLUGINS.len(), rollback),+ Act::InstallAll => {+ let h = hwnd as isize;+ start(hwnd, STARTING, move || install_all(h))+ }+ }+}++pub(crate) unsafe fn click(hwnd: HWND, id: usize) {+ if SETTINGS.get().is_some() {+ if id == ID_SWITCH {+ if let Err(e) = set_od_hidden(!od_hidden()) {+ *MSG.lock().unwrap() = (tf!("Ошибка: {e}", "Error: {e}"), false);+ }+ } else if id == ID_CANCEL {+ SETTINGS.set(None);+ }+ HOVER.set(None);+ InvalidateRect(hwnd, null(), 0);+ return;+ }+ if id == ID_OK || id == ID_CANCEL {+ return close_dialog(hwnd, id == ID_OK);+ }+ if BUSY.load(Relaxed) {+ return;+ }+ match id {+ ID_LANG => {+ i18n::set_english(!i18n::english());+ HOVER.set(None);+ InvalidateRect(hwnd, null(), 0);+ }+ ID_GEAR => {+ SETTINGS.set(PLUGINS.iter().position(|p| p.settings));+ HOVER.set(None);+ InvalidateRect(hwnd, null(), 0);+ }+ ID_ROLLBACK => ask(hwnd, Dialog {+ title: t!("Удалить WinRust?", "Remove WinRust?").into(),+ text: t!("Все компоненты будут удалены. Вернутся поиск Windows, стандартный диспетчер задач, панель задач и обычный Проводник.", "All components will be removed. Windows Search, the stock Task Manager, the taskbar and regular Explorer come back.").into(),+ ok: t!("Удалить всё", "Remove all").into(),+ danger: true,+ act: Act::Rollback,+ }),+ ID_MAIN if ready().all(|i| INSTALLED[i].load(Relaxed)) => ask(hwnd, Dialog {+ title: t!("Обновить WinRust?", "Update WinRust?").into(),+ text: t!("Все компоненты будут переустановлены из этой версии установщика. Настройки сохранятся.", "All components will be reinstalled from this version of the installer. Settings are kept.").into(),+ ok: t!("Обновить", "Update").into(),+ danger: false,+ act: Act::InstallAll,+ }),+ ID_MAIN => ask(hwnd, Dialog {+ title: t!("Установить WinRust?", "Install WinRust?").into(),+ text: t!("Компоненты Windows будут заменены:\n\u{2022} поиск Windows отключается, вместо него rust-search (Alt+Space);\n\u{2022} диспетчер задач заменяется на rtaskmgr;\n\u{2022} панель задач заменяется на topbar (внизу экрана);\n\u{2022} Проводник как оболочка отключается: папки и рабочий стол открывает rust-explorer, отключаются службы телеметрии.\n\nСоздаётся точка восстановления, «Удалить всё» вернёт систему. Если экран останется пустым: Ctrl+Alt+Del \u{2192} Диспетчер задач \u{2192} Запустить explorer.exe.", "Windows components will be replaced:\n\u{2022} Windows Search is disabled, rust-search (Alt+Space) takes its place;\n\u{2022} Task Manager is replaced by rtaskmgr;\n\u{2022} the taskbar is replaced by topbar (at the bottom of the screen);\n\u{2022} Explorer as the shell is disabled: rust-explorer opens folders and the desktop, telemetry services are disabled.\n\nA restore point is created, 'Remove all' restores the system. If the screen stays empty: Ctrl+Alt+Del \u{2192} Task Manager \u{2192} Run explorer.exe.").into(),+ ok: t!("Установить", "Install").into(),+ danger: false,+ act: Act::InstallAll,+ }),+ _ => {}+ }+}++pub(crate) unsafe extern "system" fn proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {+ match msg {+ WM_PAINT => paint(hwnd),+ WM_ERASEBKGND => return 1,+ WM_MOUSEMOVE => {+ let h = hit(hwnd, lp);+ if h != HOVER.get() {+ HOVER.set(h);+ InvalidateRect(hwnd, null(), 0);+ }+ let mut t = TRACKMOUSEEVENT { cbSize: size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: hwnd, dwHoverTime: 0 };+ TrackMouseEvent(&mut t);+ }+ WM_SETCURSOR if (lp & 0xFFFF) as u32 == HTCLIENT => {+ SetCursor(LoadCursorW(null_mut(), if HOVER.get().is_some() { IDC_HAND } else { IDC_ARROW }));+ return 1;+ }+ WM_MOUSELEAVE => {+ HOVER.set(None);+ InvalidateRect(hwnd, null(), 0);+ }+ WM_LBUTTONUP => {+ if let Some(i) = hit(hwnd, lp) {+ click(hwnd, i);+ }+ }+ WM_KEYDOWN if SETTINGS.get().is_some() && wp as u16 == VK_ESCAPE => {+ SETTINGS.set(None);+ InvalidateRect(hwnd, null(), 0);+ }+ WM_KEYDOWN if DIALOG.with_borrow(|d| d.is_some()) => match wp as u16 {+ VK_ESCAPE => close_dialog(hwnd, false),+ VK_RETURN if DIALOG.with_borrow(|d| d.as_ref().is_some_and(|d| !d.danger)) => close_dialog(hwnd, true), // a dangerous one needs the click++ _ => {}+ },+ WM_DONE => {+ InvalidateRect(hwnd, null(), 0);+ }+ WM_CLOSE if BUSY.load(Relaxed) => {} // closing mid-install would leave the system half-changed+ WM_DESTROY => PostQuitMessage(0),+ _ => return DefWindowProcW(hwnd, msg, wp, lp),+ }+ 0+}