Skip to content

Windows shell replacement in Rust: taskbar, file manager, NTFS search, task manager, disk cleaner. One installer exe.

Rust

Release v0.5.1

Lemxyc29173578a42
diff --git a/ROADMAP.md b/ROADMAP.md
index 4c2cf9e..b0b6a5e 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -46,8 +46,10 @@ emoved.txt`. `purge.exe` lists, `--ask` asks for YES (the bar's right-click menu
- **v0.5.0, from the issue tracker**: the gear menu has "Hide the bar automatically" (`%ProgramData%\WinRust\autohide.txt`, off by default); Win+Shift+S is our own region clipper (a dimmed copy of the desktop, drag a rectangle, it goes to the clipboard and `Pictures\Screenshots`); the volume keys and Surface's power + volume-up work without Explorer; a keyboard button sits in the Start search; brightness goes through the video driver (`\\.\LCD`); the Wi-Fi switch goes through Windows' radio manager (the WLAN API cannot undo airplane mode); rust-explorer shows desktop shortcut names and mapped network drives, and Space opens a picture in photoview. *built, tests; brightness read and write ran on a laptop; the clipper, volume keys, Surface buttons, Wi-Fi and Bluetooth fixes not run on a live device*
- **Speed (after v0.5.0)**: rtaskmgr's new Speed page: Game / Work profiles (services stopped and apps closed are written to `%ProgramData%\WinRust\profile.txt` and started again, apps with the token of the session's `sihost.exe` so they do not inherit admin rights), clearing the memory standby list now or automatically (topbar's thread, `%ProgramData%\WinRust\autopurge.txt`), IFEO blocks for StartMenuExperienceHost / Widgets / WidgetService / PhoneExperienceHost (only with topbar), and four new debloat groups with their own undo files: `updaters` (third-party updater services and tasks off, a weekly `winget upgrade --all` task; browsers are left alone), `defender` (exclusions for cargo/rustup/npm/pip/NuGet/Gradle caches and Steam/Epic libraries, after a confirmation), `ntfs` (no last-access times, no 8.3 names), `dns` (about 170 ad domains in hosts, no Microsoft ones). debloat.exe ships next to the task manager; uninstalling the task manager runs `--undo-speed` first. Startup lists logon/boot tasks and third-party auto-start services and the slowdown each caused (events 100/101/103 of Diagnostics-Performance); What's slow shows DPC/interrupt time, hung windows, slow disk, free vs standby memory and boot times. rust-explorer: own copier for copies and moves to another drive (parallel unless a disk has a seek penalty, `COPY_FILE_NO_BUFFERING` from 256 MB, sources deleted only after every file arrived), Compress to ZIP (files up to 64 MB compressed on all cores) and Extract here for ZIP and 7z. Emptying working sets was left out on purpose: trimmed pages go to the standby list, which already counts as available, so it only adds page faults. *tests (debloat parsing, hosts round trip, boot log parsing, task XML, profile file, copy/move, ZIP and 7z round trips); dry runs of the debloat groups ran; nothing applied on a live system yet, the boot log and the memory lists need admin and were not read here*
+- **v0.5.1 fixes**: right click on the Start button opens a Win+X-style menu (apps, power options, event viewer, system, device manager, network, disk and computer management, terminal, task manager, settings, file explorer, run, desktop, lock / sleep / restart / shut down) (#40); the shell context menu in rust-explorer now passes the click point (`CMIC_MASK_PTINVOKE`), so "Open with > Choose another app" should open on screen (#38, not confirmed on the reporter's monitor). Win+E opens rust-explorer through reshell (#41). *built, tests; the new menu and dialog were not looked at on a live screen*
## Next (in order)
+0. **Scripted shell customization** (#39, Windhawk-style): a way to load small user mods that change the bar, Start panel and file manager without rebuilding WinRust. Not started: needs a mod format (script or DLL), a sandbox, and a stable API of the shell parts first.
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.
diff --git a/ROADMAP.ru.md b/ROADMAP.ru.md
index c54e92a..dfc8b52 100644
--- a/ROADMAP.ru.md
+++ b/ROADMAP.ru.md
@@ -46,8 +46,10 @@ emoved.txt`. `purge.exe` показывает список, `--ask` просит
- **v0.5.0, по тикетам**: в меню шестерёнки есть «Скрывать панель автоматически» (`%ProgramData%\WinRust\autohide.txt`, по умолчанию выключено); Win+Shift+S — собственный выбор области (затемнённая копия рабочего стола, выделите прямоугольник, он попадает в буфер и в `Pictures\Screenshots`); клавиши громкости и «питание + громкость вверх» на Surface работают без Проводника; кнопка клавиатуры в поиске «Пуска»; яркость идёт через видеодрайвер (`\\.\LCD`); переключатель Wi-Fi идёт через менеджер радио Windows (WLAN API не отменяет режим «в самолёте»); rust-explorer показывает имена ярлыков рабочего стола и сетевые диски, а Пробел открывает картинку в photoview. *собрано, тесты; чтение и запись яркости проверены на ноутбуке; выбор области, клавиши громкости, кнопки Surface, правки Wi-Fi и Bluetooth на живом устройстве не запускались*
- **Ускорение (после v0.5.0)**: новая страница «Ускорение» в rtaskmgr: профили «Игра» и «Работа» (остановленные службы и закрытые программы записываются в `%ProgramData%\WinRust\profile.txt` и запускаются обратно; программы с токеном `sihost.exe` своего сеанса, чтобы не унаследовать права администратора), очистка списка standby сейчас или автоматически (поток в topbar, `%ProgramData%\WinRust\autopurge.txt`), блок через IFEO для StartMenuExperienceHost / Widgets / WidgetService / PhoneExperienceHost (только при topbar) и четыре новые группы debloat со своими файлами отката: `updaters` (службы и задачи сторонних апдейтеров отключены, задача `winget upgrade --all` раз в неделю; браузеры не трогаются), `defender` (исключения для кэшей cargo/rustup/npm/pip/NuGet/Gradle и библиотек Steam/Epic, после подтверждения), `ntfs` (без времени последнего доступа и имён 8.3), `dns` (около 170 рекламных доменов в hosts, без доменов Microsoft). debloat.exe лежит рядом с диспетчером; удаление диспетчера сначала запускает `--undo-speed`. «Автозагрузка» показывает задачи при входе и загрузке и сторонние службы с автозапуском и то, насколько каждая замедлила загрузку (события 100/101/103 журнала Diagnostics-Performance); «Что тормозит» показывает время DPC и прерываний, зависшие окна, медленный диск, свободную память против standby и время загрузки. rust-explorer: своё копирование для копий и переносов на другой диск (параллельно, если у дисков нет штрафа за поиск; `COPY_FILE_NO_BUFFERING` от 256 МБ; источник удаляется, только когда дошли все файлы), «Compress to ZIP» (файлы до 64 МБ сжимаются на всех ядрах) и «Extract here» для ZIP и 7z. Очистку рабочих наборов не сделали сознательно: вытесненные страницы уходят в standby, который и так считается доступной памятью, так что она только добавляет ошибок страниц. *тесты (разбор debloat, hosts туда и обратно, журнал загрузки, XML задач, файл профиля, копирование и перенос, ZIP и 7z туда и обратно); сухой прогон групп debloat запускался; на живой системе ничего не применялось, журнал загрузки и списки памяти требуют администратора и здесь не читались*
+- **Исправления v0.5.1**: правый клик по кнопке «Пуск» открывает меню в стиле Win+X (приложения, электропитание, просмотр событий, система, диспетчер устройств, сеть, управление дисками и компьютером, терминал, диспетчер задач, параметры, проводник, «Выполнить», рабочий стол, блокировка / сон / перезагрузка / завершение работы) (#40); контекстное меню оболочки в rust-explorer теперь передаёт точку клика (`CMIC_MASK_PTINVOKE`), поэтому «Открыть с помощью → Выбрать другое приложение» должно открываться на экране (#38, на мониторе автора не подтверждено). Win+E открывает rust-explorer через reshell (#41). *собрано, тесты; новое меню и диалог на живом экране не смотрели*
## Дальше (по порядку)
+0. **Скрипты для настройки оболочки** (#39, как Windhawk): способ загружать небольшие пользовательские моды, которые меняют панель, меню «Пуск» и файловый менеджер без пересборки WinRust. Не начато: сначала нужны формат модов (скрипт или DLL), песочница и стабильный API частей оболочки.
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 в виртуалке**: установка, удаление, откат, перезагрузка, по каждому плагину. На другой машине пока ничего не проверялось.
diff --git a/plugins/rust-explorer/src/main.rs b/plugins/rust-explorer/src/main.rs
index caca275..d85aeab 100644
--- a/plugins/rust-explorer/src/main.rs
+++ b/plugins/rust-explorer/src/main.rs
@@ -648,8 +648,17 @@ mod sh {
return Ok(Some(id as u32));
}
if id > 0 {
- let ci = CMINVOKECOMMANDINFO { cbSize: size_of::<CMINVOKECOMMANDINFO>() as u32, hwnd, lpVerb: PCSTR((id - 1) as usize as *const u8), nShow: SW_SHOWNORMAL.0, ..Default::default() };
- cm.InvokeCommand(&ci)?;
+ // ptInvoke: without it dialogs the shell opens ("Open with" > choose another app) land off screen
+ let ci = CMINVOKECOMMANDINFOEX {
+ cbSize: size_of::<CMINVOKECOMMANDINFOEX>() as u32,
+ fMask: CMIC_MASK_PTINVOKE,
+ hwnd,
+ lpVerb: PCSTR((id - 1) as usize as *const u8),
+ nShow: SW_SHOWNORMAL.0,
+ ptInvoke: pt,
+ ..Default::default()
+ };
+ cm.InvokeCommand(&ci as *const _ as *const CMINVOKECOMMANDINFO)?;
}
DestroyMenu(menu)?;
Ok(None)
diff --git a/plugins/topbar/src/fly.rs b/plugins/topbar/src/fly.rs
index 6afe17d..6b4e5e2 100644
--- a/plugins/topbar/src/fly.rs
+++ b/plugins/topbar/src/fly.rs
@@ -1141,7 +1141,7 @@ unsafe fn run_act(a: Act, rect: RECT, x: i32) {
}
/// Sleep (S3 / modern standby), never hibernate. SetSuspendState needs the shutdown privilege switched on in our token.
-fn sleep_now() {
+pub fn sleep_now() {
use windows_sys::Win32::{
Security::{AdjustTokenPrivileges, LookupPrivilegeValueW, SE_PRIVILEGE_ENABLED, TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES},
System::{Power::SetSuspendState, Threading::{GetCurrentProcess, OpenProcessToken}},
diff --git a/plugins/topbar/src/main.rs b/plugins/topbar/src/main.rs
index 80d382f..f7dd586 100644
--- a/plugins/topbar/src/main.rs
+++ b/plugins/topbar/src/main.rs
@@ -2315,6 +2315,54 @@ unsafe fn style_menu() {
});
}
+/// Right click on Start: the Win+X menu (Explorer's own is gone with the bar).
+unsafe fn start_menu() {
+ let bar = BAR.load(Relaxed) as HWND;
+ // (label, target); "!" targets are actions of ours, the rest goes through `open`
+ let tools: [(&str, &str, &str); 14] = [
+ ("Приложения и возможности", "Apps and Features", "ms-settings:appsfeatures"),
+ ("Электропитание", "Power Options", "powercfg.cpl"),
+ ("Просмотр событий", "Event Viewer", "eventvwr.msc"),
+ ("Система", "System", "ms-settings:about"),
+ ("Диспетчер устройств", "Device Manager", "devmgmt.msc"),
+ ("Сетевые подключения", "Network Connections", "ms-settings:network"),
+ ("Управление дисками", "Disk Management", "diskmgmt.msc"),
+ ("Управление компьютером", "Computer Management", "compmgmt.msc"),
+ ("Терминал", "Terminal", "!term"),
+ ("Диспетчер задач", "Task Manager", "taskmgr.exe"),
+ ("Параметры", "Settings", "ms-settings:"),
+ ("Проводник", "File Explorer", "shell:MyComputerFolder"),
+ ("Выполнить", "Run", "!run"),
+ ("Рабочий стол", "Desktop", "!desktop"),
+ ];
+ let power = [("Блокировка", "Lock", "!lock"), ("Сон", "Sleep", "!sleep"), ("Перезагрузка", "Restart", "!restart"), ("Завершение работы", "Shut down", "!shutdown")];
+ let mut items = Vec::new();
+ let mut targets = Vec::new();
+ for (i, (ru, en, to)) in tools.iter().chain(power.iter()).enumerate() {
+ let it = fly::MItem::new(t!(*ru, *en));
+ items.push(if i == tools.len() { it.sep() } else { it });
+ targets.push(*to);
+ }
+ let head = (null_mut(), "\u{E700}", t!("Пуск", "Start").to_string(), String::new());
+ fly::menu(tip_cx(&bar_layout(bar), 0), Some(head), items, move |i| {
+ let Some(&to) = targets.get(i) else { return };
+ let quiet = |c: &mut Command| { let _ = c.creation_flags(NO_WINDOW).spawn(); };
+ match to {
+ "!term" => {
+ let wt = std::env::var_os("LOCALAPPDATA").map(|b| PathBuf::from(b).join(r"Microsoft\WindowsApps\wt.exe")).filter(|p| p.is_file());
+ open(&wide(if wt.is_some() { "wt.exe" } else { "powershell.exe" }));
+ }
+ "!run" => quiet(Command::new("rundll32.exe").args(["shell32.dll,#61"])),
+ "!desktop" => winrust_common::desktop::toggle(),
+ "!lock" => quiet(Command::new("rundll32.exe").args(["user32.dll,LockWorkStation"])),
+ "!sleep" => fly::sleep_now(),
+ "!restart" => quiet(Command::new("shutdown").args(["/r", "/t", "0"])),
+ "!shutdown" => quiet(Command::new("shutdown").args(["/s", "/t", "0"])),
+ _ => open(&wide(to)),
+ }
+ });
+}
+
/// Puts the open, not minimized windows side by side in the work area.
unsafe fn tile_windows() {
let wins: Vec<HWND> = BTNS.with_borrow(|b| b.iter().flat_map(|b| b.wins.iter().copied()).filter(|&w| IsIconic(w) == 0).collect());
@@ -2363,11 +2411,8 @@ unsafe fn click(h: i32, left: bool, mid: bool) {
ti.into_iter().for_each(|ti| tray_click(ti, left));
}
}
- 0 => {
- if left {
- fly::toggle(fly::Kind::Start);
- }
- }
+ 0 if left => fly::toggle(fly::Kind::Start),
+ 0 => start_menu(),
1.. => {
let (wins, lnk) = BTNS.with_borrow(|b| b.get(h as usize).map(|b| (b.wins.clone(), b.pin.and_then(|p| PINS.with_borrow(|p2| p2.get(p).map(|x| x.lnk.clone()))))).unwrap_or_default());
match (wins.first(), left) {