From b2965f7207ec13451f7c8e188f48952adc5c35f9 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 19 Nov 2026 18:27:50 +0100 Subject: [PATCH] Reap stalled output on shutdown and allow orphan windows to close --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/pdf-presenter/src/native.rs | 26 +++- crates/pdf-presenter/src/output.rs | 105 +++++++++++-- crates/pdf-presenter/src/worker.rs | 2 +- crates/pdf-presenter/tests/native.rs | 180 ++++++++++++++++++++++ docs/changelog.md | 11 ++ docs/development/native-implementation.md | 22 +++ docs/interfaces/process-protocol.md | 19 +++ docs/user-guide.md | 7 +- 10 files changed, 354 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cd300d5..ce89d9c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2212,7 +2212,7 @@ dependencies = [ [[package]] name = "pdf-presenter" -version = "0.1.15" +version = "0.1.16" dependencies = [ "bytemuck", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 0fbfa3b..66693fa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ default-members = ["crates/pdf-presenter"] resolver = "3" [workspace.package] -version = "0.1.15" +version = "0.1.16" edition = "2024" license = "MIT" repository = "https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter" diff --git a/crates/pdf-presenter/src/native.rs b/crates/pdf-presenter/src/native.rs index d291e94..d4b76e0 100644 --- a/crates/pdf-presenter/src/native.rs +++ b/crates/pdf-presenter/src/native.rs @@ -265,6 +265,8 @@ fn monitors(el: &ActiveEventLoop) -> (Vec<(Monitor, MonitorHandle)>, usize) { (handles, primary) } struct Host { + parent_connected: bool, + close_requested: bool, commands: Receiver, acks: SyncSender, state: HostState, @@ -441,6 +443,7 @@ impl App { { if let Some(h) = &mut self.host { h.state.blanked = true; + h.close_requested = matches!(key, Key::Named(NamedKey::Escape)); let _ = h.acks.try_send(Ack { status: "Presentation blanked from output keyboard.".into(), ..Default::default() @@ -631,7 +634,18 @@ impl App { ); } if let Some(host) = &mut self.host { - while let Ok(state) = host.commands.try_recv() { + loop { + let state = match host.commands.try_recv() { + Ok(state) => state, + Err(mpsc::TryRecvError::Empty) => break, + Err(mpsc::TryRecvError::Disconnected) => { + host.parent_connected = false; + break; + } + }; + if !state.blanked { + host.close_requested = false; + } repaint = true; if state.quit { el.exit(); @@ -667,6 +681,10 @@ impl App { } host.state = state; } + if !host.parent_connected && (host.close_requested || self.windows.is_empty()) { + el.exit(); + return; + } while let Ok(c) = host.reader.rx.try_recv() { repaint = true; let reading = host.reading.take(); @@ -797,6 +815,7 @@ impl ApplicationHandler for App { s.execute(Action::CloseBrowser); } } else if let Some(h) = &mut self.host { + h.close_requested = true; h.state.blanked = true; let _ = h.acks.try_send(Ack { status: "Presentation blanked from output window.".into(), @@ -954,10 +973,11 @@ pub fn run(options: crate::poc::Options, path: Option) -> Re override_presenter: options.presenter, override_output: options.audience, }; - el.run_app(&mut app)?; + let result = el.run_app(&mut app); if let Some(output) = &mut app.output { output.shutdown(); } + result?; if let Some(e) = app.error { return Err(e.into()); } @@ -987,6 +1007,8 @@ pub fn run_output() -> Result<(), Failure> { let mut app = App { studio: None, host: Some(Host { + parent_connected: true, + close_requested: false, commands, acks, state: Default::default(), diff --git a/crates/pdf-presenter/src/output.rs b/crates/pdf-presenter/src/output.rs index eaa652c..6bb97f2 100644 --- a/crates/pdf-presenter/src/output.rs +++ b/crates/pdf-presenter/src/output.rs @@ -6,9 +6,10 @@ use crate::{ use serde::{Deserialize, Serialize}; use std::{ io::Read, - process::Child, + path::PathBuf, + process::{Child, Command, Stdio}, sync::{ - Arc, + Arc, Mutex, atomic::{AtomicBool, Ordering}, mpsc::{self, Receiver, SyncSender}, }, @@ -45,6 +46,7 @@ pub struct OutputLink { pub rx: Receiver, stop: Arc, manager: Option>, + child: Arc>>, } impl Default for OutputLink { fn default() -> Self { @@ -53,26 +55,39 @@ impl Default for OutputLink { } impl OutputLink { pub fn new() -> Self { + Self::with_program(std::env::current_exe().unwrap_or_default()) + } + pub fn with_program(program: PathBuf) -> Self { let (tx, commands) = mpsc::sync_channel::(2); let (results, rx) = mpsc::sync_channel(8); let stop = Arc::new(AtomicBool::new(false)); let end = stop.clone(); + let child = Arc::new(Mutex::new(None)); + let managed_child = child.clone(); let manager = std::thread::spawn(move || { let mut attempts = 0; while !end.load(Ordering::Relaxed) && attempts < 3 { attempts += 1; - let mut child = match spawn_mode("--presentation-host") { + let mut command = Command::new(&program); + command + .arg("--presentation-host") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + crate::worker::quiet_child(&mut command); + let mut process = match command.spawn() { Ok(c) => c, Err(e) => { let _ = results.try_send(Ack { - status: e, + status: e.to_string(), ..Default::default() }); return; } }; - let mut stdin = child.stdin.take().unwrap(); - let mut stdout = child.stdout.take().unwrap(); + let mut stdin = process.stdin.take().unwrap(); + let mut stdout = process.stdout.take().unwrap(); + *managed_child.lock().unwrap() = Some(process); let (ack_tx, ack_rx) = mpsc::sync_channel(8); std::thread::spawn(move || { while let Ok(ack) = read_json::(&mut stdout) { @@ -91,8 +106,7 @@ impl OutputLink { }, ); std::thread::sleep(Duration::from_millis(300)); - let _ = child.kill(); - let _ = child.wait(); + terminate_output(&managed_child); return; } let mut latest = None; @@ -109,15 +123,18 @@ impl OutputLink { heartbeat = Instant::now(); let _ = results.try_send(ack); } - if child.try_wait().ok().flatten().is_some() + if managed_child + .lock() + .unwrap() + .as_mut() + .is_none_or(|c| c.try_wait().ok().flatten().is_some()) || heartbeat.elapsed() > Duration::from_secs(8) { break; } std::thread::sleep(Duration::from_millis(4)); } - let _ = child.kill(); - let _ = child.wait(); + terminate_output(&managed_child); let _=results.try_send(Ack{status:"Presentation host stopped. Output will restart blanked; review screens before resuming.".into(),..Default::default()}); // Restart receives a fresh state from the presenter; never silently resume output. drop(last); @@ -129,6 +146,7 @@ impl OutputLink { rx, stop, manager: Some(manager), + child, } } } @@ -136,7 +154,13 @@ impl OutputLink { /// Called after the event loop exits, never from an input/render callback. pub fn shutdown(&mut self) { self.stop.store(true, Ordering::Relaxed); - let deadline = Instant::now() + Duration::from_secs(2); + let grace = Instant::now() + Duration::from_millis(500); + while self.manager.as_ref().is_some_and(|t| !t.is_finished()) && Instant::now() < grace { + std::thread::sleep(Duration::from_millis(10)); + } + // This does not use the IPC writer: it also works when that writer is blocked. + terminate_output(&self.child); + let deadline = Instant::now() + Duration::from_secs(1); while self.manager.as_ref().is_some_and(|t| !t.is_finished()) && Instant::now() < deadline { std::thread::sleep(Duration::from_millis(10)); } @@ -147,11 +171,18 @@ impl OutputLink { } } } -impl Drop for OutputLink { - fn drop(&mut self) { - self.stop.store(true, Ordering::Relaxed); +fn terminate_output(child: &Mutex>) { + if let Some(mut process) = child.lock().unwrap().take() { + let _ = process.kill(); + let _ = process.wait(); } } +impl Drop for OutputLink { + fn drop(&mut self) { + self.shutdown(); + } +} + pub struct SleepLease { child: Option, pub status: Receiver, @@ -271,3 +302,47 @@ fn hold_x11_fallback(_lease: Option, status: String) -> Result<(), Str let _ = std::io::stdin().read(&mut [0]); Ok(()) } + +#[cfg(all(test, unix))] +mod shutdown_tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn shutdown_and_drop_reap_output_even_when_its_input_pipe_is_full() { + let temp = tempfile::tempdir().unwrap(); + let program = temp.path().join("unresponsive-output"); + std::fs::write(&program, "#!/bin/sh\nexec sleep 60\n").unwrap(); + std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o700)).unwrap(); + for explicit in [true, false] { + let mut link = OutputLink::with_program(program.clone()); + let child = link.child.clone(); + let deadline = Instant::now() + Duration::from_secs(5); + let pid = loop { + if let Some(process) = child.lock().unwrap().as_ref() { + break process.id(); + } + assert!(Instant::now() < deadline, "output did not spawn"); + std::thread::sleep(Duration::from_millis(10)); + }; + link.tx + .send(HostState { + monitors: vec!["x".repeat(2 * 1024 * 1024)], + ..Default::default() + }) + .unwrap(); + // The child never reads stdin: this message is larger than the pipe capacity. + std::thread::sleep(Duration::from_millis(100)); + let start = Instant::now(); + if explicit { + link.shutdown(); + assert!(link.manager.is_none()); + } + drop(link); + assert!(start.elapsed() < Duration::from_secs(2)); + assert!(child.lock().unwrap().is_none()); + // The PID is only used immediately after reaping our own child. + assert_eq!(unsafe { libc::kill(pid as i32, 0) }, -1); + } + } +} diff --git a/crates/pdf-presenter/src/worker.rs b/crates/pdf-presenter/src/worker.rs index d6f4dba..4f090d2 100644 --- a/crates/pdf-presenter/src/worker.rs +++ b/crates/pdf-presenter/src/worker.rs @@ -229,7 +229,7 @@ pub fn run() -> Result<(), String> { } Ok(()) } -fn quiet_child(command: &mut Command) { +pub(crate) fn quiet_child(command: &mut Command) { #[cfg(target_os = "windows")] { use std::os::windows::process::CommandExt; diff --git a/crates/pdf-presenter/tests/native.rs b/crates/pdf-presenter/tests/native.rs index 803df0d..ed80e25 100644 --- a/crates/pdf-presenter/tests/native.rs +++ b/crates/pdf-presenter/tests/native.rs @@ -210,3 +210,183 @@ fn independent_output_acknowledges_frames_and_blanking() { } assert!(child.0.try_wait().unwrap().is_some(), "host did not exit"); } + +#[cfg(target_os = "linux")] +#[test] +fn orphaned_output_holds_until_closed_then_exits_on_close_or_escape() { + if std::env::var_os("PDF_PRESENTER_GUI_TESTS").is_none() { + return; + } + use pdf_presenter::{output::HostState, worker::write_json}; + use x11_dl::xlib; + let x = xlib::Xlib::open().unwrap(); + // A private X11 connection is used only by this test thread. + let display = unsafe { (x.XOpenDisplay)(std::ptr::null()) }; + assert!(!display.is_null()); + struct DisplayGuard<'a>(&'a xlib::Xlib, *mut xlib::Display); + impl Drop for DisplayGuard<'_> { + fn drop(&mut self) { + unsafe { + (self.0.XCloseDisplay)(self.1); + } + } + } + let _display = DisplayGuard(&x, display); + let root = unsafe { (x.XDefaultRootWindow)(display) }; + let pid_atom = unsafe { (x.XInternAtom)(display, c"_NET_WM_PID".as_ptr(), 0) }; + fn find( + x: &xlib::Xlib, + d: *mut xlib::Display, + w: xlib::Window, + atom: xlib::Atom, + pid: u32, + ) -> Option { + // Xlib owns returned buffers; free them after copying their contents. + unsafe { + let (mut kind, mut format, mut n, mut after) = (0, 0, 0, 0); + let mut data = std::ptr::null_mut(); + (x.XGetWindowProperty)( + d, + w, + atom, + 0, + 1, + 0, + xlib::XA_CARDINAL, + &mut kind, + &mut format, + &mut n, + &mut after, + &mut data, + ); + let matches = !data.is_null() + && format == 32 + && n == 1 + && *(data as *const std::os::raw::c_ulong) == u64::from(pid); + if !data.is_null() { + (x.XFree)(data.cast()); + } + if matches { + return Some(w); + } + let (mut root, mut parent, mut count) = (0, 0, 0); + let mut children = std::ptr::null_mut(); + if (x.XQueryTree)(d, w, &mut root, &mut parent, &mut children, &mut count) == 0 { + return None; + } + let found = if children.is_null() { + None + } else { + std::slice::from_raw_parts(children, count as usize) + .iter() + .find_map(|child| find(x, d, *child, atom, pid)) + }; + if !children.is_null() { + (x.XFree)(children.cast()); + } + found + } + } + let listing = run_native(&["--list-monitors"]); + let listing = String::from_utf8(listing.stdout).unwrap(); + let line = listing + .lines() + .find(|l| l.starts_with("Display 1:")) + .unwrap(); + let name = line + .split(" at ") + .next() + .unwrap() + .rsplit_once(' ') + .unwrap() + .0 + .split_once(": ") + .unwrap() + .1; + for escape in [false, true] { + struct ChildGuard(std::process::Child); + impl Drop for ChildGuard { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + let mut child = ChildGuard( + Command::new(env!("CARGO_BIN_EXE_pdf-presenter")) + .env("WINIT_UNIX_BACKEND", "x11") + .arg("--presentation-host") + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .spawn() + .unwrap(), + ); + let mut input = child.0.stdin.take().unwrap(); + write_json( + &mut input, + &HostState { + monitors: vec![format!("{name}#1")], + fullscreen: false, + ..Default::default() + }, + ) + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(5); + let window = loop { + if let Some(window) = find(&x, display, root, pid_atom, child.0.id()) { + break window; + } + assert!(Instant::now() < deadline, "output window not created"); + std::thread::sleep(Duration::from_millis(10)); + }; + // EOF models a vanished presenter. Keep the output alive until the operator closes it. + drop(input); + std::thread::sleep(Duration::from_millis(300)); + assert!(child.0.try_wait().unwrap().is_none()); + unsafe { + let mut event: xlib::XEvent = std::mem::zeroed(); + if escape { + event.key = xlib::XKeyEvent { + type_: xlib::KeyPress, + display, + window, + root, + keycode: (x.XKeysymToKeycode)(display, 0xff1b).into(), + same_screen: 1, + ..std::mem::zeroed() + }; + } else { + let mut data = xlib::ClientMessageData::new(); + data.set_long( + 0, + (x.XInternAtom)(display, c"WM_DELETE_WINDOW".as_ptr(), 0) as _, + ); + event.client_message = xlib::XClientMessageEvent { + type_: xlib::ClientMessage, + display, + window, + message_type: (x.XInternAtom)(display, c"WM_PROTOCOLS".as_ptr(), 0), + format: 32, + data, + ..std::mem::zeroed() + }; + } + (x.XSendEvent)( + display, + window, + 0, + if escape { xlib::KeyPressMask } else { 0 }, + &mut event, + ); + (x.XFlush)(display); + } + let deadline = Instant::now() + Duration::from_secs(3); + while child.0.try_wait().unwrap().is_none() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!( + child.0.try_wait().unwrap().is_some(), + "orphan ignored {}", + if escape { "Escape" } else { "Close" } + ); + } +} diff --git a/docs/changelog.md b/docs/changelog.md index 9753180..eb8303c 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -2,6 +2,17 @@ ## Unreleased +### 0.1.16 + +- Ensure presenter shutdown can terminate/reap its output process even when the + supervisor is blocked writing to a full IPC pipe. Run cleanup on event-loop errors + and destructor paths as well as normal exit. +- Detect loss of the presenter connection. Preserve the last audience frame, but + allow the orphaned output to exit through its window Close control or Escape. +- Add blocked-pipe shutdown/drop regression coverage and native Linux/X11 orphan + Close/Escape tests. Windows/macOS runtime acceptance remains pending. + + ### 0.1.15 - Give Windows PDF/folder dialogs the active presenter window as their owner, so diff --git a/docs/development/native-implementation.md b/docs/development/native-implementation.md index 85e663b..e30abe8 100644 --- a/docs/development/native-implementation.md +++ b/docs/development/native-implementation.md @@ -169,3 +169,25 @@ compile-check pass; Windows fullscreen/modal placement requires user runtime ret 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. + + +## 0.1.16 output lifecycle correction + +The output Close handler previously only blanked, even after the presenter pipe +closed. The native host now observes receiver disconnection and accepts Close/Escape +as exit when orphaned, while retaining crash-time last-frame preservation until then. +Normal presenter exit, event-loop errors and OutputLink destruction all shut down the +owned host. A separate shared process handle permits termination/reaping even when +the supervisor is blocked writing a large state into an unread pipe. + +Regression tests fill a fake output's pipe and verify both shutdown and Drop reap it +within two seconds. Native Linux/X11 tests create real output windows, disconnect +the parent pipe, verify the process remains alive, then send WM_DELETE_WINDOW or +Escape and verify clean exit without force-kill. Test guards kill only on failure or +cleanup. These checks do not establish Windows/macOS physical acceptance. + +46 Rust tests and 10 Python tests pass, including the native window/output tests. +Formatting, warnings-denied Clippy/rustdoc and macOS aarch64 compilation pass. +Whole-application coverage is 83.97%, with no production exclusions. Linux and Windows +x86_64 release builds succeed. Runtime retesting on Windows remains necessary for +the reported platform behavior. diff --git a/docs/interfaces/process-protocol.md b/docs/interfaces/process-protocol.md index d57b520..c96721d 100644 --- a/docs/interfaces/process-protocol.md +++ b/docs/interfaces/process-protocol.md @@ -60,3 +60,22 @@ the guard; submission failure never sets it. The native host re-enables presente 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. + + +## Output shutdown and lost presenter, 0.1.16 + +No wire fields change. EOF/failed input drops the host command sender; the native +host detects receiver disconnection instead of treating it as an empty queue forever. +An established output keeps its last frame after unexpected connection loss, while +Close or Escape requests exit on the next event-loop tick. A disconnected host with +no windows exits immediately. B still blanks. With a live presenter, output Close or +Escape retains the existing emergency-blank behavior. + +Normal presenter shutdown signals the supervisor and allows 500 ms for graceful +completion, then terminates/reaps the owned child through a separate shared process +handle. The handle is never locked during pipe writes, so a blocked writer cannot +prevent termination. A further one-second manager completion wait is bounded. +Event-loop errors and OutputLink destruction use this cleanup path as well. OS process +termination/reaping still relies on OS responsiveness; these bounds are not a promise +against kernel/driver failure. Unexpected presenter death deliberately does not use +parent-death termination for the audience, to preserve the last usable frame. diff --git a/docs/user-guide.md b/docs/user-guide.md index 5b535ed..c2a75bc 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -30,7 +30,7 @@ usable frame. The footer distinguishes requested and acknowledged displayed slid **NO OUTPUT DISPLAYED** warning marks blanking, no assigned output or no document; it remains visible when the footer is hidden. Preparing output has a separate status. Escape cancels a pending slide number/menu, closes the browser, or safely leaves -fullscreen and blanks output. Closing a presentation window blanks it; close a +fullscreen and blanks output. While the presenter is connected, closing a presentation window blanks it; close a presenter or choose Menu → Quit to end the application. Arrow keys, Page Up/Down and Space navigate from the presenter. Type a 1-based slide @@ -117,7 +117,10 @@ Rendering, notes, file dialogs and settings I/O run in supervised child processe the same executable. A stuck renderer is terminated after its deadline; the UI and last output remain available. Reopen the source to retry failed pages. A presentation host failure restarts blanked with a status message, up to three starts. If the -presenter crashes, the output process holds its last frame; B/Escape can blank it. +presenter crashes, the output process holds its last frame. B can blank it; Escape or +its normal window Close control exits the disconnected output. Closing the presenter +normally shuts down the output process too, with a separate termination fallback if +its IPC writer is stuck. Automatic reconnection to that orphaned show is not implemented yet. Sleep protection is requested for both native processes, including while blanked.