Windows shell replacement in Rust: taskbar, file manager, NTFS search, task manager, disk cleaner. One installer exe.
Rust
Release v0.5.2
Lemxy191d09fe7501
diff --git a/common/Cargo.toml b/common/Cargo.tomlindex 1b45b2d..0ca9c01 100644--- a/common/Cargo.toml+++ b/common/Cargo.toml@@ -5,4 +5,4 @@ edition = "2024"license = "MIT OR Apache-2.0"[dependencies]-windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_WindowsAndMessaging"] }+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }diff --git a/common/src/lib.rs b/common/src/lib.rsindex b66202b..f7f1f71 100644--- a/common/src/lib.rs+++ b/common/src/lib.rs@@ -12,6 +12,7 @@ pub mod desktop;pub mod journal;pub mod mem;pub mod mft;+pub mod proc;pub mod reg;pub mod settings;pub mod style;diff --git a/common/src/proc.rs b/common/src/proc.rsnew file mode 100644index 0000000..9a6bb2d--- /dev/null+++ b/common/src/proc.rs@@ -0,0 +1,133 @@+//! Process helpers on plain Win32, so nobody has to start PowerShell (30-60 MB and 0.3 s) just to list or end a process.+use std::{ffi::c_void, ptr::null_mut};+use windows_sys::Win32::{+ Foundation::{CloseHandle, INVALID_HANDLE_VALUE},+ System::{+ Diagnostics::{+ Debug::ReadProcessMemory,+ ToolHelp::{CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS},+ },+ Threading::{OpenProcess, TerminateProcess},+ },+};++const _: () = assert!(size_of::<usize>() == 8, "the PEB offsets below are x64"); // shortcut: x64 only, add the x86 offsets if a 32-bit build appears++#[link(name = "ntdll")]+unsafe extern "system" {+ fn NtQueryInformationProcess(h: *mut c_void, class: u32, out: *mut c_void, len: u32, ret: *mut u32) -> i32;+}++/// `(pid, exe name)` of every running process.+pub fn list() -> Vec<(u32, String)> {+ let mut v = vec![];+ unsafe {+ let s = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);+ if s == INVALID_HANDLE_VALUE {+ return v;+ }+ let mut e: PROCESSENTRY32W = std::mem::zeroed();+ e.dwSize = size_of::<PROCESSENTRY32W>() as u32;+ let mut ok = Process32FirstW(s, &mut e) != 0;+ while ok {+ let n = e.szExeFile.iter().position(|&c| c == 0).unwrap_or(e.szExeFile.len());+ v.push((e.th32ProcessID, String::from_utf16_lossy(&e.szExeFile[..n])));+ ok = Process32NextW(s, &mut e) != 0;+ }+ CloseHandle(s);+ }+ v+}++/// Pids of the processes with this exe name (case-insensitive, e.g. `explorer.exe`).+pub fn pids(name: &str) -> Vec<u32> {+ list().into_iter().filter(|(_, n)| n.eq_ignore_ascii_case(name)).map(|p| p.0).collect()+}++/// The command line of a process of the same user, read from its PEB. None when it cannot be opened.+pub fn cmdline(pid: u32) -> Option<String> {+ unsafe {+ let h = OpenProcess(0x0410, 0, pid); // QUERY_INFORMATION | VM_READ+ if h.is_null() {+ return None;+ }+ let read = |addr: usize, buf: *mut c_void, n: usize| ReadProcessMemory(h, addr as *const c_void, buf, n, null_mut()) != 0;+ let r = (|| {+ let mut pbi = [0usize; 6]; // PROCESS_BASIC_INFORMATION: [1] = PebBaseAddress+ if NtQueryInformationProcess(h, 0, pbi.as_mut_ptr().cast(), 48, null_mut()) != 0 {+ return None;+ }+ let mut params = 0usize; // PEB.ProcessParameters+ if !read(pbi[1] + 0x20, (&mut params as *mut usize).cast(), 8) {+ return None;+ }+ let mut us = [0u8; 16]; // RTL_USER_PROCESS_PARAMETERS.CommandLine, a UNICODE_STRING: len u16, max u16, pad, buffer ptr+ if !read(params + 0x70, us.as_mut_ptr().cast(), 16) {+ return None;+ }+ let len = u16::from_le_bytes([us[0], us[1]]) as usize;+ let buf = usize::from_le_bytes(us[8..16].try_into().ok()?);+ let mut w = vec![0u16; len / 2];+ if !read(buf, w.as_mut_ptr().cast(), len) {+ return None;+ }+ Some(String::from_utf16_lossy(&w))+ })();+ CloseHandle(h);+ r+ }+}++pub fn kill(pid: u32) {+ unsafe {+ let h = OpenProcess(1, 0, pid); // PROCESS_TERMINATE+ if !h.is_null() {+ TerminateProcess(h, 1);+ CloseHandle(h);+ }+ }+}++/// An explorer.exe started with no path: the one that runs as the shell. Folder windows (started with a path) and the COM host+/// (`/factory ... -Embedding`) are other explorer.exe processes and must stay.+fn is_shell_cmdline(c: &str) -> bool {+ let mut s = c.trim_end().to_ascii_lowercase();+ if let Some(r) = s.strip_suffix("/nouaccheck") {+ if !r.ends_with(char::is_whitespace) {+ return false;+ }+ s = r.trim_end().to_string();+ }+ s.strip_suffix('"').unwrap_or(&s).ends_with("explorer.exe")+}++/// Pids of the explorer.exe processes that are a shell.+pub fn shell_explorers() -> Vec<u32> {+ pids("explorer.exe").into_iter().filter(|&p| cmdline(p).is_some_and(|c| is_shell_cmdline(&c))).collect()+}++pub fn kill_shell_explorers() {+ shell_explorers().into_iter().for_each(kill);+}++#[cfg(test)]+mod tests {+ use super::is_shell_cmdline;++ #[test]+ fn only_a_bare_explorer_is_the_shell() {+ assert!(is_shell_cmdline(r"C:\Windows\explorer.exe"));+ assert!(is_shell_cmdline(r#""C:\Windows\explorer.exe""#));+ assert!(is_shell_cmdline(r#""C:\Windows\EXPLORER.EXE" /NoUACCheck "#));+ assert!(!is_shell_cmdline(r"C:\Windows\explorer.exe C:\Users"));+ assert!(!is_shell_cmdline(r"C:\Windows\explorer.exe /factory,{5BD95610-9434-43C2-886C-57852CC8A120} -Embedding"));+ assert!(!is_shell_cmdline(r"C:\Windows\explorer.exe ms-settings:"));+ }++ #[test]+ fn lists_own_process() {+ let me = std::process::id();+ assert!(super::list().iter().any(|(p, _)| *p == me));+ assert!(super::cmdline(me).is_some_and(|c| !c.is_empty()));+ }+}diff --git a/common/src/settings.rs b/common/src/settings.rsindex caab37a..c0bac7b 100644--- a/common/src/settings.rs+++ b/common/src/settings.rs@@ -1,52 +1,158 @@//! 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:+//! start Explorer for as long as Settings is open, then end it again, which keeps the RAM saving. Done on a background thread://! 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+/NoUACCheck)?\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' }-}-"#;+use crate::proc;+use std::{os::windows::process::CommandExt, process::{Command, Stdio}, thread::sleep, time::Duration};+use windows_sys::Win32::{+ Foundation::{HWND, LPARAM},+ UI::{+ Input::KeyboardAndMouse::keybd_event,+ WindowsAndMessaging::{EnumWindows, FindWindowExW, GetShellWindow, GetWindow, GetWindowThreadProcessId, IsHungAppWindow, IsWindowVisible, SetForegroundWindow, ShowWindow},+ },+};++const SETTINGS: &str = "SystemSettings.exe";+const NO_WINDOW: u32 = 0x0800_0000;++fn w(s: &str) -> Vec<u16> {+ s.encode_utf16().chain([0]).collect()+}++fn pid_of(h: HWND) -> u32 {+ let mut p = 0;+ unsafe { GetWindowThreadProcessId(h, &mut p) };+ p+}++fn shell_pid() -> Option<u32> {+ let h = unsafe { GetShellWindow() };+ (!h.is_null()).then(|| pid_of(h))+}++fn explorer_shell() -> bool {+ shell_pid().is_some_and(|p| proc::list().iter().any(|(i, n)| *i == p && n.eq_ignore_ascii_case("explorer.exe")))+}++/// The shell's own taskbar comes last (the topbar has a Shell_TrayWnd of its own, so only one that belongs to the shell process counts).+fn explorer_tray() -> bool {+ let Some(sp) = shell_pid() else { return false };+ let cls = w("Shell_TrayWnd");+ let mut t = std::ptr::null_mut();+ loop {+ t = unsafe { FindWindowExW(std::ptr::null_mut(), t, cls.as_ptr(), std::ptr::null()) };+ if t.is_null() {+ return false;+ }+ if pid_of(t) == sp {+ return true;+ }+ }+}++/// A fullscreen game keeps the screen: Settings opens behind it unless it is brought to the front.+fn raise() {+ let Some(sp) = proc::pids(SETTINGS).first().copied() else { return };+ let cls = w("Windows.UI.Core.CoreWindow");+ let mut c = std::ptr::null_mut();+ loop {+ c = unsafe { FindWindowExW(std::ptr::null_mut(), c, cls.as_ptr(), std::ptr::null()) };+ if c.is_null() {+ return;+ }+ if pid_of(c) == sp {+ unsafe {+ let mut o = GetWindow(c, 4); // GW_OWNER+ if o.is_null() {+ o = c;+ }+ keybd_event(0x12, 0, 0, 0); // an Alt tap lets SetForegroundWindow through+ keybd_event(0x12, 0, 2, 0);+ ShowWindow(o, 9); // SW_RESTORE+ SetForegroundWindow(o);+ }+ return;+ }+ }+}++unsafe extern "system" fn hung_cb(h: HWND, l: LPARAM) -> i32 {+ let d = unsafe { &mut *(l as *mut (u32, bool)) };+ if pid_of(h) == d.0 && unsafe { IsWindowVisible(h) != 0 && IsHungAppWindow(h) != 0 } {+ d.1 = true;+ }+ 1+}++fn hung(pid: u32) -> bool {+ let mut d = (pid, false);+ unsafe { EnumWindows(Some(hung_cb), &mut d as *mut _ as LPARAM) };+ d.1+}++/// A Settings process that hangs (opened before the shell was ready) swallows every later launch: it must go.+fn any_hung() -> bool {+ proc::pids(SETTINGS).into_iter().any(hung)+}++fn kill_stale() {+ proc::pids(SETTINGS).into_iter().filter(|&p| hung(p)).for_each(proc::kill);+}++fn wait(n: u32, mut done: impl FnMut() -> bool) {+ for _ in 0..n {+ if done() {+ return;+ }+ sleep(Duration::from_millis(100));+ }+}++fn has_desktop(p: u32) -> bool {+ proc::cmdline(p).is_some_and(|c| c.contains("--desktop"))+}++fn run(uri: &str) {+ kill_stale();+ let mut started = false;+ if !explorer_shell() {+ // our desktop is a window of class Progman too: with it up Explorer thinks a shell exists and starts as a plain folder host+ proc::pids("rust-explorer.exe").into_iter().filter(|&p| has_desktop(p)).for_each(proc::kill);+ let _ = Command::new("runas.exe").args(["/trustlevel:0x20000", r"C:\Windows\explorer.exe"]).creation_flags(NO_WINDOW).status();+ wait(200, explorer_shell);+ // the shell window appears before the immersive shell services behind it are up+ wait(150, explorer_tray);+ sleep(Duration::from_secs(1));+ started = true;+ }+ // through explorer.exe: the page opens with the user's normal token even when this process is elevated+ for _ in 0..2 {+ let _ = Command::new(r"C:\Windows\explorer.exe").arg(uri).status();+ wait(80, || !proc::pids(SETTINGS).is_empty());+ sleep(Duration::from_secs(1));+ raise();+ sleep(Duration::from_secs(3));+ raise();+ if !any_hung() {+ break;+ }+ kill_stale();+ }+ if started {+ // ends when Settings is closed, or when it hangs for good+ let mut bad = 0;+ while bad < 5 && !proc::pids(SETTINGS).is_empty() {+ sleep(Duration::from_secs(2));+ bad = if any_hung() { bad + 1 } else { 0 };+ }+ kill_stale();+ proc::kill_shell_explorers();+ let rx = std::path::PathBuf::from(std::env::var_os("ProgramFiles").unwrap_or_default()).join(r"rust-explorer\rust-explorer.exe");+ if rx.is_file() && !proc::pids("rust-explorer.exe").into_iter().any(has_desktop) {+ let _ = Command::new(rx).arg("--desktop").stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn();+ }+ }+}/// The rust-settings page that stands for an exact `ms-settings:` address (a bare `ms-settings:` is Win+I: the first page)./// Only these: any other address keeps going to Windows' own Settings.@@ -72,15 +178,15 @@ fn own_exe() -> Option<std::path::PathBuf> {exe.is_file().then_some(exe)}-/// `uri` is passed through the environment, never spliced into the script. A second call while the first still waits is harmless.+/// A second call while the first still waits is harmless.pub fn open(uri: &str) {if let (Some(page), Some(exe)) = (own_page(uri), own_exe()) {if Command::new(exe).arg(page).stdin(Stdio::null()).creation_flags(0x0800_0000).spawn().is_ok() {return;}}- 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();+ let uri = uri.to_string();+ std::thread::spawn(move || run(&uri)); // shortcut: dies with the host process, which is long-lived (reshell, topbar)}#[cfg(test)]diff --git a/plugins/rs-shell/Cargo.toml b/plugins/rs-shell/Cargo.tomlindex 0954860..bde4dda 100644--- a/plugins/rs-shell/Cargo.toml+++ b/plugins/rs-shell/Cargo.toml@@ -6,7 +6,7 @@ license = "MIT OR Apache-2.0"[dependencies]winrust-common = { path = "../../common" }-windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_System_Console", "Win32_System_RemoteDesktop", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_Graphics_GdiPlus", "Win32_System_Console", "Win32_System_RemoteDesktop", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }[build-dependencies]embed-resource = "3"diff --git a/plugins/rs-shell/src/main.rs b/plugins/rs-shell/src/main.rsindex f992361..01ae404 100644--- a/plugins/rs-shell/src/main.rs+++ b/plugins/rs-shell/src/main.rs@@ -100,18 +100,37 @@ unsafe extern "system" fn park(h: HWND, _: LPARAM) -> BOOL {}}+/// GDI+ decodes any format it knows and saves a BMP (what the desktop paints without explorer's transcoder).+fn to_bmp(src: &str, dst: &std::path::Path) {+ use windows_sys::{core::GUID, Win32::Graphics::GdiPlus::*};+ let wide = |s: &str| s.encode_utf16().chain([0]).collect::<Vec<u16>>();+ const BMP: GUID = GUID { data1: 0x557C_F400, data2: 0x1A04, data3: 0x11D3, data4: [0x9A, 0x73, 0x00, 0x00, 0xF8, 0x1E, 0xF3, 0x2E] }; // image/bmp encoder+ unsafe {+ let (mut token, mut input): (usize, GdiplusStartupInput) = (0, std::mem::zeroed());+ input.GdiplusVersion = 1;+ if GdiplusStartup(&mut token, &input, ptr::null_mut()) != 0 {+ return;+ }+ let mut img = ptr::null_mut();+ if GdipLoadImageFromFile(wide(src).as_ptr(), &mut img) == 0 {+ GdipSaveImageToFile(img, wide(&dst.to_string_lossy()).as_ptr(), &BMP, ptr::null());+ GdipDisposeImage(img);+ }+ GdiplusShutdown(token);+ }+}+fn set_wallpaper() {let Some(src) = reg(&["query", r"HKCU\Control Panel\Desktop", "/v", "WallPaper"]).map(|o| parse_run(&o)).and_then(|v| v.into_iter().next()) else { return };let mut path = PathBuf::from(&src);- // without explorer's image transcoder the desktop paints only BMP: convert once (System.Drawing) and keep the copy+ // without explorer's image transcoder the desktop paints only BMP: convert once and keep the copyif !src.to_lowercase().ends_with(".bmp") {let Ok(base) = std::env::var("LOCALAPPDATA") else { return };let bmp = PathBuf::from(base).join("rs-shell").join("wallpaper.bmp");let modified = |p: &std::path::Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();if modified(&bmp) < modified(&PathBuf::from(&src)) {let _ = std::fs::create_dir_all(bmp.parent().unwrap_or(&bmp));- let script = format!("Add-Type -AssemblyName System.Drawing; $i=[Drawing.Image]::FromFile('{}'); $i.Save('{}',[Drawing.Imaging.ImageFormat]::Bmp)", src.replace('\'', "''"), bmp.display().to_string().replace('\'', "''"));- let _ = quiet("powershell").args(["-NoProfile", "-NonInteractive", "-Command", &script]).creation_flags(NO_WINDOW).status();+ to_bmp(&src, &bmp);}path = bmp;}@@ -207,9 +226,8 @@ fn replace_on() -> bool {/// Ends the Explorer that runs as the shell (started without arguments). Folder windows (started with a path) and the COM/// host (`/factory ... -Embedding`) are other explorer.exe processes and keep running.fn kill_shell_explorer() {- let script = r#"Get-CimInstance Win32_Process -Filter "Name='explorer.exe'" | Where-Object { $_.CommandLine -match '(?i)explorer\.exe"?(\s+/NoUACCheck)?\s*$' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }"#;- let r = quiet("powershell").args(["-NoProfile", "-NonInteractive", "-Command", script]).creation_flags(NO_WINDOW).status();- log(&format!("explorer shell stopped -> {:?}", r.map(|s| s.success())));+ winrust_common::proc::kill_shell_explorers();+ log("explorer shell stopped");}/// How long after the overlay starts Explorer may be ended even without the markers below: newer Windows builds (26300)@@ -351,9 +369,21 @@ fn main() {#[cfg(test)]mod tests {- use super::{exe_path, may_end_explorer, parse_run};+ use super::{exe_path, may_end_explorer, parse_run, to_bmp};use std::time::Duration;#[test]+ fn converts_a_jpeg_to_bmp() {+ let src = r"C:\Windows\Web\Wallpaper\Windows\img0.jpg";+ if !std::path::Path::new(src).is_file() {+ return;+ }+ let dst = std::env::temp_dir().join("rs-shell-test.bmp");+ let _ = std::fs::remove_file(&dst);+ to_bmp(src, &dst);+ assert_eq!(&std::fs::read(&dst).unwrap()[..2], b"BM");+ let _ = std::fs::remove_file(dst);+ }+ #[test]fn ends_explorer_on_markers_or_after_grace() {assert!(may_end_explorer(true, Duration::ZERO));assert!(!may_end_explorer(false, Duration::from_secs(30)));diff --git a/src/install/search.rs b/src/install/search.rsindex fb2030b..86a0abb 100644--- a/src/install/search.rs+++ b/src/install/search.rs@@ -42,7 +42,11 @@ pub(crate) fn install() -> Result<(), String> {let dst = prog_dir().join("rs-launcher.exe"); // must live somewhere stable: --autostart registers its own pathlet _ = run("taskkill", &["/f", "/im", "rs-launcher.exe"]);put(&src.join("rs-launcher.exe"), &dst)?;- run(dst.to_str().unwrap(), &["--autostart"])?;+ if logon_task("rs-launcher", &dst) {+ let _ = run("reg", &["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "rs-launcher", "/f"]);+ } else {+ run(dst.to_str().unwrap(), &["--autostart"])?; // fallback: Run key+ }// 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();@@ -64,6 +68,7 @@ pub(crate) fn uninstall() -> Result<(), String> {journal()?.undo()?;let _ = run("taskkill", &["/f", "/im", "rs-launcher.exe"]);let _ = run("reg", &["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "rs-launcher", "/f"]);+ let _ = run("schtasks", &["/delete", "/tn", "rs-launcher", "/f"]);let k = svc_key("WSearch");if svc_mode(reg_dword(&k, "Start"), reg_dword(&k, "DelayedAutostart")).is_some_and(|m| m.ends_with("auto")) {let _ = run("sc.exe", &["start", "WSearch"]);diff --git a/src/install/session.rs b/src/install/session.rsindex c2fbc76..5a625a8 100644--- a/src/install/session.rs+++ b/src/install/session.rs@@ -68,6 +68,12 @@ pub(crate) fn task_user() -> String {/// 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).+/// Logon task (Limited) for the signed-in user: unlike a HKCU Run value it cannot land in an MSIX package's private registry copy.+pub(crate) fn logon_task(name: &str, exe: &Path) -> bool {+ let task = format!("{} Register-ScheduledTask -TaskName {name} -Force -Action (New-ScheduledTaskAction -Execute '{}') -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(), exe.display());+ run("powershell", &["-NoProfile", "-Command", &task]).is_ok()+}+pub(crate) fn profile_path() -> String {match env::var(i18n::reg::SID_ENV).ok().filter(|s| i18n::reg::valid_sid(s)) {Some(sid) => format!(diff --git a/src/install/topbar.rs b/src/install/topbar.rsindex 8733b49..b506c51 100644--- a/src/install/topbar.rs+++ b/src/install/topbar.rs@@ -56,7 +56,11 @@ pub(crate) fn bar_install() -> Result<(), String> {let rsh = bar_dir().join("reshell.exe"); // Win+1/2/3 desktop hotkeys, no args = hotkeyslet _ = run("taskkill", &["/f", "/im", "reshell.exe"]);put(&d.join("reshell.exe"), &rsh)?;- run("reg", &["add", RUN_KEY, "/v", "reshell", "/t", "REG_SZ", "/d", &format!("\"{}\"", rsh.display()), "/f"])?;+ if logon_task("reshell", &rsh) {+ let _ = run("reg", &["delete", RUN_KEY, "/v", "reshell", "/f"]);+ } else {+ run("reg", &["add", RUN_KEY, "/v", "reshell", "/t", "REG_SZ", "/d", &format!("\"{}\"", rsh.display()), "/f"])?; // fallback+ }let _ = Command::new("explorer.exe").arg(&rsh).spawn();run(dst.to_str().unwrap(), &["--restore"])?; // clean state in case a killed instance left the taskbar hidden// The bar runs elevated (a task with the highest run level starts it at logon without a UAC prompt): that lets it close@@ -79,6 +83,7 @@ pub(crate) fn bar_uninstall() -> Result<(), String> {let _ = run("reg", &["delete", RUN_KEY, "/v", "topbar", "/f"]);let _ = run("schtasks", &["/delete", "/tn", "topbar", "/f"]);let _ = run("reg", &["delete", RUN_KEY, "/v", "reshell", "/f"]);+ let _ = run("schtasks", &["/delete", "/tn", "reshell", "/f"]);let _ = run("taskkill", &["/f", "/im", "reshell.exe"]);let _ = run("taskkill", &["/f", "/im", "topbar.exe"]);let _ = profile_uninstall();