Own Windows file pickers and prevent duplicate dialog requests

This commit is contained in:
Dandaedre 2026-11-19 18:19:54 +01:00
parent 192ede74fe
commit 8a18759383
12 changed files with 286 additions and 18 deletions

2
Cargo.lock generated
View File

@ -2212,7 +2212,7 @@ dependencies = [
[[package]]
name = "pdf-presenter"
version = "0.1.14"
version = "0.1.15"
dependencies = [
"bytemuck",
"chrono",

View File

@ -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"

View File

@ -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",

View File

@ -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() {

View File

@ -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,

View File

@ -71,6 +71,8 @@ pub struct Studio {
pub bg: Bridge,
pub io: Bridge,
pub dialog: Bridge,
pub dialog_busy: bool,
pub dialog_owner: Option<isize>,
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 {

View File

@ -49,6 +49,8 @@ pub enum Request {
},
Pick {
folder: bool,
/// Windows owner HWND; never a pointer dereferenced by the worker.
owner: Option<isize>,
},
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<isize>) -> Result<rfd::FileDialog, String> {
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<WindowHandle<'_>, 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<DisplayHandle<'_>, 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)
}
}

View File

@ -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<Job>, SyncSender<Completion>) {
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::<Request>(&bytes).unwrap(),Request::Pick{folder:true,owner:got} if got==owner)
);
}
}

View File

@ -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

View File

@ -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.

View File

@ -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.

View File

@ -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.