From a67a8b5edd4a2dcf74bd80d9a5e5c2ca693e3efd Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:41:14 +0300 Subject: [PATCH] engine: check a paper's margins against its own axis (#1266) * engine: check a paper's margins against its own axis * doc: turn a paper's margins with the sheet when it is stored portrait * fmt: keep plotters.rs rustfmt-clean * engine: turn a device paper's margins to the page's orientation * engine: turn a page's margins when only its orientation changes PAGESETUP sets `landscape` before `page_device`, but a command that names no paper copies no device paper, so the retained margins stayed on the old sheet's axes and Sheet::from_page refused them on the new orientation, falling back to the whole sheet. Turn them with the page, using the inverse of the rotation `set_paper` applies. * engine: an orientation-only pagesetup turns the retained margins the way the page turns --------- Co-authored-by: midasmatterhorn <236787783+midasmatterhorn@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/doc/src/plotter.rs | 15 +++- crates/engine/src/cmd/layout.rs | 16 +++- crates/engine/src/cmd/plotters.rs | 44 +++++++++-- crates/engine/tests/plotters.rs | 126 ++++++++++++++++++++++++++++++ 4 files changed, 188 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/plotter.rs b/crates/doc/src/plotter.rs index abcdb9903..ca8d75610 100644 --- a/crates/doc/src/plotter.rs +++ b/crates/doc/src/plotter.rs @@ -79,15 +79,21 @@ impl Default for DevicePaper { impl DevicePaper { /// The paper with hostile values fixed: finite sizes within 1..=[`MAX_PAPER_MM`] mm /// (portrait), margins 0..=1000 mm that leave a printable area (else none), a name of at - /// most [`MAX_PLOTTER_NAME`] characters. + /// most [`MAX_PLOTTER_NAME`] characters. A sheet wider than tall is stored turned 90° and + /// its margins turn with it, so the printable area the caller measured against the sheet it + /// named is the one the stored portrait paper holds. pub fn sanitized(mut self) -> DevicePaper { let side = |v: f64| if v.is_finite() { v.clamp(1.0, MAX_PAPER_MM) } else { 1.0 }; let (w, h) = (side(self.width), side(self.height)); - self.width = w.min(h); - self.height = w.max(h); for m in &mut self.margins { *m = if m.is_finite() { m.clamp(0.0, 1000.0) } else { 0.0 }; } + if w > h { + let [l, b, r, t] = self.margins; + self.margins = [b, r, t, l]; + } + self.width = w.min(h); + self.height = w.max(h); let [l, b, r, t] = self.margins; if l + r >= self.width || b + t >= self.height { self.margins = [0.0; 4]; @@ -243,6 +249,9 @@ mod tests { assert_eq!(back.papers[1].margins, [0.0, 1000.0, 0.0, 5.0], "hostile margins clamped"); let wide = DevicePaper { margins: [150.0, 0.0, 100.0, 0.0], ..DevicePaper::default() }.sanitized(); assert_eq!(wide.margins, [0.0; 4], "margins wider than the paper are dropped"); + let turned = DevicePaper { name: "Banner".into(), width: 400.0, height: 200.0, margins: [150.0, 0.0, 150.0, 0.0] }.sanitized(); + assert_eq!((turned.width, turned.height), (200.0, 400.0), "portrait"); + assert_eq!(turned.margins, [0.0, 150.0, 0.0, 150.0], "margins turn with the sheet"); assert!(back.paper("a3 BORDERLESS").is_some()); assert!(PlotterConfig::from_file_text("{}").is_err()); assert!(PlotterConfig::from_file_text(r#"{"cadcraftPlotter": 1}"#).is_err(), "needs a name"); diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 7e42eb269..cf09d22f0 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -683,8 +683,21 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result { // The standard size the layout had before this call, so that resubmitting it (the Plot // dialog's Apply to Layout always sends `paper`) keeps the layout's paper units. let old_paper = cadcraft_render::paper_size(&page.paper).map(|ps| ps.name); + let turned = p.get("landscape").and_then(Value::as_bool).filter(|l| *l != page.landscape); + // The orientation first: a paper taken from a device turns its margins to the sheet the page + // names when `page_device` copies them. + if let Some(l) = turned { + page.landscape = l; + } // A plotter's own papers (with their printable areas) come first. let device_paper = super::plotters::page_device(cmd, p, &mut page)?; + // A page that keeps its paper keeps its margins, and the margins are measured against the + // sheet's axes: turning the orientation turns them too (#1266). Explicit margins are already + // on the new sheet's axes. + if turned.is_some() && !device_paper && p.get("margins").is_none() { + page.margins_mm = + if page.landscape { super::plotters::landscape_margins(page.margins_mm) } else { super::plotters::portrait_margins(page.margins_mm) }; + } if let Some(paper) = p.get("paper").filter(|_| !device_paper) { let n = paper.as_str().ok_or_else(|| bad(cmd, "`paper` must be a paper name"))?; let ps = cadcraft_render::paper_size(n).ok_or_else(|| { @@ -723,9 +736,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result { (None, None) if p.get("width").is_none() && p.get("height").is_none() => {} _ => return Err(bad(cmd, "`width` and `height` (mm, 0-5080) are both required for a custom size")), } - if let Some(l) = p.get("landscape").and_then(Value::as_bool) { - page.landscape = l; - } // Paper units: what one paper-space unit is on this layout, whatever the paper's own family // (an ARCH D sheet can be drawn in millimetres, #3249). if let Some(v) = p.get("paperUnits") { diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index 9208c2a0f..e687669a7 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -215,11 +215,25 @@ fn device_paper<'a>(dev: &'a PlotterConfig, name: &str) -> Option<&'a DevicePape dev.paper(name).or_else(|| dev.paper(cadcraft_render::paper_size(name)?.name)) } +/// A paper's stored portrait margins on the landscape sheet: the sheet's axes swap, so left and +/// right become bottom and top (#1266). +pub(crate) fn landscape_margins([l, b, r, t]: [f64; 4]) -> [f64; 4] { + [t, l, b, r] +} + +/// The inverse: a landscape page's margins on the stored portrait sheet, for a page that keeps +/// its paper when its orientation turns (#1266). +pub(crate) fn portrait_margins([l, b, r, t]: [f64; 4]) -> [f64; 4] { + [b, r, t, l] +} + fn set_paper(page: &mut PageSetup, p: &DevicePaper) { page.paper = p.name.clone(); page.width_mm = p.width; page.height_mm = p.height; - page.margins_mm = p.margins; + // The paper keeps its margins for its stored portrait sheet; the page measures them against + // the sheet in the orientation it names, so they turn with it (#1266). + page.margins_mm = if page.landscape { landscape_margins(p.margins) } else { p.margins }; } fn unknown_device(cmd: &str, name: &str) -> EngineError { @@ -354,9 +368,16 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result { o.remove("paper"); o.insert("width".into(), json!(pp.width)); o.insert("height".into(), json!(pp.height)); - o.insert("margins".into(), json!(pp.margins)); + // The paper's margins belong to its stored portrait sheet; the plot draws on the sheet in + // the orientation it names, so they turn to it (#1266). + let landscape = p.get("landscape").and_then(Value::as_bool).unwrap_or_else(|| match &layout { + Some(pg) => pg.landscape, + None => dev.orientation == Orientation::Landscape, + }); + let [l, b, r, t] = pp.margins; + o.insert("margins".into(), json!(if landscape { [t, l, b, r] } else { [l, b, r, t] })); if p.get("landscape").is_none() && layout.is_none() { - o.insert("landscape".into(), json!(dev.orientation == Orientation::Landscape)); + o.insert("landscape".into(), json!(landscape)); } } Ok(out) @@ -527,13 +548,22 @@ fn edit_device(cmd: &str, c: &mut PlotterConfig, p: &Value) -> Result<()> { _ => return Err(bad(cmd, "`paper.width` and `paper.height` (mm) are both required")), }; let margins = match pv.get("margins") { - None => existing.as_ref().map(|e| e.margins).unwrap_or([0.0; 4]), + None => match existing.as_ref() { + // Stored margins belong to the stored portrait sheet; naming the same sheet + // landscape turns them back, so re-saving a paper does not refuse its own + // margins. + // Naming the sheet landscape turns the stored portrait margins to it, whatever + // its new sides: sanitization turns them back for the stored (portrait) sheet. + Some(e) if w > h => { + let [l, b, r, t] = e.margins; + [t, l, b, r] + } + _ => existing.as_ref().map(|e| e.margins).unwrap_or([0.0; 4]), + }, Some(m) => { let a: Vec = m.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default(); match a[..] { - [l, b, r, t] if a.iter().all(|v| v.is_finite() && (0.0..=1000.0).contains(v)) && l + r < w.min(h) && b + t < w.max(h) => { - [l, b, r, t] - } + [l, b, r, t] if a.iter().all(|v| v.is_finite() && (0.0..=1000.0).contains(v)) && l + r < w && b + t < h => [l, b, r, t], _ => return Err(bad(cmd, "`paper.margins` must be [left, bottom, right, top] in mm, leaving a printable area")), } } diff --git a/crates/engine/tests/plotters.rs b/crates/engine/tests/plotters.rs index 81aea1221..3c642b136 100644 --- a/crates/engine/tests/plotters.rs +++ b/crates/engine/tests/plotters.rs @@ -117,6 +117,108 @@ fn page_setup_takes_a_device_and_its_papers() { assert!(report["devices"].as_array().unwrap().iter().any(|d| d == "Plan Printer")); } +#[test] +/// A paper stored portrait keeps its printable area when the page names it landscape: the margins +/// turn back to the axes the user gave, and PLOT hands them on that way (#1266). +fn a_landscape_page_gets_the_papers_margins_back() { + let mut s = session(); + s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "pdf"})).unwrap(); + let paper = json!({"name": "Banner", "width": 400, "height": 200, "margins": [150, 0, 150, 0]}); + s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": paper})).unwrap(); + // Stored portrait, 200 x 400, the side margins on the long axis. + let stored = |s: &mut Session| { + let r = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap(); + r["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").cloned().unwrap() + }; + let p = stored(&mut s); + assert_eq!((p["width"].as_f64(), p["height"].as_f64()), (Some(200.0), Some(400.0))); + assert_eq!(p["margins"], json!([0.0, 150.0, 0.0, 150.0])); + + s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Banner Printer", "paper": "Banner", "landscape": true})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (200.0, 400.0, [150.0, 0.0, 150.0, 0.0])); + // The 400 x 200 sheet's printable area is 100 x 200 mm, not the whole sheet. + let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap(); + let mm = |v: f64| v * sheet.unit_mm; + assert_eq!((mm(sheet.size.x), mm(sheet.size.y)), (400.0, 200.0)); + assert_eq!((mm(sheet.printable.min.x), mm(sheet.printable.min.y)), (150.0, 0.0)); + assert_eq!((mm(sheet.printable.max.x), mm(sheet.printable.max.y)), (250.0, 200.0)); + + // PLOT hands the margins on in the sheet's orientation. + let o = plotted(s.execute("plot", &json!({"layout": "Layout1", "paper": "Banner"})).unwrap()); + assert_eq!((o["width"].as_f64(), o["height"].as_f64()), (Some(200.0), Some(400.0))); + assert_eq!(o["margins"], json!([150.0, 0.0, 150.0, 0.0])); + + // Naming the paper landscape again at a new size keeps the margins' axes as well. + s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 500, "height": 200}})) + .unwrap(); + let p = stored(&mut s); + assert_eq!((p["width"].as_f64(), p["height"].as_f64()), (Some(200.0), Some(500.0))); + assert_eq!(p["margins"], json!([0.0, 150.0, 0.0, 150.0]), "the margins keep the short sides"); +} + +#[test] +/// A page set up on a landscape device paper keeps its printable area when a later PAGESETUP only +/// changes the orientation: no paper is copied, so the retained margins turn to the new sheet +/// instead of being saved against the wrong axes (#1266). +fn an_orientation_only_pagesetup_turns_the_retained_margins() { + let mut s = session(); + s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "pdf"})).unwrap(); + let paper = json!({"name": "Banner", "width": 400, "height": 200, "margins": [150, 0, 150, 0]}); + s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": paper})).unwrap(); + // The landscape page carries the margins on its 400 mm sides: 150 mm left and right. + s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Banner Printer", "paper": "Banner", "landscape": true})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (200.0, 400.0, [150.0, 0.0, 150.0, 0.0])); + + // A second command changes only the orientation. The paper is not copied and no margins are + // given, so the retained margins turn to the 200 x 400 portrait sheet: 150 mm top and bottom, + // leaving the same 100 x 200 mm printable area rather than falling back to the whole sheet. + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": false})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!((page.paper.as_str(), page.margins_mm), ("Banner", [0.0, 150.0, 0.0, 150.0])); + let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap(); + let mm = |v: f64| v * sheet.unit_mm; + assert_eq!((mm(sheet.size.x), mm(sheet.size.y)), (200.0, 400.0)); + assert_eq!((mm(sheet.printable.min.x), mm(sheet.printable.min.y)), (0.0, 150.0)); + assert_eq!((mm(sheet.printable.max.x), mm(sheet.printable.max.y)), (200.0, 250.0)); +} + +#[test] +/// Asymmetric retained margins turn with an orientation-only PAGESETUP in the direction the page +/// turns — a portrait page turning landscape re-measures them on the landscape axes, and turning +/// back restores the stored margins — so the printable area does not depend on how the +/// orientation was reached (#1266). +fn an_orientation_turn_turns_asymmetric_margins_the_way_the_page_turns() { + let mut s = session(); + // A page setup's default orientation is landscape, so the page is named portrait first. + s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A4", "landscape": false, "margins": [10, 20, 30, 80]})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (210.0, 297.0, [10.0, 20.0, 30.0, 80.0])); + + // Portrait to landscape: the margins turn the way `set_paper` turns a device paper's, so the + // 10 mm left margin becomes the landscape sheet's 80 mm top margin and the printable area is + // the same rectangle on the turned sheet. + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": true})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!(page.margins_mm, [80.0, 10.0, 20.0, 30.0], "the margins turn to the landscape axes"); + + // Landscape back to portrait restores the margins the page was set up with. + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": false})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!(page.margins_mm, [10.0, 20.0, 30.0, 80.0], "the round trip keeps the margins"); + + // A landscape page turns the other way when it goes portrait: the margins are re-measured on + // the portrait sheet's axes, and turning back gives them the landscape reading again. + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": true, "margins": [1, 2, 3, 4]})).unwrap(); + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": false})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!(page.margins_mm, [2.0, 3.0, 4.0, 1.0], "the landscape margins turn back to the portrait axes"); + s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": true})).unwrap(); + let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone(); + assert_eq!(page.margins_mm, [1.0, 2.0, 3.0, 4.0], "the second turn restores the landscape margins"); +} + #[test] /// PLOT and EXPORTPDF hand the hook the device's output, resolution, paper and margins, and a /// layout plots with its own page setup; unknown devices and papers are refused. @@ -239,3 +341,27 @@ fn plotwindow_picks_both_corners_with_ortho_on() { let c = hover(&mut s, Vec2::new(10.0, 4.0)); assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps the line horizontal: {c:?}"); } + +#[test] +fn paper_margins_are_checked_against_their_own_axis() { + let mut s = session(); + s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "png"})).unwrap(); + let paper = |margins: Value| json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200, "margins": margins}}); + // 250 mm of bottom + top margin leaves no printable height on a 200 mm paper. + assert!(s.execute("plottermanager", &paper(json!([0, 250, 0, 0]))).is_err()); + // 300 mm of left + right margin still leaves 100 mm of printable width on a 400 mm paper. + assert!(s.execute("plottermanager", &paper(json!([150, 0, 150, 0]))).is_ok()); + // The paper is stored portrait and the margins turn with it: the 100 x 200 printable area + // of the requested sheet stays 200 x 100 on the stored 200 x 400 one. + let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap(); + let banner = stored["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").unwrap().clone(); + assert_eq!((banner["width"].as_f64().unwrap(), banner["height"].as_f64().unwrap()), (200.0, 400.0)); + assert_eq!(banner["margins"], json!([0.0, 150.0, 0.0, 150.0])); + // Setting the same sheet again without margins keeps them: the stored margins belong to the + // portrait sheet and turn back before the per-axis check. + s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200}})) + .unwrap(); + let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap(); + let banner = stored["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").unwrap().clone(); + assert_eq!(banner["margins"], json!([0.0, 150.0, 0.0, 150.0])); +}