mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-21 01:18:43 +00:00
Print: list printers and spool from one thread at a time
On Windows 11 (winspool.drv 10.0.26100.9444) the custom_print_paper test binary died with STATUS_ACCESS_VIOLATION. Its three tests open the Print dialog at once, and each one lists printers: file.printers calls craft_print::printers(), which opens each printer's PrintTicket provider (PTOpenProvider). winspool creates a process-wide cache without a lock the first time PTOpenProvider is called for a printer whose provider is PrintConfig.dll. When two threads do this together, winspool can leave its pointer to the cache on a freed object, and the next caller enters that object's deleted critical section. The app can make the same calls from two threads: the Print dialog on the UI thread and a print job's worker. print_cmds::with_spooler holds a process-wide lock around every call PhotoCraft makes into craft-print that lists printers or reaches the spooler or a driver: craft_print::printers and submit, and rgb's printers, default_printer, page, print and settings_dialog. A panic inside the lock does not block later callers. While a print job is being handed to the spooler, File › Print waits for it before the dialog opens. Session::printer_source supplies the printers that file.printers, file.print.printers and the Print dialog list, in place of the spooler's. The tests that open Print or list printers set it, so they no longer query the system's printers or load their drivers. print_cmds::system_printer_listings counts the real listings, and the dialog and print job tests assert that it stays 0. The app leaves printer_source unset and lists the spooler's printers as before. New tests: printer_listings_enter_the_spooler_one_thread_at_a_time (eight threads list printers at once; it fails without the lock) and a_panic_inside_the_spooler_does_not_block_later_callers.
This commit is contained in:
1 parent
ead6d2197f
commit
2f797ddea3
7 files changed
+151
-23
No files matched your search
@@ -489,6 +489,9 @@ pub struct Session {
|
||||
/// A further route for File › Print when neither `lp` nor a CUPS server over IPP is
|
||||
/// reachable (the XDG Print portal in a Flatpak); see `print_cmds::Spooler`.
|
||||
pub print_spooler: Option<print_cmds::Spooler>,
|
||||
/// The printers `file.printers`, `file.print.printers` and the Print dialog list in place of
|
||||
/// the system's (tests); see `print_cmds::PrinterSource`. `None` asks the spooler.
|
||||
pub printer_source: Option<print_cmds::PrinterSource>,
|
||||
/// Background jobs (see [`jobs`]).
|
||||
jobs: jobs::Jobs,
|
||||
/// Color Sampler points dropped by the last canvas-size change (crop, Canvas Size, Image Size,
|
||||
|
||||
@@ -71,6 +71,53 @@ pub struct Spooler {
|
||||
pub run: SpoolFn,
|
||||
}
|
||||
|
||||
/// A stand-in for the system's printers, installed on `Session::printer_source` (tests):
|
||||
/// `file.printers`, `file.print.printers` and the Print dialog list these and do not ask the spooler.
|
||||
pub type PrinterSource = std::sync::Arc<dyn Fn() -> Vec<craft_print::Printer> + Send + Sync>;
|
||||
|
||||
/// Held while a thread of this process lists printers or calls into a printer driver.
|
||||
static SPOOLER: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Runs `f`, which lists printers or calls into a printer driver, while no other thread of this
|
||||
/// process does either. On Windows, two threads that open printers' PrintTicket providers for the
|
||||
/// first time at once can crash the process inside the spooler client (`winspool.drv`). A panic in
|
||||
/// an earlier caller does not block later ones.
|
||||
pub fn with_spooler<T>(f: impl FnOnce() -> T) -> T {
|
||||
let _held = SPOOLER.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
f()
|
||||
}
|
||||
|
||||
/// Counts the times this process asked the system for its printers.
|
||||
static SYSTEM_LISTINGS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
/// How many times this process has asked the system for its printers. A session with a
|
||||
/// `printer_source` does not ask.
|
||||
pub fn system_printer_listings() -> usize {
|
||||
SYSTEM_LISTINGS.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The printers `craft-print` spools to, or the session's stand-in for them.
|
||||
fn system_printer_list(s: &Session) -> Vec<craft_print::Printer> {
|
||||
with_spooler(|| match &s.printer_source {
|
||||
Some(source) => source(),
|
||||
None => {
|
||||
SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
craft_print::printers()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The printers the GDI route prints to (`craft_print::rgb`), or the session's stand-in for them.
|
||||
pub fn rgb_printers(s: &Session) -> std::result::Result<Vec<craft_print::rgb::Printer>, craft_print::rgb::PrintError> {
|
||||
with_spooler(|| match &s.printer_source {
|
||||
Some(source) => Ok(source().into_iter().map(|p| craft_print::rgb::Printer { name: p.name, default: p.default }).collect()),
|
||||
None => {
|
||||
SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
craft_print::rgb::printers()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Why the IPP route could not spool: no route at all (the app's spooler may have one), or a
|
||||
/// failure on a route that exists (a wrong printer name, a rejected job).
|
||||
enum SpoolError {
|
||||
@@ -90,7 +137,7 @@ fn spool_job(spooler: Option<&Spooler>, job: &PrintJob, lp: &craft_print::Job) -
|
||||
return app(sp);
|
||||
}
|
||||
if let Some(name) = system_spooler() {
|
||||
return craft_print::submit(&job.pdf, lp).map(|m| (m, name.to_string())).map_err(other);
|
||||
return with_spooler(|| craft_print::submit(&job.pdf, lp)).map(|m| (m, name.to_string())).map_err(other);
|
||||
}
|
||||
}
|
||||
match cups_spool(job) {
|
||||
@@ -189,10 +236,10 @@ fn cups_spool(job: &PrintJob) -> std::result::Result<String, SpoolError> {
|
||||
/// `file.printers`: the printers the system's (or `printServer`'s) print server knows, with the default. From
|
||||
/// `craft-print` (`lpstat`, the Windows spooler) where that is the route; over IPP for a named
|
||||
/// server and where there is no `lp` (a sandbox).
|
||||
fn system_printers(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn system_printers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let named = p.get("printServer").and_then(Value::as_str).filter(|v| !v.is_empty());
|
||||
if named.is_none() && system_spooler().is_some() {
|
||||
let list = craft_print::printers();
|
||||
if named.is_none() && (s.printer_source.is_some() || system_spooler().is_some()) {
|
||||
let list = system_printer_list(s);
|
||||
let default = list.iter().find(|p| p.default).map(|p| p.name.clone());
|
||||
let printers: Vec<Value> = list.into_iter().map(|p| json!({"name": p.name, "default": p.default})).collect();
|
||||
return Ok(json!({"server": Value::Null, "default": default, "printers": printers}));
|
||||
@@ -671,7 +718,7 @@ fn printer_name(p: &Value) -> Result<String> {
|
||||
if let Some(name) = p.get("printer").and_then(Value::as_str).filter(|v| !v.trim().is_empty()) {
|
||||
return Ok(name.to_string());
|
||||
}
|
||||
craft_print::rgb::default_printer().map_err(other)?.ok_or_else(|| other("no printer chosen and no default printer is set"))
|
||||
with_spooler(craft_print::rgb::default_printer).map_err(other)?.ok_or_else(|| other("no printer chosen and no default printer is set"))
|
||||
}
|
||||
|
||||
/// The driver settings chosen with Print Settings… (`printerSettings`, hex), when any.
|
||||
@@ -717,7 +764,7 @@ pub fn page_rect_top_left(page: &PrintPage) -> (f64, f64, f64, f64) {
|
||||
fn print_windows(page: &PrintPage, p: &Value, title: &str, copies: u32) -> Result<Value> {
|
||||
let printer = printer_name(p)?;
|
||||
let settings = printer_settings(p)?;
|
||||
let device_page = craft_print::rgb::page(&printer, settings.as_ref()).map_err(other)?;
|
||||
let device_page = with_spooler(|| craft_print::rgb::page(&printer, settings.as_ref())).map_err(other)?;
|
||||
if (device_page.paper.0 - page.paper.0).abs() > 2.0 || (device_page.paper.1 - page.paper.1).abs() > 2.0 {
|
||||
return Err(other("the driver paper or orientation differs from the print layout; choose the matching paper in Print Settings before printing"));
|
||||
}
|
||||
@@ -739,14 +786,14 @@ fn print_windows(page: &PrintPage, p: &Value, title: &str, copies: u32) -> Resul
|
||||
color_policy,
|
||||
primitives: &primitives,
|
||||
};
|
||||
let done = craft_print::rgb::print(&job, &image, rect).map_err(other)?;
|
||||
let done = with_spooler(|| craft_print::rgb::print(&job, &image, rect)).map_err(other)?;
|
||||
Ok(
|
||||
json!({"printer": printer, "dpi": [done.dpi.0, done.dpi.1], "deviceRect": [done.device_rect.0, done.device_rect.1, done.device_rect.2, done.device_rect.3]}),
|
||||
)
|
||||
}
|
||||
|
||||
fn printers(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
match craft_print::rgb::printers() {
|
||||
fn printers(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
match rgb_printers(s) {
|
||||
Ok(list) => Ok(json!({"supported": true, "printers": list.iter().map(|p| json!({"name": p.name, "default": p.default})).collect::<Vec<_>>()})),
|
||||
Err(craft_print::rgb::PrintError::Unsupported) => Ok(json!({"supported": false, "printers": []})),
|
||||
Err(e) => Err(other(e)),
|
||||
@@ -755,7 +802,8 @@ fn printers(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
fn printer_page(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let printer = printer_name(p)?;
|
||||
let pg = craft_print::rgb::page(&printer, printer_settings(p)?.as_ref()).map_err(other)?;
|
||||
let settings = printer_settings(p)?;
|
||||
let pg = with_spooler(|| craft_print::rgb::page(&printer, settings.as_ref())).map_err(other)?;
|
||||
Ok(
|
||||
json!({"printer": printer, "paper": [pg.paper.0, pg.paper.1], "printable": [pg.printable.0, pg.printable.1, pg.printable.2, pg.printable.3], "dpi": [pg.dpi.0, pg.dpi.1]}),
|
||||
)
|
||||
|
||||
@@ -196,12 +196,23 @@ fn native_rgb_route_preserves_pdf_only_color_and_page_content() {
|
||||
assert!(native_rgb_compatible(&page_of(1, vec![0; 2], false), "noColorManagement"));
|
||||
}
|
||||
|
||||
/// Two printers, the second the default, in place of the system spooler's.
|
||||
fn test_printers() -> PrinterSource {
|
||||
std::sync::Arc::new(|| {
|
||||
vec![
|
||||
craft_print::Printer { name: "Studio".into(), default: false, two_sided: None },
|
||||
craft_print::Printer { name: "Office".into(), default: true, two_sided: Some(true) },
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printer_commands_answer_without_a_document_and_reject_bad_settings() {
|
||||
let mut s = Session::new();
|
||||
s.printer_source = Some(test_printers());
|
||||
let r = s.execute("file.print.printers", json!({})).unwrap();
|
||||
assert_eq!(r["supported"], cfg!(windows));
|
||||
assert!(r["printers"].is_array());
|
||||
assert_eq!(r["supported"], true);
|
||||
assert_eq!(r["printers"], json!([{"name": "Studio", "default": false}, {"name": "Office", "default": true}]));
|
||||
assert!(s.execute("file.print.page", json!({"printer": "Anything", "printerSettings": "zz"})).is_err());
|
||||
let mut s = session("rgb", 8);
|
||||
assert!(s.execute("file.print", json!({"printer": "Anything", "printerSettings": "0102", "send": true})).is_err());
|
||||
@@ -433,13 +444,60 @@ fn disabled_printing_never_spools() {
|
||||
#[test]
|
||||
fn printers_lists_the_spooler_destinations_without_a_document() {
|
||||
let mut s = Session::new();
|
||||
s.printer_source = Some(test_printers());
|
||||
let r = s.execute("file.printers", json!({})).unwrap();
|
||||
let list = r["printers"].as_array().unwrap();
|
||||
assert!(list.iter().all(|p| p["name"].is_string() && p["default"].is_boolean()));
|
||||
match r["default"].as_str() {
|
||||
Some(d) => assert!(list.iter().any(|p| p["name"] == d && p["default"] == true)),
|
||||
None => assert!(list.iter().all(|p| p["default"] == false)),
|
||||
assert_eq!(r["printers"], json!([{"name": "Studio", "default": false}, {"name": "Office", "default": true}]));
|
||||
assert_eq!(r["default"], "Office");
|
||||
s.printer_source = Some(std::sync::Arc::new(Vec::new));
|
||||
let r = s.execute("file.printers", json!({})).unwrap();
|
||||
assert_eq!((r["printers"].clone(), r["default"].clone()), (json!([]), Value::Null));
|
||||
}
|
||||
|
||||
/// Threads that list printers at the same time enter the spooler one at a time: the stand-in
|
||||
/// printer list records how many threads were inside it at once.
|
||||
#[test]
|
||||
fn printer_listings_enter_the_spooler_one_thread_at_a_time() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Barrier};
|
||||
const THREADS: usize = 8;
|
||||
let inside = Arc::new(AtomicUsize::new(0));
|
||||
let most = Arc::new(AtomicUsize::new(0));
|
||||
let start = Arc::new(Barrier::new(THREADS));
|
||||
let threads: Vec<_> = (0..THREADS)
|
||||
.map(|i| {
|
||||
let (inside, most, start) = (Arc::clone(&inside), Arc::clone(&most), Arc::clone(&start));
|
||||
std::thread::spawn(move || {
|
||||
let mut s = Session::new();
|
||||
s.printer_source = Some(Arc::new(move || {
|
||||
let now = inside.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
most.fetch_max(now, Ordering::SeqCst);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
inside.fetch_sub(1, Ordering::SeqCst);
|
||||
vec![craft_print::Printer { name: "Office".into(), default: true, two_sided: None }]
|
||||
}));
|
||||
start.wait();
|
||||
for _ in 0..3 {
|
||||
let id = if i % 2 == 0 { "file.printers" } else { "file.print.printers" };
|
||||
assert_eq!(s.execute(id, json!({})).unwrap()["printers"][0]["name"], "Office");
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for t in threads {
|
||||
t.join().unwrap();
|
||||
}
|
||||
assert_eq!(most.load(Ordering::SeqCst), 1, "two threads were in the printer listing at once");
|
||||
}
|
||||
|
||||
/// A caller that panics inside the spooler leaves it usable for later callers.
|
||||
#[test]
|
||||
fn a_panic_inside_the_spooler_does_not_block_later_callers() {
|
||||
let panicked = std::thread::spawn(|| with_spooler::<()>(|| panic!("a driver call panicked"))).join();
|
||||
assert!(panicked.is_err());
|
||||
assert_eq!(with_spooler(|| 7), 7);
|
||||
let mut s = Session::new();
|
||||
s.printer_source = Some(test_printers());
|
||||
assert_eq!(s.execute("file.printers", json!({})).unwrap()["default"], "Office");
|
||||
}
|
||||
|
||||
/// Spooling tests run in a child process: `disable_printing` is process-wide and a test above
|
||||
|
||||
@@ -13,6 +13,8 @@ fn fresh() -> Session {
|
||||
// Belt and braces with the EXTERNAL skip below: nothing in this process may reach a printer.
|
||||
photocraft_engine::print_cmds::disable_printing();
|
||||
let mut s = Session::new();
|
||||
// `file.printers` and `file.print.printers` list no printers and do not ask the spooler.
|
||||
s.printer_source = Some(std::sync::Arc::new(Vec::new));
|
||||
s.execute("file.new", json!({"width": 24, "height": 16})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 1, "y": 1, "width": 6, "height": 5})).unwrap();
|
||||
|
||||
@@ -758,7 +758,7 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 {
|
||||
f.entry(k.to_string()).or_insert(v);
|
||||
}
|
||||
// Windows: the system's printers, and the paper from the chosen printer's driver settings.
|
||||
if let Ok(list) = craft_print::rgb::printers() {
|
||||
if let Ok(list) = photocraft_engine::print_cmds::rgb_printers(&app.session) {
|
||||
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 !known(&s(&f, "printer", "")) {
|
||||
@@ -774,7 +774,7 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 {
|
||||
fn driver_page(f: &mut Map<String, Value>) {
|
||||
let printer = s(f, "printer", "");
|
||||
let settings = f.get("printerSettings").and_then(Value::as_str).and_then(|h| craft_print::rgb::DevMode::from_hex(h).ok());
|
||||
match craft_print::rgb::page(&printer, settings.as_ref()) {
|
||||
match photocraft_engine::print_cmds::with_spooler(|| craft_print::rgb::page(&printer, settings.as_ref())) {
|
||||
Ok(pg) => {
|
||||
f.insert("paper".into(), json!([pg.paper.0, pg.paper.1]));
|
||||
f.insert("orientation".into(), json!("portrait"));
|
||||
@@ -976,7 +976,7 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Va
|
||||
if ui.button(tl!("Print Settings…")).clicked() {
|
||||
let printer = s(f, "printer", "");
|
||||
let current = f.get("printerSettings").and_then(Value::as_str).and_then(|h| craft_print::rgb::DevMode::from_hex(h).ok());
|
||||
match craft_print::rgb::settings_dialog(&printer, current.as_ref(), None) {
|
||||
match photocraft_engine::print_cmds::with_spooler(|| craft_print::rgb::settings_dialog(&printer, current.as_ref(), None)) {
|
||||
Ok(Some(dm)) => {
|
||||
f.insert("printerSettings".into(), json!(dm.to_hex()));
|
||||
driver_page(f);
|
||||
@@ -1168,6 +1168,8 @@ mod tests {
|
||||
|
||||
fn app() -> (PhotocraftApp, egui::Context) {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
// Print lists this printer and does not ask the spooler.
|
||||
app.session.printer_source = Some(Arc::new(|| vec![craft_print::Printer { name: "Test printer".into(), default: true, two_sided: None }]));
|
||||
app.run("file.new", json!({"width": 120, "height": 80, "name": "web"})).unwrap();
|
||||
(app, egui::Context::default())
|
||||
}
|
||||
@@ -1447,9 +1449,12 @@ mod tests {
|
||||
let (mut app, ctx) = app();
|
||||
let id = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap()["dialog"].as_u64().unwrap();
|
||||
let f = &app.ui.dialog_mut(id).unwrap().fields;
|
||||
assert!(f.get("__systemPrinters").is_some_and(Value::is_array));
|
||||
assert_eq!(f["__systemPrinters"], json!([{"name": "Test printer", "default": true}]));
|
||||
assert_eq!((f["__printers"].clone(), f["printer"].clone()), (json!(["Test printer"]), json!("Test printer")));
|
||||
assert!(params(f).get("__systemPrinters").is_none());
|
||||
assert!(params(f).get("__printers").is_none());
|
||||
// Every test in this binary that opens Print lists the session's printers.
|
||||
assert_eq!(photocraft_engine::print_cmds::system_printer_listings(), 0, "a test asked the system spooler for its printers");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -703,6 +703,8 @@ fn printing_keeps_drawing_and_reports_only_the_final_spooler_result() {
|
||||
assert!(h.state().ui.status_error);
|
||||
}
|
||||
}
|
||||
// The job and its status do not ask the system spooler for its printers.
|
||||
assert_eq!(photocraft_engine::print_cmds::system_printer_listings(), 0, "a test asked the system spooler for its printers");
|
||||
}
|
||||
|
||||
fn layer_count(app: &PhotocraftApp) -> usize {
|
||||
|
||||
@@ -6,15 +6,24 @@ use serde_json::{Map, Value, json};
|
||||
|
||||
fn app() -> (PhotocraftApp, u64) {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default());
|
||||
// Exercise PDF paper controls even when native printers are available, on every OS. Print
|
||||
// lists this printer and does not ask the spooler.
|
||||
app.session.printer_source =
|
||||
Some(std::sync::Arc::new(|| vec![craft_print::Printer { name: "Test native printer".into(), default: true, two_sided: None }]));
|
||||
app.run("file.new", json!({"width": 120, "height": 80, "name": "Custom paper"})).unwrap();
|
||||
let id = open_print(&mut app);
|
||||
assert_no_system_listing();
|
||||
// Every UI path in these fixtures is safe even if an unexpected Enter confirms the dialog.
|
||||
app.ui.dialog_mut(id).unwrap().fields.insert("dryRun".into(), json!(true));
|
||||
// Exercise PDF paper controls even when native printers are available, on every OS.
|
||||
app.ui.dialog_mut(id).unwrap().fields.insert("__printers".into(), json!(["Test native printer"]));
|
||||
assert_eq!(app.ui.dialog_mut(id).unwrap().fields["__printers"], json!(["Test native printer"]));
|
||||
(app, id)
|
||||
}
|
||||
|
||||
/// No test in this binary asks the system spooler for its printers.
|
||||
fn assert_no_system_listing() {
|
||||
assert_eq!(photocraft_engine::print_cmds::system_printer_listings(), 0, "a test asked the system spooler for its printers");
|
||||
}
|
||||
|
||||
fn show(ui: &mut egui::Ui, app: &mut PhotocraftApp) {
|
||||
if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) {
|
||||
photocraft_ui_egui::dialogs::show(app, ui.ctx());
|
||||
@@ -105,6 +114,7 @@ fn custom_paper_ui_edits_reach_preview_and_pdf_and_restore_when_reopened() {
|
||||
assert!(String::from_utf8_lossy(&pdf).contains("/MediaBox [0 0 666.00 522.00]"));
|
||||
assert_eq!(h.state().session.file_menu.last_print.as_ref().unwrap()["paper"], json!([522.0, 666.0]));
|
||||
let id = open_print(h.state_mut());
|
||||
assert_no_system_listing();
|
||||
h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("dryRun".into(), json!(true));
|
||||
h.run_steps(3);
|
||||
assert!(shown(&h, "Custom"), "reopening array-valued settings must show Custom");
|
||||
|
||||
Reference in new issue
Block a user