Merge pull request #10581 from dotCooCoo/fix/print-paper-size-to-cups

Print: the job asks CUPS for the paper size chosen
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-02 17:20:21 -08:00
commit 15cc3b048f
7 files changed
+611 -26

No files matched your search

+223 -11
View File
@@ -25,6 +25,9 @@ impl PrintService for SystemPrint {
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, &note))))
}
fn applies_paper(&self) -> bool {
!cfg!(windows)
}
fn turns_landscape(&self) -> bool {
// macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright
// paper. craft-print turns each sheet to its own orientation on Windows.
@@ -173,17 +176,135 @@ mod system {
if printer.contains(['/', '\\']) || printer.starts_with('.') {
return Vec::new();
}
const PPD_CAP: u64 = 16 << 20;
let mut bytes = Vec::new();
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
if read.is_err() {
return Vec::new();
let named = cups_server();
// A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue,
// so its sizes come from the server.
if scheduler_is_local(named.as_deref()) {
const PPD_CAP: u64 = 16 << 20;
let mut bytes = Vec::new();
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() };
if !papers.is_empty() {
return papers;
}
}
vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes))
// A driverless or remote queue has no PPD here: `lpoptions` asks the queue's server for its sizes.
let mut command = Command::new("lpoptions");
command.args(["-p", printer, "-l"]);
let papers = paper_output(&mut command)
.map(|out| vectorcraft_ui_egui::print::lpoptions_papers(&String::from_utf8_lossy(&out)))
.unwrap_or_default();
if !papers.is_empty() {
return papers;
}
// A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses.
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
let server = ipp_server(named, |s| std::path::Path::new(s).exists());
let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers };
use std::io::Write as _;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let test_path =
std::env::temp_dir().join(format!("vectorcraft-printer-papers-{}-{}.test", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let Ok(mut test) = std::fs::File::options().write(true).create_new(true).open(&test_path) else { return papers };
let written = test.write_all(
b"{\n\
VERSION 1.1\n\
OPERATION Get-Printer-Attributes\n\
GROUP operation-attributes-tag\n\
ATTR charset attributes-charset utf-8\n\
ATTR language attributes-natural-language en\n\
ATTR uri printer-uri $uri\n\
ATTR keyword requested-attributes media-supported\n\
STATUS successful-ok\n\
}\n",
);
drop(test);
if written.is_err() {
let _ = std::fs::remove_file(&test_path);
return papers;
}
let mut command = Command::new("ipptool");
command.args(["-T", "10", "-tv", &uri]).arg(&test_path);
let output = paper_output(&mut command);
let _ = std::fs::remove_file(&test_path);
output.map(|out| vectorcraft_ui_egui::print::ipp_papers(&String::from_utf8_lossy(&out))).unwrap_or_default()
}
}
/// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`.
#[cfg(not(windows))]
const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"];
/// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server
/// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default
/// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local
/// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job
/// does not go to.
///
/// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri
#[cfg(not(windows))]
pub(super) fn ipp_server(named: Option<String>, exists: impl Fn(&str) -> bool) -> Option<String> {
match named {
Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None,
Some(server) => Some(server),
None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()),
}
}
/// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or
/// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName`
/// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts.
#[cfg(not(windows))]
fn cups_server() -> Option<String> {
if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) {
return Some(server.trim().to_string());
}
if cfg!(target_os = "macos") {
return None;
}
let home = std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".cups/client.conf"));
home.into_iter().chain([std::path::PathBuf::from("/etc/cups/client.conf")]).find_map(|path| {
use std::io::Read as _;
let mut text = String::new();
std::fs::File::open(path).and_then(|f| f.take(1 << 16).read_to_string(&mut text)).ok()?;
client_conf_server_name(&text)
})
}
/// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path,
/// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback
/// name on another port is a second scheduler, whose queues the local PPD folder does not describe.
#[cfg(not(windows))]
pub(super) fn scheduler_is_local(server: Option<&str>) -> bool {
let Some(server) = server.map(str::trim) else { return true };
if server.starts_with('/') {
return true;
}
// A network name may end in `/version=1.1`.
let server = server.split_once('/').map_or(server, |(server, _)| server);
let (host, port) = if let Some(rest) = server.strip_prefix('[') {
rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':')))
} else if server.matches(':').count() == 1 {
server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port)))
} else {
(server, None)
};
let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1";
loopback && port.is_none_or(|port| port.trim() == "631")
}
/// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a
/// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is
/// dropped and the rest of the line is kept as written.
#[cfg(not(windows))]
pub(super) fn client_conf_server_name(text: &str) -> Option<String> {
text.lines().rev().find_map(|line| {
let kept = match line.find('#') {
Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]),
Some(at) => line[..at].to_string(),
None => line.to_string(),
};
let (key, value) = kept.trim().split_once(char::is_whitespace)?;
(key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string())
})
}
/// Drain output while polling the child, and stop discovery after ten seconds.
#[cfg(windows)]
fn paper_output(command: &mut Command) -> Option<Vec<u8>> {
use std::io::Read as _;
use std::process::Stdio;
@@ -226,10 +347,14 @@ mod system {
if job.direct_pdf {
return super::direct_pdf::print(job);
}
// Copies, layout, marks and colour management are already in the PDF. Preserve its
// physical sheet size and the queue's duplex default without printing copies twice.
let settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
craft::print::submit(job.pdf, &settings).map_err(|e| e.to_string())
craft::print::submit(job.pdf, &settings(job)).map_err(|e| e.to_string())
}
/// The spooler's settings for `job`. Copies, layout, marks and colour management are already in the PDF. Preserve
/// its physical sheet size and the queue's duplex default without printing copies twice. The driver's paper
/// keyword goes to CUPS as `media`, so the queue feeds the paper the job was laid out for.
pub(crate) fn settings(job: &PrintJob) -> craft::print::Job {
let options = job.paper.map(|paper| ("media".to_string(), paper.to_string())).into_iter().collect();
craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), options, ..Default::default() }
}
#[cfg(windows)]
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
@@ -476,3 +601,90 @@ mod turn_tests {
);
}
}
#[cfg(all(test, not(windows)))]
mod client_conf_tests {
use super::system::{client_conf_server_name, ipp_server, scheduler_is_local};
#[test]
fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() {
let none = |_: &str| false;
let socket = |s: &str| s == "/run/cups/cups.sock";
assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631");
assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None);
assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked");
assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631"));
assert_eq!(ipp_server(None, socket), None);
assert_eq!(ipp_server(None, none).as_deref(), Some("localhost"));
}
#[test]
fn only_a_scheduler_on_this_machine_counts_as_local() {
for local in [
None,
Some("/run/cups/cups.sock"),
Some("localhost"),
Some("LocalHost:631"),
Some("localhost:631"),
Some("127.0.0.1:631"),
Some("::1"),
Some("[::1]:631"),
Some("[::1]"),
Some("localhost/version=1.1"),
Some("localhost:631/version=1.1"),
] {
assert!(scheduler_is_local(local), "{local:?}");
}
for remote in [
"print.example.com",
"print.example.com:631",
"192.0.2.7",
"[2001:db8::1]:631",
"2001:db8::1",
"localhost.example.com",
"print.example.com:631/version=1.1",
"localhost:8631",
"127.0.0.1:8631",
"[::1]:8631",
"localhost:8631/version=1.1",
] {
assert!(!scheduler_is_local(Some(remote)), "{remote}");
}
}
#[test]
fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() {
assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com"));
assert_eq!(client_conf_server_name("ServerName print.example.com # office\n").as_deref(), Some("print.example.com"));
assert_eq!(client_conf_server_name("ServerName print.example.com#office\n").as_deref(), Some("print.example.com"));
assert_eq!(client_conf_server_name("ServerName /run/cups\\#1.sock\n").as_deref(), Some("/run/cups#1.sock"));
// After an escaped first `#`, a later `#` stays as written.
assert_eq!(client_conf_server_name("ServerName a\\#b#c\n").as_deref(), Some("a#b#c"));
// A later line that is only a comment, or a directive whose value is all comment, leaves the earlier one.
assert_eq!(client_conf_server_name("ServerName a.example\n# ServerName b.example\nServerName # none\n").as_deref(), Some("a.example"));
assert_eq!(client_conf_server_name("ServerName a.example\nServerName b.example\n").as_deref(), Some("b.example"));
}
}
#[cfg(test)]
mod job_settings_tests {
use super::system::settings;
use vectorcraft_ui_egui::print::PrintJob;
fn job(paper: Option<&str>) -> PrintJob<'_> {
PrintJob { printer: Some("Card"), title: "Badge", pdf: b"%PDF", paper, direct_pdf: false }
}
#[test]
fn the_chosen_paper_goes_to_cups_as_media() {
let args = craft::print::lp_args(&settings(&job(Some("CR80"))));
assert!(args.windows(2).any(|w| w == ["-o", "media=CR80"]), "{args:?}");
assert!(args.windows(2).any(|w| w == ["-d", "Card"]), "{args:?}");
}
#[test]
fn without_a_paper_the_queue_keeps_its_own() {
let args = craft::print::lp_args(&settings(&job(None)));
assert!(!args.iter().any(|a| a.starts_with("media=")), "{args:?}");
}
}
+1 -1
View File
@@ -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; 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}",
"{} 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), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), 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",
+26 -8
View File
@@ -219,6 +219,17 @@ fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a P
papers.iter().find(|p| p.key == key)
}
/// The driver's keyword for the paper the Size row names, for the job to ask the queue for: the printer's own paper
/// (`printer:CR80`), or the driver's paper of the size of one of the dialog's own papers (`letter` on a driver that lists
/// `Letter`). `None` when the driver lists no such paper, or names it with characters a keyword can't hold.
fn driver_paper_key<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a str> {
let paper = printer_paper(fields, papers).or_else(|| {
let own = Media::from_name(fields.text("media")?).filter(|m| *m != Media::Custom)?;
papers.iter().find(|p| own_media_of(p) == Some(own))
})?;
crate::print::is_paper_keyword(&paper.key).then_some(paper.key.as_str())
}
/// Whether two papers have the same Width and Height, to within half a point.
fn same_size(a: &Paper, b: &Paper) -> bool {
(a.width - b.width).abs() <= 0.5 && (a.height - b.height).abs() <= 0.5
@@ -575,15 +586,16 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
// The paper chosen from the previous list, read before the list is replaced.
let chosen = on(dialogs, |p| printer_paper(p.fields(), &open.papers.1).cloned()).flatten();
if printer_changed || open.papers_pending {
let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed);
// The held answer still names a paper from the previous list.
if let Some(answer) = &mut d.ok
&& let Some(paper) = printer_paper(&answer.fields, &open.papers.1)
&& (pending || !printer_paper(&answer.fields, &papers).is_some_and(|new| same_size(paper, new)))
{
answer.fields.set("width", paper.width);
answer.fields.set("height", paper.height);
answer.fields.set("media", Media::Custom.id());
}
let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed);
// While the new printer's lookup runs, the Size list keeps the sizes before it, so the paper chosen keeps its
// name and size until the driver answers.
papers_changed = !pending;
@@ -759,7 +771,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
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)));
on(dialogs, |p| p.answer_ok(result.map_err(|e| crate::i18n::message(crate::i18n::current(), &e).into())));
}
true
}
@@ -824,17 +836,23 @@ fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &st
if open.mode == PrintMode::PresetEditor {
return save_preset(app, open, name, settings);
}
let (printer, to_file) = match &answer.settings.destination {
Destination::Printer(name) if name != PDF_FILE => (name.as_str(), false),
_ => ("", true),
};
let direct_pdf = answer.fields.bool("directPdf").unwrap_or(false);
let applies_paper = !to_file && !direct_pdf && app.services.print.as_ref().is_some_and(|s| s.applies_paper());
if matches!(answer.finish, PrintFinish::Print) && applies_paper && (open.papers_pending || open.papers.0 != printer) {
return Err("The printer's paper sizes are still loading; try Print again in a moment.".into());
}
// Laid out first, so a bad range or overlap is refused before anything is kept.
app.session.execute("print.preview", &json!({ "settings": settings })).map_err(|e| e.to_string())?;
app.run("print.setup", json!({ "settings": settings }))?;
match answer.finish {
PrintFinish::Print => {
let (printer, to_file) = match &answer.settings.destination {
Destination::Printer(name) if name != PDF_FILE => (name.as_str(), false),
_ => ("", true),
};
let direct_pdf = answer.fields.bool("directPdf").unwrap_or(false);
crate::print::run(app, &json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf })).map(|_| ())
let paper = if applies_paper { driver_paper_key(&answer.fields, &open.papers.1) } else { None };
let job = json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf, "paper": paper });
crate::print::run(app, &job).map(|_| ())
}
// Done only keeps the settings.
_ => Ok(()),
+207
View File
@@ -650,6 +650,107 @@ fn windows_paper_sizes_are_read_in_hundredths_of_an_inch() {
assert_eq!((got[3].0, got[3].1), ("256", "256"), "no name: the number");
}
#[test]
fn a_queue_without_a_ppd_lists_the_paper_sizes_lpoptions_reports() {
let out = "ColorModel/Color Mode: Gray *RGB\n\
PageSize/Media Size: *Letter A4 Legal na_index-4x6_4x6in iso_a5_148x210mm B5 ISOB4 Custom.WIDTHxHEIGHT Unknown Letter\r\n\
media/Media: om_cr80_54x85.6mm tiny_1x1mm\n\
InputSlot/Source: *Auto Tray1\n";
let papers = crate::print::lpoptions_papers(out);
let got: Vec<(&str, i64, i64)> = papers.iter().map(|p| (p.key.as_str(), p.width.round() as i64, p.height.round() as i64)).collect();
// The custom size, the keyword of unknown size, the repeated Letter and a size below 72 pt are left out.
assert_eq!(
got,
[
("Letter", 612, 792),
("A4", 595, 842),
("Legal", 612, 1008),
("na_index-4x6_4x6in", 288, 432),
("iso_a5_148x210mm", 420, 595),
// CUPS names the JIS B sizes B4 and B5, and the ISO ones ISOB4 and ISOB5.
("B5", 516, 729),
("ISOB4", 709, 1001),
("om_cr80_54x85.6mm", 153, 243)
]
);
assert!(crate::print::lpoptions_papers("PageSize: \nbroken\nInputSlot: *A4\n").is_empty());
}
#[test]
fn a_queue_without_any_ppd_lists_the_media_its_ipp_attributes_report() {
let out = "\"get-printer-attributes.test\":\n\
\x20 media-default (keyword) = na_letter_8.5x11in\n\
\x20 media-supported (1setOf keyword) = na_letter_8.5x11in,iso_a4_210x297mm,custom_min_1x1in,oe_photo-l_3.5x5in,na_letter_8.5x11in\r\n\
\x20 media-ready (1setOf keyword) = iso_a5_148x210mm\n";
let papers = crate::print::ipp_papers(out);
let got: Vec<(&str, i64, i64)> = papers.iter().map(|p| (p.key.as_str(), p.width.round() as i64, p.height.round() as i64)).collect();
// Only media-supported counts; the custom range and the repeated Letter are left out.
assert_eq!(got, [("na_letter_8.5x11in", 612, 792), ("iso_a4_210x297mm", 595, 842), ("oe_photo-l_3.5x5in", 252, 360)]);
assert!(crate::print::ipp_papers("media-supported (1setOf keyword) = \n").is_empty());
}
#[test]
fn the_ipp_lookup_asks_the_scheduler_cups_uses_for_the_queue() {
use crate::print::ipp_queue_uri;
assert_eq!(ipp_queue_uri(None, None, "Office+Color").as_deref(), Some("ipp://localhost/printers/Office%2BColor"));
assert_eq!(ipp_queue_uri(Some(" "), None, "Lab").as_deref(), Some("ipp://localhost/printers/Lab"));
assert_eq!(ipp_queue_uri(Some("print.example.com:631/version=1.1"), None, "Lab").as_deref(), Some("ipp://print.example.com:631/printers/Lab"));
assert_eq!(ipp_queue_uri(Some("/run/cups/cups.sock"), None, "Lab"), None, "a domain socket has no URI");
assert_eq!(ipp_queue_uri(None, None, ""), None);
}
#[test]
fn the_ipp_lookup_uses_ipp_port_for_a_server_without_a_port() {
use crate::print::{ipp_port, ipp_queue_uri};
assert_eq!(ipp_queue_uri(Some("print.example.com"), Some(8631), "Lab").as_deref(), Some("ipp://print.example.com:8631/printers/Lab"));
assert_eq!(
ipp_queue_uri(None, Some(8631), "Lab").as_deref(),
Some("ipp://localhost/printers/Lab"),
"with no server named, CUPS uses its domain socket, not IPP_PORT"
);
assert_eq!(
ipp_queue_uri(Some("print.example.com:631"), Some(8631), "Lab").as_deref(),
Some("ipp://print.example.com:631/printers/Lab"),
"a port in the server name wins"
);
assert_eq!(ipp_queue_uri(Some("[::1]"), Some(8631), "Lab").as_deref(), Some("ipp://[::1]:8631/printers/Lab"));
assert_eq!(ipp_queue_uri(Some("[::1]:632"), Some(8631), "Lab").as_deref(), Some("ipp://[::1]:632/printers/Lab"));
assert_eq!(ipp_port(Some("8631")), Some(8631));
for invalid in [None, Some(""), Some("0"), Some("70000"), Some("ipp")] {
assert_eq!(ipp_port(invalid), None, "{invalid:?}");
}
assert_eq!(ipp_queue_uri(Some("print.example.com"), ipp_port(Some("x")), "Lab").as_deref(), Some("ipp://print.example.com/printers/Lab"));
}
/// What the paper-keyword service was asked to print on: each job's paper.
type SentPapers = Rc<RefCell<Vec<Option<String>>>>;
/// One printer, Card, whose driver lists US Letter and a CR80 card, and which keeps each job's paper keyword.
struct KeywordPrint(SentPapers, bool);
impl PrintService for KeywordPrint {
fn applies_paper(&self) -> bool {
self.1
}
fn printers(&mut self) -> Vec<Printer> {
vec![Printer::new("Card").is_default(true), Printer::new("Slow")]
}
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
self.0.borrow_mut().push(job.paper.map(str::to_string));
Ok("Sent".into())
}
fn papers(&mut self, printer: &str, _fresh: bool) -> Papers {
if printer == "Slow" {
return Papers::Pending;
}
let paper = |key: &str, label: &str, width, height| crate::print::Paper { key: key.into(), label: label.into(), width, height };
Papers::Ready(vec![paper("Letter", "US Letter", 612.0, 792.0), paper("CR80", "CR80 Card", 153.0, 243.0)])
}
}
#[test]
fn windows_paper_sizes_that_share_a_name_are_all_listed() {
// A driver form whose name looks like a size suffix is a size of its own.
@@ -684,6 +785,77 @@ impl PrintService for WindowsForms {
}
}
#[test]
fn the_job_asks_the_queue_for_the_driver_paper_chosen() {
let sent = SentPapers::default();
let services = Services { print: Some(Box::new(KeywordPrint(sent.clone(), true))), ..Default::default() };
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
for (media, keyword) in [("printer:CR80", Some("CR80")), ("letter", Some("Letter")), ("custom", None)] {
app.run("file.print", json!({})).unwrap();
pump(&mut app);
set(&mut app, "media", json!(media));
pump(&mut app);
confirm(&mut app);
assert!(!is_open(&app));
assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), keyword, "{media}");
}
assert_eq!(sent.borrow().len(), 3);
// Printing to Slow is refused while its paper sizes are still loading.
app.run("file.print", json!({})).unwrap();
pump(&mut app);
set(&mut app, "media", json!("letter"));
set(&mut app, "printer", json!("Slow"));
pump(&mut app);
confirm(&mut app);
assert!(is_open(&app));
assert_eq!(sent.borrow().len(), 3);
call(&mut app, "ui.dialog.cancel", json!({}));
// Without the dialog, the keyword is given as `paper`, and anything else is refused before printing.
app.run("file.print", json!({"printer": "Card", "paper": "iso_a4_210x297mm"})).unwrap();
assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), Some("iso_a4_210x297mm"));
for bad in [json!("US Letter"), json!(""), json!("a=b"), json!("Letter,Tray1"), json!("Let'ter"), json!("Let\\ter"), json!(4)] {
assert!(app.run("file.print", json!({"printer": "Card", "paper": bad})).is_err(), "{bad}");
}
assert!(app.run("file.print", json!({"toFile": true, "paper": "Letter"})).is_err());
assert_eq!(sent.borrow().len(), 4, "no refused job was sent");
}
#[test]
fn a_job_without_a_paper_keyword_prints_while_the_paper_lookup_is_pending() {
let sent = SentPapers::default();
let services = Services { print: Some(Box::new(KeywordPrint(sent.clone(), false))), ..Default::default() };
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
app.run("file.print", json!({})).unwrap();
pump(&mut app);
set(&mut app, "printer", json!("Slow"));
pump(&mut app);
confirm(&mut app);
assert!(!is_open(&app));
assert_eq!(*sent.borrow(), [None]);
}
struct PendingKeywordPrint(Rc<Cell<bool>>, SentPapers);
impl PrintService for PendingKeywordPrint {
fn printers(&mut self) -> Vec<Printer> {
PendingTwin(self.0.clone()).printers()
}
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
KeywordPrint(self.1.clone(), true).print(job)
}
fn applies_paper(&self) -> bool {
true
}
fn papers(&mut self, printer: &str, fresh: bool) -> Papers {
PendingTwin(self.0.clone()).papers(printer, fresh)
}
}
#[test]
fn distinct_windows_sizes_matching_one_built_in_size_are_selectable() {
let out = "11\tA5\t582\t827\n11\tA5\t583\t827\n";
@@ -706,6 +878,41 @@ fn distinct_windows_sizes_matching_one_built_in_size_are_selectable() {
}
}
#[test]
fn a_held_print_keeps_the_paper_keyword_when_the_lookup_finishes() {
let ready = Rc::new(Cell::new(false));
let sent = SentPapers::default();
let services = Services { print: Some(Box::new(PendingKeywordPrint(ready.clone(), sent.clone()))), ..Default::default() };
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
app.run("file.print", json!({})).unwrap();
pump(&mut app);
set(&mut app, "media", json!("printer:CR80"));
pump(&mut app);
set(&mut app, "printer", json!("Twin"));
pump(&mut app);
let ctx = ctx(&app);
let (id, _) = top(&app).expect("the print dialog is open");
let _ = app.dialogs().expect("a window host").with(|host| host.confirm_by_id(&ctx, id));
ready.set(true);
pump(&mut app);
pump(&mut app);
assert!(!is_open(&app));
assert_eq!(*sent.borrow(), [Some("CR80".to_string())]);
}
#[test]
fn an_explicit_paper_is_refused_when_the_print_path_cannot_apply_it() {
let (mut app, jobs) = app();
assert!(app.run("file.print", json!({"paper": "Letter"})).is_err());
assert!(jobs.borrow().is_empty());
let sent = SentPapers::default();
app.services.print = Some(Box::new(KeywordPrint(sent.clone(), true)));
assert!(app.run("file.print", json!({"paper": "Letter", "directPdf": true})).is_err());
assert!(sent.borrow().is_empty());
}
#[test]
fn windows_forms_stay_selected_when_queue_enumeration_order_changes() {
for out in ["256\tCustom\t400\t600\n256\tCustom\t500\t700\n", "11\tA5\t582\t827\n11\tA5\t583\t827\n"] {
+1 -1
View File
@@ -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; 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}",
"{} 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), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), 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",
+143 -4
View File
@@ -13,6 +13,7 @@
use serde_json::{Value, json};
use vectorcraft_engine::cmd::fileio;
use vectorcraft_engine::script::printing::{PreparedPrint, Printers};
use vectorcraft_pdf::Media;
use crate::{VectorcraftApp, io};
@@ -25,6 +26,9 @@ pub struct PrintJob<'a> {
/// The job's name in the print queue.
pub title: &'a str,
pub pdf: &'a [u8],
/// The printer driver's keyword for the paper the job prints on (`Letter`, `CR80`, `iso_a4_210x297mm`), sent to
/// CUPS as the job's `media`; `None` leaves the paper to the queue.
pub paper: Option<&'a str>,
/// Send the PDF to the printer's own PDF interpreter over its RAW TCP port instead of
/// spooling it through the platform driver (Windows).
pub direct_pdf: bool,
@@ -42,6 +46,10 @@ pub trait PrintService {
fn printers(&mut self) -> Vec<Printer>;
/// Send `job` to its printer → what happened, for the status bar.
fn print(&mut self, job: &PrintJob) -> Result<String, String>;
/// Whether the service applies the job's paper keyword when printing through the driver.
fn applies_paper(&self) -> bool {
false
}
/// Desktop services can submit on the existing background worker; browser services stay
/// on the UI thread to invoke their print dialog.
fn shared_print(&self) -> Option<SharedPrintFn> {
@@ -194,6 +202,118 @@ pub fn windows_papers(out: &str) -> Vec<Paper> {
papers
}
/// The paper sizes of a queue that has no local PPD, from `lpoptions -p NAME -l` (`PageSize/Media Size: *Letter A4
/// na_legal_8.5x14in`), which asks the queue's server: each choice of its `PageSize` or `media` line, sized by a PWG
/// self-describing name (`iso_a4_210x297mm`, `na_letter_8.5x11in`) or by one of the dialog's own paper names. Custom
/// sizes (`Custom.WxH`), keywords of unknown size and the limits of [`ppd_papers`] are left out.
pub fn lpoptions_papers(out: &str) -> Vec<Paper> {
let mut papers: Vec<Paper> = Vec::new();
for line in out.lines() {
let Some((head, choices)) = line.trim_end_matches('\r').split_once(':') else { continue };
let key = head.split('/').next().unwrap_or_default().trim();
if !key.eq_ignore_ascii_case("PageSize") && !key.eq_ignore_ascii_case("media") {
continue;
}
for choice in choices.split_whitespace().map(|c| c.trim_start_matches('*')) {
if !is_paper_keyword(choice) || choice.get(..7).is_some_and(|p| p.eq_ignore_ascii_case("custom.")) {
continue;
}
let size = pwg_size(choice).or_else(|| cups_b_size(choice)).or_else(|| Media::from_name(choice).and_then(Media::size));
if let Some((width, height)) = size {
push_paper(&mut papers, Paper { key: choice.into(), label: choice.into(), width, height });
}
}
}
papers
}
/// The IPP URI of the queue `printer` on the CUPS scheduler `server` (`CUPS_SERVER` or a `ServerName`: `host`,
/// `host:port`, `host:port/version=1.1`; `None` or empty for this machine's). `None` for a domain-socket server (a path),
/// which `ipptool` can't reach by URI. A server named without a port of its own gets `port` (from [`ipp_port`]) when
/// there is one; a bracketed IPv6 host (`[::1]`) has a port only after its `]`. With no server named, the URI is
/// `localhost` on the IPP default port, for a CUPS that reaches its own scheduler through its domain socket; a caller
/// whose CUPS has no socket names `localhost` to get `port`. The queue name is percent-encoded.
pub fn ipp_queue_uri(server: Option<&str>, port: Option<u16>, printer: &str) -> Option<String> {
let named = server.map(str::trim).filter(|s| !s.is_empty());
let port = if named.is_some() { port } else { None };
let server = named.unwrap_or("localhost");
if server.starts_with('/') || printer.is_empty() {
return None;
}
let host = server.split('/').next().unwrap_or_default();
if host.is_empty() || host.contains(['@', '?', '#', ' ']) {
return None;
}
let mut name = String::new();
for b in printer.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
name.push(char::from(b));
} else {
name.push_str(&format!("%{b:02X}"));
}
}
let has_port = match host.strip_prefix('[') {
Some(rest) => rest.split_once(']').is_some_and(|(_, after)| after.starts_with(':')),
None => host.contains(':'),
};
let port = match port {
Some(port) if !has_port => format!(":{port}"),
_ => String::new(),
};
Some(format!("ipp://{host}{port}/printers/{name}"))
}
/// The port CUPS clients use for a server named without one, from the value of `IPP_PORT`: `None` when it is unset,
/// empty or not a port number from 1 to 65535.
pub fn ipp_port(value: Option<&str>) -> Option<u16> {
value.and_then(|v| v.trim().parse::<u16>().ok()).filter(|p| *p != 0)
}
/// The size in points of a CUPS PPD keyword for a B size: `B4` and `B5` are the JIS sizes, `ISOB4` and `ISOB5` the ISO
/// ones.
fn cups_b_size(keyword: &str) -> Option<(f64, f64)> {
let mm = match keyword.to_ascii_uppercase().as_str() {
"B4" => (257.0, 364.0),
"B5" => (182.0, 257.0),
"ISOB4" => (250.0, 353.0),
"ISOB5" => (176.0, 250.0),
_ => return None,
};
Some((mm.0 * 72.0 / 25.4, mm.1 * 72.0 / 25.4))
}
/// The paper sizes of a queue that serves no PPD at all, from the `media-supported` line of `ipptool -tv URI
/// get-printer-attributes.test` (`media-supported (1setOf keyword) = na_letter_8.5x11in,iso_a4_210x297mm`): each PWG
/// self-describing name, sized by its name. Custom ranges (`custom_min_…`, `custom_max_…`) and the limits of
/// [`ppd_papers`] are left out.
pub fn ipp_papers(out: &str) -> Vec<Paper> {
let mut papers: Vec<Paper> = Vec::new();
for line in out.lines() {
let Some((head, values)) = line.trim_end_matches('\r').split_once('=') else { continue };
if head.split_whitespace().next() != Some("media-supported") {
continue;
}
for name in values.split(',').map(str::trim) {
if !is_paper_keyword(name) || name.get(..7).is_some_and(|p| p.eq_ignore_ascii_case("custom_")) {
continue;
}
if let Some((width, height)) = pwg_size(name) {
push_paper(&mut papers, Paper { key: name.into(), label: name.into(), width, height });
}
}
}
papers
}
/// The size in points a PWG 5101.1 self-describing media name ends with (`_8.5x11in`, `_210x297mm`).
fn pwg_size(name: &str) -> Option<(f64, f64)> {
let dims = name.rsplit('_').next()?;
let (dims, scale) = if let Some(d) = dims.strip_suffix("mm") { (d, 72.0 / 25.4) } else { (dims.strip_suffix("in")?, 72.0) };
let (w, h) = dims.split_once('x')?;
let (w, h) = (w.parse::<f64>().ok()?, h.parse::<f64>().ok()?);
(w.is_finite() && h.is_finite()).then_some((w * scale, h * scale))
}
/// `print.printers`: the system's printers, and what the print service offers.
pub fn printers(app: &mut VectorcraftApp) -> Value {
let (printers, setup) = app.services.print.as_mut().map(|s| (s.printers(), s.has_setup())).unwrap_or_default();
@@ -282,7 +402,7 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec<PreparedPri
fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result<String, String>, jobs: &[PreparedPrint]) -> Result<Vec<String>, String> {
let mut notes = Vec::new();
for (sent, job) in jobs.iter().enumerate() {
match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, direct_pdf: false }) {
match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, paper: None, direct_pdf: false }) {
Ok(note) => notes.push(note),
Err(e) if sent == 0 => return Err(e),
Err(e) => return Err(format!("{e} ({sent} of {} print jobs were sent)", jobs.len())),
@@ -291,6 +411,21 @@ fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result<String, String>, jo
Ok(notes)
}
/// `file.print`'s `paper`: the printer driver's keyword for the paper (absent or null: none). Anything but printable
/// ASCII without spaces, `,`, `/`, `:`, `=`, `"`, `'` or `\`, up to 64 characters, is an error.
fn paper_param(p: &Value) -> Result<Option<String>, String> {
match p.get("paper") {
None | Some(Value::Null) => Ok(None),
Some(Value::String(k)) if is_paper_keyword(k) => Ok(Some(k.clone())),
Some(v) => Err(format!("paper must be a printer driver's paper keyword, such as `Letter` or `CR80`, not {v}")),
}
}
/// A driver's paper keyword: 1 to 64 printable ASCII characters other than space, `,`, `/`, `:`, `=`, `"`, `'` and `\`.
pub fn is_paper_keyword(k: &str) -> bool {
!k.is_empty() && k.len() <= 64 && k.bytes().all(|b| b.is_ascii_graphic() && !matches!(b, b',' | b'/' | b':' | b'=' | b'"' | b'\'' | b'\\'))
}
/// `file.print` with settings: print the active document with `settings` (over the document's, or
/// over those of the print preset `preset` names) on `printer` (default: the system's default), or
/// save the job as a PDF at `path` (else a picked file, the web downloads it) with `toFile`, a
@@ -301,6 +436,11 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string);
let postscript = s("format").as_deref() == Some("postscript") || s("path").is_some_and(|path| fileio::extension(&path) == "ps");
let to_file = p.get("toFile").and_then(Value::as_bool).unwrap_or(false) || s("path").is_some() || postscript;
let paper = paper_param(p)?;
let direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false);
if paper.is_some() && (to_file || direct_pdf || !app.services.print.as_ref().is_some_and(|s| s.applies_paper())) {
return Err("The print service cannot apply a paper keyword for this job.".into());
}
let mut q = json!({});
for k in ["preset", "settings", "format", "level", "flattenerPreset", "maxPages"] {
// An explicit null `maxPages` goes on, so the engine rejects it instead of printing every page.
@@ -338,7 +478,6 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let pdf = data.as_ref().and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or("the print job has no data")?;
let title = app.session.active().map(|d| d.title()).unwrap_or_default();
let printer = s("printer").filter(|n| !n.is_empty());
let direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false);
let service = app.services.print.as_mut().ok_or("no print service")?;
if let Some(submit) = service.shared_print() {
let pending_printer = printer.clone();
@@ -348,7 +487,7 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
format!("Printing {title}"),
None,
move |_| {
submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf })
submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, paper: paper.as_deref(), direct_pdf })
.map(|note| json!({ "note": note, "printer": printer }))
},
move |app, result| {
@@ -370,7 +509,7 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
}
return Ok(v);
}
let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf })?;
let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, paper: paper.as_deref(), direct_pdf })?;
app.status(done);
v["printer"] = json!(printer);
v["printed"] = json!(true);
+10 -1
View File
@@ -13522,7 +13522,16 @@ prints at most that many pages, copies counted; with more, `file.print` composes
`{pages, format}`. A composite job without `skipBlank` that prints its artboards is counted on the artboards before
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.
default printer) or, with `toFile`, a `path` or no printing available, saves the PDF. `paper` names the printer
driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its
`media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is
not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or
remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket,
`localhost`, `127.0.0.1` or `::1` (each with no port or port 631), lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes
of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux,
`client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is
asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. CUPS's own domain socket named as the
server is asked as `localhost` on port 631; another socket path is not asked.
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.