Windows shell replacement in Rust: taskbar, file manager, NTFS search, task manager, disk cleaner. One installer exe.
Rust
Release v0.4.0
Lemxy61dd4d20f5b9
diff --git a/Cargo.lock b/Cargo.lockindex 3d7c458..a0b7f4c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -154,7 +154,7 @@ dependencies = [[[package]]name = "plugin-launcher"-version = "0.3.0"+version = "0.4.0"dependencies = ["embed-resource","windows-sys",@@ -170,6 +170,10 @@ dependencies = ["unicode-ident",]+[[package]]+name = "purge"+version = "0.1.0"+[[package]]name = "quote"version = "1.0.47"diff --git a/Cargo.toml b/Cargo.tomlindex afd16e9..0396f0d 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[package]name = "plugin-launcher"-version = "0.3.0"+version = "0.4.0"edition = "2024"[[bin]]@@ -28,6 +28,7 @@ members = ["plugins/wiztree","plugins/photoview","plugins/debloat",+ "plugins/purge",]# 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.diff --git a/README.md b/README.mdindex 73825cc..6d92b27 100644--- a/README.md+++ b/README.md@@ -14,7 +14,11 @@ English | [Русский](README.ru.md)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.+3. Tick the components you want (all are ticked by default) and press **Install WinRust**. They are installed in the right order; one that fails or is skipped does not stop the others, the window lists what went wrong.++Windows Search is optional: on a stripped Windows (for example a debloated LTSC image without the Windows Search service) that step is skipped with a warning instead of failing the install.++If UAC asks for **another administrator's** password, the per-user settings (startup entries, scheduled tasks, PowerShell profile, search permissions) still go to the user who is signed in, not to the administrator you typed. If the installer cannot tell who that is, it stops before changing anything.**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.@@ -37,6 +41,7 @@ The installer is in English. The **Русский** button in its corner (or "Wi| **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` |+| **purge** | Removes the bundled junk like Tiny11 does: Clipchamp, News, Weather, Xbox overlays, Teams, Cortana, Widgets, Skype and more, plus telemetry tasks | **IRREVERSIBLE, no undo.** Apps are removed for all users and from the image; the Store, Settings, Start and runtimes stay. Run `purge.exe` first: it only lists. **Command line only:** `install purge --yes` (OneDrive and Edge: `purge.exe --apply --onedrive --edge`) || chrome-rs | A browser | Not installable yet |Every change is reversible: uninstall puts back the values that were there before.@@ -77,6 +82,7 @@ In short: **85–99% faster or smaller in every size/speed test, and equal on id+**Task Manager** (Russian UI)@@ -125,12 +131,12 @@ Result: `target\release\plugin-launcher.exe`, with every plugin inside. Close aFrom a terminal **with administrator rights**:```plugin-launcher list-plugin-launcher install <plugin> --yes (without --yes it only prints the warning and changes nothing)+plugin-launcher install <plugin>... --yes (one or more names, or `all` for what the window installs; without --yes it only prints the warnings and changes nothing)plugin-launcher update <plugin> (reinstall from payload\ next to the exe)plugin-launcher uninstall <plugin>plugin-launcher rollback --yes (remove everything)```-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`.+Several plugins in one command are installed in the table's order (topbar before rust-explorer); one that fails does not stop the rest. Exit codes: 0 success, 1 error (at least one plugin failed), 2 bad arguments or no `--yes`. With no arguments the window opens. Install log: `%ProgramData%\plugin-launcher\install.log`.### Adding a plugin1. A crate in `plugins/<name>`, added to `members` in the root `Cargo.toml`.diff --git a/README.ru.md b/README.ru.mdindex 1296ef6..99a7a1d 100644--- a/README.ru.md+++ b/README.ru.md@@ -14,7 +14,11 @@1. Скачайте `WinRust.exe` из [последнего релиза](https://github.com/Lemxy/WinRust/releases/latest) (Windows 10/11, x64).2. Запустите от имени администратора.-3. Нажмите **Install WinRust**. Установщик поставит все компоненты в правильном порядке.+3. Отметьте галочками нужные компоненты (по умолчанию отмечены все) и нажмите **Install WinRust**. Они ставятся в правильном порядке; упавший или пропущенный компонент не останавливает остальные, окно покажет, что пошло не так.++Поиск Windows необязателен: в урезанной Windows (например, LTSC-образ без службы Windows Search) этот шаг пропускается с предупреждением, а не ломает установку.++Если UAC просит пароль **другого администратора**, пользовательские настройки (автозапуск, задачи планировщика, профиль PowerShell, права поиска) всё равно записываются тому, кто вошёл в систему, а не введённому администратору. Если установщик не может определить этого пользователя, он останавливается, ничего не изменив.**Обновление:** скачайте новый `WinRust.exe` со страницы релизов, запустите от имени администратора и нажмите **Update WinRust** («Обновить WinRust» в русском режиме). Установленные плагины обновятся, недостающие поставятся; ваши настройки и сохранённые исходные значения Windows остаются.@@ -37,6 +41,7 @@| **wiztree** | Карта занятого места на диске («WinRust Disk» в Пуске) | Ничего, кроме файла и ярлыка || **photoview** | Быстрый просмотр фото | Добавляется в «Открыть с помощью» (по умолчанию не назначается) || **debloat** | Отключает телеметрию, Copilot, Recall, рекламу в Пуске, фоновый Edge | Службы и политики реестра; старые значения сохраняются и возвращаются при удалении. **Только из командной строки:** `install debloat --yes` |+| **purge** | Удаляет предустановленный мусор, как Tiny11: Clipchamp, Новости, Погода, Xbox-оверлеи, Teams, Cortana, виджеты, Skype и др., а также задачи телеметрии | **НЕОБРАТИМО, отката нет.** Приложения удаляются для всех пользователей и из образа; Магазин, Параметры, Пуск и среды выполнения остаются. Сначала запустите `purge.exe`: он только показывает список. **Только из командной строки:** `install purge --yes` (OneDrive и Edge: `purge.exe --apply --onedrive --edge`) || chrome-rs | Браузер | Пока не ставится |Все изменения обратимы: удаление возвращает те значения, что были до установки.@@ -77,6 +82,7 @@+**Диспетчер задач** (русский интерфейс)@@ -125,12 +131,12 @@ powershell -ExecutionPolicy Bypass -File scripts\build-all.ps1Из терминала **с правами администратора**:```plugin-launcher list-plugin-launcher install <плагин> --yes (без --yes только покажет предупреждение и ничего не изменит)+plugin-launcher install <плагин>... --yes (одно или несколько имён, либо `all` = то, что ставит окно; без --yes только покажет предупреждения и ничего не изменит)plugin-launcher update <плагин> (переустановить из payload\ рядом с exe)plugin-launcher uninstall <плагин>plugin-launcher rollback --yes (удалить всё)```-Коды выхода: 0 успех, 1 ошибка, 2 неверные аргументы или нет `--yes`. Без аргументов открывается окно. Журнал установки: `%ProgramData%\plugin-launcher\install.log`.+Несколько плагинов в одной команде ставятся в порядке таблицы (topbar раньше rust-explorer); упавший не останавливает остальные. Коды выхода: 0 успех, 1 ошибка (хотя бы один плагин не встал), 2 неверные аргументы или нет `--yes`. Без аргументов открывается окно. Журнал установки: `%ProgramData%\plugin-launcher\install.log`.### Новый плагин1. Crate в `plugins/<имя>`, добавить его в `members` корневого `Cargo.toml`.diff --git a/ROADMAP.md b/ROADMAP.mdindex efb4f1e..7d32d8b 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -11,11 +11,14 @@ Each item says how far it was checked: **tests** (unit tests), **built** (compil- "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*+- Choose what to install (#7): a checkbox per component in the window, several names or `all` on the command line; a component that fails or is skipped does not stop the rest, the failures are listed at the end. A missing Windows Search service (stripped LTSC builds) is a warning, not an error, for both install and uninstall of rust-search. *built*+- The signed-in user, not the elevated account (#4): if UAC was answered with another administrator, per-user settings (HKCU, scheduled tasks, the PowerShell profile, the rust-search pipe permission, the rs-launcher Run key, debloat's HKCU policies) go to the owner of explorer.exe (or topbar / rust-explorer / rs-shell) in the session, through `HKU\<SID>`. If that user cannot be determined, install stops before writing anything. Uninstall carries on with a warning. *tests (key rewriting), 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)*+- Command line: `list | install <plugin>...|all --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*- Review fixes (v0.3.0): rs-du keeps its quarantine list next to its exe (admin-only), `payload\` two levels up only from `target\release`, rtaskmgr and rust-explorer save and restore another program's Task Manager / folder settings, rust-search brings Windows Search back before removing its files, DiagTrack is left to debloat, one `reg query` parser with a test. *tests, built*+- Settings without Explorer (Win+I and the bar's menus): Settings is a Store app that opens only while Explorer is the shell, so a hidden helper starts Explorer, waits for its taskbar, opens the page, brings the window to the front (also over a fullscreen game), and puts rust-explorer back when Settings is closed; a hung Settings process is killed first. The bar hides only for fullscreen games and video. *built, ran by hand*- 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@@ -31,8 +34,11 @@ Each item says how far it was checked: **tests** (unit tests), **built** (compil- **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*+- **purge**: removes the bundled Store apps (installed and provisioned) and the telemetry scheduled tasks like Tiny11 does; OneDrive and Edge only with `--onedrive` / `--edge`. IRREVERSIBLE, a log in `%ProgramData%\winrust-purge emoved.txt`. `purge.exe` lists, `--ask` asks for YES (the bar's right-click menu), `--apply` removes. Protected names (Store, Settings, Start, runtimes) are tested. *tests, dry run ran; `--apply` not run*## Next (in order)+0. **Phones and safe removal in rust-explorer** (#2): not started, too big for a quick fix. (a) MTP/PTP phones have no drive letter, so they need the Windows Portable Devices API (`IPortableDeviceManager`, `IPortableDeviceContent`, enumerate objects, read and write through `IPortableDeviceResources` streams) behind a second "file system" in rust-explorer next to the path-based one; copy, paste, delete and drag and drop have to be redone on it. (b) Safe removal: a tray icon in topbar (it already hosts tray icons) that lists removable drives, and `CM_Request_Device_Eject` on the device node of the chosen drive (flush first, report "in use" with the process that holds it). (b) is the smaller half and works for USB sticks and disks; (a) is what the issue is mostly about. Needs a real phone and a USB stick to test: nothing here can be checked by unit tests alone.+0. **Taskbar-style reordering in topbar** (#6, wish): dragging a file onto the bar already pins it. Missing: dragging the window buttons to change their order, and dragging a button off the bar to unpin. Needs the order stored (like `topbar-start.txt`) and a drag state in `topbar` (mouse capture, an insertion marker, a repaint per move).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.diff --git a/ROADMAP.ru.md b/ROADMAP.ru.mdindex c645b03..943bdfd 100644--- a/ROADMAP.ru.md+++ b/ROADMAP.ru.md@@ -8,12 +8,15 @@### Установщик- Исправления после ревью (v0.3.0): rs-du хранит список карантина рядом со своим exe (писать туда может только администратор), `payload\` двумя уровнями выше берётся только из `target\release`, rtaskmgr и rust-explorer сохраняют и возвращают чужие настройки диспетчера задач и папок, rust-search сначала возвращает поиск Windows и только потом удаляет свои файлы, DiagTrack оставлен debloat, один разбор вывода `reg query` с тестом. *тесты, собрано*+- Параметры без Проводника (Win+I и меню панели): Параметры — Store-приложение, оно открывается только при Проводнике в роли оболочки, поэтому скрытый помощник запускает Проводник, ждёт его панель, открывает страницу, выводит окно на передний план (в том числе поверх полноэкранной игры) и возвращает rust-explorer после закрытия Параметров; зависший процесс Параметров сначала убивается. Панель скрывается только для полноэкранных игр и видео. *собрано, проверено вручную*- Один `plugin-launcher.exe`, в который вшиты все плагины (распаковка в Program Files, не в %TEMP%), статический CRT, тёмное окно на Win32/GDI. *запускалось*- «Install WinRust» ставит недостающее по порядку (topbar раньше rust-explorer), когда всё стоит, обновляет; «Удалить всё» удаляет в обратном порядке. *собрано*- Сбой установки откатывает свои изменения (кроме обновления рабочей копии); исходные значения (WSearch, строка поиска, настройки Проводника, службы) сохраняются в `HKLM\SOFTWARE\plugin-launcher\<плагин>` и возвращаются при удалении; несмертельные ошибки пишутся в `%ProgramData%\plugin-launcher\install.log`. *собрано*- Точка восстановления перед установкой. *собрано*+- Выбор, что ставить (#7): в окне галочка у каждого компонента, в командной строке несколько имён или `all`; упавший или пропущенный компонент не останавливает остальные, ошибки перечисляются в конце. Отсутствие службы Windows Search (урезанные сборки LTSC) для rust-search при установке и удалении теперь предупреждение, а не ошибка. *собрано*+- Пользователь сеанса, а не элевированная учётная запись (#4): если в UAC введён другой администратор, пользовательские настройки (HKCU, задачи планировщика, профиль PowerShell, право на канал rust-search, Run-ключ rs-launcher, HKCU-политики debloat) пишутся владельцу explorer.exe (или topbar / rust-explorer / rs-shell) этого сеанса через `HKU\<SID>`. Если пользователя определить нельзя, установка останавливается до любых записей. Удаление продолжается с предупреждением. *тесты (подмена ключей), собрано*- Одна кнопка ставит недостающее **и** обновляет установленное: запуск нового `WinRust.exe` доносит исправления до всех плагинов (v0.2.1). *собрано*-- Командная строка: `list | install <плагин> --yes | update <плагин> | uninstall <плагин> | rollback --yes`, коды выхода 0/1/2; окно и командная строка вызывают одни и те же функции. Запускались только команды, которые ничего не меняют. *запускалось (частично)*+- Командная строка: `list | install <плагин>...|all --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. *тесты*@@ -31,8 +34,11 @@- **wiztree**: карта занятого места по MFT. *тесты (только раскладка); на живом диске не запускался*- **photoview**: просмотр фото на WIC, поворот по EXIF, пункт «Открыть с помощью». *запускалось; EXIF-ориентации 5 и 7 не проверялись*- **debloat**: службы и политики (телеметрия, Copilot, Recall, реклама, фоновый Edge), старые значения в `%ProgramData%\winrust-debloat\undo.txt`, `--undo`. *сухой прогон запускался; `--apply`/`--undo` нет*+- **purge**: удаляет предустановленные Store-приложения (установленные и из образа) и задачи телеметрии, как Tiny11; OneDrive и Edge только с `--onedrive` / `--edge`. НЕОБРАТИМО, журнал в `%ProgramData%\winrust-purge emoved.txt`. `purge.exe` показывает список, `--ask` просит ввести YES (меню по правому клику на панели), `--apply` удаляет. Защищённые имена (Магазин, Параметры, Пуск, среды выполнения) проверены тестами. *тесты, пробный запуск выполнен; `--apply` не запускался*## Дальше (по порядку)+0. **Телефоны и безопасное извлечение в rust-explorer** (#2): не начато, для быстрой правки слишком много. (а) У MTP/PTP-телефонов нет буквы диска, поэтому нужен Windows Portable Devices API (`IPortableDeviceManager`, `IPortableDeviceContent`, перечисление объектов, чтение и запись через потоки `IPortableDeviceResources`) как вторая «файловая система» в rust-explorer рядом с путевой; копирование, вставку, удаление и перетаскивание придётся переделать под неё. (б) Безопасное извлечение: значок в трее topbar (трей там уже есть), список съёмных дисков и `CM_Request_Device_Eject` для узла выбранного диска (сначала сброс буферов, при «занято» показать, какой процесс держит). Часть (б) меньше и работает для флешек и дисков; (а) это то, о чём в основном issue. Для проверки нужны настоящий телефон и флешка: одними юнит-тестами не обойтись.+0. **Перестановка кнопок на панели как на панели задач** (#6, пожелание): перетаскивание файла на панель уже закрепляет его. Нет: перетаскивания кнопок окон для смены порядка и вытаскивания кнопки с панели для открепления. Нужно хранить порядок (как `topbar-start.txt`) и состояние перетаскивания в `topbar` (захват мыши, маркер вставки, перерисовка на каждое движение).1. **Проверка на чистой Windows 11 в виртуалке**: установка, удаление, откат, перезагрузка, по каждому плагину. На другой машине пока ничего не проверялось.2. **Один журнал отката для всех плагинов**: каждое изменение (значение реестра, служба, файл) записывается как «было → стало» до того, как сделано; удаление и откат проигрывают журнал назад. Заменяет ручной uninstall каждого плагина. Сначала нужен шаг 1 и миграция для установок текущей версии.3. **Реестр через Win32 API** (`RegGetValueW`/`RegSetValueExW`) вместо запуска `reg.exe` и разбора его вывода.diff --git a/ReShell/src/hotkeys.rs b/ReShell/src/hotkeys.rsindex c7d29e1..36f7923 100644--- a/ReShell/src/hotkeys.rs+++ b/ReShell/src/hotkeys.rs@@ -4,7 +4,7 @@//! 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, 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::*}};+use windows_sys::Win32::{Foundation::*, System::{LibraryLoader::GetModuleHandleW, Registry::*}, UI::{Input::KeyboardAndMouse::*, WindowsAndMessaging::*}};static PREV: AtomicUsize = AtomicUsize::new(usize::MAX);static HOOK: AtomicIsize = AtomicIsize::new(0);@@ -49,13 +49,8 @@ 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);- }+ winrust_common::settings::open("ms-settings:");}/// What Win+<key> does here instead of in Explorer.diff --git a/common/src/lib.rs b/common/src/lib.rsindex 0f31223..4b03634 100644--- a/common/src/lib.rs+++ b/common/src/lib.rs@@ -11,6 +11,7 @@ use std::{pub mod desktop;pub mod mft;pub mod reg;+pub mod settings;pub mod style;static LANG: AtomicU8 = AtomicU8::new(0); // 0 = not read yet, 1 = English, 2 = Russiandiff --git a/common/src/reg.rs b/common/src/reg.rsindex a638258..082339b 100644--- a/common/src/reg.rs+++ b/common/src/reg.rs@@ -18,10 +18,40 @@ pub fn dword(out: &str) -> Option<u32> {}}+/// Set by the installer for its children when the signed-in user is not the elevated account (UAC was answered with another+/// administrator): the SID of the signed-in user. Per-user keys then go to `HKU\<sid>`, not to the elevated account's HKCU.+pub const SID_ENV: &str = "WINRUST_SID";++pub fn valid_sid(s: &str) -> bool {+ s.starts_with("S-1-") && s.len() > 4 && s.chars().all(|c| c.is_ascii_digit() || c == '-' || c == 'S')+}++/// A reg.exe key argument aimed at the user `sid`: `HKCU\x` becomes `HKU\<sid>\x`. Anything else (HKLM, values, flags) is unchanged.+pub fn for_user(arg: &str, sid: &str) -> String {+ let rest = ["HKCU", "HKEY_CURRENT_USER"].iter().find_map(|p| arg.strip_prefix(p).filter(|r| r.is_empty() || r.starts_with('\\')));+ rest.map_or_else(|| arg.to_string(), |r| format!("HKU\\{sid}{r}"))+}++/// `for_user` for the SID the installer passed in the environment; the arguments as they are when it passed none.+pub fn user_args(args: &[&str]) -> Vec<String> {+ let sid = std::env::var(SID_ENV).ok().filter(|s| valid_sid(s));+ args.iter().map(|a| sid.as_deref().map_or_else(|| a.to_string(), |s| for_user(a, s))).collect()+}+#[cfg(test)]mod tests {use super::*;+ #[test]+ fn aims_hkcu_at_the_given_user() {+ assert_eq!(for_user(r"HKCU\Software\X", "S-1-5-21-1-2-3-1001"), r"HKU\S-1-5-21-1-2-3-1001\Software\X");+ assert_eq!(for_user("HKEY_CURRENT_USER", "S-1-5-21-9"), r"HKU\S-1-5-21-9");+ assert_eq!(for_user(r"HKLM\SOFTWARE\X", "S-1-5-21-9"), r"HKLM\SOFTWARE\X");+ assert_eq!(for_user(r"HKCUX\a", "S-1-5-21-9"), r"HKCUX\a");+ assert_eq!(for_user("/v", "S-1-5-21-9"), "/v");+ assert!(valid_sid("S-1-5-21-1-2-3-1001") && !valid_sid("S-1-5-x; calc") && !valid_sid(""));+ }+#[test]fn reads_reg_query_output() {let key = "\r\nHKEY_LOCAL_MACHINE\\SOFTWARE\\REG_X\r\n";diff --git a/common/src/settings.rs b/common/src/settings.rsnew file mode 100644index 0000000..99be0ba--- /dev/null+++ b/common/src/settings.rs@@ -0,0 +1,55 @@+//! Opens a Settings page (`ms-settings:...`). Settings is a Store app: it opens only while Explorer is the shell (activation+//! fails with 0x80040900 otherwise, also with a shell window of our own registered). So with rust-explorer in place of Explorer:+//! start Explorer for as long as Settings is open, then end it again, which keeps the RAM saving. Done by a hidden PowerShell:+//! it waits for processes, a hook or UI thread must not. Shared by Win+I (reshell) and the topbar's menus.+use std::{os::windows::process::CommandExt, process::{Command, Stdio}};++const PS: &str = r#"+Add-Type -Namespace W -Name U -MemberDefinition '[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern System.IntPtr GetShellWindow(); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(System.IntPtr h, out uint p); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern System.IntPtr FindWindowEx(System.IntPtr p, System.IntPtr a, string c, string t); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern System.IntPtr GetWindow(System.IntPtr h, uint c); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool SetForegroundWindow(System.IntPtr h); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool ShowWindow(System.IntPtr h, int c); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern void keybd_event(byte k, byte s, uint f, System.UIntPtr e);'+function ExplorerShell { $h=[W.U]::GetShellWindow(); if($h -eq [IntPtr]::Zero){return $false}; $p=0; [void][W.U]::GetWindowThreadProcessId($h,[ref]$p); (Get-Process -Id $p -ErrorAction SilentlyContinue).Name -eq 'explorer' }+function ExplorerTray { $h=[W.U]::GetShellWindow(); if($h -eq [IntPtr]::Zero){return $false}; $sp=0; [void][W.U]::GetWindowThreadProcessId($h,[ref]$sp); $t=[IntPtr]::Zero+ while(($t=[W.U]::FindWindowEx([IntPtr]::Zero,$t,'Shell_TrayWnd',$null)) -ne [IntPtr]::Zero){ $tp=0; [void][W.U]::GetWindowThreadProcessId($t,[ref]$tp); if($tp -eq $sp){return $true} }+ $false }+# a fullscreen game keeps the screen: Settings opens behind it unless it is brought to the front+function Raise { $sp=(Get-Process SystemSettings -ErrorAction SilentlyContinue | Select-Object -First 1).Id; if(-not $sp){return}; $c=[IntPtr]::Zero+ while(($c=[W.U]::FindWindowEx([IntPtr]::Zero,$c,'Windows.UI.Core.CoreWindow',$null)) -ne [IntPtr]::Zero){ $cp=0; [void][W.U]::GetWindowThreadProcessId($c,[ref]$cp)+ if($cp -eq $sp){ $o=[W.U]::GetWindow($c,4); if($o -eq [IntPtr]::Zero){$o=$c}; [W.U]::keybd_event(0x12,0,0,[UIntPtr]::Zero); [W.U]::keybd_event(0x12,0,2,[UIntPtr]::Zero); [void][W.U]::ShowWindow($o,9); [void][W.U]::SetForegroundWindow($o); return } } }+# a Settings process that hangs (opened before the shell was ready) swallows every later launch: it must go+function KillStale { Get-Process SystemSettings -ErrorAction SilentlyContinue | Where-Object { -not $_.Responding } | Stop-Process -Force }+KillStale+$started=$false+if(-not (ExplorerShell)){+ # our desktop is a window of class Progman too: with it up Explorer thinks a shell exists and starts as a plain folder host+ Get-Process rust-explorer -ErrorAction SilentlyContinue | ForEach-Object { if((Get-CimInstance Win32_Process -Filter "ProcessId=$($_.Id)").CommandLine -match '--desktop'){ Stop-Process -Id $_.Id -Force } }+ & runas.exe /trustlevel:0x20000 C:\Windows\explorer.exe+ for($i=0;$i -lt 200 -and -not (ExplorerShell);$i++){ Start-Sleep -Milliseconds 100 }+ # the shell window appears before the immersive shell services behind it are up: Explorer's own taskbar comes last (the+ # topbar has a Shell_TrayWnd of its own, so only one that belongs to the shell process counts)+ for($i=0;$i -lt 150 -and -not (ExplorerTray);$i++){ Start-Sleep -Milliseconds 100 }+ Start-Sleep -Milliseconds 1000+ $started=$true+}+# through explorer.exe: the page opens with the user's normal token even when this process is elevated+for($try=0;$try -lt 2;$try++){+ & C:\Windows\explorer.exe $env:WR_URI+ for($i=0;$i -lt 80 -and -not (Get-Process SystemSettings -ErrorAction SilentlyContinue);$i++){ Start-Sleep -Milliseconds 100 }+ Start-Sleep -Seconds 1; Raise; Start-Sleep -Seconds 3; Raise+ if(-not (Get-Process SystemSettings -ErrorAction SilentlyContinue | Where-Object { -not $_.Responding })){ break }+ KillStale+}+if($started){+ # ends when Settings is closed, or when it hangs for good+ $bad=0+ while($bad -lt 5 -and (Get-Process SystemSettings -ErrorAction SilentlyContinue)){ Start-Sleep -Seconds 2; if(Get-Process SystemSettings -ErrorAction SilentlyContinue | Where-Object { -not $_.Responding }){ $bad++ } else { $bad=0 } }+ KillStale+ Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object { $_.CommandLine -match '(?i)explorer\.exe"?\s*$' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }+ $rx="$env:ProgramFiles\rust-explorer\rust-explorer.exe"+ if((Test-Path $rx) -and -not (Get-CimInstance Win32_Process -Filter "Name='rust-explorer.exe'" | Where-Object { $_.CommandLine -match '--desktop' })){ Start-Process $rx -ArgumentList '--desktop' }+}+"#;++/// `uri` is passed through the environment, never spliced into the script. A second call while the first still waits is harmless.+pub fn open(uri: &str) {+ let _ = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-Command", PS])+ .env("WR_URI", uri).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).creation_flags(0x0800_0000).spawn();+}diff --git a/docs/screenshots/topbar-menu-new.png b/docs/screenshots/topbar-menu-new.pngnew file mode 100644index 0000000..353fc69Binary files /dev/null and b/docs/screenshots/topbar-menu-new.png differdiff --git a/payload.txt b/payload.txtindex f259e63..608a40c 100644--- a/payload.txt+++ b/payload.txt@@ -11,3 +11,4 @@ rs-shell.exe = target/release/rs-shell.exewiztree.exe = target/release/wiztree.exephotoview.exe = target/release/photoview.exedebloat.exe = target/release/debloat.exe+purge.exe = target/release/purge.exediff --git a/plugins/debloat/src/main.rs b/plugins/debloat/src/main.rsindex 8aee060..6db6330 100644--- a/plugins/debloat/src/main.rs+++ b/plugins/debloat/src/main.rs@@ -50,7 +50,9 @@ const REGS: &[(&str, &str, u32, &str)] = &[];fn run(prog: &str, args: &[&str]) -> (bool, String) {- match Command::new(prog).args(args).output() {+ // HKCU = the signed-in user's when the installer was elevated as another administrator (WINRUST_SID)+ let args: Vec<String> = if prog == "reg" { winrust_common::reg::user_args(args) } else { args.iter().map(|a| a.to_string()).collect() };+ match Command::new(prog).args(&args).output() {Ok(o) => (o.status.success(), String::from_utf8_lossy(&o.stdout).into_owned()),Err(e) => (false, e.to_string()),}diff --git a/plugins/purge/Cargo.toml b/plugins/purge/Cargo.tomlnew file mode 100644index 0000000..bf54cec--- /dev/null+++ b/plugins/purge/Cargo.toml@@ -0,0 +1,4 @@+[package]+name = "purge"+version = "0.1.0"+edition = "2024"diff --git a/plugins/purge/src/main.rs b/plugins/purge/src/main.rsnew file mode 100644index 0000000..f592613--- /dev/null+++ b/plugins/purge/src/main.rs@@ -0,0 +1,231 @@+// purge show what would be removed (nothing is modified)+// purge --apply REMOVE it, for good (admin). There is no undo: only a log of what went is kept+// purge --ask list, then ask to type YES before removing (what the topbar menu starts, in its own window)+// purge --onedrive (with --apply) also uninstall OneDrive purge --edge (with --apply) also try to uninstall Edge+//+// What Tiny11 cuts out of the image, done on a running system: bundled Store apps (installed and provisioned, so new+// users do not get them back) and the telemetry scheduled tasks. Never touched: the Store, Settings, the shell hosts,+// runtimes and everything in PROTECTED. Reinstalling an app means Store or winget; deleted tasks do not come back.+use std::{env, fs, io::Write, path::PathBuf, process::Command};++/// Apps to remove: a package name starts with one of these (a name of 5+ letters without a dot also matches anywhere).+const JUNK: &[&str] = &[+ "Clipchamp.Clipchamp", "Microsoft.BingNews", "Microsoft.BingWeather", "Microsoft.BingSearch", "Microsoft.Copilot",+ "Microsoft.Windows.Ai.Copilot.Provider", "Microsoft.549981C3F5F10", // Cortana+ "Microsoft.GamingApp", "Microsoft.XboxGameOverlay", "Microsoft.XboxGamingOverlay", "Microsoft.XboxSpeechToTextOverlay", "Microsoft.Xbox.TCUI",+ "Microsoft.GetHelp", "Microsoft.Getstarted", "Microsoft.MicrosoftOfficeHub", "Microsoft.Office.OneNote", "Microsoft.MicrosoftSolitaireCollection",+ "Microsoft.People", "Microsoft.PowerAutomateDesktop", "Microsoft.Todos", "Microsoft.WindowsAlarms", "microsoft.windowscommunicationsapps",+ "Microsoft.WindowsFeedbackHub", "Microsoft.WindowsMaps", "Microsoft.WindowsSoundRecorder", "Microsoft.YourPhone", "Microsoft.ZuneMusic",+ "Microsoft.ZuneVideo", "MicrosoftCorporationII.MicrosoftFamily", "MicrosoftCorporationII.QuickAssist", "MicrosoftTeams", "MSTeams",+ "Microsoft.OutlookForWindows", "Microsoft.Windows.DevHome", "MicrosoftWindows.Client.WebExperience", // Widgets+ "Microsoft.SkypeApp", "Microsoft.MixedReality.Portal", "Microsoft.Microsoft3DViewer", "Microsoft.Print3D", "Microsoft.Wallet",+ "SpotifyAB.SpotifyMusic", "Disney.", "Netflix", "TikTok", "Facebook", "Instagram", "LinkedIn", "Twitter", "AmazonVideo", "king.com.", "Duolingo",+];++/// Never removed, whatever JUNK says: removing these breaks Settings, Start, the Store, sign-in or other apps.+const PROTECTED: &[&str] = &[+ "Microsoft.WindowsStore", "Microsoft.StorePurchaseApp", "Microsoft.DesktopAppInstaller", "windows.immersivecontrolpanel",+ "Microsoft.Windows.ShellExperienceHost", "Microsoft.Windows.StartMenuExperienceHost", "MicrosoftWindows.Client.", "Microsoft.Windows.",+ "Microsoft.NET", "Microsoft.VCLibs", "Microsoft.UI.Xaml", "Microsoft.WindowsAppRuntime", "Microsoft.SecHealthUI", "Microsoft.AAD.BrokerPlugin",+ "Microsoft.AccountsControl", "Microsoft.LockApp", "Microsoft.XboxIdentityProvider", "Microsoft.GamingServices", "Microsoft.WindowsTerminal",+ "Microsoft.WindowsCalculator", "Microsoft.Paint", "Microsoft.ScreenSketch", "Microsoft.Windows.Photos", "Microsoft.WindowsNotepad",+];++/// Telemetry scheduled tasks (Tiny11 deletes the same ones).+const TASKS: &[&str] = &[+ r"\Microsoft\Windows\Application Experience\Microsoft Compatibility Appraiser",+ r"\Microsoft\Windows\Application Experience\ProgramDataUpdater",+ r"\Microsoft\Windows\Application Experience\StartupAppTask",+ r"\Microsoft\Windows\Customer Experience Improvement Program\Consolidator",+ r"\Microsoft\Windows\Customer Experience Improvement Program\UsbCeip",+ r"\Microsoft\Windows\Customer Experience Improvement Program\KernelCeipTask",+ r"\Microsoft\Windows\Feedback\Siuf\DmClient",+ r"\Microsoft\Windows\Feedback\Siuf\DmClientOnScenarioDownload",+ r"\Microsoft\Windows\Windows Error Reporting\QueueReporting",+];++fn starts(name: &str, list: &[&str]) -> bool {+ let n = name.to_lowercase();+ list.iter().any(|p| n.starts_with(&p.to_lowercase()))+}++/// Removable junk. "Microsoft.Windows." is protected as a whole, except the few items that are JUNK by their full name.+fn is_junk(name: &str) -> bool {+ let keep = starts(name, PROTECTED) && !starts(name, &["Microsoft.Windows.Ai.Copilot.Provider", "Microsoft.Windows.DevHome", "MicrosoftWindows.Client.WebExperience"]);+ let n = name.to_lowercase();+ !keep && JUNK.iter().any(|p| n.starts_with(&p.to_lowercase()) || (p.len() >= 5 && !p.contains('.') && n.contains(&p.to_lowercase())))+}++enum Item {+ Appx { full: String, name: String },+ Prov { pkg: String, name: String },+}++fn run(prog: &str, args: &[&str]) -> (bool, String) {+ match Command::new(prog).args(args).output() {+ Ok(o) => (o.status.success(), String::from_utf8_lossy(&o.stdout).into_owned()),+ Err(e) => (false, e.to_string()),+ }+}++fn ps(script: &str) -> (bool, String) {+ run("powershell", &["-NoProfile", "-NonInteractive", "-Command", script])+}++/// `appx|FullName|Name|NonRemovable` and `prov|PackageName|DisplayName` lines of the listing script.+fn parse(out: &str) -> Vec<Item> {+ let mut v = vec![];+ for l in out.lines().map(str::trim) {+ let f: Vec<&str> = l.split('|').collect();+ // a name with a quote would break out of the removal command: such a package is left alone+ if f.iter().any(|x| x.contains('\'')) {+ continue;+ }+ match f.as_slice() {+ ["appx", full, name, nonremovable] if *nonremovable != "True" && is_junk(name) => v.push(Item::Appx { full: full.to_string(), name: name.to_string() }),+ ["prov", pkg, name] if is_junk(name) => v.push(Item::Prov { pkg: pkg.to_string(), name: name.to_string() }),+ _ => {}+ }+ }+ v+}++fn found() -> Result<Vec<Item>, String> {+ let (ok, out) = ps(r#"Get-AppxPackage -AllUsers | ForEach-Object { "appx|$($_.PackageFullName)|$($_.Name)|$($_.NonRemovable)" }; Get-AppxProvisionedPackage -Online | ForEach-Object { "prov|$($_.PackageName)|$($_.DisplayName)" }"#);+ if !ok && out.trim().is_empty() {+ return Err("cannot list apps (run as administrator)".into());+ }+ Ok(parse(&out))+}++fn task_exists(t: &str) -> bool {+ run("schtasks.exe", &["/Query", "/TN", t]).0+}++fn onedrive_setup() -> Option<PathBuf> {+ let root = PathBuf::from(env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into()));+ ["SysWOW64", "System32"].iter().map(|d| root.join(d).join("OneDriveSetup.exe")).find(|p| p.is_file())+}++fn edge_setup() -> Option<PathBuf> {+ let base = PathBuf::from(env::var("ProgramFiles(x86)").unwrap_or_else(|_| r"C:\Program Files (x86)".into())).join(r"Microsoft\Edge\Application");+ let mut vs: Vec<PathBuf> = fs::read_dir(base).ok()?.flatten().map(|e| e.path().join(r"Installer\setup.exe")).filter(|p| p.is_file()).collect();+ vs.sort();+ vs.pop()+}++fn plan(od: bool, edge: bool) {+ println!("Dry run: nothing is removed. --apply REMOVES it FOR GOOD (no undo).\n");+ match found() {+ Ok(items) => {+ for i in &items {+ match i {+ Item::Appx { name, .. } => println!(" app (installed) {name}"),+ Item::Prov { name, .. } => println!(" app (provisioned) {name}"),+ }+ }+ println!(" {} app entries found", items.len());+ }+ Err(e) => println!(" {e}"),+ }+ for t in TASKS.iter().filter(|t| task_exists(t)) {+ println!(" task {t}");+ }+ if od {+ println!(" OneDrive {}", onedrive_setup().map_or("not present".into(), |p| p.display().to_string()));+ }+ if edge {+ println!(" Edge {}", edge_setup().map_or("not present".into(), |p| p.display().to_string()));+ }+}++fn apply(od: bool, edge: bool) -> Result<(), String> {+ let dir = PathBuf::from(env::var("ProgramData").unwrap_or_else(|_| r"C:\ProgramData".into())).join("winrust-purge");+ fs::create_dir_all(&dir).map_err(|e| format!("{}: {e} (run as admin)", dir.display()))?;+ let mut log = fs::OpenOptions::new().create(true).append(true).open(dir.join("removed.txt")).map_err(|e| e.to_string())?;+ let mut failed = 0;+ let mut did = |what: String, ok: bool| {+ println!("{} {what}", if ok { "removed" } else { "FAILED " });+ if ok {+ let _ = writeln!(log, "{what}");+ } else {+ failed += 1;+ }+ };+ for i in found()? {+ match i {+ Item::Appx { full, name } => did(format!("app {name}"), ps(&format!("Remove-AppxPackage -Package '{full}' -AllUsers -ErrorAction Stop")).0),+ Item::Prov { pkg, name } => did(format!("provisioned {name}"), ps(&format!("Remove-AppxProvisionedPackage -Online -PackageName '{pkg}' -ErrorAction Stop")).0),+ }+ }+ for t in TASKS.iter().filter(|t| task_exists(t)) {+ did(format!("task {t}"), run("schtasks.exe", &["/Delete", "/TN", t, "/F"]).0);+ }+ if od {+ let _ = run("taskkill", &["/f", "/im", "OneDrive.exe"]);+ match onedrive_setup() {+ Some(p) => did("OneDrive".into(), run(&p.display().to_string(), &["/uninstall"]).0),+ None => println!("skip OneDrive: not present"),+ }+ }+ if edge {+ match edge_setup() {+ // Windows only lets Edge go outside the EU when this value exists+ Some(p) => {+ let _ = run("reg", &["add", r"HKLM\SOFTWARE\Microsoft\EdgeUpdateDev", "/v", "AllowUninstall", "/t", "REG_SZ", "/d", "", "/f"]);+ did("Edge (best effort, Windows may refuse)".into(), run(&p.display().to_string(), &["--uninstall", "--system-level", "--verbose-logging", "--force-uninstall"]).0)+ }+ None => println!("skip Edge: not present"),+ }+ }+ println!("\nThis cannot be undone. A log of what was removed: {}", dir.join("removed.txt").display());+ if failed > 0 { Err(format!("{failed} item(s) failed (run as administrator)")) } else { Ok(()) }+}++fn main() {+ let a: Vec<String> = env::args().skip(1).collect();+ let has = |f: &str| a.iter().any(|x| x == f);+ let r = if has("--ask") {+ plan(has("--onedrive"), has("--edge"));+ print!("+This REMOVES the apps above FOR GOOD, there is no undo. Type YES to continue: ");+ let _ = std::io::stdout().flush();+ let mut line = String::new();+ let _ = std::io::stdin().read_line(&mut line);+ let r = if line.trim() == "YES" { apply(has("--onedrive"), has("--edge")) } else { println!("Nothing removed."); Ok(()) };+ println!("+Press Enter to close.");+ let _ = std::io::stdin().read_line(&mut line);+ r+ } else if has("--apply") {+ apply(has("--onedrive"), has("--edge"))+ } else {+ plan(has("--onedrive"), has("--edge"));+ Ok(())+ };+ if let Err(e) = r {+ eprintln!("{e}");+ std::process::exit(1);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn junk_goes_and_the_system_stays() {+ for n in ["Microsoft.BingNews", "Clipchamp.Clipchamp", "Microsoft.ZuneMusic", "MicrosoftTeams", "king.com.CandyCrushSaga", "Microsoft.Windows.DevHome", "MicrosoftWindows.Client.WebExperience", "5319275A.Facebook"] {+ assert!(is_junk(n), "{n}");+ }+ for n in ["Microsoft.WindowsStore", "windows.immersivecontrolpanel", "Microsoft.Windows.ShellExperienceHost", "Microsoft.Windows.StartMenuExperienceHost", "Microsoft.WindowsCalculator", "Microsoft.XboxIdentityProvider", "MicrosoftWindows.Client.CBS", "Microsoft.VCLibs.140.00", "Microsoft.Windows.Photos"] {+ assert!(!is_junk(n), "{n}");+ }+ }++ #[test]+ fn parses_listing_and_skips_nonremovable_and_quotes() {+ let out = "appx|Microsoft.BingNews_1_x64__8wekyb|Microsoft.BingNews|False\nappx|Microsoft.ZuneMusic_1|Microsoft.ZuneMusic|True\nprov|Clipchamp.Clipchamp_1|Clipchamp.Clipchamp\nprov|X'Y|Microsoft.BingNews\nappx|a|Microsoft.WindowsStore|False\n";+ assert_eq!(parse(out).len(), 2);+ }+}diff --git a/plugins/rs-shell/src/main.rs b/plugins/rs-shell/src/main.rsindex f6e98bd..d49fe81 100644--- a/plugins/rs-shell/src/main.rs+++ b/plugins/rs-shell/src/main.rs@@ -147,7 +147,7 @@ fn run_shell() {set_wallpaper();// no bar yet (its logon task is gone in user mode): start it and its hotkey helper from our folder, with our normal rightsif !bar_up() { log(&format!("topbar spawn -> {:?}", quiet(find_exe("topbar.exe")).spawn().map(|_| ()))); }- let hotkeys = dir().join("reshell.exe");+ let hotkeys = find_exe("reshell.exe"); // lives in topbar's folder, not oursif hotkeys.exists() { log(&format!("reshell spawn -> {:?}", quiet(&hotkeys).spawn().map(|_| ()))); }let desktop = dir().join("rust-explorer.exe");// the rust-explorer desktop: class "Progman" (so Wallpaper Engine finds it), title "rs-desktop" (explorer's is "Program Manager")@@ -241,6 +241,10 @@ fn overlay() {log(&format!("overlay start (replace explorer: {replace})"));let wp = thread::spawn(set_wallpaper); // makes sure the BMP the desktop window paints exists (and refreshes the wallpaper)if !bar_up() { log(&format!("topbar spawn -> {:?}", quiet(find_exe("topbar.exe")).spawn().map(|_| ()))); }+ // Win+I / Win+E / Win+D live in reshell: its Run entry may be missing (another account's HKCU), and without it Explorer's own Win+I+ // fails once the shell is gone. A second copy exits at once (one hook per session).+ let hk = find_exe("reshell.exe");+ if hk.exists() { log(&format!("reshell spawn -> {:?}", quiet(&hk).spawn().map(|_| ()))); }let _ = wp.join(); // the BMP conversion (only on a fresh install or a new wallpaper) finishes before the desktop paints itlet desktop = dir().join("rust-explorer.exe");let up = || unsafe { !FindWindowW(wide("Progman").as_ptr(), wide("rs-desktop").as_ptr()).is_null() };diff --git a/plugins/rust-search/src/bin/rs-launcher.rs b/plugins/rust-search/src/bin/rs-launcher.rsindex 608f810..d97e005 100644--- a/plugins/rust-search/src/bin/rs-launcher.rs+++ b/plugins/rust-search/src/bin/rs-launcher.rs@@ -1323,7 +1323,7 @@ fn main() {if std::env::args().nth(1).as_deref() == Some("--autostart") {let exe = std::env::current_exe().unwrap();let ok = std::process::Command::new("reg")- .args(["add", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "rs-launcher", "/t", "REG_SZ", "/d", &format!("\"{}\"", exe.display()), "/f"])+ .args(winrust_common::reg::user_args(&["add", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "rs-launcher", "/t", "REG_SZ", "/d", &format!("\"{}\"", exe.display()), "/f"])).status().map(|s| s.success()).unwrap_or(false);diff --git a/plugins/rust-search/src/main.rs b/plugins/rust-search/src/main.rsindex 74e7ffc..189eb35 100644--- a/plugins/rust-search/src/main.rs+++ b/plugins/rust-search/src/main.rs@@ -568,9 +568,15 @@ fn install_dir() -> std::path::PathBuf {/// Runs `rs --serve` for every fixed NTFS drive at boot, as SYSTEM, from Program Files (admin-only writable:/// a SYSTEM task must never run a binary from a user-writable folder). The installing user gets the pipes.fn install() -> Result<(), String> {- let who = ps("whoami /user /fo csv /nh")?;- let sid = who.trim().rsplit('"').nth(1).unwrap_or("").to_string(); // "DOM\user","S-1-5-..."- if !sid.starts_with("S-1-") || !sid.chars().all(|c| c.is_ascii_digit() || c == '-' || c == 'S') {+ // the installer passes the signed-in user's SID when UAC was answered with another administrator+ let (sid, who) = match env::var(winrust_common::reg::SID_ENV).ok().filter(|s| winrust_common::reg::valid_sid(s)) {+ Some(sid) => (sid, String::new()),+ None => {+ let who = ps("whoami /user /fo csv /nh")?;+ (who.trim().rsplit('"').nth(1).unwrap_or("").to_string(), who) // "DOM\user","S-1-5-..."+ }+ };+ if !winrust_common::reg::valid_sid(&sid) {return Err(format!("cannot determine your SID from: {who}"));}let drives = fixed_ntfs_drives();diff --git a/plugins/topbar/src/fly.rs b/plugins/topbar/src/fly.rsindex fb399f8..eff1c1d 100644--- a/plugins/topbar/src/fly.rs+++ b/plugins/topbar/src/fly.rs@@ -283,6 +283,42 @@ pub fn start_toggle(path: &str) {let _ = std::fs::write(pin_file(), p.join("\n"));}+static EXE_GEN: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);++/// Programs that have no Start menu shortcut (a loose loliland.exe): asks rust-search for .exe files matching what is typed+/// and adds them to the app list, where the normal ranking picks them up. Debounced; the panel repaints when they arrive.+fn find_loose_exes(hw: HWND) {+ let q = QUERY.with_borrow(|q| q.trim().to_string());+ let gen_ = EXE_GEN.fetch_add(1, Relaxed) + 1;+ let rs = PathBuf::from(std::env::var_os("ProgramFiles").unwrap_or_default()).join(r"rs-search\rs.exe");+ if q.chars().count() < 2 || !rs.is_file() {+ return;+ }+ let hw = hw as isize;+ std::thread::spawn(move || {+ std::thread::sleep(std::time::Duration::from_millis(200));+ if EXE_GEN.load(Relaxed) != gen_ {+ return; // typed on: a newer search is coming+ }+ let Ok(o) = Command::new(&rs).arg(&q).creation_flags(NO_WINDOW).output() else { return };+ let mut apps = APPS.lock().unwrap();+ let mut added = false;+ for line in String::from_utf8_lossy(&o.stdout).lines().filter(|l| l.to_lowercase().ends_with(".exe")).take(12) {+ let w = wide(line);+ if apps.iter().any(|a| a.1 == w) {+ continue;+ }+ let name = std::path::Path::new(line).file_stem().unwrap_or_default().to_string_lossy().to_string();+ apps.push((name, w));+ added = true;+ }+ drop(apps);+ if added {+ unsafe { InvalidateRect(hw as HWND, null(), 0) };+ }+ });+}+fn filtered() -> Vec<usize> {let q = QUERY.with_borrow(|q| q.to_lowercase());let mut apps = APPS.lock().unwrap();@@ -610,7 +646,8 @@ fn menu_rows() -> (Vec<(i32, i32)>, i32) {/// Right-click menu of an empty spot of the bar.pub fn context_menu(x: i32) {- let items = vec![+ let pu = crate::purge_installed();+ let mut items = vec![MItem::new(t!("Параметры Windows", "Windows Settings")).hint("Win+I"),MItem::new(t!("Персонализация", "Personalization")),MItem::new(t!("Диспетчер задач", "Task Manager")).hint("Ctrl+Shift+Esc").sep(),@@ -618,13 +655,18 @@ pub fn context_menu(x: i32) {MItem::new(t!("Программы WinRust на English", "WinRust apps in Русский")), // shared with the other WinRust programsMItem::new(t!("Закрыть панель", "Close the bar")).danger().sep(),];- menu(x, None, items, |i| unsafe {+ if pu {+ items.insert(4, MItem::new(t!("Удалить мусор Windows (необратимо)", "Remove Windows junk (irreversible)")).danger());+ }+ menu(x, None, items, move |i| unsafe {+ let i = if pu && i > 4 { i - 1 } else if pu && i == 4 { 99 } else { i };match i {0 => open(&wide("ms-settings:")),1 => open(&wide("ms-settings:personalization")),// with rtaskmgr-win32 installed this is our task manager; a full path because explorer.exe does not search PATH2 => open(&wide(&format!(r"{}\System32\taskmgr.exe", std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into())))),3 => open_cleaner(),+ 99 => crate::open_purge(),4 => crate::i18n::set_english(!crate::i18n::english()),_ => _ = PostMessageW(FindWindowW(wide("topbar").as_ptr(), null()), WM_CLOSE, 0, 0), // quits the bar, brings the Windows taskbar back}@@ -1466,6 +1508,7 @@ unsafe extern "system" fn proc(hw: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LR});SCROLL.set(0);SEL.set(0);+ find_loose_exes(hw);}}InvalidateRect(hw, null(), 0);diff --git a/plugins/topbar/src/main.rs b/plugins/topbar/src/main.rsindex 989fa59..e426873 100644--- a/plugins/topbar/src/main.rs+++ b/plugins/topbar/src/main.rs@@ -1387,7 +1387,7 @@ unsafe fn bar_anim(hwnd: HWND) {}unsafe fn bar_step(hwnd: HWND) {- let target = if FULLSCREEN.load(Relaxed) || DESK_HIDE.load(Relaxed) { 0.0 } else { 1.0 };+ let target = if FULLSCREEN.load(Relaxed) { 0.0 } else { 1.0 }; // hides only for a fullscreen game or video: not over the desktop, not in any stylelet now = now_ms();let dt = now.saturating_sub(BAR_T.replace(now)).min(50) as f32;let p = BAR_P.get();@@ -1971,6 +1971,9 @@ unsafe fn open(path: &[u16]) {if p.to_lowercase().ends_with(".lnk") {bump(&p);}+ if p.to_lowercase().starts_with("ms-settings:") {+ return winrust_common::settings::open(&p); // needs Explorer as shell: it is started for the time Settings is open+ }// Always through explorer.exe: it starts the target with the desktop user's normal token. ShellExecuteW from here would// inherit this bar's admin rights, and an elevated app cannot receive files dragged in from normal windows (UIPI), and// PrtSc / Win+Shift+S (ms-screenclip:) do not work when started elevated. With an argument and no explorer shell@@ -2167,6 +2170,18 @@ unsafe fn on_drop(hwnd: HWND, hd: HDROP) {InvalidateRect(hwnd, null(), 0);}+/// The junk remover (purge, installed on request): lists what it would delete and asks for YES in its own elevated console.+pub(crate) fn purge_installed() -> bool {+ std::env::var_os("ProgramFiles").is_some_and(|pf| PathBuf::from(pf).join(r"purge\purge.exe").is_file())+}++unsafe fn open_purge() {+ if let Some(pf) = std::env::var_os("ProgramFiles") {+ let exe = PathBuf::from(pf).join(r"purge\purge.exe");+ ShellExecuteW(null_mut(), wide("runas").as_ptr(), wide(&exe.to_string_lossy()).as_ptr(), wide("--ask").as_ptr(), null(), SW_SHOWNORMAL);+ }+}+unsafe fn open_cleaner() {let Some(pf) = std::env::var_os("ProgramFiles") else { return };let exe = PathBuf::from(pf).join(r"rtaskmgr\rs-du.exe");diff --git a/src/cli.rs b/src/cli.rsindex 990d233..21ad04a 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -4,7 +4,7 @@ use crate::*;// ---------- command line ----------//// plugin-launcher list-// plugin-launcher install <plugin> --yes (without --yes it only prints the warning: nothing is changed)+// plugin-launcher install <plugin>... --yes (several names, or `all`; without --yes it only prints the warnings: 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@@ -26,7 +26,7 @@ pub(crate) fn cli(args: &[String]) -> i32 {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 usage = "usage: plugin-launcher list | install <plugin>...|all --yes | update <plugin> | uninstall <plugin> | rollback --yes";let result = match words.as_slice() {["list"] => {for p in PLUGINS {@@ -34,12 +34,43 @@ pub(crate) fn cli(args: &[String]) -> i32 {}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),- },+ ["install", names @ ..] if !names.is_empty() => {+ // several names, or `all` (what the window installs); order of the table, so topbar comes before rust-explorer+ let mut idx = Vec::new();+ for n in names {+ match *n {+ "all" => idx.extend(ready()),+ n => match find(n) {+ Some(i) => idx.push(i),+ None => return { say(&format!("unknown plugin: {n}")); 2 },+ },+ }+ }+ idx.sort_unstable();+ idx.dedup();+ if !yes {+ for &i in &idx {+ say(&format!("{}: {}", PLUGINS[i].name, PLUGINS[i].warn.get()));+ }+ return { say("Nothing changed. Repeat with --yes to install."); 2 };+ }+ // one that fails or is already there does not stop the rest+ let mut failed = false;+ for i in idx {+ if (PLUGINS[i].installed)() {+ say(&format!("{} is already installed", PLUGINS[i].name));+ continue;+ }+ match install_plugin(i) {+ Ok(m) => say(&m),+ Err(e) => {+ failed = true;+ say(&format!("error: {}: {e}", PLUGINS[i].name));+ }+ }+ }+ return if failed { 1 } else { 0 };+ }["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 },diff --git a/src/install/explorer.rs b/src/install/explorer.rsindex 48a0ffb..ccd693f 100644--- a/src/install/explorer.rs+++ b/src/install/explorer.rs@@ -82,7 +82,7 @@ pub(crate) fn rx_install() -> Result<(), String> {}// 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());+ let task = format!("{} 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", task_user(), sh.display());if run("powershell", &["-NoProfile", "-Command", &task]).is_ok() {let _ = run("reg", &["delete", RUN_KEY, "/v", "rs-overlay", "/f"]);} else {@@ -92,6 +92,8 @@ pub(crate) fn rx_install() -> Result<(), String> {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);+ // the bar's Start panel and the search list Start Menu shortcuts only: without one rust-explorer has no entry (and no icon) there+ soft(t!("ярлык «Rust Explorer» в меню Пуск не создан", "Start menu shortcut 'Rust Explorer' was not created"), shortcut(&start_lnk("Rust Explorer"), &fm, ""));// 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());@@ -121,6 +123,7 @@ pub(crate) fn rx_uninstall() -> Result<(), String> {}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_file(start_lnk("Rust Explorer"));let _ = fs::remove_dir_all(rx_dir());if r.is_ok() {let _ = run("reg", &["delete", RX_STATE, "/f"]);diff --git a/src/install/mod.rs b/src/install/mod.rsindex adbb46e..690229a 100644--- a/src/install/mod.rs+++ b/src/install/mod.rs@@ -3,17 +3,20 @@use crate::*;mod explorer;mod search;+mod session;mod taskmgr;mod tools;mod topbar;-pub(crate) use {explorer::*, search::*, taskmgr::*, tools::*, topbar::*};+pub(crate) use {explorer::*, search::*, session::*, 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}"))?;+ // reg.exe: HKCU means the signed-in user's, not the elevated account's (see session.rs)+ let owned: Vec<String> = if prog == "reg" { i18n::reg::user_args(args) } else { args.iter().map(|a| a.to_string()).collect() };+ let o = Command::new(prog).args(&owned).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()))+ Err(format!("{prog} {}: {}{}", owned.join(" "), String::from_utf8_lossy(&o.stdout).trim(), String::from_utf8_lossy(&o.stderr).trim()))}}@@ -120,6 +123,7 @@ pub(crate) fn checkpoint() -> Result<(), String> {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"))?;+ init().inspect_err(|e| log(&tf!("{}: ОШИБКА {e}", "{}: ERROR {e}", p.name)))?; // before anything is written: no user, no installlet was = (p.installed)(); // already installed = an update: a failure must not remove the working copyWARN.lock().unwrap().clear();soft(t!("точка восстановления не создана", "restore point was not created"), checkpoint());@@ -141,6 +145,7 @@ 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"))?;WARN.lock().unwrap().clear();+ init_soft();uninst().inspect_err(|e| log(&tf!("{}: ОШИБКА удаления {e}", "{}: uninstall ERROR {e}", p.name)))?;let w = WARN.lock().unwrap().clone();log(&format!("{}: {} {}", p.name, t!("удалён", "removed"), w.join(" | ")));@@ -149,6 +154,7 @@ pub(crate) fn uninstall_plugin(i: usize) -> Result<String, String> {}pub(crate) fn rollback() -> Result<String, String> {+ init_soft();// reverse install order: rust-explorer (which switched Explorer off) goes before topbar, else the session is left with no panel and no shelllet 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/install/search.rs b/src/install/search.rsindex 17569bd..aa19203 100644--- a/src/install/search.rs+++ b/src/install/search.rs@@ -23,6 +23,11 @@ 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"])}+/// Stripped Windows builds (LTSC ISOs run through a debloater) have no WSearch service: nothing to switch off, not an error.+pub(crate) fn has_wsearch() -> bool {+ run("sc.exe", &["query", "WSearch"]).is_ok()+}+pub(crate) fn install() -> Result<(), String> {// originals first: if anything below fails, the rollback restores exactly thesesave_dword("WSearchStart", reg_dword(WS_KEY, "Start"));@@ -37,8 +42,12 @@ pub(crate) fn install() -> Result<(), String> {// 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"]);+ if has_wsearch() {+ run("sc.exe", &["config", "WSearch", "start=", "disabled"])?;+ let _ = run("sc.exe", &["stop", "WSearch"]);+ } else {+ WARN.lock().unwrap().push(t!("службы Windows Search (WSearch) нет в этой системе: шаг пропущен", "the Windows Search service (WSearch) does not exist on this system: step skipped").into());+ }// SearchHost.exe (the Start/Win+S search UI) is not a service, so it gets the same IFEO trick as taskmgr: Windows runs `cmd /c exit` instead.run("reg", &["add", SH_KEY, "/v", "Debugger", "/t", "REG_SZ", "/d", "cmd.exe /c exit", "/f"])?;let _ = run("taskkill", &["/f", "/im", "SearchHost.exe"]);@@ -58,8 +67,8 @@ pub(crate) fn uninstall() -> Result<(), String> {(Some(4), _) => "disabled",_ => "delayed-auto",};- let svc = run("sc.exe", &["config", "WSearch", "start=", mode]);- if svc.is_ok() && mode.ends_with("auto") {+ let svc = if has_wsearch() { run("sc.exe", &["config", "WSearch", "start=", mode]) } else { Ok(()) }; // nothing to restore without the service+ if svc.is_ok() && mode.ends_with("auto") && has_wsearch() {let _ = run("sc.exe", &["start", "WSearch"]);}let r = svc.and(taskbar_search(reg_dword(STATE, "SearchboxMode").unwrap_or(2)));diff --git a/src/install/session.rs b/src/install/session.rsnew file mode 100644index 0000000..c2fbc76--- /dev/null+++ b/src/install/session.rs@@ -0,0 +1,78 @@+//! Who the per-user settings belong to. UAC can be answered with another administrator's password: the installer then runs as+//! that account, and its HKCU, `$PROFILE` and scheduled-task user are the wrong ones. The right account is the one whose+//! explorer.exe (or, with Explorer replaced, topbar / rust-explorer) runs in this session; its SID goes to every child in+//! WINRUST_SID, and `out()` aims `HKCU\...` at `HKU\<sid>` while it is set.+use crate::*;+use std::sync::OnceLock;++pub(crate) struct Session {+ pub sid: String,+ /// The elevated token belongs to someone else: only then is WINRUST_SID set, so the usual case keeps using plain HKCU.+ pub other: bool,+}++static SESSION: OnceLock<Result<Session, String>> = OnceLock::new();++const FIND: &str = r#"$s=(Get-Process -Id $PID).SessionId; $o=$null+foreach($n in 'explorer','topbar','rust-explorer','rs-shell'){+ $o=Get-CimInstance Win32_Process -Filter "Name='$n.exe'" | Where-Object { $_.SessionId -eq $s } | ForEach-Object { (Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid } | Where-Object { $_ } | Select-Object -First 1+ if($o){break}+}+if(-not $o){ exit 3 }+$o; [Security.Principal.WindowsIdentity]::GetCurrent().User.Value"#;++/// (session user's SID, elevated token's SID) from the two lines the script prints.+pub(crate) fn parse(out: &str) -> Result<(String, String), String> {+ let mut l = out.lines().map(str::trim).filter(|l| !l.is_empty());+ match (l.next(), l.next()) {+ (Some(a), Some(b)) if i18n::reg::valid_sid(a) && i18n::reg::valid_sid(b) => Ok((a.into(), b.into())),+ _ => Err(tf!("не удалось определить пользователя сеанса: {}", "could not determine the signed-in user: {}", out.trim())),+ }+}++fn detect() -> Result<Session, String> {+ let (sid, token) = parse(&out("powershell", &["-NoProfile", "-NonInteractive", "-Command", FIND]).map_err(|e| {+ tf!("не удалось определить пользователя сеанса (нет запущенного explorer.exe, topbar или rust-explorer): {e}", "could not determine the signed-in user (no running explorer.exe, topbar or rust-explorer): {e}")+ })?)?;+ if matches!(sid.as_str(), "S-1-5-18" | "S-1-5-19" | "S-1-5-20") {+ return Err(t!("оболочка сеанса запущена не от обычного пользователя (SYSTEM или служба)", "the session shell does not run as a normal user (SYSTEM or a service)").into());+ }+ Ok(Session { other: sid != token, sid })+}++/// Settles the target user once and, when it is not the elevated account, tells the children. An Err means: change nothing.+pub(crate) fn init() -> Result<&'static Session, String> {+ let s = SESSION.get_or_init(detect).as_ref().map_err(Clone::clone)?;+ if s.other {+ log(&format!("elevated as another account: per-user settings go to {}", s.sid));+ unsafe { env::set_var(i18n::reg::SID_ENV, &s.sid) };+ }+ Ok(s)+}++/// Uninstall must work even when the user cannot be told (a broken session is when it is needed most): then the elevated+/// account's own HKCU is used and the failure becomes a warning.+pub(crate) fn init_soft() {+ if let Err(e) = init() {+ soft(t!("пользователь сеанса не определён, настройки пользователя убираются у текущей учётной записи", "signed-in user unknown, per-user settings are removed from the current account"), Err(e));+ }+}++/// PowerShell: `$u` = the account scheduled tasks are registered for.+pub(crate) fn task_user() -> String {+ match env::var(i18n::reg::SID_ENV).ok().filter(|s| i18n::reg::valid_sid(s)) {+ Some(sid) => format!("$u=(New-Object Security.Principal.SecurityIdentifier '{sid}').Translate([Security.Principal.NTAccount]).Value;"),+ None => "$u=[Security.Principal.WindowsIdentity]::GetCurrent().Name;".into(),+ }+}++/// PowerShell: `$p` = this shell's CurrentUserCurrentHost profile of the target user (Documents may be redirected: the+/// User Shell Folders value of that user's hive says where).+pub(crate) fn profile_path() -> String {+ match env::var(i18n::reg::SID_ENV).ok().filter(|s| i18n::reg::valid_sid(s)) {+ Some(sid) => format!(+ r"$h=(Get-ItemProperty 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{sid}').ProfileImagePath; $d=(Get-ItemProperty 'Registry::HKEY_USERS\{sid}\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders').Personal; $d=[Environment]::ExpandEnvironmentVariables($d.Replace('%USERPROFILE%',$h)); $p=Join-Path $d ($(if($PSVersionTable.PSEdition -eq 'Core'){{'PowerShell'}}else{{'WindowsPowerShell'}}) + '\Microsoft.PowerShell_profile.ps1');"+ ),+ None => "$p=$PROFILE;".into(),+ }+}diff --git a/src/install/taskmgr.rs b/src/install/taskmgr.rsindex ebbc82c..eb68a98 100644--- a/src/install/taskmgr.rs+++ b/src/install/taskmgr.rs@@ -29,7 +29,7 @@ pub(crate) fn tm_install() -> Result<(), String> {// the search (and the bar's Start panel) lists Start Menu shortcuts only, so without one the task manager is invisible to themsoft(t!("ярлык в меню Пуск не создан, поиск не увидит диспетчер", "Start menu shortcut was not created, search will not find the task manager"), shortcut(&start_lnk("Task manager"), &dst, ""));// elevated start without a UAC prompt (the exe re-launches itself through this task), so it can end protected processes- 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());+ let task = format!("{} 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", task_user(), 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"])})diff --git a/src/install/tools.rs b/src/install/tools.rsindex 4cf7e07..25c9ab8 100644--- a/src/install/tools.rs+++ b/src/install/tools.rs@@ -1,4 +1,4 @@-//! wiztree, photoview, debloat: small stand-alone tools, one exe each in its own Program Files folder.+//! wiztree, photoview, debloat, purge: 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 ----------@@ -11,6 +11,10 @@ pub(crate) fn pv_dir() -> PathBuf {program_files().join("photoview")}+pub(crate) fn pu_dir() -> PathBuf {+ program_files().join("purge")+}+pub(crate) fn db_dir() -> PathBuf {program_files().join("debloat")}@@ -98,3 +102,15 @@ pub(crate) fn db_uninstall() -> Result<(), String> {tool_remove("debloat.exe", &db_dir(), None);Ok(())}++/// Installing = removing: purge.exe --apply deletes the bundled apps and telemetry tasks FOR GOOD. Uninstalling only deletes+/// purge.exe itself; there is nothing to put back. OneDrive and Edge are not part of it (`purge.exe --apply --onedrive --edge`).+pub(crate) fn pu_install() -> Result<(), String> {+ tool_install("purge.exe", &pu_dir(), None)?;+ out(&pu_dir().join("purge.exe").display().to_string(), &["--apply"]).map(|_| ())+}++pub(crate) fn pu_uninstall() -> Result<(), String> {+ tool_remove("purge.exe", &pu_dir(), None);+ Ok(())+}diff --git a/src/install/topbar.rs b/src/install/topbar.rsindex ffbd28d..8733b49 100644--- a/src/install/topbar.rs+++ b/src/install/topbar.rs@@ -22,18 +22,20 @@ pub(crate) fn set_od_hidden(v: bool) -> Result<(), 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?','');";+// The profile is the signed-in user's (session.rs), also when UAC was answered with another administrator.+pub(crate) fn ps_strip() -> String {+ format!(r"{} $t=[string]$(if(Test-Path $p){{Get-Content $p -Raw}}); $t=[regex]::Replace($t,'(?s)# >>> topbar >>>.*?# <<< topbar <<<\r?\n?','');", profile_path())+}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"))+ shells_run(&format!("{}$b=@'\n{PS_BLOCK}'@; New-Item -Force -ItemType Directory (Split-Path $p) | Out-Null; Set-Content $p ($t.TrimEnd() + [Environment]::NewLine + $b) -Encoding utf8", ps_strip()))}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}}"))+ shells_run(&format!("{} if($t.Trim()){{Set-Content $p $t -Encoding utf8}}elseif(Test-Path $p){{Remove-Item $p}}", ps_strip()))}/// Runs `script` in every shell. Only the first (always present) can fail the call: a missing pwsh is not an error.@@ -60,7 +62,7 @@ pub(crate) fn bar_install() -> Result<(), String> {// 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());+ let task = format!("{} 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", task_user(), 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 {diff --git a/src/main.rs b/src/main.rsindex fd44034..5842aa7 100644--- a/src/main.rs+++ b/src/main.rs@@ -146,6 +146,16 @@ const PLUGINS: &[Plugin] = &[bulk: false, // changes system behaviour: only on request, never as part of "install everything"glyph: "\u{E74D}", // delete},+ Plugin {+ name: "purge",+ desc: Tr("БЕЗВОЗВРАТНО удаляет предустановленный мусор, как Tiny11: Clipchamp, Новости, Погода, Xbox-оверлеи, Teams, Cortana, виджеты, Skype, Solitaire и др., а также задачи телеметрии. Отката нет.", "PERMANENTLY removes the bundled junk like Tiny11 does: Clipchamp, News, Weather, Xbox overlays, Teams, Cortana, Widgets, Skype, Solitaire and more, plus telemetry tasks. There is no undo."),+ warn: Tr("НЕОБРАТИМО: приложения будут удалены для всех пользователей и из образа (новые пользователи их тоже не получат), задачи телеметрии удалены. Вернуть можно только из Store или winget. Магазин, Параметры, Пуск, Калькулятор, Фото и среды выполнения не затрагиваются. OneDrive и Edge не входят: purge.exe --apply --onedrive --edge. Сначала посмотрите список: purge.exe без параметров ничего не меняет.", "IRREVERSIBLE: apps are removed for all users and from the image (new users will not get them), telemetry tasks are deleted. They come back only from the Store or winget. The Store, Settings, Start, Calculator, Photos and runtimes are not touched. OneDrive and Edge are not included: purge.exe --apply --onedrive --edge. Look at the list first: purge.exe with no arguments changes nothing."),+ installed: || pu_dir().join("purge.exe").is_file(),+ actions: Some((pu_install, pu_uninstall)),+ settings: false,+ bulk: false, // destructive and permanent: only on request, never as part of "install everything"+ glyph: "\u{E74D}", // delete+ },Plugin { name: "chrome-rs", desc: Tr("Браузер на Rust. Установка пока недоступна (заглушка).", "A browser in Rust. Installation is not available yet (placeholder)."), warn: Tr("", ""), installed: || false, actions: None, settings: false, bulk: true, glyph: "\u{E774}" }, // globe];@@ -157,6 +167,8 @@ fn refresh() {f.store((p.installed)(), Relaxed);}}+// which components the window's checkboxes have ticked (all by default); the one button installs / updates only these+static SELECTED: [AtomicBool; PLUGINS.len()] = [const { AtomicBool::new(true) }; PLUGINS.len()];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) }; }diff --git a/src/ui.rs b/src/ui.rsindex 0df75b3..1253faa 100644--- a/src/ui.rs+++ b/src/ui.rs@@ -114,6 +114,7 @@ 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 ID_CHECK: usize = 100; // + plugin index: the row's checkboxpub(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).@@ -121,6 +122,17 @@ pub(crate) fn ready() -> impl Iterator<Item = usize> {(0..PLUGINS.len()).filter(|&i| PLUGINS[i].actions.is_some() && PLUGINS[i].bulk)}+/// The components the checkboxes have ticked, in install order.+pub(crate) fn chosen() -> impl Iterator<Item = usize> {+ ready().filter(|&i| SELECTED[i].load(Relaxed))+}++/// Checkbox at the left end of row `k`, and the larger area that toggles it.+pub(crate) fn check_box(k: usize, w: f32) -> (Box4, Box4) {+ let r = row_box(k, w);+ ([r[0] + 12.0, r[1] + 22.0, r[0] + 30.0, r[1] + 40.0], [r[0] + 4.0, r[1] + 8.0, r[0] + 38.0, r[3] - 8.0])+}+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]@@ -216,14 +228,16 @@ pub(crate) unsafe fn paint(hwnd: HWND) {// component listui.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 pos = chosen().position(|i| i == job); // where install_all is now+ let n_sel = chosen().count();+ let n_sel_inst = chosen().filter(|&i| INSTALLED[i].load(Relaxed)).count();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));+ let queued = busy && !installed && SELECTED[i].load(Relaxed) && (job == STARTING || ready().position(|j| j == job).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));}@@ -231,7 +245,13 @@ pub(crate) unsafe fn paint(hwnd: HWND) {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 (cb, _) = check_box(k, w);+ let sel = SELECTED[i].load(Relaxed);+ ui.round(cb, 5.0, if sel { ACCENT } else { PANEL }, if sel { ACCENT } else { lerp(BORDER, TEXT, if hot(ID_CHECK + i) { 0.4 } else { 0.0 }) });+ if sel {+ ui.text_in("\u{E73E}", cb, 11.0, 700, rgb(255, 255, 255), DT_CENTER | DT_VCENTER | DT_SINGLELINE, "Segoe MDL2 Assets");+ }+ let tile = [r[0] + 42.0, r[1] + 13.0, r[0] + 78.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);@@ -271,26 +291,30 @@ pub(crate) unsafe fn paint(hwnd: HWND) {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) };+ let done = if job == n { 0.0 } else { pos.map_or(0.0, |q| (q as f32 + 0.5) / n_sel 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))+ pos.map_or(t!("Подготовка…", "Preparing…").into(), |q| tf!("Устанавливается {} ({} из {})", "Installing {} ({} of {})", PLUGINS[job].name, q + 1, n_sel))};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 {+ let all = n_sel_inst == n_sel && n_sel > 0;+ let label = if n_sel == 0 {+ t!("Отметьте компоненты", "Tick the components").to_string()+ } else if n_sel < N_READY {+ if all { tf!("Обновить выбранное ({n_sel})", "Update selected ({n_sel})") } else { tf!("Установить выбранное ({n_sel})", "Install selected ({n_sel})") }+ } else 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, fg) = if all || n_sel == 0 { (PANEL, if n_sel == 0 { DIM } else { 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);@@ -411,6 +435,9 @@ pub(crate) unsafe fn hit(hwnd: HWND, lp: isize) -> Option<usize> {if gear_box(w).is_some_and(|(i, b)| INSTALLED[i].load(Relaxed) && inside(b)) {return Some(ID_GEAR);}+ if let Some(i) = ready().enumerate().find_map(|(k, i)| inside(check_box(k, w).1).then_some(i)) {+ return Some(ID_CHECK + i);+ }if inside(lang_box(w)) {return Some(ID_LANG);}@@ -439,22 +466,27 @@ pub(crate) fn start(hwnd: HWND, which: usize, job: impl FnOnce() -> Result<Strin}/// 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.+/// Only the ticked ones. A failed or skipped one does not stop the others (rust-explorer refuses by itself while topbar is+/// missing); the failures are listed at the end. `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() {+ let all = chosen().all(|i| (PLUGINS[i].installed)());+ let (mut done, mut failed, mut warned) = (Vec::new(), Vec::new(), false);+ for i in chosen() {// installed ones are updated too: a newer installer must bring its fixes to them, not only add what is missingJOB.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));+ failed.push(format!("{}: {e}", PLUGINS[i].name));+ continue;}warned |= !WARN.lock().unwrap().is_empty(); // install_plugin clears the list for each componentdone.push(PLUGINS[i].name);refresh();}+ if !failed.is_empty() {+ let ok = if done.is_empty() { String::new() } else { tf!(" Готово: {}.", " Done: {}.", done.join(", ")) };+ return Err(format!("{}.{ok}", failed.join("; ")));+ }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(", ")))}@@ -501,6 +533,11 @@ pub(crate) unsafe fn click(hwnd: HWND, id: usize) {return;}match id {+ i if i >= ID_CHECK => {+ SELECTED[i - ID_CHECK].fetch_xor(true, Relaxed);+ InvalidateRect(hwnd, null(), 0);+ }+ ID_MAIN if chosen().next().is_none() => {}ID_LANG => {i18n::set_english(!i18n::english());HOVER.set(None);@@ -518,13 +555,20 @@ pub(crate) unsafe fn click(hwnd: HWND, id: usize) {danger: true,act: Act::Rollback,}),- ID_MAIN if ready().all(|i| INSTALLED[i].load(Relaxed)) => ask(hwnd, Dialog {+ ID_MAIN if chosen().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 if chosen().count() < N_READY => ask(hwnd, Dialog {+ title: t!("Установить выбранное?", "Install the selected?").into(),+ text: tf!("Будет установлено или обновлено: {}.\n\nКомпоненты меняют систему (подробности в описании каждого). Создаётся точка восстановления, «Удалить всё» вернёт систему.", "To be installed or updated: {}.\n\nThe components change the system (see each one's description). A restore point is created, 'Remove all' restores the system.", chosen().map(|i| PLUGINS[i].name).collect::<Vec<_>>().join(", ")).into(),+ ok: t!("Установить", "Install").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(),