Skip to content

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

Rust

Release v0.5.2

Lemxy472ffc4b87ad
diff --git a/README.md b/README.md
index cf01d69..2382a4f 100644
--- a/README.md
+++ b/README.md
@@ -38,8 +38,8 @@ On uninstall, `rust-explorer` restores the service startup values and the svchos
|---|---|---|
| **rust-search** | File search over all NTFS drives, Alt+Space | Disables the Windows Search service, blocks SearchHost.exe, hides the taskbar search box |
| **rtaskmgr-win32** | Task Manager (Ctrl+Shift+Esc opens it) | `taskmgr.exe` is redirected to it (the system file is untouched). Also installs the **rs-du** disk cleaner. The **Speed** page has opt-in, reversible switches: Game / Work profiles (stop background services, close launchers or sync apps, start them again), clear the memory standby cache (now, or automatically while topbar runs), block the Windows Start menu, widgets and Phone Link processes, one weekly `winget upgrade` instead of third-party updaters, Defender exclusions for build caches and game libraries, faster NTFS (no last-access times, no 8.3 names), an ad-blocking hosts file. **Startup** also lists logon/boot tasks and third-party auto-start services, with how much each slowed the last boots (Windows' own boot log). **What's slow** shows driver time (DPC/interrupts), hung windows, slow disk and boot times. Uninstall turns all of it back |
-| **topbar** | A Windows 11-style bottom bar: windows, clock, volume, menus | Hides the stock taskbar. Also installs **reshell** (hotkeys: Win+1/2/3 and Win+\` switch desktops, Win+D shows the desktop, Win+I opens Settings, Win+E the file manager; brings the taskbar back if the bar dies), **rs-du**, and a block in your PowerShell profile (`zoxide`, `grep`=rg, `ll`=eza, `cat`=bat; does nothing if they are missing) |
-| **rust-explorer** | A file manager with tabs, and the desktop | Folders and drives open in it; **Explorer stops being the shell** (comes back by itself if topbar fails). On fresh installs, adjusts the startup settings of PcaSvc, InventorySvc, lfsvc, cbdhsvc and DoSvc, and the svchost grouping threshold, when their values can be backed up. Its own copier (several files at once on SSDs, unbuffered for big files, progress in the status line) and right-click **Compress to ZIP** (all cores) / **Extract here** (ZIP and 7z). Requires topbar |
+| **topbar** | A Windows 11-style bottom bar: windows, clock, volume, menus | Hides the stock taskbar. Also installs **reshell** (hotkeys: Win+1/2/3 and Win+\` switch desktops, Win+D shows the desktop, Win+I opens Settings, Win+E the file manager; brings the taskbar back if the bar dies), **rs-du**, and a block in your PowerShell profile (`zoxide`, `grep`=rg, `ll`=eza, `cat`=bat; does nothing if they are missing). The gear menu puts the bar at the bottom / left / right edge and can put the buttons at the left end, like Windows 10 |
+| **rust-explorer** | A file manager with tabs, and the desktop | Folders and drives open in it; **Explorer stops being the shell** (comes back by itself if topbar fails). On fresh installs, adjusts the startup settings of PcaSvc, InventorySvc, lfsvc, cbdhsvc and DoSvc, and the svchost grouping threshold, when their values can be backed up. Its own copier (several files at once on SSDs, unbuffered for big files, progress in the status line) and right-click **Compress to ZIP** (all cores) / **Extract here** (ZIP and 7z), our own ZIP engine; a `.zip` opens like a folder (browse, copy out, open files from it). "Show in folder" from other programs selects the file (for the common folders: Downloads, Documents, Desktop, Pictures, Music, Videos and pinned ones, also when no window is open); the mouse back / forward buttons work; right click the desktop to hide its icons. Requires topbar |
| **wiztree** | A disk-usage map ("WinRust Disk" in Start) | Nothing, apart from the file and a shortcut |
| **photoview** | A fast photo viewer | Adds it to "Open with" (it does not become the default) |
| **rust-settings** | Settings in Rust: display (resolution, refresh rate), sound (volume), power plan and drive space, per-app volume and device choice, night light, display arrangement by dragging, network adapters, Wi-Fi on every adapter (password or 802.1X), VPN and proxy, Bluetooth, apps, Windows Update, disk cleanup, theme, about | Nothing, apart from the file and a shortcut. Win+I and the bar menus open this window instead of Windows Settings (only a few rare pages still open the system ones) |
diff --git a/README.ru.md b/README.ru.md
index e45ed0c..4f41120 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -38,8 +38,8 @@
|---|---|---|
| **rust-search** | Поиск файлов по всем NTFS-дискам, Alt+Space | Отключается служба поиска Windows, блокируется SearchHost.exe, прячется строка поиска на панели |
| **rtaskmgr-win32** | Диспетчер задач (Ctrl+Shift+Esc открывает его) | Запуск `taskmgr.exe` перенаправляется на него (системный файл не трогается). Заодно ставится чистильщик диска **rs-du**. На странице **«Ускорение»** обратимые переключатели, всё по желанию: профили «Игра» и «Работа» (останавливают фоновые службы, закрывают лаунчеры или синхронизацию и потом запускают обратно), очистка кэша памяти standby (сейчас или автоматически, пока работает topbar), блок процессов меню «Пуск» Windows, виджетов и «Связи с телефоном», один еженедельный `winget upgrade` вместо сторонних апдейтеров, исключения Defender для кэшей сборки и библиотек игр, быстрее NTFS (без времени последнего доступа и имён 8.3), блокировка рекламы через hosts. **«Автозагрузка»** показывает ещё задачи при входе и загрузке и сторонние службы с автозапуском и то, насколько каждая замедлила последние загрузки (журнал самой Windows). **«Что тормозит»** показывает время драйверов (DPC и прерывания), зависшие окна, медленный диск и время загрузки. Удаление всё возвращает |
-| **topbar** | Нижняя панель в стиле Windows 11: окна, часы, громкость, меню | Стандартная панель задач прячется. Заодно ставятся **reshell** (хоткеи: Win+1/2/3 и Win+\` переключают рабочие столы, Win+D показывает рабочий стол, Win+I открывает Параметры, Win+E файловый менеджер; возвращает панель задач, если topbar упал), **rs-du** и блок в профиле PowerShell (`zoxide`, `grep`=rg, `ll`=eza, `cat`=bat; молчит, если их нет) |
-| **rust-explorer** | Файловый менеджер с вкладками и рабочий стол | Папки и диски открываются в нём; **Проводник перестаёт быть оболочкой** (возвращается сам, если topbar не работает). При первой установке меняются настройки запуска PcaSvc, InventorySvc, lfsvc, cbdhsvc и DoSvc, а также порог группировки svchost, если удалось сохранить их исходные значения. Своё копирование (на SSD несколько файлов сразу, большие файлы без кэша, прогресс в строке состояния) и в меню правой кнопки **«Compress to ZIP»** (на всех ядрах) и **«Extract here»** (ZIP и 7z). Нужен topbar |
+| **topbar** | Нижняя панель в стиле Windows 11: окна, часы, громкость, меню | Стандартная панель задач прячется. Заодно ставятся **reshell** (хоткеи: Win+1/2/3 и Win+\` переключают рабочие столы, Win+D показывает рабочий стол, Win+I открывает Параметры, Win+E файловый менеджер; возвращает панель задач, если topbar упал), **rs-du** и блок в профиле PowerShell (`zoxide`, `grep`=rg, `ll`=eza, `cat`=bat; молчит, если их нет). Меню шестерёнки ставит панель снизу / слева / справа и может сдвинуть кнопки к левому краю, как в Windows 10 |
+| **rust-explorer** | Файловый менеджер с вкладками и рабочий стол | Папки и диски открываются в нём; **Проводник перестаёт быть оболочкой** (возвращается сам, если topbar не работает). При первой установке меняются настройки запуска PcaSvc, InventorySvc, lfsvc, cbdhsvc и DoSvc, а также порог группировки svchost, если удалось сохранить их исходные значения. Своё копирование (на SSD несколько файлов сразу, большие файлы без кэша, прогресс в строке состояния) и в меню правой кнопки **«Compress to ZIP»** (на всех ядрах) и **«Extract here»** (ZIP и 7z), собственный ZIP-движок; `.zip` открывается как папка (просмотр, копирование наружу, открытие файлов оттуда). «Показать в папке» из других программ выделяет файл (для частых папок: Загрузки, Документы, Рабочий стол, Изображения, Музыка, Видео и закреплённых, в том числе когда окно не открыто); работают кнопки мыши «назад / вперёд»; ПКМ по рабочему столу скрывает значки. Нужен topbar |
| **wiztree** | Карта занятого места на диске («WinRust Disk» в Пуске) | Ничего, кроме файла и ярлыка |
| **photoview** | Быстрый просмотр фото | Добавляется в «Открыть с помощью» (по умолчанию не назначается) |
| **rust-settings** | Параметры на Rust: экран (разрешение, частота, ночной свет, расположение мониторов перетаскиванием), звук (устройства, громкость по приложениям), схема питания, место на дисках и очистка, сетевые адаптеры, Wi-Fi на всех адаптерах (пароль или 802.1X), VPN и прокси, Bluetooth, приложения, Центр обновления, тема, о системе | Ничего, кроме файла и ярлыка. Win+I и меню панели открывают это окно вместо Параметров Windows (лишь несколько редких разделов по-прежнему системные) |
diff --git a/ROADMAP.md b/ROADMAP.md
index b0b6a5e..e823111 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -47,6 +47,7 @@ emoved.txt`. `purge.exe` lists, `--ask` asks for YES (the bar's right-click menu
- **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*
+- **v0.5.2**: topbar can sit on the left or right edge (gear menu), the buttons can go to the left end like Windows 10 (`align-left.txt`), and a maximized window no longer hides the floating dock (#51, #56, #58). rust-explorer: Ctrl+A, mouse back / forward buttons, Quick access follows moved known folders and you can pin folders, the desktop menu hides the icons (`desktop-icons-hidden.txt`), our own ZIP engine and a `.zip` opens like a folder, Rename in the file menu (#42, #50, #54, #62). "Show in folder" from browsers and other programs selects the file: rust-explorer registers as a shell window in `IShellWindows`, and the desktop process keeps stand-ins for Downloads, Documents, Desktop, Pictures, Music, Videos and pinned folders, because Windows waits 20 s for its own window when none exists (#60; other folders without an open window still wait). "Open file location" in the search, the task manager and WinRust Disk goes to rust-explorer (#61). The task manager shows one GPU once (#59). topbar search: Ctrl+A, Ctrl+Backspace (#52). Installer: rust-explorer is opt-in for new installs, a shell switch in the gear panel, service startup values come back on uninstall, rollback journals are kept when validation fails, logon tasks for reshell and rs-launcher instead of HKCU Run values (MSIX), PowerShell calls replaced by Win32. Foreign PRs #43, #45, #46, #17 squashed. *built, tests; "Show in folder" checked on a live system with PowerShell, not with a browser; the side bar and "buttons on the left" 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.
diff --git a/ROADMAP.ru.md b/ROADMAP.ru.md
index dfc8b52..cc2ca71 100644
--- a/ROADMAP.ru.md
+++ b/ROADMAP.ru.md
@@ -47,6 +47,7 @@ emoved.txt`. `purge.exe` показывает список, `--ask` просит
- **Ускорение (после 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). *собрано, тесты; новое меню и диалог на живом экране не смотрели*
+- **v0.5.2**: topbar можно поставить у левого или правого края (меню шестерёнки), кнопки можно сдвинуть к левому краю как в Windows 10 (`align-left.txt`), развёрнутое окно больше не прячет плавающий док (#51, #56, #58). rust-explorer: Ctrl+A, кнопки мыши «назад / вперёд», «Быстрый доступ» следует за перенесёнными папками и папки можно закреплять, меню рабочего стола скрывает значки (`desktop-icons-hidden.txt`), свой ZIP-движок и `.zip` открывается как папка, «Переименовать» в меню файла (#42, #50, #54, #62). «Показать в папке» из браузеров и других программ выделяет файл: rust-explorer регистрируется как окно оболочки в `IShellWindows`, а процесс рабочего стола держит заглушки для Загрузок, Документов, Рабочего стола, Изображений, Музыки, Видео и закреплённых папок, потому что без окна Windows ждёт своё окно 20 с (#60; другие папки без открытого окна всё ещё ждут). «Открыть расположение файла» в поиске, диспетчере задач и WinRust Disk ведёт в rust-explorer (#61). Диспетчер задач показывает один GPU один раз (#59). Поиск topbar: Ctrl+A, Ctrl+Backspace (#52). Установщик: rust-explorer не отмечен для новых установок, переключатель оболочки в панели шестерёнки, значения запуска служб возвращаются при удалении, журналы отката сохраняются при ошибке проверки, задачи входа для reshell и rs-launcher вместо значений Run в HKCU (MSIX), вызовы PowerShell заменены на Win32. Чужие PR #43, #45, #46, #17 влиты squash. *собрано, тесты; «Показать в папке» проверено на живой системе через PowerShell, не из браузера; боковую панель и «кнопки слева» на живом экране не смотрели*
## Дальше (по порядку)
0. **Скрипты для настройки оболочки** (#39, как Windhawk): способ загружать небольшие пользовательские моды, которые меняют панель, меню «Пуск» и файловый менеджер без пересборки WinRust. Не начато: сначала нужны формат модов (скрипт или DLL), песочница и стабильный API частей оболочки.
diff --git a/plugins/rust-explorer/src/main.rs b/plugins/rust-explorer/src/main.rs
index fba1d56..68e5f05 100644
--- a/plugins/rust-explorer/src/main.rs
+++ b/plugins/rust-explorer/src/main.rs
@@ -1297,7 +1297,15 @@ unsafe extern "system" fn proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESU
let (start, pick) = if desk() { (sh::desktop_dirs().into_iter().next().unwrap_or_default(), None) } else { start_target() };
load(h, start);
if let Some(name) = pick { select_row(&name); }
- if !desk() { shellwin::register(h as isize); shellwin::navigated(&cur_dir()); }
+ if desk() {
+ use windows::Win32::UI::Shell::{FOLDERID_Desktop, FOLDERID_Documents, FOLDERID_Downloads, FOLDERID_Music, FOLDERID_Pictures, FOLDERID_Videos};
+ let mut dirs: Vec<PathBuf> = [&FOLDERID_Desktop, &FOLDERID_Downloads, &FOLDERID_Documents, &FOLDERID_Pictures, &FOLDERID_Music, &FOLDERID_Videos].iter().filter_map(|id| sh::known_dir(id)).collect();
+ dirs.extend(ui::pins());
+ shellwin::register_resident(&dirs);
+ } else {
+ shellwin::navigated(&cur_dir());
+ shellwin::register(h as isize);
+ }
0
}
// the bar came, went or changed size (it sets the work area), or the screen changed: the icon list follows
diff --git a/plugins/rust-explorer/src/shellwin.rs b/plugins/rust-explorer/src/shellwin.rs
index 348af33..83c6106 100644
--- a/plugins/rust-explorer/src/shellwin.rs
+++ b/plugins/rust-explorer/src/shellwin.rs
@@ -1,7 +1,11 @@
//! Makes the file manager findable as a shell window, so `SHOpenFolderAndSelectItems` ("Show in folder" in browsers, chat apps...)
//! selects the file in it. Explorer finds the window in `IShellWindows` by folder, then asks it for `Document`, the folder-view
//! service, and calls `IShellView::SelectItem`. Everything else the shell might ask for answers "not implemented".
-use std::{cell::RefCell, sync::Mutex, ffi::c_void, os::windows::ffi::OsStrExt, path::{Path, PathBuf}};
+//!
+//! Only a window that already exists when the app calls is found: when there is none, Windows starts the folder's handler and
+//! waits 20 s for a window of its own that never comes. So the always-running desktop process also registers stand-ins for
+//! the common folders (Downloads...); their `SelectItem` opens a real window on the file.
+use std::{cell::RefCell, ffi::c_void, os::windows::{ffi::OsStrExt, process::CommandExt}, path::{Path, PathBuf}, sync::Mutex};
use windows::{
core::*,
Win32::{
@@ -14,48 +18,67 @@ use windows::{
/// Posted to the window when the shell wants a file selected: lp = Box<PathBuf>. The shell calls us on an RPC thread, so the UI does the work.
pub const WM_SHELL_SELECT: u32 = WM_APP + 6;
-struct Reg { sw: IShellWindows, cookie: i32 }
-thread_local! { static REG: RefCell<Option<Reg>> = const { RefCell::new(None) }; }
+struct Reg { sw: IShellWindows, cookie: i32, live: bool } // live: the window whose folder changes (not a stand-in)
+thread_local! { static REG: RefCell<Vec<Reg>> = const { RefCell::new(Vec::new()) }; }
static DIR: Mutex<String> = Mutex::new(String::new());
fn nope<T>() -> Result<T> { Err(E_NOTIMPL.into()) }
-fn url() -> String { format!("file:///{}", DIR.lock().unwrap().replace('\\', "/")) }
+fn url(dir: &str) -> String { format!("file:///{}", cur(dir).replace('\\', "/")) }
+/// The folder an entry stands for: its own, or (empty) the one the live window shows now.
+fn cur(dir: &str) -> String { if dir.is_empty() { DIR.lock().unwrap().clone() } else { dir.to_string() } }
fn wide(s: &std::ffi::OsStr) -> Vec<u16> { s.encode_wide().chain([0]).collect() }
-/// Registers the window (call once, after the folder is shown, on the UI thread).
-pub fn register(hwnd: isize) {
- let _ = (|| -> Result<()> {
- unsafe {
- let sw: IShellWindows = CoCreateInstance(&ShellWindows, None, CLSCTX_ALL)?;
- let me: IWebBrowser2 = Browser { hwnd: hwnd as isize }.into();
- let cookie = sw.Register(&me.cast::<IDispatch>()?, hwnd as i32, SWC_BROWSER)?;
- REG.set(Some(Reg { sw, cookie }));
+fn pidl_variant(dir: &Path) -> Option<(VARIANT, *mut ITEMIDLIST)> {
+ let w = wide(dir.as_os_str());
+ unsafe {
+ let mut pidl = std::ptr::null_mut();
+ SHParseDisplayName(PCWSTR(w.as_ptr()), None, &mut pidl, 0, None).ok()?;
+ InitVariantFromBuffer(pidl as *const c_void, ILGetSize(Some(pidl))).ok().map(|v| (v, pidl))
+ }
+}
+
+fn add(hwnd: isize, dir: &Path, resident: bool) -> Result<()> {
+ unsafe {
+ let sw: IShellWindows = CoCreateInstance(&ShellWindows, None, CLSCTX_ALL)?;
+ let me: IWebBrowser2 = Browser { hwnd, dir: if resident { dir.to_string_lossy().into_owned() } else { String::new() }, resident }.into();
+ let cookie = sw.Register(&me.cast::<IDispatch>()?, hwnd as i32, SWC_BROWSER)?;
+ if let Some((v, pidl)) = pidl_variant(dir) {
+ let _ = sw.OnNavigate(cookie, &v);
+ CoTaskMemFree(Some(pidl as *const c_void));
}
- Ok(())
- })();
+ REG.with_borrow_mut(|r| r.push(Reg { sw, cookie, live: !resident }));
+ }
+ Ok(())
+}
+
+/// Registers the window (call once, after the folder is shown, on the UI thread).
+pub fn register(hwnd: isize) { let _ = add(hwnd, Path::new(&DIR.lock().unwrap().clone()), false); }
+
+/// The always-running desktop process: stand-ins for `dirs`, so "Show in folder" there opens a window on the file.
+pub fn register_resident(dirs: &[PathBuf]) {
+ // the shell may bring this window to the front; a hidden one on its own keeps the desktop where it is
+ let h = unsafe { CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, w!("STATIC"), w!(""), WS_POPUP, 0, 0, 0, 0, None, None, None, None) };
+ if let Ok(h) = h { for d in dirs { let _ = add(h.0 as isize, d, true); } }
}
/// The window now shows `dir`: the shell matches later requests against it.
pub fn navigated(dir: &Path) {
*DIR.lock().unwrap() = dir.to_string_lossy().into_owned();
- REG.with_borrow(|r| {
- let Some(r) = r else { return };
- let w = wide(dir.as_os_str());
- unsafe {
- let mut pidl = std::ptr::null_mut();
- if SHParseDisplayName(PCWSTR(w.as_ptr()), None, &mut pidl, 0, None).is_err() { return; }
- if let Ok(v) = InitVariantFromBuffer(pidl as *const c_void, ILGetSize(Some(pidl))) { let _ = r.sw.OnNavigate(r.cookie, &v); }
- CoTaskMemFree(Some(pidl as *const c_void));
+ REG.with_borrow(|rs| {
+ for r in rs.iter().filter(|r| r.live) {
+ if let Some((v, pidl)) = pidl_variant(dir) {
+ unsafe { let _ = r.sw.OnNavigate(r.cookie, &v); CoTaskMemFree(Some(pidl as *const c_void)); }
+ }
}
});
}
pub fn revoke() {
- if let Some(r) = REG.take() { unsafe { let _ = r.sw.Revoke(r.cookie); } }
+ for r in REG.take() { unsafe { let _ = r.sw.Revoke(r.cookie); } }
}
#[implement(IWebBrowser2)]
-struct Browser { hwnd: isize }
+struct Browser { hwnd: isize, dir: String, resident: bool }
impl IDispatch_Impl for Browser_Impl {
fn GetTypeInfoCount(&self) -> Result<u32> { Ok(0) }
fn GetTypeInfo(&self, _: u32, _: u32) -> Result<ITypeInfo> { nope() }
@@ -65,7 +88,7 @@ impl IDispatch_Impl for Browser_Impl {
/// What `Document` returns: only the folder-view service is answered.
#[implement(IDispatch, IServiceProvider)]
-struct Doc { hwnd: isize }
+struct Doc { hwnd: isize, dir: String, resident: bool }
impl IDispatch_Impl for Doc_Impl {
fn GetTypeInfoCount(&self) -> Result<u32> { Ok(0) }
fn GetTypeInfo(&self, _: u32, _: u32) -> Result<ITypeInfo> { nope() }
@@ -74,13 +97,14 @@ impl IDispatch_Impl for Doc_Impl {
}
impl IServiceProvider_Impl for Doc_Impl {
fn QueryService(&self, _svc: *const GUID, riid: *const GUID, out: *mut *mut c_void) -> Result<()> {
- let v: IShellView = View { hwnd: self.hwnd }.into();
+
+ let v: IShellView = View { hwnd: self.hwnd, dir: self.dir.clone(), resident: self.resident }.into();
unsafe { v.query(&*riid, out).ok() }
}
}
#[implement(IShellView)]
-struct View { hwnd: isize }
+struct View { hwnd: isize, dir: String, resident: bool }
impl IOleWindow_Impl for View_Impl {
fn GetWindow(&self) -> Result<HWND> { Ok(HWND(self.hwnd as *mut c_void)) }
fn ContextSensitiveHelp(&self, _: BOOL) -> Result<()> { Ok(()) }
@@ -96,23 +120,28 @@ impl IShellView_Impl for View_Impl {
fn AddPropertySheetPages(&self, _: u32, _: LPFNSVADDPROPSHEETPAGE, _: LPARAM) -> Result<()> { nope() }
fn SaveViewState(&self) -> Result<()> { Ok(()) }
fn SelectItem(&self, pidl: *const ITEMIDLIST, _flags: u32) -> Result<()> {
- let path = item_path(pidl).ok_or(E_FAIL)?;
- unsafe { PostMessageW(Some(HWND(self.hwnd as *mut c_void)), WM_SHELL_SELECT, WPARAM(0), LPARAM(Box::into_raw(Box::new(path)) as isize))? };
+
+ let path = item_path(pidl, &cur(&self.dir)).ok_or(E_FAIL)?;
+ if self.resident {
+ let exe = std::env::current_exe().map_err(|_| E_FAIL)?;
+ std::process::Command::new(exe).raw_arg(format!("/select,\"{}\"", path.display())).spawn().map_err(|_| E_FAIL)?;
+ } else {
+ unsafe { PostMessageW(Some(HWND(self.hwnd as *mut c_void)), WM_SHELL_SELECT, WPARAM(0), LPARAM(Box::into_raw(Box::new(path)) as isize))? };
+ }
Ok(())
}
fn GetItemObject(&self, _: &_SVGIO, _: *const GUID, _: *mut *mut c_void) -> Result<()> { nope() }
}
/// The file system path of the item the shell sent: relative to the folder we showed (or absolute).
-fn item_path(pidl: *const ITEMIDLIST) -> Option<PathBuf> {
+fn item_path(pidl: *const ITEMIDLIST, dir: &str) -> Option<PathBuf> {
let name = |p: *const ITEMIDLIST| unsafe {
let s = SHGetNameFromIDList(p, SIGDN_FILESYSPATH).ok()?;
let r = s.to_string().ok();
CoTaskMemFree(Some(s.0 as *const c_void));
r.map(PathBuf::from)
};
- let dir = DIR.lock().unwrap().clone();
- let w = wide(std::ffi::OsStr::new(&dir));
+ let w = wide(std::ffi::OsStr::new(dir));
let joined = unsafe {
let mut base = std::ptr::null_mut();
SHParseDisplayName(PCWSTR(w.as_ptr()), None, &mut base, 0, None).ok().and_then(|_| {
@@ -123,7 +152,7 @@ fn item_path(pidl: *const ITEMIDLIST) -> Option<PathBuf> {
p
})
};
- joined.filter(|p| p.parent().is_some_and(|d| d.as_os_str().eq_ignore_ascii_case(&dir))).or_else(|| name(pidl))
+ joined.filter(|p| p.parent().is_some_and(|d| d.as_os_str().eq_ignore_ascii_case(dir))).or_else(|| name(pidl))
}
// the rest of the browser interface: nothing to offer
@@ -139,7 +168,7 @@ impl IWebBrowser_Impl for Browser_Impl {
fn Application(&self) -> Result<windows::Win32::System::Com::IDispatch> { nope() }
fn Parent(&self) -> Result<windows::Win32::System::Com::IDispatch> { nope() }
fn Container(&self) -> Result<windows::Win32::System::Com::IDispatch> { nope() }
- fn Document(&self) -> Result<windows::Win32::System::Com::IDispatch> { Ok(Doc { hwnd: self.hwnd }.into()) }
+ fn Document(&self) -> Result<windows::Win32::System::Com::IDispatch> { Ok(Doc { hwnd: self.hwnd, dir: self.dir.clone(), resident: self.resident }.into()) }
fn TopLevelContainer(&self) -> Result<windows::Win32::Foundation::VARIANT_BOOL> { nope() }
fn Type(&self) -> Result<BSTR> { nope() }
fn Left(&self) -> Result<i32> { nope() }
@@ -150,8 +179,8 @@ impl IWebBrowser_Impl for Browser_Impl {
fn SetWidth(&self, _width: i32) -> Result<()> { nope() }
fn Height(&self) -> Result<i32> { nope() }
fn SetHeight(&self, _height: i32) -> Result<()> { nope() }
- fn LocationName(&self) -> Result<BSTR> { Ok(BSTR::from(url())) }
- fn LocationURL(&self) -> Result<BSTR> { Ok(BSTR::from(url())) }
+ fn LocationName(&self) -> Result<BSTR> { Ok(BSTR::from(url(&self.dir))) }
+ fn LocationURL(&self) -> Result<BSTR> { Ok(BSTR::from(url(&self.dir))) }
fn Busy(&self) -> Result<windows::Win32::Foundation::VARIANT_BOOL> { nope() }
}
impl IWebBrowserApp_Impl for Browser_Impl {