From 8a187593839df4543bde42c4d703353f8952eb1d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 19 Nov 2026 18:19:54 +0100 Subject: [PATCH] Own Windows file pickers and prevent duplicate dialog requests --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/pdf-presenter/src/localization.rs | 1 + crates/pdf-presenter/src/native.rs | 40 ++++++++ crates/pdf-presenter/src/presenter_ui.rs | 29 +++--- crates/pdf-presenter/src/studio.rs | 23 ++++- crates/pdf-presenter/src/worker.rs | 41 +++++++- crates/pdf-presenter/tests/chooser.rs | 114 ++++++++++++++++++++++ docs/changelog.md | 11 +++ docs/development/native-implementation.md | 18 ++++ docs/interfaces/process-protocol.md | 19 ++++ docs/user-guide.md | 4 + 12 files changed, 286 insertions(+), 18 deletions(-) create mode 100644 crates/pdf-presenter/tests/chooser.rs diff --git a/Cargo.lock b/Cargo.lock index 13f7f6f..cd300d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2212,7 +2212,7 @@ dependencies = [ [[package]] name = "pdf-presenter" -version = "0.1.14" +version = "0.1.15" dependencies = [ "bytemuck", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 2de8ab5..0fbfa3b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ default-members = ["crates/pdf-presenter"] resolver = "3" [workspace.package] -version = "0.1.14" +version = "0.1.15" edition = "2024" license = "MIT" repository = "https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter" diff --git a/crates/pdf-presenter/src/localization.rs b/crates/pdf-presenter/src/localization.rs index dbf0e33..ff3b28f 100644 --- a/crates/pdf-presenter/src/localization.rs +++ b/crates/pdf-presenter/src/localization.rs @@ -39,6 +39,7 @@ pub fn tr<'a>(ctx: &egui::Context, text: &'a str) -> &'a str { return text; } match text { + "File chooser already open" => "Sélecteur de fichiers déjà ouvert", "Appearance" => "Apparence", "Preferences" => "Préférences", "Storage locations" => "Emplacements de stockage", diff --git a/crates/pdf-presenter/src/native.rs b/crates/pdf-presenter/src/native.rs index e99ae55..d291e94 100644 --- a/crates/pdf-presenter/src/native.rs +++ b/crates/pdf-presenter/src/native.rs @@ -513,10 +513,26 @@ impl App { s.layout_open, s.browser_open, ); + let chooser_was_open = s.dialog_busy; s.poll(); let actions = std::mem::take(&mut s.actions); repaint |= !actions.is_empty(); for action in actions { + #[cfg(target_os = "windows")] + if matches!(action, Action::Pick(_)) && !s.dialog_busy { + use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; + s.dialog_owner = self + .windows + .iter() + .filter(|w| w.role == Role::Presenter) + .find(|w| w.window.has_focus()) + .or_else(|| self.windows.iter().find(|w| w.role == Role::Presenter)) + .and_then(|w| w.window.window_handle().ok()) + .and_then(|h| match h.as_raw() { + RawWindowHandle::Win32(h) => Some(h.hwnd.get()), + _ => None, + }); + } if matches!(action, Action::OpenBrowser) { for window in self.windows.iter().filter(|w| w.role == Role::Browser) { window.window.set_minimized(false); @@ -525,6 +541,30 @@ impl App { } s.execute(action); } + if chooser_was_open != s.dialog_busy { + repaint = true; + for window in &self.windows { + if window.role == Role::Browser { + window.window.set_window_level(if s.dialog_busy { + winit::window::WindowLevel::Normal + } else { + winit::window::WindowLevel::AlwaysOnTop + }); + } + #[cfg(target_os = "windows")] + if !s.dialog_busy && window.role == Role::Presenter { + use winit::{ + platform::windows::WindowExtWindows, + raw_window_handle::{HasWindowHandle, RawWindowHandle}, + }; + // The worker can time out while COM has the owner disabled. + window.window.set_enable(true); + if window.window.window_handle().ok().is_some_and(|h| matches!(h.as_raw(),RawWindowHandle::Win32(h) if Some(h.hwnd.get()) == s.dialog_owner)) { + window.window.focus_window(); + } + } + } + } if let Some(output) = &self.output { while let Ok(ack) = output.rx.try_recv() { if ack.generation == s.buffer_generation() { diff --git a/crates/pdf-presenter/src/presenter_ui.rs b/crates/pdf-presenter/src/presenter_ui.rs index 340424f..51053ea 100644 --- a/crates/pdf-presenter/src/presenter_ui.rs +++ b/crates/pdf-presenter/src/presenter_ui.rs @@ -828,18 +828,23 @@ fn menu(ui: &mut Ui, s: &mut Studio) { let locale = ui.ctx().clone(); ui.set_min_width(260.); let actions_before = s.actions.len(); - button( - ui, - tr(&locale, "Open PDF…"), - Action::Pick(false), - &mut s.actions, - ); - button( - ui, - tr(&locale, "Open picture folder…"), - Action::Pick(true), - &mut s.actions, - ); + ui.add_enabled_ui(!s.dialog_busy, |ui| { + button( + ui, + tr(&locale, "Open PDF…"), + Action::Pick(false), + &mut s.actions, + ); + button( + ui, + tr(&locale, "Open picture folder…"), + Action::Pick(true), + &mut s.actions, + ); + }); + if s.dialog_busy { + ui.label(tr(&locale, "File chooser already open")); + } ui.separator(); button( ui, diff --git a/crates/pdf-presenter/src/studio.rs b/crates/pdf-presenter/src/studio.rs index 8dc052c..9e768f8 100644 --- a/crates/pdf-presenter/src/studio.rs +++ b/crates/pdf-presenter/src/studio.rs @@ -71,6 +71,8 @@ pub struct Studio { pub bg: Bridge, pub io: Bridge, pub dialog: Bridge, + pub dialog_busy: bool, + pub dialog_owner: Option, fg_busy: bool, bg_busy: bool, fg_job: Option<(usize, u32)>, @@ -155,6 +157,8 @@ impl Studio { bg: Bridge::with_program(Duration::from_secs(30), worker_program.clone()), io, dialog: Bridge::with_program(Duration::from_secs(300), worker_program.clone()), + dialog_busy: false, + dialog_owner: None, fg_busy: false, bg_busy: false, fg_job: None, @@ -252,8 +256,21 @@ impl Studio { self.status = "Opening document in an isolated worker…".into(); } Action::Pick(folder) => { - if !self.dialog.submit(0, 0, Request::Pick { folder }) { - self.status = "A file chooser is already active.".into(); + if !self.dialog_busy { + self.dialog_busy = self.dialog.submit( + 0, + 0, + Request::Pick { + folder, + owner: self.dialog_owner, + }, + ); + self.status = if self.dialog_busy { + "File chooser open — select a presentation or cancel." + } else { + "Could not open the file chooser. Try again." + } + .into(); } } Action::Go(page) => { @@ -364,6 +381,8 @@ impl Studio { self.pending_save = false; } while let Ok(c) = self.dialog.rx.try_recv() { + self.dialog_busy = false; + self.status = "File chooser closed.".into(); match c.result { Ok(p) => { if let Some(path) = p.reply.picked { diff --git a/crates/pdf-presenter/src/worker.rs b/crates/pdf-presenter/src/worker.rs index c200cc5..d6f4dba 100644 --- a/crates/pdf-presenter/src/worker.rs +++ b/crates/pdf-presenter/src/worker.rs @@ -49,6 +49,8 @@ pub enum Request { }, Pick { folder: bool, + /// Windows owner HWND; never a pointer dereferenced by the worker. + owner: Option, }, SleepTest(u64), } @@ -200,8 +202,8 @@ pub fn run() -> Result<(), String> { } Request::LoadSettings(path) => reply.settings = Some(settings::read(&path)?), Request::SaveSettings { path, settings } => settings::write(&path, &settings)?, - Request::Pick { folder } => { - let dialog = rfd::FileDialog::new().set_title("Open presentation"); + Request::Pick { folder, owner } => { + let dialog = picker_dialog(owner)?; reply.picked = if folder { dialog.pick_folder() } else { @@ -378,3 +380,38 @@ impl Drop for Bridge { self.stop.store(true, Ordering::Relaxed); } } + +fn picker_dialog(owner: Option) -> Result { + let dialog = rfd::FileDialog::new().set_title("Open presentation"); + #[cfg(target_os = "windows")] + { + use winit::raw_window_handle::{ + DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawWindowHandle, + Win32WindowHandle, WindowHandle, + }; + struct Owner(std::num::NonZeroIsize); + impl HasWindowHandle for Owner { + fn window_handle(&self) -> Result, HandleError> { + // The parent passes its live presenter HWND over private same-build IPC. + // rfd copies this OS identifier; no worker memory is dereferenced. + Ok(unsafe { + WindowHandle::borrow_raw(RawWindowHandle::Win32(Win32WindowHandle::new(self.0))) + }) + } + } + impl HasDisplayHandle for Owner { + fn display_handle(&self) -> Result, HandleError> { + Ok(DisplayHandle::windows()) + } + } + let owner = owner + .and_then(std::num::NonZeroIsize::new) + .ok_or("No presenter window available for the file chooser")?; + Ok(dialog.set_parent(&Owner(owner))) + } + #[cfg(not(target_os = "windows"))] + { + let _ = owner; + Ok(dialog) + } +} diff --git a/crates/pdf-presenter/tests/chooser.rs b/crates/pdf-presenter/tests/chooser.rs new file mode 100644 index 0000000..9539a42 --- /dev/null +++ b/crates/pdf-presenter/tests/chooser.rs @@ -0,0 +1,114 @@ +use pdf_presenter::{ + studio::{Action, Studio}, + worker::{Completion, Job, Reply, Request, ResultPacket}, +}; +use std::sync::mpsc::{self, Receiver, SyncSender}; + +fn controlled_chooser() -> (Studio, Receiver, SyncSender) { + let mut studio = Studio::with_program(true, None, env!("CARGO_BIN_EXE_pdf-presenter").into()); + let (requests, jobs) = mpsc::sync_channel(4); + let (results, replies) = mpsc::sync_channel(4); + // Replace only the chooser transport: no native dialog or renderer is opened. + studio.dialog.tx = requests; + studio.dialog.rx = replies; + (studio, jobs, results) +} + +#[test] +fn repeated_pdf_and_folder_requests_never_queue_another_chooser() { + let (mut s, jobs, results) = controlled_chooser(); + s.dialog_owner = Some(12345); + s.requested = 7; + s.blanked = true; + for i in 0..100 { + s.execute(Action::Pick(i % 2 != 0)); + } + assert!(s.dialog_busy); + let job = jobs.try_recv().unwrap(); + assert!(matches!( + job.request, + Request::Pick { + folder: false, + owner: Some(12345) + } + )); + assert!(jobs.try_recv().is_err()); + results + .send(Completion { + generation: 0, + tag: 0, + result: Ok(ResultPacket { + reply: Reply::default(), + data: vec![], + }), + }) + .unwrap(); + s.poll(); + assert!(!s.dialog_busy); + assert_eq!(s.requested, 7); + assert!(s.blanked); + for _ in 0..5 { + s.poll(); + assert!(jobs.try_recv().is_err()); + } + s.execute(Action::Pick(true)); + assert!(s.dialog_busy); + assert!(matches!( + jobs.try_recv().unwrap().request, + Request::Pick { folder: true, .. } + )); +} + +#[test] +fn chooser_selection_errors_timeout_and_submission_failure_release_the_guard() { + let (mut s, jobs, results) = controlled_chooser(); + for result in [ + Err("Worker deadline exceeded".into()), + Ok(ResultPacket { + reply: Reply { + error: Some("Dialog unavailable".into()), + ..Default::default() + }, + data: vec![], + }), + Ok(ResultPacket { + reply: Reply { + picked: Some("missing-test-presentation.pdf".into()), + ..Default::default() + }, + data: vec![], + }), + ] { + s.execute(Action::Pick(false)); + assert!(s.dialog_busy); + jobs.try_recv().unwrap(); + results + .send(Completion { + generation: 0, + tag: 0, + result, + }) + .unwrap(); + s.poll(); + assert!(!s.dialog_busy); + assert!(jobs.try_recv().is_err()); + } + drop(jobs); + s.execute(Action::Pick(false)); + assert!(!s.dialog_busy); + assert!(s.status.contains("Could not open")); +} + +#[test] +fn chooser_owner_survives_private_protocol_roundtrip() { + for owner in [None, Some(1234567)] { + let request = Request::Pick { + folder: true, + owner, + }; + let bytes = serde_json::to_vec(&request).unwrap(); + assert!( + matches!(serde_json::from_slice::(&bytes).unwrap(),Request::Pick{folder:true,owner:got} if got==owner) + ); + } +} diff --git a/docs/changelog.md b/docs/changelog.md index 5f7cf6c..9753180 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -2,6 +2,17 @@ ## Unreleased +### 0.1.15 + +- Give Windows PDF/folder dialogs the active presenter window as their owner, so + they remain above its fullscreen view. Restore owner input/focus on completion, + including worker failure/timeout; temporarily lower a topmost slide browser. +- Permit only one outstanding chooser request across all presenter windows. Disable + Open controls while it is active; repeated clicks cannot queue more dialogs. +- Test a 100-request burst, cancellation, selection, failures, retry and owner IPC. + Windows compilation passes; native Windows modal placement still needs user retest. + + ### 0.1.14 - Replace the floating Menu with an anchored dropdown; present display assignments diff --git a/docs/development/native-implementation.md b/docs/development/native-implementation.md index 0a10aa5..85e663b 100644 --- a/docs/development/native-implementation.md +++ b/docs/development/native-implementation.md @@ -151,3 +151,21 @@ regressions, and 10 Python tests pass. Formatting, Clippy/rustdoc with warnings and macOS aarch64 compile-check pass. Whole-application coverage is 82.73% (75% floor), without production exclusions. Linux and Windows x86_64 release builds succeed. Windows/macOS runtime validation remains open. + + +## 0.1.15 Windows chooser correction + +The reported Windows dialog was unowned because rfd ran in a worker without the +presenter's HWND. Repeated Open actions were also admitted into the four-entry worker +queue. The worker now receives the active presenter HWND and uses it as the common +dialog owner, retaining the killable-worker design. A shared outstanding-request guard +prevents queuing, and native completion restores owner input/focus even after timeout. + +44 Rust tests and 10 Python tests pass. The new controlled-transport regression sends +100 alternating PDF/folder requests, verifies exactly one admission and no delayed +reopening after cancellation, then tests explicit retry, selection, worker error, +timeout and submission failure. Windows x86_64 release compilation and macOS aarch64 +compile-check pass; Windows fullscreen/modal placement requires user runtime retest. +Formatting and warnings-denied Clippy/rustdoc pass. Whole-app coverage is 82.88% with +no production exclusions. An initial coverage run failed to merge a corrupted worker +profile; a fresh full run passed. Linux release is rebuilt for the shared admission fix. diff --git a/docs/interfaces/process-protocol.md b/docs/interfaces/process-protocol.md index c712943..d57b520 100644 --- a/docs/interfaces/process-protocol.md +++ b/docs/interfaces/process-protocol.md @@ -41,3 +41,22 @@ previews or obsolete generations/resolutions. READY requires both presenter and counts to reach the deck total. Stale acknowledgments cannot mark another resolution ready. The bounded JSON envelope and raw-frame limits remain unchanged. This protocol still requires the same executable build at both ends. + + +## File chooser ownership and admission, 0.1.15 + +`Pick` carries `folder` and optional `owner` (a signed native Windows HWND integer; +null on other platforms). This identifier belongs to the parent presenter process, +is never dereferenced as worker memory, and is passed to the Windows common dialog +as its owner. Only the active presenter (or first available presenter) supplies it; +an audience window is never the owner. Windows requests without an owner fail clearly. +The protocol remains private and requires matching executable builds. + +The shared Studio admits exactly one outstanding chooser job, including across +mirrored presenters and alternating PDF/folder requests. Repeated Open actions are +ignored and the corresponding menu controls are disabled until a completion arrives. +Success, cancellation, worker error and the existing 300-second deadline all release +the guard; submission failure never sets it. The native host re-enables presenter +input and restores owner focus after completion, including a worker killed while the +common dialog had disabled its owner. Existing slide-browser windows temporarily +lose topmost status while the chooser is active. Rendering/output stay independent. diff --git a/docs/user-guide.md b/docs/user-guide.md index 7b1f32c..5b535ed 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -3,6 +3,10 @@ Run the portable executable and choose Menu → Open PDF or Open picture folder. You can also drop a file/folder on the presenter, pass its path on the command line, or use `--open PATH`. The source is read-only. A failed load keeps the previous show. +Only one file/folder chooser can be open at a time: Open commands are disabled until +you select a source, cancel or the chooser times out. On Windows the chooser belongs +to the active presenter window and appears above its fullscreen view. Repeated clicks +do not queue additional dialogs. A single connected monitor starts presenter-only rehearsal; `--windowed` disables fullscreen for the session. `--list-monitors` lists CLI display numbers.