Windows shell replacement in Rust: taskbar, file manager, NTFS search, task manager, disk cleaner. One installer exe.
Rust
Make rust-explorer opt-in for new installs (PR #43)
Lemxyf32367bd345d
diff --git a/Cargo.toml b/Cargo.tomlindex a10e5ea..f4265c9 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -9,6 +9,10 @@ name = "plugin-launcher"path = "src/main.rs"test = false # the embedded manifest demands admin: a test exe could not start from a normal shell+[[test]]+name = "install-selection"+path = "src/selection.rs"+[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_System_Registry", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }diff --git a/README.md b/README.mdindex b2863f9..776ec13 100644--- a/README.md+++ b/README.md@@ -14,13 +14,13 @@ 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. 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.+3. Tick the components you want and press the install button. On a fresh install, `rust-explorer` is unchecked. Tick it to replace the Windows Explorer shell. 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.+**Update:** download the new `WinRust.exe` from the releases page, run it as administrator and select the components you want to update or install. An existing `rust-explorer` stays selected by default for updates. Your settings and the saved original Windows values stay.The installer is in English. The **Русский** button in its corner (or "WinRust apps in Русский" in the bar's right-click menu) switches every WinRust program to Russian.@@ -138,11 +138,13 @@ 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 (one or more names, or `all` for what the window installs; without --yes it only prints the warnings and changes nothing)+plugin-launcher install <plugin>... --yes (one or more names, or `all` for the default components; without --yes it only prints warnings)plugin-launcher update <plugin> (reinstall from payload\ next to the exe)plugin-launcher uninstall <plugin>plugin-launcher rollback --yes (remove everything)```++To include `rust-explorer` in a fresh bulk install, run `plugin-launcher install all rust-explorer --yes`. If `topbar` is already installed, you can install `rust-explorer` on its own.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 plugindiff --git a/README.ru.md b/README.ru.mdindex ba58d71..4f899a8 100644--- a/README.ru.md+++ b/README.ru.md@@ -14,13 +14,13 @@1. Скачайте `WinRust.exe` из [последнего релиза](https://github.com/Lemxy/WinRust/releases/latest) (Windows 10/11, x64).2. Запустите от имени администратора.-3. Отметьте галочками нужные компоненты (по умолчанию отмечены все) и нажмите **Install WinRust**. Они ставятся в правильном порядке; упавший или пропущенный компонент не останавливает остальные, окно покажет, что пошло не так.+3. Отметьте галочками нужные компоненты и нажмите кнопку установки. При первой установке `rust-explorer` не отмечен. Отметьте его, если хотите заменить оболочку Проводника Windows. Они ставятся в правильном порядке; упавший или пропущенный компонент не останавливает остальные, окно покажет, что пошло не так.Поиск Windows необязателен: в урезанной Windows (например, LTSC-образ без службы Windows Search) этот шаг пропускается с предупреждением, а не ломает установку.Если UAC просит пароль **другого администратора**, пользовательские настройки (автозапуск, задачи планировщика, профиль PowerShell, права поиска) всё равно записываются тому, кто вошёл в систему, а не введённому администратору. Если установщик не может определить этого пользователя, он останавливается, ничего не изменив.-**Обновление:** скачайте новый `WinRust.exe` со страницы релизов, запустите от имени администратора и нажмите **Update WinRust** («Обновить WinRust» в русском режиме). Установленные плагины обновятся, недостающие поставятся; ваши настройки и сохранённые исходные значения Windows остаются.+**Обновление:** скачайте новый `WinRust.exe` со страницы релизов, запустите от имени администратора и выберите компоненты для обновления или установки. Если `rust-explorer` уже установлен, он по умолчанию отмечен для обновления. Ваши настройки и сохранённые исходные значения Windows остаются.Установщик открывается на английском. Кнопка **Русский** в его углу (или «Программы WinRust на English» в меню панели по правому клику) переключает язык всех программ WinRust.@@ -138,11 +138,13 @@ powershell -ExecutionPolicy Bypass -File scripts\build-all.ps1Из терминала **с правами администратора**:```plugin-launcher list-plugin-launcher install <плагин>... --yes (одно или несколько имён, либо `all` = то, что ставит окно; без --yes только покажет предупреждения и ничего не изменит)+plugin-launcher install <плагин>... --yes (одно или несколько имён, либо `all` для компонентов по умолчанию; без --yes только покажет предупреждения)plugin-launcher update <плагин> (переустановить из payload\ рядом с exe)plugin-launcher uninstall <плагин>plugin-launcher rollback --yes (удалить всё)```++Чтобы включить `rust-explorer` в первую установку всех компонентов, выполните `plugin-launcher install all rust-explorer --yes`. Если `topbar` уже установлен, можно установить `rust-explorer` отдельно.Несколько плагинов в одной команде ставятся в порядке таблицы (topbar раньше rust-explorer); упавший не останавливает остальные. Коды выхода: 0 успех, 1 ошибка (хотя бы один плагин не встал), 2 неверные аргументы или нет `--yes`. Без аргументов открывается окно. Журнал установки: `%ProgramData%\plugin-launcher\install.log`.### Новый плагинdiff --git a/src/cli.rs b/src/cli.rsindex 21ad04a..06017e5 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 (several names, or `all`; without --yes it only prints the warnings: nothing is changed)+// plugin-launcher install <plugin>... --yes (several names, or `all` for the defaults; without --yes it only prints warnings)// 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@@ -35,11 +35,11 @@ pub(crate) fn cli(args: &[String]) -> i32 {return 0;}["install", names @ ..] if !names.is_empty() => {- // several names, or `all` (what the window installs); order of the table, so topbar comes before rust-explorer+ // Order of the table, so topbar comes before rust-explorer if both are requested.let mut idx = Vec::new();for n in names {match *n {- "all" => idx.extend(ready()),+ "all" => idx.extend(ready().filter(|&i| selected_by_default(PLUGINS[i].name, false))),n => match find(n) {Some(i) => idx.push(i),None => return { say(&format!("unknown plugin: {n}")); 2 },diff --git a/src/main.rs b/src/main.rsindex 0c68688..57808cd 100644--- a/src/main.rs+++ b/src/main.rs@@ -10,8 +10,9 @@ extern crate winrust_common;use winrust_common as i18n;mod cli;mod install;+mod selection;mod ui;-use {cli::*, install::*, ui::*};+use {cli::*, install::*, selection::*, ui::*};use std::{cell::Cell,env, fs,@@ -72,7 +73,7 @@ struct Plugin {installed: fn() -> bool,actions: Option<(fn() -> Result<(), String>, fn() -> Result<(), String>)>, // (install, uninstall); None = stubsettings: bool, // shows a gear button that opens the plugin's settings panel- bulk: bool, // part of the one-click "install everything" (the window lists only these); false = command line only+ bulk: bool, // visible in the window and eligible for bulk install; false = command line onlyglyph: &'static str, // Segoe MDL2 Assets icon}const PLUGINS: &[Plugin] = &[@@ -107,7 +108,7 @@ const PLUGINS: &[Plugin] = &[glyph: "\u{E700}", // menu},Plugin {- name: "rust-explorer",+ name: RUST_EXPLORER,desc: Tr("Файловый менеджер на Rust вместо Проводника: папки и диски открываются в нём (Win+E тоже), рабочий стол рисует он сам. Обычный explorer.exe как оболочка ОТКЛЮЧАЕТСЯ. Нужен topbar.", "A Rust file manager instead of Explorer: folders and drives open in it (Win+E too), and it draws the desktop itself. The regular explorer.exe as the shell is DISABLED. Requires topbar."),warn: Tr("ОБЫЧНЫЙ Explorer будет ОТКЛЮЧЁН: после установки панель задач, рабочий стол и окна папок дают topbar и rust-explorer. Сначала установите topbar, без него не будет панели. Ещё для экономии RAM отключаются службы PcaSvc, InventorySvc, lfsvc (геолокация), cbdhsvc (журнал буфера Win+V), DoSvc ставится вручную, службы svchost объединяются (полностью после перезагрузки); удаление плагина вернёт их. Если что-то пойдёт не так: Ctrl+Alt+Del, Диспетчер задач, Запустить новую задачу, explorer.exe; затем удалите плагин.", "The REGULAR Explorer will be DISABLED: after install, topbar and rust-explorer provide the taskbar, the desktop and folder windows. Install topbar first, without it there will be no bar. To save RAM the services PcaSvc, InventorySvc, lfsvc (geolocation) and cbdhsvc (Win+V clipboard history) are also disabled, DoSvc is set to manual, and svchost services are merged (fully after a reboot); uninstalling the plugin restores them. If something goes wrong: Ctrl+Alt+Del, Task Manager, Run new task, explorer.exe; then uninstall the plugin."),installed: || rx_dir().join("rust-explorer.exe").is_file(),@@ -177,8 +178,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()];+// Initialized when the window opens. Refreshing installed state preserves the user's checkbox choices.+static SELECTED: [AtomicBool; PLUGINS.len()] = [const { AtomicBool::new(false) }; 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) }; }@@ -188,8 +189,11 @@ fn main() {if !args.is_empty() {std::process::exit(cli(&args));}+ refresh();+ for i in ready() {+ SELECTED[i].store(selected_by_default(PLUGINS[i].name, INSTALLED[i].load(Relaxed)), Relaxed);+ }unsafe {- refresh();let (mut token, mut input): (usize, GdiplusStartupInput) = (0, zeroed());input.GdiplusVersion = 1;GdiplusStartup(&mut token, &input, null_mut());diff --git a/src/selection.rs b/src/selection.rsnew file mode 100644index 0000000..a5c881e--- /dev/null+++ b/src/selection.rs@@ -0,0 +1,24 @@+//! Default component selection for the installer window and `install all`.++pub(crate) const RUST_EXPLORER: &str = "rust-explorer";++pub(crate) fn selected_by_default(name: &str, installed: bool) -> bool {+ name != RUST_EXPLORER || installed+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn fresh_install_does_not_replace_explorer_by_default() {+ assert!(!selected_by_default(RUST_EXPLORER, false));+ assert!(selected_by_default("topbar", false));+ assert!(selected_by_default("rust-search", false));+ }++ #[test]+ fn existing_rust_explorer_is_selected_for_gui_updates() {+ assert!(selected_by_default(RUST_EXPLORER, true));+ }+}diff --git a/src/ui.rs b/src/ui.rsindex c63bec2..60aadbe 100644--- a/src/ui.rs+++ b/src/ui.rs@@ -557,18 +557,25 @@ pub(crate) unsafe fn click(hwnd: HWND, id: usize) {}),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(),+ text: t!("Выбранные компоненты будут переустановлены из этой версии установщика. Настройки сохранятся.", "The selected 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 if chosen().count() < N_READY => {+ let mut 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(", "));+ if let Some(i) = chosen().find(|&i| PLUGINS[i].name == RUST_EXPLORER && !INSTALLED[i].load(Relaxed)) {+ text.push_str("\n\n");+ text.push_str(PLUGINS[i].warn.get());+ }+ ask(hwnd, Dialog {+ title: t!("Установить выбранное?", "Install the selected?").into(),+ text,+ 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(),