A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
feat(shell): implement disposable processes for shell actions and improve file operation handling
CristianOlivera19c983700c518
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2516857..ec4b410 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,12 @@ copia la sección de la versión que se publica a la release de GitHub.### English+- Opening apps and shell file operations run in temporary helper processes so+ slow shell handlers and native progress dialogs keep the dock responsive.+ Transfers run in order; ordinary launch helpers time out after 30 seconds,+ while file operations and administrator launches keep their native user controls.+- Recycle Bin notifications share one drive scan at a time, preserving changes+ that arrive during a scan without starting overlapping disk queries.- Shell icons and app names load in the background through a bounded queue,keeping the dock responsive while the shell is slow. Repeated requests sharethe same load, and unused pixel buffers are released.@@ -46,6 +52,13 @@ copia la sección de la versión que se publica a la release de GitHub.### Español+- Abrir apps y ejecutar operaciones de archivos del shell se hace en procesos+ auxiliares temporales para mantener la respuesta del dock mientras el shell+ tarda o muestra el progreso. Las transferencias se ejecutan en orden; las+ aperturas normales tienen un límite de 30 segundos, mientras las operaciones+ de archivos y las aperturas como administrador conservan sus controles nativos.+- Los avisos de Papelera comparten una sola lectura de discos a la vez y+ conservan los cambios que lleguen durante esa lectura, sin consultas solapadas.- Los iconos y nombres del shell se cargan en segundo plano con una colalimitada para que el dock responda mientras el shell tarda. Las solicitudesrepetidas comparten la misma carga y se liberan los píxeles que ya no se usan.diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex a94258e..04291f7 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -15,7 +15,7 @@ use std::{env,sync::{OnceLock,- atomic::{AtomicIsize, Ordering},+ atomic::{AtomicIsize, AtomicU8, Ordering},},thread,time::Instant,@@ -33,7 +33,7 @@ use muelle_core::{use muelle_shell::{appbar::{ABN_FULLSCREENAPP, AppBar, Edge},files, launcher,- pins::{app_exists, link_target, taskbar_pins, taskbar_pins_if_readable, unpin_from_taskbar},+ pins::{app_exists, link_target, taskbar_pins, taskbar_pins_if_readable},power,recycle_bin::{self, BinWatch},status,@@ -95,6 +95,7 @@ use crate::{menu::{self, MenuItem},menubar::MenuBar,scene::{Drag, Frame, Scene, SceneInput, SlotContent, Theme},+ shell_work::{self, Action as ShellAction},strings::{self, text},thumbnails::Thumbnails,};@@ -238,6 +239,44 @@ static FOREGROUND_HOOK: AtomicIsize = AtomicIsize::new(0);/// The window in front before the Alt+Tab switcher opened.static LAST_FRONT: AtomicIsize = AtomicIsize::new(0);+/// One drive scan at a time; changes during a scan request one more pass.+struct BinQueryGate(AtomicU8);++impl BinQueryGate {+ const RUNNING: u8 = 1;+ const DIRTY: u8 = 2;++ const fn new() -> Self {+ Self(AtomicU8::new(0))+ }++ fn request(&self) -> bool {+ if self.0.fetch_or(Self::DIRTY, Ordering::AcqRel) & Self::RUNNING != 0 {+ return false;+ }+ self.0+ .compare_exchange(+ Self::DIRTY,+ Self::RUNNING | Self::DIRTY,+ Ordering::AcqRel,+ Ordering::Acquire,+ )+ .is_ok()+ }++ fn begin_pass(&self) {+ self.0.fetch_and(!Self::DIRTY, Ordering::AcqRel);+ }++ fn needs_another_pass(&self) -> bool {+ self.0+ .compare_exchange(Self::RUNNING, 0, Ordering::AcqRel, Ordering::Acquire)+ .is_err()+ }+}++static BIN_QUERY: BinQueryGate = BinQueryGate::new();+#[derive(Clone, PartialEq)]struct Entry {kind: ItemKind,@@ -2617,24 +2656,40 @@ pub fn drop_files(x: i32, _y: i32) -> DROPEFFECT {/// (measured at 50–75 ms), so the UI is not blocked. The result arrives via/// `BIN_STATE`.fn query_bin_in_background() {+ if !BIN_QUERY.request() {+ return;+ }let window = MAIN_WINDOW.load(Ordering::Relaxed);- thread::spawn(move || {- // SAFETY: COM is initialized and released on this thread; the message- // is harmless if the window no longer exists.- unsafe {- let com = CoInitializeEx(None, COINIT_APARTMENTTHREADED);- let full = recycle_bin::has_items();- if com.is_ok() {- CoUninitialize();+ let spawned = thread::Builder::new()+ .name("muelle-recycle-query".into())+ .spawn(move || {+ power::set_thread_efficiency(true);+ // SAFETY: COM is initialized and released on this thread; the message+ // is harmless if the window no longer exists.+ unsafe {+ let com = CoInitializeEx(None, COINIT_APARTMENTTHREADED);+ loop {+ BIN_QUERY.begin_pass();+ let full = recycle_bin::has_items();+ let _ = PostMessageW(+ Some(HWND(window as *mut _)),+ BIN_STATE,+ WPARAM(usize::from(full)),+ LPARAM(0),+ );+ if !BIN_QUERY.needs_another_pass() {+ break;+ }+ }+ if com.is_ok() {+ CoUninitialize();+ }}- let _ = PostMessageW(- Some(HWND(window as *mut _)),- BIN_STATE,- WPARAM(usize::from(full)),- LPARAM(0),- );- }- });+ });+ if let Err(error) = spawned {+ BIN_QUERY.0.store(0, Ordering::Release);+ eprintln!("muelle: no se pudo consultar la Papelera: {error}");+ }}fn main_window() -> HWND {@@ -2642,46 +2697,44 @@ fn main_window() -> HWND {}fn run_outside(outside: Outside) {- let report = |result: Result<(), launcher::LaunchError>| {+ let submit = |action| {+ let result = shell_work::dispatch(action);if let Err(error) = result {- eprintln!("muelle: {error}");+ eprintln!("muelle: operación no iniciada: {error:#}");+ shell_work::notify_not_started();}};match outside {- Outside::Open(id) => report(launcher::open(&id)),+ Outside::Open(id) => submit(ShellAction::Open { id }),Outside::OpenStart => launcher::open_start_menu(),Outside::Activate(windows) => launcher::activate(&windows),Outside::Minimize(windows) => launcher::minimize(&windows),- Outside::Reveal(path) => report(launcher::reveal(&path)),- Outside::OpenWith(app, files) => report(launcher::open_with(&app, &files)),- Outside::Recycle(paths) => files::recycle(main_window(), &paths),+ Outside::Reveal(path) => submit(ShellAction::Reveal { path }),+ Outside::OpenWith(app, files) => submit(ShellAction::OpenWith { app, files }),+ Outside::Recycle(files) => submit(ShellAction::Recycle { files }),Outside::Transfer {folder,files: paths,copy,- } => files::transfer(main_window(), &paths, &folder, copy),- Outside::EmptyBin => {- let owner = HWND(MAIN_WINDOW.load(Ordering::Relaxed) as *mut _);- recycle_bin::empty(owner);- }+ } => submit(ShellAction::Transfer {+ files: paths,+ folder,+ copy,+ }),+ Outside::EmptyBin => submit(ShellAction::EmptyBin),Outside::QuitDock => request_quit(),- Outside::OpenAsAdmin(id) => report(launcher::open_as_admin(&id)),+ Outside::OpenAsAdmin(id) => submit(ShellAction::OpenAsAdmin { id }),Outside::ShowDesktop => launcher::show_desktop(),- Outside::UnpinFromTaskbar(id) => {- // The shell command may load extensions: keep it off the UI thread.- thread::spawn(move || {- // SAFETY: COM for this short-lived thread only.- let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };- let _ = unpin_from_taskbar(&id);- });- }+ Outside::UnpinFromTaskbar(id) => submit(ShellAction::Unpin { id }),Outside::OpenSettings => {// The settings app is installed next to the dock.let settings = env::current_exe().ok().map(|exe| exe.with_file_name("muelle-settings.exe"));match settings {- Some(path) if path.exists() => report(launcher::open(&path.to_string_lossy())),+ Some(path) if path.exists() => submit(ShellAction::Open {+ id: path.to_string_lossy().into_owned(),+ }),_ => eprintln!("muelle: no se encontró muelle-settings.exe junto al dock"),}}@@ -3131,3 +3184,31 @@ pub fn run() -> Result<()> {let _ = taking_over.join();Ok(())}++#[cfg(test)]+mod performance_tests {+ use super::BinQueryGate;++ #[test]+ fn recycle_notifications_share_one_scan_and_preserve_the_last_change() {+ let gate = BinQueryGate::new();+ assert!(gate.request());+ gate.begin_pass();+ for _ in 0..10_000 {+ assert!(!gate.request());+ }+ assert!(gate.needs_another_pass());+ gate.begin_pass();+ assert!(!gate.needs_another_pass());+ assert!(gate.request());+ }++ #[test]+ fn quiet_recycle_scan_allows_the_next_independent_scan() {+ let gate = BinQueryGate::new();+ assert!(gate.request());+ gate.begin_pass();+ assert!(!gate.needs_another_pass());+ assert!(gate.request());+ }+}diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rsindex 759ce54..f4061a1 100644--- a/apps/dock/src/main.rs+++ b/apps/dock/src/main.rs@@ -7,6 +7,7 @@//! - `muelle --autostart on|off` enables or disables startup with Windows//! - `muelle --guard <pid>` internal watchdog process//! - `muelle --usage-worker` internal one-shot quota reader+//! - `muelle --shell-worker` internal one-shot shell action#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]@@ -19,6 +20,7 @@ mod guard;mod menu;mod menubar;mod scene;+mod shell_work;mod strings;mod thumbnails;mod usage;@@ -67,6 +69,7 @@ fn main() -> Result<()> {["--autostart", "off"] => Ok(autostart::set(None)?),[guard::FLAG, pid] => guard::run(pid.parse().context("pid no válido")?),["--usage-worker"] => usage::worker_main(),+ [shell_work::FLAG] => shell_work::worker_main(),_ => bail!("uso: muelle [--quit | --restore | --autostart on|off]"),}}diff --git a/apps/dock/src/shell_work.rs b/apps/dock/src/shell_work.rsnew file mode 100644index 0000000..6a92d5e--- /dev/null+++ b/apps/dock/src/shell_work.rs@@ -0,0 +1,384 @@+//! Slow shell actions run in disposable processes. File operations already+//! started can finish even if the dock exits; no shell extension runs on its UI.++use std::{+ env,+ io::{Read, Write},+ os::windows::{io::AsRawHandle, process::CommandExt},+ process::{Command, Stdio},+ sync::{+ Arc, Mutex, OnceLock,+ mpsc::{SyncSender, sync_channel},+ },+ thread,+};++use anyhow::{Context, Result, bail};+use muelle_shell::{files, launcher, pins::unpin_from_taskbar, recycle_bin};+use serde::{Deserialize, Serialize};+use windows::Win32::{+ Foundation::{HANDLE, HWND, WAIT_TIMEOUT},+ System::Com::{+ COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE, CoInitializeEx, CoUninitialize,+ },+ System::Threading::WaitForSingleObject,+ UI::WindowsAndMessaging::AllowSetForegroundWindow,+};++pub const FLAG: &str = "--shell-worker";+const MAX_REQUEST_BYTES: u64 = 4 * 1024 * 1024;+const CREATE_NO_WINDOW: u32 = 0x0800_0000;++#[derive(Debug, Serialize, Deserialize)]+#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]+pub enum Action {+ Open {+ id: String,+ },+ OpenAsAdmin {+ id: String,+ },+ Reveal {+ path: String,+ },+ OpenWith {+ app: String,+ files: Vec<String>,+ },+ Recycle {+ files: Vec<String>,+ },+ Transfer {+ folder: String,+ files: Vec<String>,+ copy: bool,+ },+ EmptyBin,+ Unpin {+ id: String,+ },+}++impl Action {+ fn launch_timeout_ms(&self) -> Option<u32> {+ match self {+ Self::Open { .. } | Self::OpenWith { .. } | Self::Reveal { .. } => Some(30_000),+ // File progress and UAC can legitimately wait for a user decision.+ _ => None,+ }+ }++ fn modifies_files(&self) -> bool {+ matches!(+ self,+ Self::Recycle { .. } | Self::Transfer { .. } | Self::EmptyBin+ )+ }++ fn run(self) -> Result<()> {+ // The helper owns the native progress/confirmation windows. Making+ // the dock their owner would disable its input during long operations.+ let owner = HWND::default();+ match self {+ Self::Open { id } => launcher::open(&id)?,+ Self::OpenAsAdmin { id } => launcher::open_as_admin(&id)?,+ Self::Reveal { path } => launcher::reveal(&path)?,+ Self::OpenWith { app, files } => launcher::open_with(&app, &files)?,+ Self::Recycle { files: paths } => {+ files::recycle(owner, &paths)?;+ }+ Self::Transfer {+ folder,+ files: paths,+ copy,+ } => {+ files::transfer(owner, &paths, &folder, copy)?;+ }+ Self::EmptyBin => recycle_bin::empty(owner),+ Self::Unpin { id } => {+ let _ = unpin_from_taskbar(&id);+ }+ }+ Ok(())+ }+}++/// Fixed worker count and bounded queue; sending never waits for a shell job.+struct Queue<T> {+ sender: SyncSender<T>,+}++impl<T: Send + 'static> Queue<T> {+ fn new(+ workers: usize,+ capacity: usize,+ run: impl Fn(T) + Send + Sync + 'static,+ ) -> Result<Self> {+ let (sender, receiver) = sync_channel::<T>(capacity);+ let receiver = Arc::new(Mutex::new(receiver));+ let run = Arc::new(run);+ for index in 0..workers {+ let receiver = Arc::clone(&receiver);+ let run = Arc::clone(&run);+ thread::Builder::new()+ .name(format!("muelle-shell-{index}"))+ .spawn(move || {+ loop {+ let job = {+ let Ok(receiver) = receiver.lock() else { break };+ receiver.recv()+ };+ let Ok(job) = job else { break };+ // No shell call or process wait holds the queue lock.+ run(job);+ }+ })?;+ }+ Ok(Self { sender })+ }++ fn submit(&self, job: T) -> Result<()> {+ self.sender+ .try_send(job)+ .map_err(|_| anyhow::anyhow!("la cola del shell está llena o no está disponible"))+ }+}++struct Workers {+ launches: Queue<Action>,+ files: Queue<Action>,+}++impl Workers {+ fn new() -> Result<Self> {+ let execute = |action| {+ if let Err(error) = start_helper(action) {+ eprintln!("muelle: operación del shell: {error:#}");+ }+ };+ Ok(Self {+ launches: Queue::new(2, 16, execute)?,+ // Preserve file-operation order and avoid competing transfers.+ files: Queue::new(1, 4, execute)?,+ })+ }+}++pub fn dispatch(action: Action) -> Result<()> {+ static WORKERS: OnceLock<Result<Workers, String>> = OnceLock::new();+ let workers = WORKERS.get_or_init(|| Workers::new().map_err(|error| error.to_string()));+ let workers = workers+ .as_ref()+ .map_err(|error| anyhow::anyhow!("{error}"))?;+ if action.modifies_files() {+ workers.files.submit(action)+ } else {+ workers.launches.submit(action)+ }+}++/// A rejected request must be visible to the user, without blocking the UI+/// or creating a new dialog for every repeated click on a full queue.+pub fn notify_not_started() {+ use std::sync::atomic::{AtomicBool, Ordering};+ use windows::Win32::UI::WindowsAndMessaging::{MB_ICONWARNING, MB_OK, MessageBoxW};+ static SHOWING: AtomicBool = AtomicBool::new(false);+ if SHOWING.swap(true, Ordering::AcqRel) {+ return;+ }+ let message = crate::strings::text().shell_operation_failed;+ let shown = thread::Builder::new()+ .name("muelle-shell-notice".into())+ .spawn(move || {+ // SAFETY: Independent native dialog; it never disables the dock.+ unsafe {+ MessageBoxW(+ None,+ &windows::core::HSTRING::from(message),+ windows::core::w!("Muelle"),+ MB_OK | MB_ICONWARNING,+ );+ }+ SHOWING.store(false, Ordering::Release);+ });+ if shown.is_err() {+ SHOWING.store(false, Ordering::Release);+ }+}++fn start_helper(action: Action) -> Result<()> {+ let timeout = action.launch_timeout_ms();+ let input = serde_json::to_vec(&action)?;+ if input.len() as u64 > MAX_REQUEST_BYTES {+ bail!("la operación contiene demasiados datos");+ }+ let mut child = Command::new(env::current_exe()?)+ .arg(FLAG)+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ // A launched app may inherit a standard handle. Waiting for a stderr+ // pipe to close could then hold this slot for that app's entire life.+ .stderr(Stdio::inherit())+ .creation_flags(CREATE_NO_WINDOW)+ .spawn()+ .context("no se pudo iniciar el auxiliar del shell")?;+ // SAFETY: Give this child the foreground right granted by the dock click.+ unsafe {+ let _ = AllowSetForegroundWindow(child.id());+ }+ if let Some(mut stdin) = child.stdin.take() {+ // Closing the pipe after writing is the helper's end-of-request marker.+ stdin.write_all(&input)?;+ }+ let timed_out = timeout.is_some_and(|milliseconds| {+ // SAFETY: `child` owns this process handle throughout the bounded wait.+ unsafe { WaitForSingleObject(HANDLE(child.as_raw_handle()), milliseconds) == WAIT_TIMEOUT }+ });+ if timed_out {+ // Ordinary activation must not permanently consume both slots.+ // Transfers and UAC are exempt from this deadline.+ child+ .kill()+ .context("no se pudo cerrar el auxiliar de apertura atascado")?;+ }+ let status = child.wait()?;+ if timed_out {+ bail!("el shell no respondió a la apertura en 30 segundos");+ }+ if !status.success() {+ bail!("el auxiliar del shell terminó con {status}");+ }+ Ok(())+}++fn read_action(input: impl Read) -> Result<Action> {+ let mut bytes = Vec::new();+ input.take(MAX_REQUEST_BYTES + 1).read_to_end(&mut bytes)?;+ if bytes.len() as u64 > MAX_REQUEST_BYTES {+ bail!("la operación contiene demasiados datos");+ }+ Ok(serde_json::from_slice(&bytes)?)+}++pub fn worker_main() -> Result<()> {+ let action = read_action(std::io::stdin().lock())?;+ // SAFETY: The helper owns this apartment and balances it after the native+ // shell action returns. Shell launch calls wait for activation before exit.+ unsafe {+ CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE).ok()?;+ }+ let result = action.run();+ unsafe { CoUninitialize() };+ result+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::{+ sync::{Condvar, mpsc::channel},+ time::Duration,+ };++ #[test]+ fn full_queue_rejects_without_waiting_for_a_blocked_operation() -> Result<()> {+ let gate = Arc::new((Mutex::new(false), Condvar::new()));+ let release = Arc::clone(&gate);+ let (started, waiting) = channel();+ let queue = Queue::new(1, 1, move |_: ()| {+ let _ = started.send(());+ let (lock, wake) = &*gate;+ let open = lock+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ drop(+ wake.wait_while(open, |open| !*open)+ .unwrap_or_else(std::sync::PoisonError::into_inner),+ );+ })?;+ queue.submit(())?;+ waiting.recv_timeout(Duration::from_secs(2))?;+ queue.submit(())?;+ assert!(queue.submit(()).is_err());+ drop(queue);+ *release+ .0+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = true;+ release.1.notify_all();+ Ok(())+ }++ #[test]+ fn file_actions_use_the_serial_queue() {+ assert!(+ Action::Transfer {+ folder: "x".into(),+ files: vec![],+ copy: true+ }+ .modifies_files()+ );+ assert!(Action::EmptyBin.modifies_files());+ assert!(!Action::Open { id: "x".into() }.modifies_files());+ }++ #[test]+ fn malformed_requests_are_rejected_before_any_shell_call() {+ assert!(read_action(br#"{"operation":"unknown"}"#.as_slice()).is_err());+ assert!(read_action(br#"{"operation":"open","id":5}"#.as_slice()).is_err());+ }++ #[test]+ fn deadlines_exempt_file_operations_and_explicit_admin_launches() {+ assert!(+ Action::Open { id: "x".into() }+ .launch_timeout_ms()+ .is_some()+ );+ assert!(+ Action::Transfer {+ folder: "x".into(),+ files: vec![],+ copy: true+ }+ .launch_timeout_ms()+ .is_none()+ );+ assert!(Action::EmptyBin.launch_timeout_ms().is_none());+ assert!(+ Action::OpenAsAdmin { id: "x".into() }+ .launch_timeout_ms()+ .is_none()+ );+ }++ #[test]+ fn oversized_requests_are_rejected_before_any_shell_call() {+ assert!(read_action(std::io::repeat(0).take(MAX_REQUEST_BYTES + 2)).is_err());+ }++ #[test]+ fn request_pipe_preserves_unicode_paths_spaces_and_copy_mode() -> Result<()> {+ let action = Action::Transfer {+ folder: r"C:\Destino con espacios\á".into(),+ files: vec![r"C:\Origen\diseño final.txt".into()],+ copy: true,+ };+ let bytes = serde_json::to_vec(&action)?;+ let parsed = read_action(bytes.as_slice())?;+ match parsed {+ Action::Transfer {+ folder,+ files,+ copy,+ } => {+ assert_eq!(folder, r"C:\Destino con espacios\á");+ assert_eq!(files, [r"C:\Origen\diseño final.txt"]);+ assert!(copy);+ }+ _ => bail!("la operación de copia cambió durante el transporte"),+ }+ Ok(())+ }+}diff --git a/apps/dock/src/strings.rs b/apps/dock/src/strings.rsindex 92034a9..4d1c95a 100644--- a/apps/dock/src/strings.rs+++ b/apps/dock/src/strings.rs@@ -34,9 +34,11 @@ pub struct Strings {pub usage_resets: &'static str,pub usage_updated: &'static str,pub usage_used: &'static str,+ pub shell_operation_failed: &'static str,}const ES: Strings = Strings {+ shell_operation_failed: "No se pudo iniciar la operación. Inténtalo de nuevo en un momento.",open: "&Abrir",new_window: "&Nueva ventana",keep_in_dock: "&Mantener en el Dock",@@ -66,6 +68,7 @@ const ES: Strings = Strings {};const EN: Strings = Strings {+ shell_operation_failed: "The operation could not start. Please try again in a moment.",open: "&Open",new_window: "&New Window",keep_in_dock: "&Keep in Dock",diff --git a/crates/muelle-shell/src/files.rs b/crates/muelle-shell/src/files.rsindex d4a0295..512ff66 100644--- a/crates/muelle-shell/src/files.rs+++ b/crates/muelle-shell/src/files.rs@@ -1,6 +1,7 @@//! Shell file operations with the standard Windows progress, confirmation,//! and undo behavior.+use thiserror::Error;use windows::{Win32::{Foundation::HWND,@@ -11,19 +12,34 @@ use windows::{core::PCWSTR,};+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Outcome {+ Completed,+ Cancelled,+}++#[derive(Debug, Error)]+#[error("la operación de archivos del shell falló (código {0})")]+pub struct FileError(i32);+/// Sends files to the recycle bin.-pub fn recycle(owner: HWND, files: &[String]) {- run(owner, FO_DELETE, files, None);+pub fn recycle(owner: HWND, files: &[String]) -> Result<Outcome, FileError> {+ run(owner, FO_DELETE, files, None)}/// Moves (or copies) files into `folder`.-pub fn transfer(owner: HWND, files: &[String], folder: &str, copy: bool) {+pub fn transfer(+ owner: HWND,+ files: &[String],+ folder: &str,+ copy: bool,+) -> Result<Outcome, FileError> {run(owner,if copy { FO_COPY } else { FO_MOVE },files,Some(folder),- );+ )}/// `true` if both paths are on the same volume, where Explorer moves instead of copying.@@ -44,9 +60,14 @@ fn path_list<'a>(paths: impl IntoIterator<Item = &'a str>) -> Vec<u16> {list}-fn run(owner: HWND, operation: u32, files: &[String], destination: Option<&str>) {+fn run(+ owner: HWND,+ operation: u32,+ files: &[String],+ destination: Option<&str>,+) -> Result<Outcome, FileError> {if files.is_empty() {- return;+ return Ok(Outcome::Completed);}let from = path_list(files.iter().map(String::as_str));let to = destination.map(|folder| path_list([folder]));@@ -58,10 +79,15 @@ fn run(owner: HWND, operation: u32, files: &[String], destination: Option<&str>)fFlags: FOF_ALLOWUNDO.0 as u16,..Default::default()};- // SAFETY: The path buffers outlive the call. Cancelling or failing shows- // the shell's own message, so the result needs no handling here.- unsafe {- let _ = SHFileOperationW(&mut request);+ // SAFETY: The path buffers outlive the call. Preserve the native shell's+ // confirmations and progress UI, and distinguish cancellation from failure.+ let code = unsafe { SHFileOperationW(&mut request) };+ if request.fAnyOperationsAborted.as_bool() {+ Ok(Outcome::Cancelled)+ } else if code == 0 {+ Ok(Outcome::Completed)+ } else {+ Err(FileError(code))}}@@ -69,6 +95,14 @@ fn run(owner: HWND, operation: u32, files: &[String], destination: Option<&str>)mod tests {use super::*;+ #[test]+ fn empty_transfer_finishes_without_calling_the_shell() {+ assert_eq!(+ transfer(HWND::default(), &[], "", true).ok(),+ Some(Outcome::Completed)+ );+ }+#[test]fn path_list_should_end_with_two_nuls() {assert_eq!(path_list(["a", "b"]), [97, 0, 98, 0, 0]);diff --git a/crates/muelle-shell/src/launcher.rs b/crates/muelle-shell/src/launcher.rsindex bc9a930..ba050cf 100644--- a/crates/muelle-shell/src/launcher.rs+++ b/crates/muelle-shell/src/launcher.rs@@ -15,7 +15,7 @@ use windows::{KEYEVENTF_KEYUP, SendInput, VIRTUAL_KEY, VK_A, VK_B, VK_D, VK_ESCAPE, VK_LCONTROL,VK_LWIN, VK_N, VK_RETURN, VK_S, VK_SPACE, VK_TAB, VK_V, VK_W,},- Shell::ShellExecuteW,+ Shell::{SEE_MASK_NOASYNC, SHELLEXECUTEINFOW, ShellExecuteExW},WindowsAndMessaging::{ASFW_ANY, AllowSetForegroundWindow, FindWindowW, GetForegroundWindow,GetWindowRect, GetWindowThreadProcessId, HWND_TOP, IsIconic, IsWindowVisible,@@ -46,56 +46,43 @@ fn allow_foreground() {}pub fn open(id: &str) -> Result<(), LaunchError> {- shell_execute(w!("open"), id)+ shell_execute(w!("open"), id, None)}/// Opens `id` as administrator, with the UAC prompt, as the taskbar's/// "Run as administrator" and Ctrl+Shift+click do.pub fn open_as_admin(id: &str) -> Result<(), LaunchError> {- shell_execute(w!("runas"), id)+ shell_execute(w!("runas"), id, None)}-fn shell_execute(verb: PCWSTR, id: &str) -> Result<(), LaunchError> {+fn shell_execute(verb: PCWSTR, id: &str, arguments: Option<&str>) -> Result<(), LaunchError> {allow_foreground();+ let file = HSTRING::from(id);+ let arguments = arguments.map(HSTRING::from);+ let mut request = SHELLEXECUTEINFOW {+ cbSize: size_of::<SHELLEXECUTEINFOW>() as u32,+ // A disposable caller must finish activation (including DDE) before+ // its thread exits. This does not wait for the launched app to close.+ fMask: SEE_MASK_NOASYNC,+ lpVerb: verb,+ lpFile: PCWSTR(file.as_ptr()),+ lpParameters: arguments+ .as_ref()+ .map_or(PCWSTR::null(), |value| PCWSTR(value.as_ptr())),+ nShow: SW_SHOWNORMAL.0,+ ..Default::default()+ };// SAFETY: The strings live for the duration of the call.- let result =- unsafe { ShellExecuteW(None, verb, &HSTRING::from(id), None, None, SW_SHOWNORMAL) };- // ShellExecute returns a value greater than 32 on success.- let code = result.0 as isize;- if code > 32 {- Ok(())- } else {- Err(LaunchError {- id: id.to_owned(),- code,- })- }+ unsafe { ShellExecuteExW(&mut request) }.map_err(|error| LaunchError {+ id: id.to_owned(),+ code: error.code().0 as isize,+ })}/// Opens `files` with the executable `app`.pub fn open_with(app: &str, files: &[String]) -> Result<(), LaunchError> {let arguments: Vec<String> = files.iter().map(|file| format!("\"{file}\"")).collect();- allow_foreground();- // SAFETY: The strings live for the duration of the call.- let result = unsafe {- ShellExecuteW(- None,- w!("open"),- &HSTRING::from(app),- &HSTRING::from(arguments.join(" ")),- None,- SW_SHOWNORMAL,- )- };- let code = result.0 as isize;- if code > 32 {- Ok(())- } else {- Err(LaunchError {- id: app.to_owned(),- code,- })- }+ shell_execute(w!("open"), app, Some(&arguments.join(" ")))}/// `true` if the window in front belongs to a program running as@@ -355,28 +342,11 @@ fn keep_under(flyout: HWND, (center, top): (i32, i32)) {}pub fn reveal(path: &str) -> Result<(), LaunchError> {- let arguments = HSTRING::from(format!("/select,\"{path}\""));- allow_foreground();- // SAFETY: The strings live for the duration of the call.- let result = unsafe {- ShellExecuteW(- None,- w!("open"),- w!("explorer.exe"),- &arguments,- None,- SW_SHOWNORMAL,- )- };- let code = result.0 as isize;- if code > 32 {- Ok(())- } else {- Err(LaunchError {- id: path.to_owned(),- code,- })- }+ shell_execute(+ w!("open"),+ "explorer.exe",+ Some(&format!("/select,\"{path}\"")),+ )}/// Asks the windows to close, as the close button does; each app can prompt