mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
fix(print): keep native printer discovery off the UI thread
This commit is contained in:
1 parent
f2b9a6a2f0
commit
872aa8d216
5 files changed
+239
-4
No files matched your search
@@ -44,6 +44,7 @@ impl PhotocraftApp {
|
||||
session,
|
||||
ui: UiState::default(),
|
||||
services,
|
||||
printer_discovery: None,
|
||||
canvases: HashMap::new(),
|
||||
navigator_textures: HashMap::new(),
|
||||
display_memo: HashMap::new(),
|
||||
|
||||
@@ -15,6 +15,8 @@ use crate::state::DialogKind;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
mod print;
|
||||
mod printer_discovery;
|
||||
pub(crate) use printer_discovery::PrinterDiscovery;
|
||||
mod web;
|
||||
|
||||
pub use print::open_print;
|
||||
|
||||
@@ -60,8 +60,28 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 {
|
||||
] {
|
||||
f.entry(k.to_string()).or_insert(v);
|
||||
}
|
||||
refresh_printers(app, &mut f);
|
||||
app.ui.open_dialog(DialogKind::Command, f)
|
||||
// Injected sources are deterministic test adapters. Native discovery is always off-UI.
|
||||
app.printer_discovery = None;
|
||||
let discovery = if app.session.printer_source.is_some() {
|
||||
refresh_printers(app, &mut f);
|
||||
None
|
||||
} else {
|
||||
match super::PrinterDiscovery::start() {
|
||||
Ok(ticket) => {
|
||||
f.insert("__printerListingPending".into(), json!(true));
|
||||
f.insert("__printerListingSelection".into(), json!(s(&f, "printer", "")));
|
||||
f.insert("__printerListingSettings".into(), f.get("printerSettings").cloned().unwrap_or(Value::Null));
|
||||
Some(ticket)
|
||||
}
|
||||
Err(error) => {
|
||||
f.insert("__printerListingError".into(), json!(error));
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let id = app.ui.open_dialog(DialogKind::Command, f);
|
||||
app.printer_discovery = discovery.map(|ticket| (id, ticket));
|
||||
id
|
||||
}
|
||||
|
||||
fn refresh_printers(app: &mut PhotocraftApp, f: &mut Map<String, Value>) {
|
||||
@@ -76,7 +96,11 @@ fn refresh_printers(app: &mut PhotocraftApp, f: &mut Map<String, Value>) {
|
||||
fn take_printer_lists(app: &mut PhotocraftApp, f: &mut Map<String, Value>) {
|
||||
let printers = photocraft_engine::print_cmds::printers_without_waiting(&mut app.session);
|
||||
f.insert("__systemPrinters".into(), printers["printers"].clone());
|
||||
if let Ok(list) = photocraft_engine::print_cmds::rgb_printers_without_waiting(&app.session) {
|
||||
take_rgb_printers(f, photocraft_engine::print_cmds::rgb_printers_without_waiting(&app.session));
|
||||
}
|
||||
|
||||
fn take_rgb_printers(f: &mut Map<String, Value>, list: photocraft_engine::print_cmds::RgbPrinters) {
|
||||
if let Ok(list) = list {
|
||||
f.insert("__printers".into(), json!(list.iter().map(|p| p.name.clone()).collect::<Vec<_>>()));
|
||||
let known = |n: &str| list.iter().any(|p| p.name == n);
|
||||
if !list.is_empty() && !known(&s(f, "printer", "")) {
|
||||
@@ -87,6 +111,50 @@ fn take_printer_lists(app: &mut PhotocraftApp, f: &mut Map<String, Value>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Poll only this dialog's ticket. No I/O and no automatic retry after cancellation/error.
|
||||
fn poll_printers(app: &mut PhotocraftApp, f: &mut Map<String, Value>, id: u64) {
|
||||
let Some((owner, ticket)) = &app.printer_discovery else {
|
||||
f.remove("__printerListingPending");
|
||||
return;
|
||||
};
|
||||
if *owner != id {
|
||||
f.remove("__printerListingPending");
|
||||
return;
|
||||
}
|
||||
let Some(answer) = ticket.poll() else { return };
|
||||
app.printer_discovery = None;
|
||||
f.remove("__printerListingPending");
|
||||
match answer {
|
||||
Ok((printers, rgb)) => {
|
||||
f.insert("__systemPrinters".into(), printers.get("printers").cloned().unwrap_or_else(|| json!([])));
|
||||
// An asynchronous answer must not undo a choice made while discovery was running.
|
||||
let selection = f.get("printer").cloned();
|
||||
let settings = f.get("printerSettings").cloned();
|
||||
let changed = f.get("__printerListingSelection") != selection.as_ref()
|
||||
|| f.get("__printerListingSettings").unwrap_or(&Value::Null) != settings.as_ref().unwrap_or(&Value::Null);
|
||||
take_rgb_printers(f, rgb);
|
||||
if changed {
|
||||
if let Some(selection) = selection {
|
||||
f.insert("printer".into(), selection);
|
||||
}
|
||||
match settings {
|
||||
Some(settings) => {
|
||||
f.insert("printerSettings".into(), settings);
|
||||
}
|
||||
None => {
|
||||
f.remove("printerSettings");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
f.insert("__printerListingError".into(), json!(error));
|
||||
}
|
||||
}
|
||||
f.remove("__printerListingSelection");
|
||||
f.remove("__printerListingSettings");
|
||||
}
|
||||
|
||||
/// Whether the driver's paper, as `driver_page` took it, is wider than tall: the Orientation
|
||||
/// buttons show landscape then.
|
||||
pub(super) fn driver_paper_is_wide(f: &Map<String, Value>) -> bool {
|
||||
@@ -342,11 +410,21 @@ pub(super) fn print_preview_image(l: photocraft_engine::print_cmds::PrintLayout,
|
||||
/// the position row stays present while centered so switching to manual cannot move the page.
|
||||
pub(super) fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>, id: u64) {
|
||||
if b(f, "__printerListingPending", false) {
|
||||
refresh_printers(app, f);
|
||||
if app.session.printer_source.is_some() {
|
||||
refresh_printers(app, f);
|
||||
} else {
|
||||
poll_printers(app, f, id);
|
||||
}
|
||||
if b(f, "__printerListingPending", false) {
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
if let Some(error) = f.get("__printerListingError").and_then(Value::as_str) {
|
||||
ui.label(error);
|
||||
}
|
||||
if b(f, "__printerListingPending", false) {
|
||||
ui.label(tl!("Finding printers…"));
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return };
|
||||
// PDF exports and previews retain editable paper on Windows too. Only a real native
|
||||
@@ -716,3 +794,46 @@ pub(crate) fn print_status(app: &mut PhotocraftApp, r: &Value) {
|
||||
};
|
||||
app.ui.status_error = false;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod discovery_tests {
|
||||
use super::*;
|
||||
fn app() -> PhotocraftApp {
|
||||
PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default())
|
||||
}
|
||||
#[test]
|
||||
fn pending_poll_is_nonblocking_and_wrong_dialog_does_not_consume_result() {
|
||||
let mut app = app();
|
||||
let (send, ticket) = super::super::PrinterDiscovery::test_ticket();
|
||||
app.printer_discovery = Some((7, ticket));
|
||||
let mut fields = json!({"__printerListingPending": true}).as_object().unwrap().clone();
|
||||
for _ in 0..100 {
|
||||
poll_printers(&mut app, &mut fields, 7);
|
||||
}
|
||||
assert_eq!(fields["__printerListingPending"], true);
|
||||
send.send(Err("old dialog failure".into())).unwrap();
|
||||
poll_printers(&mut app, &mut fields, 8);
|
||||
assert!(!fields.contains_key("__printerListingError"));
|
||||
assert!(app.printer_discovery.is_some());
|
||||
poll_printers(&mut app, &mut fields, 7);
|
||||
assert_eq!(fields["__printerListingError"], "old dialog failure");
|
||||
assert!(app.printer_discovery.is_none());
|
||||
}
|
||||
#[test]
|
||||
fn late_listing_preserves_selection_and_driver_settings_edited_while_pending() {
|
||||
let mut app = app();
|
||||
let (send, ticket) = super::super::PrinterDiscovery::test_ticket();
|
||||
app.printer_discovery = Some((1, ticket));
|
||||
let mut fields = json!({"__printerListingPending": true, "__printerListingSelection": "Old", "printer": "User choice", "printerSettings": "0011"})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone();
|
||||
send.send(Ok((json!({"printers": [{"name": "Other"}]}), Ok(vec![craft_print::rgb::Printer { name: "Other".into(), default: true }])))).unwrap();
|
||||
poll_printers(&mut app, &mut fields, 1);
|
||||
assert_eq!(fields["printer"], "User choice");
|
||||
assert_eq!(fields["printerSettings"], "0011");
|
||||
assert_eq!(fields["__printers"], json!(["Other"]));
|
||||
assert!(!fields.contains_key("__printerListingPending"));
|
||||
assert!(app.printer_discovery.is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
//! Native discovery may block in the OS resolver/driver. Never run it on the UI thread.
|
||||
use photocraft_engine::print_cmds::RgbPrinters;
|
||||
use serde_json::Value;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc;
|
||||
|
||||
type Answer = Result<(Value, RgbPrinters), String>;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
static DISCOVERING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// There is at most one discovery worker in the process, with no work queue. Dropping a
|
||||
/// ticket discards its answer, NOT the OS call: a stuck resolver keeps the permit until it
|
||||
/// returns. Reopening a dialog must not accumulate detached threads or reuse a stale answer.
|
||||
pub(crate) struct PrinterDiscovery {
|
||||
rx: mpsc::Receiver<Answer>,
|
||||
}
|
||||
|
||||
impl PrinterDiscovery {
|
||||
pub(super) fn start() -> Result<Self, String> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
Self::spawn(&DISCOVERING, || {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
let printers = session.execute("file.printers", serde_json::json!({})).map_err(|e| e.to_string())?;
|
||||
Ok((printers, photocraft_engine::print_cmds::rgb_printers(&session)))
|
||||
})
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
Err("Printer discovery is not available in the browser".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn spawn(busy: &'static AtomicBool, discover: impl FnOnce() -> Answer + Send + 'static) -> Result<Self, String> {
|
||||
if busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() {
|
||||
return Err("Printer discovery is still running. Close and reopen Print after it finishes to try again.".into());
|
||||
}
|
||||
struct Permit(&'static AtomicBool);
|
||||
impl Drop for Permit {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::Release);
|
||||
}
|
||||
}
|
||||
let permit = Permit(busy);
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
// Do not join on the UI thread; the permit outlives the dialog until the OS returns.
|
||||
let _worker = std::thread::Builder::new()
|
||||
.name("printer-discovery".into())
|
||||
.spawn(move || {
|
||||
let _permit = permit;
|
||||
let _ = tx.send(discover());
|
||||
})
|
||||
.map_err(|e| format!("Cannot start printer discovery: {e}"))?;
|
||||
Ok(Self { rx })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn test_ticket() -> (mpsc::SyncSender<Answer>, Self) {
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
(tx, Self { rx })
|
||||
}
|
||||
|
||||
pub(super) fn poll(&self) -> Option<Answer> {
|
||||
match self.rx.try_recv() {
|
||||
Ok(answer) => Some(answer),
|
||||
Err(mpsc::TryRecvError::Empty) => None,
|
||||
Err(mpsc::TryRecvError::Disconnected) => Some(Err("Printer discovery stopped without a result".into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn closing_a_stalled_discovery_does_not_admit_more_workers_or_reuse_its_answer() {
|
||||
static BUSY: AtomicBool = AtomicBool::new(false);
|
||||
let (release, wait) = mpsc::channel();
|
||||
let (finished, done) = mpsc::channel();
|
||||
let ticket = PrinterDiscovery::spawn(&BUSY, move || {
|
||||
wait.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
|
||||
finished.send(()).unwrap();
|
||||
Err("old dialog".into())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(ticket.poll().is_none());
|
||||
drop(ticket);
|
||||
for _ in 0..100 {
|
||||
assert!(PrinterDiscovery::spawn(&BUSY, || panic!("must not run")).is_err());
|
||||
}
|
||||
release.send(()).unwrap();
|
||||
done.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while BUSY.load(Ordering::Acquire) && std::time::Instant::now() < deadline {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
let next = PrinterDiscovery::spawn(&BUSY, || Err("new dialog".into())).unwrap();
|
||||
loop {
|
||||
if let Some(answer) = next.poll() {
|
||||
assert_eq!(answer.unwrap_err(), "new dialog");
|
||||
break;
|
||||
}
|
||||
assert!(std::time::Instant::now() < deadline);
|
||||
std::thread::yield_now();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -354,6 +354,8 @@ pub struct PhotocraftApp {
|
||||
pub session: Session,
|
||||
pub ui: UiState,
|
||||
pub services: Services,
|
||||
/// One dialog-owned discovery ticket; closing/reopening never queues another blocked resolver.
|
||||
printer_discovery: Option<(u64, file_ui::PrinterDiscovery)>,
|
||||
/// Canvas caches per (document, display): CPU textures hold monitor values; the GPU
|
||||
/// canvas state is shared (`canvas::GPU_OUTPUT`).
|
||||
canvases: HashMap<(DocId, u32), canvas::CanvasCache>,
|
||||
|
||||
Reference in new issue
Block a user