mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 20:18:38 -05:00
Merge pull request #10592 from dotCooCoo/fix/print-dialog-printer-discovery
Print: the dialog finds printers on a background job
This commit is contained in:
9 files changed
+382
-17
No files matched your search
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied.
|
||||
|
||||
- 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged.
|
||||
|
||||
- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
|
||||
@@ -19,6 +19,9 @@ impl PrintService for SystemPrint {
|
||||
let note = system::print(job)?;
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_printers(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintersFn> {
|
||||
Some(std::sync::Arc::new(system::queues))
|
||||
}
|
||||
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
||||
Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e))))
|
||||
}
|
||||
@@ -145,6 +148,10 @@ mod system {
|
||||
pub fn printers() -> Vec<Printer> {
|
||||
craft::print::printers().into_iter().map(Printer::from).collect()
|
||||
}
|
||||
/// The installed queues and the default one, without asking each driver for its capabilities.
|
||||
pub fn queues() -> Vec<Printer> {
|
||||
craft::print::printer_queues().into_iter().map(Printer::from).collect()
|
||||
}
|
||||
/// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings.
|
||||
pub fn papers(printer: &str) -> Vec<Paper> {
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -1991,7 +1991,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.print",
|
||||
"Print…",
|
||||
"Cmd+P",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
),
|
||||
(
|
||||
"print.printers",
|
||||
|
||||
@@ -1498,6 +1498,11 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val
|
||||
};
|
||||
match (set, answer) {
|
||||
(Some(Ok(_)), Some(answer)) => {
|
||||
if answer == "ui.dialog.confirm"
|
||||
&& let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms)
|
||||
{
|
||||
crate::dialogs::print::prepare_confirm(app, host, id);
|
||||
}
|
||||
craft::automation::dialogs::dialog_method(host, ctx, answer, &json!({ "dialog": params["dialog"] }))
|
||||
}
|
||||
// A set answers with the dialog it set, `{id, parent, key, fields}`, as production did.
|
||||
|
||||
@@ -24,7 +24,7 @@ use craft::print::ui::{
|
||||
};
|
||||
use craft::ui::buttons::ToggleButton;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, Politeness, Props as _, Show as _, ShowContainer as _, announce};
|
||||
use craft::ui::dialog::{DialogId, StackDialog as _};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::layout::empty_cell;
|
||||
@@ -119,6 +119,9 @@ struct Open {
|
||||
papers_pending: bool,
|
||||
/// The ids of the Size choices the dialog was last given.
|
||||
media: Vec<String>,
|
||||
/// The printer discovery still running on a background job. The dialog takes its list once it has arrived, so
|
||||
/// PDF File stays available while the system's printers are looked up.
|
||||
discovery: Option<mpsc::Receiver<Vec<Printer>>>,
|
||||
}
|
||||
|
||||
/// The document (uid, revision) and the settings a cached preview belongs to.
|
||||
@@ -292,13 +295,14 @@ fn start(
|
||||
) -> Result<Value, String> {
|
||||
let dialogs = app.dialogs().ok_or("no window to show the dialog in")?;
|
||||
let ctx = app.ui_ctx.clone().ok_or("no window to show the dialog in")?;
|
||||
let (printers, service) = destinations(app);
|
||||
let background = shared_printers(app).is_some();
|
||||
let (printers, service) = if background { (listed(Vec::new(), true), true) } else { destinations(app) };
|
||||
let mut state = State::default();
|
||||
state.settings.destination = Destination::Printer(
|
||||
printers.iter().find(|p| p.default).or(printers.first().filter(|_| service)).map_or_else(|| PDF_FILE.to_string(), |p| p.name.clone()),
|
||||
);
|
||||
state.printers = printers;
|
||||
let header = if service && cfg!(windows) {
|
||||
let mut header = if service && cfg!(windows) {
|
||||
vec![
|
||||
Param::new("directPdf", tl!("Send PDF directly (bypass driver)"), ParamKind::bool(false))
|
||||
.tooltip(tl!("Writes the print-ready PDF to the printer's TCP/IP RAW port, for PCL-only drivers that change the custom page size.")),
|
||||
@@ -306,6 +310,10 @@ fn start(
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
header.push(Param::custom("__discovery", "", |ui, fields, _| {
|
||||
let text = if fields.bool("__discovery") == Some(true) { tl!("Finding printers. PDF File and Done are available.") } else { "" };
|
||||
Text::new(text).show(ui)
|
||||
}));
|
||||
let taken: Vec<String> = taken_names(app);
|
||||
let named = editing.clone();
|
||||
let driver = driver(has_setup(app), &state.settings.destination);
|
||||
@@ -325,13 +333,30 @@ fn start(
|
||||
.json_form(|fields, out| out.extend(nested(form::json_of(&KEYS, fields))))
|
||||
.check_name(move |name: &str| refusal(&taken, &named, name).map(|_| PresetError::NameTaken))
|
||||
.held_ok();
|
||||
let discovery = (background && mode == PrintMode::Print).then(|| discover(app));
|
||||
if discovery.is_some() {
|
||||
hosted.set_settings_valid(false);
|
||||
hosted.set_field("__discovery", true.into());
|
||||
}
|
||||
// The name row is the dialog's own.
|
||||
if mode == PrintMode::PresetEditor {
|
||||
hosted.set_json_field(&ctx, "name", json!(name))?;
|
||||
}
|
||||
let id = dialogs.with(|h| h.open(hosted));
|
||||
app.print_dialog.open =
|
||||
Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver, papers: (printer, papers), papers_pending, media });
|
||||
app.print_dialog.open = Some(Open {
|
||||
id,
|
||||
mode,
|
||||
document,
|
||||
preset,
|
||||
editing,
|
||||
art: None,
|
||||
preview: None,
|
||||
driver,
|
||||
papers: (printer, papers),
|
||||
papers_pending,
|
||||
media,
|
||||
discovery,
|
||||
});
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -394,12 +419,49 @@ fn insert_at(map: &mut Map<String, Value>, path: &[&str], v: Value) {
|
||||
/// and PDF File last; and whether there is a print service.
|
||||
fn destinations(app: &mut VectorcraftApp) -> (Vec<Printer>, bool) {
|
||||
let service = app.services.print.is_some();
|
||||
let mut list: Vec<Printer> = app.services.print.as_mut().map(|s| s.printers()).unwrap_or_default();
|
||||
let list: Vec<Printer> = app.services.print.as_mut().map(|s| s.printers()).unwrap_or_default();
|
||||
(listed(list, service), service)
|
||||
}
|
||||
|
||||
/// The Printer list of the system's printers `list`: the default printer by itself when a print `service` names none,
|
||||
/// and PDF File last.
|
||||
fn listed(mut list: Vec<Printer>, service: bool) -> Vec<Printer> {
|
||||
if service && list.is_empty() {
|
||||
list.push(Printer::new("").label(tl!(DEFAULT_PRINTER)));
|
||||
}
|
||||
list.push(Printer::new(PDF_FILE).label(tl!(PDF_FILE)));
|
||||
(list, service)
|
||||
list
|
||||
}
|
||||
|
||||
/// The print service's background printer discovery, if it has one.
|
||||
fn shared_printers(app: &VectorcraftApp) -> Option<crate::print::SharedPrintersFn> {
|
||||
app.services.print.as_ref().and_then(|s| s.shared_printers())
|
||||
}
|
||||
|
||||
/// The Printer list for the dialog to take ([`HostedPrint::listen`]): found on a background job when the print service
|
||||
/// has a background discovery, otherwise listed here.
|
||||
fn discover(app: &mut VectorcraftApp) -> mpsc::Receiver<Vec<Printer>> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
match shared_printers(app) {
|
||||
Some(find) => {
|
||||
let ctx = app.ui_ctx.clone();
|
||||
app.jobs().spawn(
|
||||
"printer-discovery",
|
||||
Box::new(move || {
|
||||
// The dialog may have closed and dropped the receiver; nothing waits for the list then.
|
||||
let _ = tx.send(listed(find(), true));
|
||||
if let Some(ctx) = ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
None => {
|
||||
// The receiver is held by the dialog, so the send cannot fail.
|
||||
let _ = tx.send(destinations(app).0);
|
||||
}
|
||||
}
|
||||
rx
|
||||
}
|
||||
|
||||
/// Whether the print service can open a printer's settings (`print.printerSetup`).
|
||||
@@ -456,9 +518,25 @@ fn on<R>(dialogs: &WindowDialogs, f: impl FnOnce(&mut HostedPrint) -> R) -> Opti
|
||||
dialogs.with(|h| h.get_mut::<HostedPrint>().map(f))
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_confirm(app: &VectorcraftApp, host: &mut craft::ui::dialog::DialogHost, id: DialogId) {
|
||||
if let Some(open) = &app.print_dialog.open
|
||||
&& open.id == id
|
||||
&& let Some(p) = host.get_mut::<HostedPrint>()
|
||||
{
|
||||
discovery_valid(p, open.mode, open.discovery.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
/// Enables Print unless the dialog prints to a printer while the printer list is still being looked up.
|
||||
fn discovery_valid(p: &mut HostedPrint, mode: PrintMode, pending: bool) {
|
||||
let physical = matches!(&p.state().settings.destination, Destination::Printer(name) if name != PDF_FILE);
|
||||
p.set_settings_valid(mode != PrintMode::Print || !(pending || p.state().discovering()) || !physical);
|
||||
}
|
||||
|
||||
/// One pass of the pump over the open dialog; false once it has closed.
|
||||
fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, open: &mut Open) -> bool {
|
||||
let setup = has_setup(app);
|
||||
// Setup… looks the printers up again on some systems, so the row shows it once the discovery has ended.
|
||||
let setup = has_setup(app) && open.discovery.is_none();
|
||||
let Some(mut d) = on(dialogs, |p| {
|
||||
// The printer row shows Setup… for the printer chosen, and none for PDF File.
|
||||
let driver = driver(setup, &p.state().settings.destination);
|
||||
@@ -576,6 +654,12 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
.collect();
|
||||
on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()]));
|
||||
}
|
||||
if d.refresh {
|
||||
if open.discovery.is_none() {
|
||||
open.discovery = Some(discover(app));
|
||||
}
|
||||
announce(ctx, tl!("Finding printers. PDF File and Done are available."), Politeness::Polite);
|
||||
}
|
||||
if open.document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) {
|
||||
let message = tl!("Return to the original drawing to print it");
|
||||
on(dialogs, |p| {
|
||||
@@ -592,12 +676,31 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
open.driver = d.driver;
|
||||
ctx.request_repaint();
|
||||
}
|
||||
if d.refresh {
|
||||
let (list, _) = destinations(app);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
// The receiver is held by the dialog below, so the send cannot fail.
|
||||
let _ = tx.send(list);
|
||||
on(dialogs, |p| p.listen(rx));
|
||||
let discovery_pending = open.discovery.is_some();
|
||||
if let Some(rx) = &open.discovery {
|
||||
let found = match rx.try_recv() {
|
||||
Ok(list) => Some(Some(list)),
|
||||
Err(mpsc::TryRecvError::Disconnected) => Some(None),
|
||||
Err(mpsc::TryRecvError::Empty) => None,
|
||||
};
|
||||
if let Some(list) = found {
|
||||
open.discovery = None;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
// A discovery that stopped without a list leaves the default printer and PDF File.
|
||||
// The receiver is held by the dialog below, so the send cannot fail.
|
||||
let _ = tx.send(list.unwrap_or_else(|| listed(Vec::new(), true)));
|
||||
on(dialogs, |p| {
|
||||
p.listen(rx);
|
||||
p.state_mut().poll(ctx);
|
||||
let selected = match &p.state().settings.destination {
|
||||
Destination::Printer(name) if name.is_empty() => tl!(DEFAULT_PRINTER).to_string(),
|
||||
Destination::Printer(name) => name.clone(),
|
||||
_ => tl!(PDF_FILE).to_string(),
|
||||
};
|
||||
let message = crate::i18n::fmt(tl!("Printers are ready. Selected printer: {printer}."), &[("printer", &selected)]);
|
||||
announce(ctx, message, Politeness::Polite);
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(printer) = d.setup
|
||||
&& let Err(e) = app.run("print.printerSetup", json!({ "printer": printer }))
|
||||
@@ -630,7 +733,10 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
Err(_) => Some(tl!("Can't print these settings: see the Summary")),
|
||||
};
|
||||
on(dialogs, |p| {
|
||||
let pending = open.discovery.is_some() || p.state().discovering();
|
||||
p.set_sheet(sheet);
|
||||
discovery_valid(p, open.mode, pending);
|
||||
p.set_field("__discovery", pending.into());
|
||||
p.set_message(message.map(Into::into));
|
||||
});
|
||||
if changed {
|
||||
@@ -643,7 +749,15 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
p.set_field("__inks", FieldValue::Json(inks));
|
||||
});
|
||||
}
|
||||
if let Some(answer) = d.ok {
|
||||
// Physical printing waits until the dialog has applied the discovered list.
|
||||
if open.mode == PrintMode::Print
|
||||
&& discovery_pending
|
||||
&& d.ok.as_ref().is_some_and(|answer| {
|
||||
matches!(answer.finish, PrintFinish::Print) && matches!(&answer.settings.destination, Destination::Printer(name) if name != PDF_FILE)
|
||||
})
|
||||
{
|
||||
on(dialogs, HostedPrint::release_ok);
|
||||
} else if let Some(answer) = d.ok {
|
||||
let result = accept(app, open, &answer, &d.name);
|
||||
on(dialogs, |p| p.answer_ok(result.map_err(Into::into)));
|
||||
}
|
||||
|
||||
@@ -1117,6 +1117,232 @@ pub(super) fn field_names(out: &egui::FullOutput) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A print service with a background printer discovery, which counts the lists made on the UI thread.
|
||||
struct SlowDiscovery {
|
||||
/// How many times the dialog listed the printers on the UI thread.
|
||||
listed_here: Rc<Cell<usize>>,
|
||||
jobs: Jobs,
|
||||
printers: Vec<Printer>,
|
||||
}
|
||||
|
||||
impl PrintService for SlowDiscovery {
|
||||
fn printers(&mut self) -> Vec<Printer> {
|
||||
self.listed_here.set(self.listed_here.get() + 1);
|
||||
MockPrint(Jobs::default()).printers()
|
||||
}
|
||||
|
||||
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
||||
MockPrint(self.jobs.clone()).print(job)
|
||||
}
|
||||
|
||||
fn shared_printers(&self) -> Option<crate::print::SharedPrintersFn> {
|
||||
let printers = self.printers.clone();
|
||||
Some(std::sync::Arc::new(move || printers.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The message the Print dialog shows while the printer discovery runs.
|
||||
const PENDING_MESSAGE: &str = "Finding printers. PDF File and Done are available.";
|
||||
|
||||
/// Checks the dialog's next frame: whether it shows the discovery message, and whether Print is enabled. Done always
|
||||
/// is.
|
||||
fn discovery_controls(app: &mut VectorcraftApp, pending: bool, enabled: bool) {
|
||||
use egui::accesskit::Role;
|
||||
let ctx = ctx(app);
|
||||
let out = crate::testing::app_frame(app, &ctx, Default::default());
|
||||
let nodes = out.platform_output.accesskit_update.expect("an accessibility tree").nodes;
|
||||
let button = |name| nodes.iter().map(|(_, node)| node).find(|node| node.role() == Role::Button && node.label() == Some(name)).unwrap();
|
||||
assert_eq!(!button("Print").is_disabled(), enabled, "Print availability follows discovery and destination");
|
||||
assert!(!button("Done").is_disabled(), "Done stays available");
|
||||
assert_eq!(nodes.iter().any(|(_, node)| node.label() == Some(PENDING_MESSAGE) || node.value() == Some(PENDING_MESSAGE)), pending);
|
||||
}
|
||||
|
||||
/// An app with a drawing whose print service finds `printers` on a background job that waits until the test runs it,
|
||||
/// as a slow print server would; with the count of lists made on the UI thread, the jobs printed, and the jobs.
|
||||
fn discovery_app(printers: Vec<Printer>) -> (VectorcraftApp, Rc<Cell<usize>>, Jobs, std::sync::Arc<craft::host::ManualJobs>) {
|
||||
let listed_here = Rc::new(Cell::new(0));
|
||||
let printed = Jobs::default();
|
||||
let service = SlowDiscovery { listed_here: listed_here.clone(), jobs: printed.clone(), printers };
|
||||
let services = Services { print: Some(Box::new(service)), ..Default::default() };
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
|
||||
let jobs = std::sync::Arc::new(craft::host::ManualJobs::new());
|
||||
app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs.clone()).build());
|
||||
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
|
||||
(app, listed_here, printed, jobs)
|
||||
}
|
||||
|
||||
/// The dialog opens and works while the printer discovery waits on a background job, and shows the system's printers
|
||||
/// once the job has run.
|
||||
#[test]
|
||||
fn printer_discovery_runs_off_the_ui_thread() {
|
||||
use egui::accesskit::Role;
|
||||
let (mut app, listed_here, printed, jobs) = discovery_app(MockPrint(Jobs::default()).printers());
|
||||
let pending_message = PENDING_MESSAGE;
|
||||
let controls = discovery_controls;
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
app.run("file.new", json!({"width": 180, "height": 100})).unwrap();
|
||||
let ctx = ctx(&app);
|
||||
let out = crate::testing::app_frame(&mut app, &ctx, Default::default());
|
||||
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
|
||||
assert!(
|
||||
nodes.iter().any(|(_, node)| node.role() == Role::Button && node.label() == Some("Print") && node.is_disabled()),
|
||||
"physical Print is disabled in the first frame"
|
||||
);
|
||||
assert!(
|
||||
nodes.iter().any(|(_, node)| {
|
||||
node.role() == Role::Status
|
||||
&& node.live() == Some(egui::accesskit::Live::Polite)
|
||||
&& node.label().is_some_and(|text| text.contains(pending_message))
|
||||
}),
|
||||
"printer discovery is announced before Print is pressed"
|
||||
);
|
||||
assert_eq!(listed_here.get(), 0, "the printers are not listed on the UI thread");
|
||||
assert_eq!(jobs.waiting(), 1, "discovery starts even after switching drawings before the first pump");
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, false);
|
||||
assert_eq!(jobs.waiting(), 1, "the discovery waits on a background job");
|
||||
assert_ne!(fields(&app)["printer"], "Proofer", "the list has not arrived");
|
||||
set(&mut app, "printer", json!("PDF File"));
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, true);
|
||||
let out = crate::testing::app_frame(&mut app, &ctx, Default::default());
|
||||
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
|
||||
assert!(nodes.iter().any(|(_, node)| node.label() == Some("Print preview image")), "PDF preview stays available during discovery");
|
||||
set(&mut app, "sheet", json!(0));
|
||||
pump(&mut app);
|
||||
assert_eq!(fields(&app)["sheet"], 0, "PDF preview accepts page selection during discovery");
|
||||
set(&mut app, "printer", json!(""));
|
||||
pump(&mut app);
|
||||
set(&mut app, "section", json!("Graphics"));
|
||||
pump(&mut app);
|
||||
assert_eq!(jobs.waiting(), 1, "one discovery at a time");
|
||||
confirm(&mut app);
|
||||
assert!(is_open(&app), "physical printing waits for discovery");
|
||||
assert!(printed.borrow().is_empty());
|
||||
let (id, _) = top(&app).unwrap();
|
||||
app.dialogs().unwrap().with(|host| {
|
||||
host.get_mut::<craft::print::ui::HostedPrint>().unwrap().set_settings_valid(true);
|
||||
let _ = host.confirm_by_id(&ctx, id);
|
||||
assert_eq!(host.held_state(id), Some(craft::ui::dialog::HeldOk::Waiting));
|
||||
});
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
// The frame's pump takes the list and announces it.
|
||||
let out = crate::testing::app_frame(&mut app, &ctx, Default::default());
|
||||
assert_eq!(app.dialogs().unwrap().with(|host| host.held_state(id)), None, "the pump discards the held physical answer");
|
||||
assert!(printed.borrow().is_empty(), "the captured placeholder must not submit to the default printer");
|
||||
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
|
||||
assert!(
|
||||
nodes.iter().any(|(_, node)| {
|
||||
node.role() == Role::Status
|
||||
&& node.live() == Some(egui::accesskit::Live::Polite)
|
||||
&& node.label().is_some_and(|text| text.contains("Printers are ready. Selected printer: Proofer."))
|
||||
}),
|
||||
"the applied printer list and selected queue are announced"
|
||||
);
|
||||
pump(&mut app);
|
||||
assert!(is_open(&app), "the held Print answer waits for the dialog to apply the list");
|
||||
assert!(printed.borrow().is_empty(), "the captured placeholder must not submit to the default printer");
|
||||
assert_eq!(fields(&app)["printer"], "Proofer", "the system's default printer, once the list arrives");
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
controls(&mut app, false, true);
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(printed.borrow().len(), 1);
|
||||
assert_eq!(printed.borrow()[0].0.as_deref(), Some("Proofer"));
|
||||
|
||||
let picker = crate::tests_picks::scripted(&mut app);
|
||||
let written: Written = Rc::default();
|
||||
let w = written.clone();
|
||||
app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| {
|
||||
w.borrow_mut().push((path.to_string(), bytes.to_vec()));
|
||||
Ok(())
|
||||
}));
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
call(&mut app, "ui.dialog.set", json!({"dialog": "top", "field": "printer", "value": "PDF File", "action": "confirm"}));
|
||||
picker.answer_saved("/tmp/discovery-combined.pdf", None);
|
||||
crate::tests_picks::poll(&mut app, &ctx);
|
||||
assert_eq!(written.borrow().len(), 1, "PDF selection and confirmation work in one call before a frame");
|
||||
assert_eq!(printed.borrow().len(), 1, "PDF confirmation does not submit a physical job");
|
||||
assert_eq!(jobs.waiting(), 1, "PDF confirmation does not wait for discovery");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
}
|
||||
|
||||
/// While the printer discovery runs, Done keeps the settings and PDF File saves, and a held Print to a printer waits.
|
||||
#[test]
|
||||
fn done_and_pdf_file_work_while_printers_are_found() {
|
||||
let (mut app, listed_here, printed, jobs) = discovery_app(MockPrint(Jobs::default()).printers());
|
||||
let controls = discovery_controls;
|
||||
let ctx = ctx(&app);
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
assert_eq!(jobs.waiting(), 1);
|
||||
let (id, _) = top(&app).unwrap();
|
||||
let _ = app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id));
|
||||
set(&mut app, "printer", json!("PDF File"));
|
||||
super::print::pump(&mut app, &ctx);
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, true);
|
||||
assert_eq!(printed.borrow().len(), 0, "the held physical destination is checked even after selecting PDF File");
|
||||
set(&mut app, "printer", json!(""));
|
||||
set(&mut app, "copies", json!(2));
|
||||
set(&mut app, "choice", json!("done"));
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app), "Done can save settings while discovery is pending");
|
||||
assert_eq!(app.session.active().unwrap().doc.print_setup.as_ref().unwrap()["copies"], 2);
|
||||
assert_eq!(printed.borrow().len(), 0, "Done does not submit a print job");
|
||||
assert_eq!(jobs.waiting(), 1, "Done did not wait for discovery");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
|
||||
let picker = crate::tests_picks::scripted(&mut app);
|
||||
let written: Written = Rc::default();
|
||||
let w = written.clone();
|
||||
app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| {
|
||||
w.borrow_mut().push((path.to_string(), bytes.to_vec()));
|
||||
Ok(())
|
||||
}));
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
set(&mut app, "printer", json!("PDF File"));
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, true);
|
||||
confirm(&mut app);
|
||||
picker.answer_saved("/tmp/discovery.pdf", None);
|
||||
crate::tests_picks::poll(&mut app, &ctx);
|
||||
assert_eq!(written.borrow().len(), 1, "PDF File saves while discovery is pending");
|
||||
assert_eq!(pages(&written.borrow()[0].1), 2, "PDF File keeps the copies saved by Done");
|
||||
assert_eq!(printed.borrow().len(), 0);
|
||||
assert_eq!(jobs.waiting(), 1, "PDF File does not wait for discovery");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
}
|
||||
|
||||
/// A discovery that finds no printers leaves Default Printer chosen, and Print goes to it once the list is applied.
|
||||
#[test]
|
||||
fn an_empty_discovery_keeps_the_default_printer() {
|
||||
let (mut app, listed_here, printed, jobs) = discovery_app(vec![]);
|
||||
let controls = discovery_controls;
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, false);
|
||||
confirm(&mut app);
|
||||
assert!(is_open(&app));
|
||||
assert_eq!(fields(&app)["printer"], "");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
pump(&mut app);
|
||||
pump(&mut app);
|
||||
controls(&mut app, false, true);
|
||||
assert_eq!(fields(&app)["printer"], "", "an empty result keeps Default Printer selected");
|
||||
let (id, _) = top(&app).unwrap();
|
||||
assert_eq!(app.dialogs().unwrap().with(|host| host.held_state(id)), None, "a blocked Print leaves no stale refusal");
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(printed.borrow().len(), 1);
|
||||
assert_eq!(printed.borrow()[0].0, None);
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
}
|
||||
|
||||
/// Every number and length field of the dialog's sections has a name that tells it from the others in its row.
|
||||
#[test]
|
||||
fn every_number_and_length_field_is_named() {
|
||||
|
||||
@@ -1992,7 +1992,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.print",
|
||||
"Print…",
|
||||
"Cmd+P",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
),
|
||||
(
|
||||
"print.printers",
|
||||
|
||||
@@ -33,6 +33,9 @@ pub struct PrintJob<'a> {
|
||||
/// Submission callable from the desktop background worker.
|
||||
pub type SharedPrintFn = std::sync::Arc<dyn Fn(&PrintJob<'_>) -> Result<String, String> + Send + Sync>;
|
||||
|
||||
/// Printer discovery callable from a background job.
|
||||
pub type SharedPrintersFn = std::sync::Arc<dyn Fn() -> Vec<Printer> + Send + Sync>;
|
||||
|
||||
/// The platform's printing ([`crate::Services::print`]).
|
||||
pub trait PrintService {
|
||||
/// The printers the system knows (none: only the default one, or the browser's dialog).
|
||||
@@ -44,6 +47,11 @@ pub trait PrintService {
|
||||
fn shared_print(&self) -> Option<SharedPrintFn> {
|
||||
None
|
||||
}
|
||||
/// The printer discovery the Print dialog runs on a background job. Without one, the dialog lists
|
||||
/// [`PrintService::printers`] on the UI thread.
|
||||
fn shared_printers(&self) -> Option<SharedPrintersFn> {
|
||||
None
|
||||
}
|
||||
/// Whether the system turns a landscape page to fit the paper. macOS's print queues put
|
||||
/// each page on the paper as it is, so their jobs are written upright (`file.print`'s
|
||||
/// `forPrinter`); Windows and the browser's print dialog turn them themselves.
|
||||
|
||||
@@ -13340,6 +13340,9 @@ prints at most that many pages, copies counted; with more, `file.print` composes
|
||||
its raster effects are rendered. In the app, `file.print` with no params opens the Print
|
||||
dialog, and with params it prints through the system (`printer`: a name from `print.printers`, default the system's
|
||||
default printer) or, with `toFile`, a `path` or no printing available, saves the PDF.
|
||||
In the desktop Print dialog, installed printers appear once the background lookup has returned and the dialog has
|
||||
applied the list. `ui.dialog.set` accepts a named `printer` once it appears in that list. PDF File is available at once.
|
||||
The dialog shows and announces printer discovery. Physical Print is disabled until the list is applied; PDF File and Done remain available.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}}
|
||||
|
||||
Reference in new issue
Block a user