diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 6546b2ff5b..5bebc27656 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -181,7 +181,7 @@ fn media_choices(papers: &[Paper], current: &str) -> Vec<(String, String)> { } else { let mut out: Vec<(String, String)> = Vec::new(); for p in papers { - let id = own_media_of(p).map_or_else(|| format!("{PRINTER_PAPER}{}", p.key), |m| m.id().to_string()); + let id = own_media_choice(p, papers).map_or_else(|| format!("{PRINTER_PAPER}{}", p.key), |m| m.id().to_string()); if out.iter().all(|(i, _)| *i != id) { out.push((id, p.label.clone())); } @@ -203,6 +203,13 @@ fn own_media_of(p: &Paper) -> Option { Media::ALL.iter().copied().find(|m| m.size().is_some_and(|(mw, mh)| (mw.min(mh) - w).abs() <= 0.5 && (mw.max(mh) - h).abs() <= 0.5)) } +/// [`own_media_of`] `p`, unless another of `papers` with a different size matches the same size: both then stay +/// the printer's own papers. +fn own_media_choice(p: &Paper, papers: &[Paper]) -> Option { + let own = own_media_of(p)?; + (!papers.iter().any(|q| own_media_of(q) == Some(own) && (q.width, q.height) != (p.width, p.height))).then_some(own) +} + /// The printer's paper the Size row names (`printer:CR80`), when it is one of `papers`. fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a Paper> { let key = fields.text("media")?.strip_prefix(PRINTER_PAPER)?; @@ -521,7 +528,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, if let Some(new) = printer_paper(fields, &open.papers.1) && chosen.as_ref().is_none_or(|old| same_size(old, new)) { - let own = own_media_of(new)?; + let own = own_media_choice(new, &open.papers.1)?; fields.set("media", own.id()); return Some((own.id().to_string(), settings(fields))); } diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index d2ebf74122..131de851bd 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -650,6 +650,110 @@ 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 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. + let out = "256\tCustom\t400\t600\r\n256\tCustom\t500\t1181\r\n256\tCustom\t400\t600\r\n256\tCustom 500x1181\t520\t720\r\n\ + 256\tCustom (4 x 6 in)\t300\t300\r\n"; + let papers = crate::print::windows_papers(out); + let labels: Vec<&str> = papers.iter().map(|p| p.label.as_str()).collect(); + // Both sizes named Custom are listed, with their sizes; the repeat of the first size is left out, + // and a shown name another form already has gets a number. + assert_eq!(labels, ["Custom (4 x 6 in) 2", "Custom (5 x 11.81 in)", "Custom 500x1181", "Custom (4 x 6 in)"]); + let mut keys: Vec<&str> = papers.iter().map(|p| p.key.as_str()).collect(); + keys.sort_unstable(); + keys.dedup(); + assert_eq!(keys.len(), 4, "{keys:?}"); + assert!((papers[1].width - 360.0).abs() < 1e-9 && (papers[1].height - 850.32).abs() < 1e-9); +} + +struct WindowsForms(&'static str); + +impl PrintService for WindowsForms { + fn printers(&mut self) -> Vec { + vec![Printer::new("Forward").is_default(true), Printer::new("Reverse")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { + let out = if printer == "Reverse" { self.0.lines().rev().collect::>().join("\n") } else { self.0.to_string() }; + Papers::Ready(crate::print::windows_papers(&out)) + } +} + +#[test] +fn distinct_windows_sizes_matching_one_built_in_size_are_selectable() { + let out = "11\tA5\t582\t827\n11\tA5\t583\t827\n"; + let papers = crate::print::windows_papers(out); + assert_eq!(papers.len(), 2); + assert!(papers[0].width < papers[1].width); + assert_eq!(papers[0].height, papers[1].height); + let services = Services { print: Some(Box::new(WindowsForms(out))), ..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); + for paper in &papers { + let media = format!("printer:{}", paper.key); + set(&mut app, "media", json!(media)); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], media); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(paper.width), Some(paper.height)), "{f}"); + } +} + +#[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"] { + let papers = crate::print::windows_papers(out); + let reverse = crate::print::windows_papers(&out.lines().rev().collect::>().join("\n")); + for paper in &papers { + let other = reverse.iter().find(|p| (p.width, p.height) == (paper.width, paper.height)).unwrap(); + assert_eq!(paper.key, other.key); + } + let services = Services { print: Some(Box::new(WindowsForms(out))), ..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); + for paper in &papers { + set(&mut app, "printer", json!("Forward")); + pump(&mut app); + let media = format!("printer:{}", paper.key); + set(&mut app, "media", json!(media)); + pump(&mut app); + set(&mut app, "printer", json!("Reverse")); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], media); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(paper.width), Some(paper.height)), "{f}"); + } + } +} + +#[test] +fn long_windows_paper_labels_keep_dimensions_and_collision_numbers() { + let name = "é".repeat(128); + let suffix = " (4 x 6 in)"; + let prefix: String = name.chars().take(128 - suffix.chars().count()).collect(); + let collision = format!("{prefix}{suffix}"); + let out = format!("256\t{name}\t400\t600\n256\t{name}\t500\t700\n256\t{collision}\t300\t300\n"); + let papers = crate::print::windows_papers(&out); + assert_eq!(papers.len(), 3); + assert!(papers.iter().all(|p| p.label.chars().count() <= 128)); + assert!(papers[0].label.ends_with(" (4 x 6 in) 2"), "{:?}", papers[0]); + assert!(papers[1].label.ends_with(" (5 x 7 in)"), "{:?}", papers[1]); + assert_eq!(papers[2].label, collision); + for (i, paper) in papers.iter().enumerate() { + assert!(papers[i + 1..].iter().all(|p| p.label != paper.label)); + } +} + /// A print queue that puts each page on the paper as it is, as `lp` does. struct UprightQueue(Jobs); diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 0451cb5b5c..c1ab63a121 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -141,7 +141,9 @@ pub fn ppd_papers(ppd: &str) -> Vec { } /// 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. +/// printer settings list them (`PrinterSettings.PaperSizes`). The same limits as [`ppd_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 { let mut papers: Vec = Vec::new(); for line in out.lines() { @@ -150,9 +152,37 @@ pub fn windows_papers(out: &str) -> Vec { let (Ok(w), Ok(h)) = (w.parse::(), h.parse::()) else { continue }; if !key.is_empty() { let label = if label.is_empty() { key } else { label }; - push_paper(&mut papers, Paper { key: label.into(), label: label.into(), width: w * 0.72, height: h * 0.72 }); + let (width, height) = (w * 0.72, h * 0.72); + let key = format!("{label}\t{w}x{h}"); + push_paper(&mut papers, Paper { key, label: label.into(), width, height }); } } + // Sizes that share a name show their size in inches after it. + // A shown name that is still another paper's gets a number after it. + let names: Vec = papers.iter().map(|p| p.key.split('\t').next().unwrap_or_default().to_string()).collect(); + let inches = |pt: f64| (pt / 0.72).round() / 100.0; + for i in 0..papers.len() { + if names.iter().filter(|n| **n == names[i]).count() < 2 { + papers[i].key = names[i].clone(); + continue; + } + let p = &papers[i]; + let suffix = format!(" ({} x {} {})", inches(p.width), inches(p.height), tl!("in")); + let with_suffix = |suffix: &str| { + let name: String = names[i].chars().take(MAX_PAPER_LABEL.saturating_sub(suffix.chars().count())).collect(); + format!("{name}{suffix}") + }; + let shown = |label: &str| { + papers.iter().enumerate().any(|(j, q)| j != i && q.label.chars().take(MAX_PAPER_LABEL).eq(label.chars().take(MAX_PAPER_LABEL))) + }; + let mut label = with_suffix(&suffix); + let mut n = 2; + while shown(&label) && n < MAX_PAPERS + 2 { + label = with_suffix(&format!("{suffix} {n}")); + n += 1; + } + papers[i].label = label.chars().take(MAX_PAPER_LABEL).collect(); + } papers }