diff --git a/common/Cargo.toml b/common/Cargo.toml index 37a78b0b..3a0748f3 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_Diagnostics_Debug", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_Registry", "Win32_System_RemoteDesktop", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "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_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_Power", "Win32_System_Registry", "Win32_System_RemoteDesktop", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] } diff --git a/common/src/lib.rs b/common/src/lib.rs index e1c45e64..4777a096 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -15,6 +15,7 @@ pub mod journal; pub mod launch; pub mod mem; pub mod mft; +pub mod power; pub mod proc; pub mod reg; pub mod search; diff --git a/common/src/power.rs b/common/src/power.rs new file mode 100644 index 00000000..2670d4d2 --- /dev/null +++ b/common/src/power.rs @@ -0,0 +1,77 @@ +//! Shut down, restart, sleep, sign out. Used by the topbar (sleep) and the desktop's Alt+F4 box (rust-explorer). +use std::{ + io, + os::windows::process::CommandExt, + process::{Command, Stdio}, + ptr::{null, null_mut}, +}; +use windows_sys::Win32::{ + Foundation::CloseHandle, + Security::{AdjustTokenPrivileges, LookupPrivilegeValueW, SE_PRIVILEGE_ENABLED, TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES}, + System::{Power::SetSuspendState, Threading::{GetCurrentProcess, OpenProcessToken}}, +}; + +const NO_WINDOW: u32 = 0x0800_0000; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Action { + ShutDown, + Restart, + Sleep, + SignOut, +} + +impl Action { + /// What `shutdown.exe` is given; None: not its job (sleep). + fn shutdown_args(self) -> Option<&'static [&'static str]> { + match self { + Action::ShutDown => Some(&["/s", "/t", "0"]), + Action::Restart => Some(&["/r", "/t", "0"]), + Action::SignOut => Some(&["/l"]), + Action::Sleep => None, + } + } + + /// Does it. Sleep returns only after wake-up: call from a thread that may block. + pub fn run(self) -> io::Result<()> { + match self.shutdown_args() { + Some(args) => Command::new("shutdown.exe").args(args).creation_flags(NO_WINDOW).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn().map(drop), + None => { + sleep_now(); + Ok(()) + } + } + } +} + +/// Sleep (S3 / modern standby), never hibernate. SetSuspendState needs the shutdown privilege switched on in our token. +/// Not `rundll32 powrprof.dll,SetSuspendState`: rundll32 passes garbage arguments and the PC hibernates instead. +pub fn sleep_now() { + unsafe { + let mut tok = null_mut(); + if OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &mut tok) != 0 { + let mut tp: TOKEN_PRIVILEGES = std::mem::zeroed(); + tp.PrivilegeCount = 1; + tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + let name: Vec = "SeShutdownPrivilege".encode_utf16().chain([0]).collect(); + if LookupPrivilegeValueW(null(), name.as_ptr(), &mut tp.Privileges[0].Luid) != 0 { + AdjustTokenPrivileges(tok, 0, &tp, 0, null_mut(), null_mut()); + } + CloseHandle(tok); + } + SetSuspendState(false, false, false); + } +} + +#[cfg(test)] +mod tests { + use super::Action; + + #[test] + fn each_action_asks_for_the_right_thing() { + assert_eq!(Action::ShutDown.shutdown_args(), Some(&["/s", "/t", "0"][..])); + assert_eq!(Action::Restart.shutdown_args(), Some(&["/r", "/t", "0"][..])); + assert_eq!(Action::SignOut.shutdown_args(), Some(&["/l"][..])); + assert_eq!(Action::Sleep.shutdown_args(), None); + } +} diff --git a/plugins/rust-explorer/src/main.rs b/plugins/rust-explorer/src/main.rs index b36269e0..11264c47 100644 --- a/plugins/rust-explorer/src/main.rs +++ b/plugins/rust-explorer/src/main.rs @@ -26,6 +26,7 @@ mod zipx; // our own ZIP engine (deflate, inflate, container) mod jobs; // our own copier, ZIP packer, ZIP/7z unpacker (background, progress in the status line) mod shellwin; // registers the window as a shell window: "Show in folder" from other apps selects the file mod menu; // the folder's own menu, painted in our colours +mod power; // the desktop's Alt+F4: shut down, restart, sleep, sign out mod ui; // the look: palette, painted tabs / toolbar / address pill / status line, dark theme static DESKTOP: AtomicBool = AtomicBool::new(false); @@ -1972,6 +1973,9 @@ unsafe extern "system" fn proc(h: HWND, m: u32, wp: WPARAM, lp: LPARAM) -> LRESU WM_CONTEXTMENU if desk() && (icons_hidden() || wp as HWND == h) => { bg_menu(h); 0 } desk::SPAWN_WORKERW if desk() => { desk::spawn_workerw(h); 0 } WM_TIMER if desk() && wp == 7 => { desk::check_live(ST.with_borrow(|st| st.list)); 0 } + // Alt+F4 on the desktop or its icon list (Windows passes it up to us) ends up here. Like Explorer's desktop it + // offers to shut down; DefWindowProcW would destroy the desktop, wallpaper and icons included (#189) + WM_CLOSE if desk() => { power::ask(); 0 } WM_DESTROY => { if !desk() { save_place(h); } shellwin::revoke(); PostQuitMessage(0); 0 } _ => DefWindowProcW(h, m, wp, lp), } diff --git a/plugins/rust-explorer/src/power.rs b/plugins/rust-explorer/src/power.rs new file mode 100644 index 00000000..cad9bda9 --- /dev/null +++ b/plugins/rust-explorer/src/power.rs @@ -0,0 +1,164 @@ +//! The shut-down box behind Alt+F4 on the desktop (#189). Explorer shows one there, so our desktop shows its own: +//! Windows' task dialog (keyboard, screen reader, high contrast and DPI come with it) with one command link per action. +#![allow(unsafe_op_in_unsafe_fn)] +use crate::w; +use std::{ffi::c_void, ptr, sync::atomic::{AtomicBool, AtomicIsize, Ordering::SeqCst}}; +use winrust_common::{power::Action, t}; +use windows_sys::Win32::{ + Foundation::{HWND, LPARAM, WPARAM}, + System::LibraryLoader::{GetProcAddress, LoadLibraryW}, + UI::WindowsAndMessaging::{HWND_TOPMOST, MB_ICONWARNING, MessageBoxW, SWP_NOMOVE, SWP_NOSIZE, SetForegroundWindow, SetWindowPos}, +}; + +static OPEN: AtomicBool = AtomicBool::new(false); // one box at a time +static BOX: AtomicIsize = AtomicIsize::new(0); // its window while it is on screen + +/// Top to bottom. The first one has the focus, like in Explorer's box: Alt+F4, Enter shuts down. +const ACTIONS: [Action; 4] = [Action::ShutDown, Action::Restart, Action::Sleep, Action::SignOut]; +const FIRST_ID: i32 = 101; // clear of the dialog's own ids (IDOK, IDCANCEL...) + +fn action_of(id: i32) -> Option { + usize::try_from(id - FIRST_ID).ok().and_then(|i| ACTIONS.get(i)).copied() +} + +/// `&` marks the key that picks the line. +fn label(a: Action) -> &'static str { + match a { + Action::ShutDown => t!("&Завершение работы", "&Shut down", ja: "シャットダウン(&U)", pt: "&Desligar", zh: "关机(&U)"), + Action::Restart => t!("&Перезагрузка", "&Restart", ja: "再起動(&R)", pt: "&Reiniciar", zh: "重启(&R)"), + Action::Sleep => t!("&Сон", "S&leep", ja: "スリープ(&S)", pt: "&Suspender", zh: "睡眠(&S)"), + Action::SignOut => t!("&Выйти из системы", "Sign &out", ja: "サインアウト(&O)", pt: "S&air", zh: "注销(&O)"), + } +} + +// TASKDIALOG_BUTTON and TASKDIALOGCONFIG (commctrl.h, byte-packed). +#[repr(C, packed)] +struct Button { + id: i32, + text: *const u16, +} + +type Callback = unsafe extern "system" fn(HWND, u32, WPARAM, LPARAM, isize) -> i32; + +#[repr(C, packed)] +struct Config { + size: u32, + parent: HWND, + instance: *mut c_void, + flags: i32, + common_buttons: i32, + title: *const u16, + main_icon: *const u16, + heading: *const u16, + content: *const u16, + button_count: u32, + buttons: *const Button, + default_button: i32, + radio_count: u32, + radios: *const Button, + default_radio: i32, + verification: *const u16, + expanded: *const u16, + expanded_control: *const u16, + collapsed_control: *const u16, + footer_icon: *const u16, + footer: *const u16, + callback: Option, + callback_data: isize, + width: u32, +} + +const _: () = assert!(size_of::() == if cfg!(target_pointer_width = "64") { 160 } else { 96 }); + +const ALLOW_CANCEL: i32 = 0x0008; // TDF_ALLOW_DIALOG_CANCELLATION: Esc, Alt+F4 and the close button +const COMMAND_LINKS: i32 = 0x0010; // TDF_USE_COMMAND_LINKS +const CANCEL_BUTTON: i32 = 0x0008; // TDCBF_CANCEL_BUTTON +const CREATED: u32 = 0; // TDN_CREATED +const DESTROYED: u32 = 5; // TDN_DESTROYED + +type TaskDialogIndirect = unsafe extern "system" fn(*const Config, *mut i32, *mut i32, *mut i32) -> i32; + +/// The box has no owner (the desktop must stay at the bottom), so it is brought above the other windows itself. +unsafe extern "system" fn on_event(h: HWND, event: u32, _: WPARAM, _: LPARAM, _: isize) -> i32 { + match event { + CREATED => { + BOX.store(h as isize, SeqCst); + SetWindowPos(h, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); + SetForegroundWindow(h); + } + DESTROYED => BOX.store(0, SeqCst), + _ => {} + } + 0 // S_OK +} + +/// Shows the box and waits. Ok(None): cancelled. +unsafe fn show() -> Result, String> { + // looked up at run time: only comctl32 v6 (our manifest) exports it, and the test exe has no manifest, so a normal + // import would stop it from starting at all + let lib = LoadLibraryW(w("comctl32.dll").as_ptr()); + let Some(f) = GetProcAddress(lib, c"TaskDialogIndirect".as_ptr().cast()) else { return Err("TaskDialogIndirect is missing".into()) }; + let dialog: TaskDialogIndirect = std::mem::transmute(f); + let texts: Vec> = ACTIONS.iter().map(|&a| w(label(a))).collect(); + let buttons: Vec