Use the shared CUPS catalog for VectorCraft paper choices

Preserve the application paper-editor limits and exact media keys through the existing lp submission. Replace the app-local discovery contributed by dotCooCoo in #10581 with its shared implementation and keep adapter coverage for the driver choices.
This commit is contained in:
Codex committed 2026-12-02 21:32:48 +01:00
1 parent c77e8a9c26
commit 2145405a3a
4 files changed
+36 -384

No files matched your search

+8 -150
View File
@@ -148,146 +148,22 @@ mod system {
pub fn printers() -> Vec<Printer> {
craft::print::printers().into_iter().map(Printer::from).collect()
}
/// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings.
/// The paper sizes of an installed printer, discovered on the worker by craft-print.
pub fn papers(printer: &str) -> Vec<Paper> {
#[cfg(windows)]
{
let forms = craft::print::printer_papers(printer);
vectorcraft_ui_egui::print::windows_driver_papers(forms.into_iter().map(|form| (form.name, form.width, form.height)))
}
#[cfg(not(windows))]
#[cfg(unix)]
{
use std::io::Read as _;
// CUPS queue names never hold `/`, so the name can't leave the PPD folder.
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));
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;
}
// 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());
// With no server named, CUPS uses its domain socket when it exists, and `localhost` on `IPP_PORT` otherwise.
let server = cups_server().or_else(|| {
let sockets = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"];
(!sockets.iter().any(|s| std::path::Path::new(s).exists())).then(|| "localhost".to_string())
});
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()
let catalog = craft::print::cups::media_catalog(printer);
vectorcraft_ui_egui::print::cups_driver_papers(catalog.sizes.into_iter().map(|size| (size.key, size.label, size.width, size.height)))
}
}
/// 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)
})
}
/// 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(not(windows))]
fn paper_output(command: &mut Command) -> Option<Vec<u8>> {
use std::io::Read as _;
use std::process::Stdio;
use std::time::{Duration, Instant};
const LIMIT: Duration = Duration::from_secs(10);
let started = Instant::now();
let mut child = command.stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?;
let (send, receive) = std::sync::mpsc::channel();
let stdout = child.stdout.take();
let reader = std::thread::Builder::new().name("printer-paper-output".into()).spawn(move || {
let mut bytes = Vec::new();
// Retain at most 16 MiB, but drain the rest so the child can finish.
let read = stdout.map(|mut out| {
out.by_ref().take(16 << 20).read_to_end(&mut bytes)?;
std::io::copy(&mut out, &mut std::io::sink())
});
let _ = send.send(read.and_then(Result::ok).map(|_| bytes));
});
if reader.is_err() {
let _ = child.kill();
let _ = child.wait();
return None;
}
loop {
match child.try_wait() {
Ok(Some(status)) => {
return if status.success() { receive.recv_timeout(LIMIT.saturating_sub(started.elapsed())).ok().flatten() } else { None };
}
Ok(None) if started.elapsed() < LIMIT => std::thread::sleep(Duration::from_millis(25)),
_ => {
let _ = child.kill();
let _ = child.wait();
return None;
}
}
#[cfg(not(any(unix, windows)))]
{
let _ = printer;
Vec::new()
}
}
pub fn print(job: &PrintJob) -> Result<String, String> {
@@ -549,24 +425,6 @@ mod turn_tests {
}
}
#[cfg(all(test, not(windows)))]
mod client_conf_tests {
use super::system::client_conf_server_name;
#[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;
+18 -87
View File
@@ -617,21 +617,24 @@ fn a_preset_size_the_printer_does_not_list_stays_a_choice() {
}
#[test]
fn a_ppd_lists_its_paper_dimensions_by_name() {
let ppd = "*OpenUI *PageSize/Media Size: PickOne\r\n\
*PageSize Letter/US Letter: \"<</PageSize[612 792]>>setpagedevice\"\r\n\
*PageSize CR80/CR80 Card: \"<</PageSize[153 243]>>setpagedevice\"\r\n\
*CloseUI: *PageSize\r\n\
*PaperDimension Letter: \"612 792\"\r\n\
*PaperDimension CR80: \"153 243\"\r\n\
*PaperDimension CR80: \"100 100\"\r\n\
*PaperDimension Stamp/Stamp: \"20 20\"\r\n\
*PaperDimension Bad: \"612\"\r\n\
*PaperDimension Roll/Banner Roll: \"612 14400\"\r\n";
let papers = crate::print::ppd_papers(ppd);
let got: Vec<(&str, &str, f64, f64)> = papers.iter().map(|p| (p.key.as_str(), p.label.as_str(), p.width, p.height)).collect();
// The repeated CR80, a size below 72 pt and a line without a height are left out.
assert_eq!(got, [("Letter", "US Letter", 612.0, 792.0), ("CR80", "CR80 Card", 153.0, 243.0), ("Roll", "Banner Roll", 612.0, 14400.0)]);
fn shared_cups_forms_keep_exact_keywords_and_apply_the_paper_editor_limits() {
// The catalog's dimensions are already in points. Keep the PPD label and the exact keys
// for the distinct JIS and ISO sizes and fixed custom forms.
let sizes = [
("CR80", "CR80 Card", 153.0, 243.0),
("B5", "JIS B5", 516.0, 729.0),
("ISOB5", "ISO B5", 499.0, 709.0),
("Custom.288x432", "Driver custom form", 288.0, 432.0),
("Roll", "Banner Roll", 612.0, 14400.0),
("CR80", "Duplicate", 100.0, 100.0),
("Tiny", "Tiny Stamp", 20.0, 20.0),
("TooLong", "Very long roll", 612.0, 14401.0),
];
let papers = crate::print::cups_driver_papers(sizes.into_iter().map(|(key, label, width, height)| (key.into(), label.into(), width, height)));
assert_eq!(papers.iter().map(|p| p.key.as_str()).collect::<Vec<_>>(), ["CR80", "B5", "ISOB5", "Custom.288x432", "Roll"]);
assert_eq!(papers[0].label, "CR80 Card");
assert!(papers[1].width > papers[2].width && papers[1].height > papers[2].height);
assert_eq!((papers[3].width, papers[3].height), (288.0, 432.0));
}
#[test]
@@ -650,78 +653,6 @@ 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>>>>;
+6 -142
View File
@@ -13,7 +13,6 @@
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};
@@ -116,40 +115,17 @@ fn push_paper(papers: &mut Vec<Paper>, paper: Paper) {
}
}
/// The paper sizes of a PPD: each `*PaperDimension` entry (`*PaperDimension CR80/CR80 Card: "153 243"`), named by
/// its own label or else by the `*PageSize` entry with the same keyword. Sizes outside 72–14400 pt, repeated keywords
/// and malformed lines are skipped.
pub fn ppd_papers(ppd: &str) -> Vec<Paper> {
fn entry<'a>(line: &'a str, key: &str) -> Option<(&'a str, &'a str, &'a str)> {
let rest = line.strip_prefix('*')?.strip_prefix(key)?.strip_prefix(' ')?;
let (head, value) = rest.split_once(':')?;
let (name, label) = head.split_once('/').map_or((head.trim(), ""), |(n, l)| (n.trim(), l.trim()));
(!name.is_empty() && !name.contains(char::is_whitespace)).then_some((name, label, value.trim()))
}
let mut labels: Vec<(&str, &str)> = Vec::new();
let mut papers: Vec<Paper> = Vec::new();
for line in ppd.lines().map(|l| l.trim_end_matches('\r')) {
if let Some((name, label, _)) = entry(line, "PageSize") {
if !label.is_empty() && labels.len() < MAX_PAPERS {
labels.push((name, label));
}
} else if let Some((name, label, value)) = entry(line, "PaperDimension") {
let mut nums = value.trim_matches('"').split_whitespace().map(str::parse::<f64>);
let (Some(Ok(width)), Some(Ok(height)), None) = (nums.next(), nums.next(), nums.next()) else { continue };
push_paper(&mut papers, Paper { key: name.into(), label: label.into(), width, height });
}
}
for p in &mut papers {
if p.label.is_empty() {
let label = labels.iter().find(|(n, _)| *n == p.key).map_or(p.key.as_str(), |(_, l)| l);
p.label = label.chars().take(MAX_PAPER_LABEL).collect();
}
/// Keep CUPS queue keywords and labels, while applying the limits of VectorCraft's paper editor.
pub fn cups_driver_papers(forms: impl IntoIterator<Item = (String, String, f64, f64)>) -> Vec<Paper> {
let mut papers = Vec::new();
for (key, label, width, height) in forms {
push_paper(&mut papers, Paper { key, label, width, height });
}
papers
}
/// The paper sizes in tab-separated lines of number, name, width and height (hundredths of an inch), as Windows'
/// printer settings list them (`PrinterSettings.PaperSizes`). The same limits as [`ppd_papers`] apply. A name
/// printer settings list them (`PrinterSettings.PaperSizes`). The same limits as [`cups_driver_papers`] apply. A name
/// listed again with another size stays in the list, keyed by its name and size, and every size of that name
/// shows its size in inches after the name; one listed again with the same size is left out.
pub fn windows_papers(out: &str) -> Vec<Paper> {
@@ -209,118 +185,6 @@ pub fn windows_driver_papers(forms: impl IntoIterator<Item = (String, f64, f64)>
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();
+4 -5
View File
@@ -13268,11 +13268,10 @@ dialog, and with params it prints through the system (`printer`: a name from `pr
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) 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.
not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper.
For CUPS queues, the system's CUPS clients select the scheduler, including its configured port. VectorCraft reads
local PPD dimensions, queue options from `lpoptions -l`, and IPP media for driverless queues. For remote schedulers
the installed `ipptool` client can supplement the queue options over TLS.
```json
{"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}}