From f7a24278bb0bfdb709a9c7a06fbdc4d033c40e6e Mon Sep 17 00:00:00 2001 From: CamWight <91156642+CamWight@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:01:47 +0000 Subject: [PATCH] Drawing export: a sheet can be exported on Blueprint or Prussian Blue paper (#10679) (#10681) * Drawing export: a sheet as PNG at a chosen dpi and colour, and one reply shape (#4890 EX1) drawing.export {format: png, dpi?, colour?} writes the sheet's scene through the sheet PNG writer: 25 to 2400 dpi (300 when not given), grey, black and white, RGB or transparent (grey when not given). dpi and colour are refused on an SVG. A path must end in the format's extension, which ExportFormat::extension gives for every format. One reply shape for every format: text (SVG) or data (base64 PNG) when no path is given, in place of svg; report.pixels gives a PNG's size. A PNG held for the reply stops at 64 MiB, as an SVG does, and the refusal says to give a path; a file may be as large as the sheet needs. Co-Authored-By: Claude Opus 5.5 * Drawing export: a sheet on blue paper, in SVG and PNG (#10679) One rule for the two papers and their ink, used by both writers. White stays the default, byte for byte. A blue paper's PNG is rgb; the other colours are refused by name. A picture keeps its own colours. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../locales/pending/drawing-export-paper.json | 34 ++++ crates/engine/src/cmd/delete.rs | 5 +- crates/engine/src/cmd/drawing_export.rs | 98 ++++++++--- crates/engine/src/cmd/drawing_export_tests.rs | 153 +++++++++++++++--- crates/engine/src/drawing_pictures_tests.rs | 4 +- crates/engine/src/schema/drawing_export.rs | 84 +++++++++- crates/io/src/paper.rs | 29 +++- crates/io/src/paper/png.rs | 31 +++- crates/io/src/paper/svg.rs | 34 +++- crates/io/src/paper_tests.rs | 121 ++++++++++++++ 10 files changed, 529 insertions(+), 64 deletions(-) create mode 100644 assets/locales/pending/drawing-export-paper.json create mode 100644 crates/io/src/paper_tests.rs diff --git a/assets/locales/pending/drawing-export-paper.json b/assets/locales/pending/drawing-export-paper.json new file mode 100644 index 000000000..13843ffe5 --- /dev/null +++ b/assets/locales/pending/drawing-export-paper.json @@ -0,0 +1,34 @@ +{ + "en": { + "export.paper.blueprint": "Blueprint Blue", + "export.paper.prussian_blue": "Prussian Blue (Historical)" + }, + "ar": { + "export.paper.blueprint": "أزرق المخطط", + "export.paper.prussian_blue": "أزرق بروسي (تاريخي)" + }, + "de": { + "export.paper.blueprint": "Blaupausenblau", + "export.paper.prussian_blue": "Preußischblau (historisch)" + }, + "he": { + "export.paper.blueprint": "כחול שרטוט", + "export.paper.prussian_blue": "כחול פרוסי (היסטורי)" + }, + "ja": { + "export.paper.blueprint": "ブループリントブルー", + "export.paper.prussian_blue": "プルシアンブルー(歴史的)" + }, + "ko": { + "export.paper.blueprint": "블루프린트 블루", + "export.paper.prussian_blue": "프러시안 블루(역사적)" + }, + "vi": { + "export.paper.blueprint": "Xanh bản vẽ", + "export.paper.prussian_blue": "Xanh Phổ (lịch sử)" + }, + "zh": { + "export.paper.blueprint": "蓝图蓝", + "export.paper.prussian_blue": "普鲁士蓝(历史)" + } +} diff --git a/crates/engine/src/cmd/delete.rs b/crates/engine/src/cmd/delete.rs index 1f3186a40..f5c404db7 100644 --- a/crates/engine/src/cmd/delete.rs +++ b/crates/engine/src/cmd/delete.rs @@ -569,7 +569,8 @@ mod tests { run(&mut s, "drawing.view.edit", json!({"view": ids::encode(view), "set": {"visual_style": "visible"}})); } let sheet = ids::encode(s.drawing("test").unwrap().sheets[0].id); - let svg = run(&mut s, "drawing.export", json!({"sheet": sheet}))["svg"].clone(); + let svg = run(&mut s, "drawing.export", json!({"sheet": sheet}))["text"].clone(); + assert!(svg.is_string(), "{svg}"); let (doc, steps) = (s.doc.clone(), s.undo.len()); let reply = run(&mut s, "select.set", json!({"items": [item(drawing, front), item(drawing, dimension), item(drawing, balloon)]})); assert_eq!(reply["selected"], json!(3)); @@ -577,7 +578,7 @@ mod tests { run(&mut s, "select.set", json!({"items": [item(drawing, right)], "add": true})); assert_eq!(s.selection.len(), 4); assert!(std::sync::Arc::ptr_eq(&doc, &s.doc) && s.undo.len() == steps); - assert_eq!(run(&mut s, "drawing.export", json!({"sheet": sheet}))["svg"], svg); + assert_eq!(run(&mut s, "drawing.export", json!({"sheet": sheet}))["text"], svg); run(&mut s, "select.clear", json!({})); assert!(s.selection.is_empty()); } diff --git a/crates/engine/src/cmd/drawing_export.rs b/crates/engine/src/cmd/drawing_export.rs index 4ca0625c3..3d94a0f39 100644 --- a/crates/engine/src/cmd/drawing_export.rs +++ b/crates/engine/src/cmd/drawing_export.rs @@ -1,20 +1,24 @@ //! `drawing.export` (#4890 A7): one sheet of the open drawing written out from its scene //! ([`crate::drawing_scene::build`]), the scene the sheet page draws, so a file shows what the page -//! does. SVG for now: PNG comes with the sheet PNG writer (#4890 A4) and DXF with the shared DXF -//! writer (#5319). A sheet with a view that failed, an image that won't decode or a picture that -//! can't be drawn isn't written; the refusal names them. +//! does: SVG, or PNG at a chosen dpi and colour. DXF comes with the shared DXF writer (#5319). A +//! sheet with a view that failed, an image that won't decode or a picture that can't be drawn isn't +//! written; the refusal names them. Without a path the reply holds the document, as text or as +//! base64. Both can be on a blue paper (#10679). use std::path::Path; use serde_json::Value; +use solidcraft_doc::canvas::base64_encode; use solidcraft_doc::drawing::DEFAULT_DPI; use solidcraft_doc::ids; +use solidcraft_io::MAX_DRAWING_BYTES; +use solidcraft_io::paper::{DPI, PaperColour, PngColour, PngOptions}; use super::CommandSpec; use crate::drawing_pictures::SheetPictures; use crate::drawing_scene::{Status, sheet_id}; use crate::params::bad; -use crate::schema::drawing_export::{ExportFormat, ExportParams, ExportReport, ExportResult}; +use crate::schema::drawing_export::{ExportColour, ExportFormat, ExportParams, ExportReport, ExportResult}; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; @@ -30,24 +34,62 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Export Sheet", cr .doc_only() .contract(&CONTRACT) .output(output_schema_for::) - .params("sheet: id or name; format?: svg (default; png and dxf are not supported yet); path?: .svg file (else the reply holds the SVG text) → {sheet, format, bytes, path | svg, report: {widths_snapped, pieces_merged}, views: [{view, status: drawn|placeholder|failed, reason?, stats?}]}. The sheet as drawing.scene draws it: its drawing border, each image on it, then each view's lines, then its title block's lines. Refused, naming them, while any view on the sheet failed or any image won't decode; a placeholder view draws nothing. No model is evaluated.")]; + .params("sheet: id or name; format?: svg (default) | png (dxf is not supported yet); path?: a file with the format's extension (else the reply holds the document: text for svg, base64 data for png, at most 64 MiB); png only: dpi?: 25 to 2400 (default the sheet's own), colour?: grey (default) | black_white | rgb | transparent; paper?: white (default) | blueprint | prussian_blue, whose png is rgb → {sheet, format, bytes, path | text | data, report: {widths_snapped, pieces_merged, pixels?: [width, height]}, views: [{view, status: drawn|placeholder|failed, reason?, stats?}]}. The sheet as drawing.scene draws it: its drawing border, each image on it, then each view's lines, then its title block's lines. Refused, naming them, while any view on the sheet failed or any image won't decode; a placeholder view draws nothing. No model is evaluated.")]; + +/// A document held for the reply, refused once it passes `limit` bytes: a larger one goes to a file. +struct Held { + bytes: Vec, + limit: usize, +} + +impl std::io::Write for Held { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.bytes.len().saturating_add(buf.len()) > self.limit { + return Err(std::io::Error::other(format!("over {} MiB for the reply: give a path", self.limit >> 20))); + } + self.bytes.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} fn export(s: &mut Session, p: &Value) -> Result { let request: ExportParams = crate::schema::read(CMD, p)?; - match request.format { - ExportFormat::Svg => {} - ExportFormat::Png => return Err(bad(CMD, "not supported yet: PNG needs the sheet PNG writer (#4890 A4)")), + let d = s.drawing(CMD)?.clone(); + let sheet = sheet_id(&d, &request.sheet, CMD)?; + let paper: Option = request.paper.into(); + let png = match request.format { + ExportFormat::Svg => None, + ExportFormat::Png => { + // The sheet's own resolution unless the call gives one. + let own = d.sheets.iter().find(|s| s.id == sheet).map(|s| s.dpi); + let dpi = request.dpi.or(own).unwrap_or(PngOptions::default().dpi); + if !DPI.contains(&dpi) { + return Err(bad(CMD, "`dpi` is 25 to 2400")); + } + let colour = match (paper, request.colour) { + (None, colour) => colour.unwrap_or_default().into(), + (Some(paper), None | Some(ExportColour::Rgb)) => PngColour::On(paper), + (Some(_), Some(_)) => return Err(bad(CMD, "a blue `paper` is rgb: `grey`, `black_white` and `transparent` are for white paper")), + }; + Some(PngOptions { dpi, colour }) + } ExportFormat::Dxf => return Err(bad(CMD, "not supported yet: DXF needs the shared DXF writer (#5319)")), + }; + if png.is_none() && (request.dpi.is_some() || request.colour.is_some()) { + return Err(bad(CMD, "`dpi` and `colour` are for png only")); } + let extension = request.format.extension(); if let Some(path) = &request.path { - let svg = Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("svg")); - if path.len() > MAX_PATH_BYTES || !svg { - return Err(bad(CMD, "path must be a .svg file")); + let named = Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case(extension)); + if path.len() > MAX_PATH_BYTES || !named { + return Err(bad(CMD, format!("path must be a .{extension} file"))); } solidcraft_io::vfs::check(path).map_err(|e| EngineError::Other(e.to_string()))?; } - let d = s.drawing(CMD)?.clone(); - let sheet = sheet_id(&d, &request.sheet, CMD)?; let built = crate::drawing_scene::build(s, &d, sheet)?; let failed: Vec = built .views @@ -62,24 +104,38 @@ fn export(s: &mut Session, p: &Value) -> Result { } let prepared = built.scene.prepare().map_err(|e| bad(CMD, e.to_string()))?; let pictures = SheetPictures::new(s, &d, sheet).map_err(|e| bad(CMD, e))?; - let (svg, written) = solidcraft_io::paper::paper_svg(&prepared, &pictures, DEFAULT_DPI).map_err(|e| bad(CMD, e.to_string()))?; - let bytes = svg.len(); - let (path, svg) = match request.path { + let (document, grid, pixels) = match png { + None => { + let (svg, grid) = solidcraft_io::paper::paper_svg_on(&prepared, paper, &pictures, DEFAULT_DPI).map_err(|e| bad(CMD, e.to_string()))?; + (svg, grid, None) + } + Some(options) => { + // Bounded only for the reply: a file may be as large as the sheet needs. + let limit = if request.path.is_some() { usize::MAX } else { MAX_DRAWING_BYTES }; + let mut held = Held { bytes: Vec::new(), limit }; + let written = solidcraft_io::paper::paper_png(&prepared, options, &pictures, &mut held).map_err(|e| bad(CMD, e.to_string()))?; + (held.bytes, written.grid, Some(written.pixels)) + } + }; + let bytes = document.len(); + let (path, text, data) = match request.path { Some(path) => { // Checked again just before writing, as the view DXF does. solidcraft_io::vfs::check(&path).map_err(|e| EngineError::Other(e.to_string()))?; - solidcraft_io::write_atomic(Path::new(&path), &svg, false).map_err(|e| EngineError::Other(e.to_string()))?; - (Some(path), None) + solidcraft_io::write_atomic(Path::new(&path), &document, false).map_err(|e| EngineError::Other(e.to_string()))?; + (Some(path), None, None) } - None => (None, Some(String::from_utf8(svg).map_err(|e| EngineError::Other(e.to_string()))?)), + None if png.is_some() => (None, None, Some(base64_encode(&document))), + None => (None, Some(String::from_utf8(document).map_err(|e| EngineError::Other(e.to_string()))?), None), }; let reply = ExportResult { sheet: ids::encode(sheet), format: request.format, bytes, path, - svg, - report: ExportReport { widths_snapped: written.widths_snapped, pieces_merged: written.pieces_merged }, + text, + data, + report: ExportReport { widths_snapped: grid.widths_snapped, pieces_merged: grid.pieces_merged, pixels }, views: built.views.into_iter().map(Into::into).collect(), dimensions: super::drawing_scene::dimension_results(built.dimensions), param_warnings: Vec::new(), diff --git a/crates/engine/src/cmd/drawing_export_tests.rs b/crates/engine/src/cmd/drawing_export_tests.rs index 992cf6404..a766a49d2 100644 --- a/crates/engine/src/cmd/drawing_export_tests.rs +++ b/crates/engine/src/cmd/drawing_export_tests.rs @@ -1,6 +1,8 @@ use serde_json::{Value, json}; use solidcraft_doc::MAX_PLACEMENT_DEPTH; +use solidcraft_doc::canvas::base64_decode; use solidcraft_geom::paper::NoPictures; +use solidcraft_io::paper::{PngColour, paper_png}; use super::*; use crate::drawing_scene::tests::{front_and_top, nest}; @@ -16,11 +18,22 @@ fn refused(s: &mut Session, p: Value) -> String { s.execute(CMD, &p).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("accepted: {p}")) } +/// The scene of sheet `sheet` of the drawing open, built at once. +fn sheet_scene(s: &Session, sheet: u64) -> solidcraft_geom::paper::Scene { + let d = s.drawing("test").unwrap().clone(); + crate::drawing_scene::build(s, &d, sheet).unwrap().scene +} + /// The SVG of sheet `sheet` of the drawing open, written straight from its built scene. fn scene_svg(s: &Session, sheet: u64) -> Vec { - let d = s.drawing("test").unwrap().clone(); - let built = crate::drawing_scene::build(s, &d, sheet).unwrap(); - solidcraft_io::paper::paper_svg(&built.scene.prepare().unwrap(), &NoPictures, DEFAULT_DPI).unwrap().0 + solidcraft_io::paper::paper_svg(&sheet_scene(s, sheet).prepare().unwrap(), &NoPictures, DEFAULT_DPI).unwrap().0 +} + +/// The PNG of sheet `sheet` of the drawing open, written straight from its built scene. +fn scene_png(s: &Session, sheet: u64, options: PngOptions) -> Vec { + let mut png = Vec::new(); + paper_png(&sheet_scene(s, sheet).prepare().unwrap(), options, &NoPictures, &mut png).unwrap(); + png } /// A sheet exports as its scene's SVG, byte for byte, by id or by name: the reply holds it, with @@ -33,7 +46,7 @@ fn a_sheet_exports_as_its_scenes_svg() { let schema = output_schema_for::(); assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}"); let svg = scene_svg(&s, sheet); - assert_eq!(reply["svg"].as_str().map(str::as_bytes), Some(svg.as_slice())); + assert_eq!(reply["text"].as_str().map(str::as_bytes), Some(svg.as_slice())); assert_eq!((&reply["format"], reply["bytes"].as_u64(), reply.get("path")), (&json!("svg"), Some(svg.len() as u64), None), "{reply}"); // Each view on the sheet, in id order, as drawing.scene lists them. let views: Vec<_> = reply["views"].as_array().unwrap().iter().map(|v| (v["view"].clone(), v["status"].clone())).collect(); @@ -41,15 +54,15 @@ fn a_sheet_exports_as_its_scenes_svg() { in_order.sort_unstable(); assert_eq!(views, in_order.map(|v| (json!(ids::encode(v)), json!("drawn")))); let name = s.drawing("test").unwrap().sheets[0].name.clone(); - assert_eq!(run(&mut s, CMD, json!({"sheet": name, "format": "svg"}))["svg"], reply["svg"]); + assert_eq!(run(&mut s, CMD, json!({"sheet": name, "format": "svg"}))["text"], reply["text"]); assert!(std::sync::Arc::ptr_eq(&doc, &s.doc) && s.evaluations == evaluations); // The sheet named, not the first: a second sheet, with no views, exports as its own scene. let added = run(&mut s, "drawing.sheet.add", json!({})); let second = ids::decode(added["sheet"].as_str().unwrap()).unwrap(); let other = run(&mut s, CMD, json!({"sheet": ids::encode(second)})); assert_eq!((&other["sheet"], other["views"].as_array().map(Vec::len)), (&json!(ids::encode(second)), Some(0)), "{other}"); - assert_eq!(other["svg"].as_str().map(str::as_bytes), Some(scene_svg(&s, second).as_slice())); - assert_ne!(other["svg"], reply["svg"]); + assert_eq!(other["text"].as_str().map(str::as_bytes), Some(scene_svg(&s, second).as_slice())); + assert_ne!(other["text"], reply["text"]); } /// With a path the file holds the same SVG and the reply names it instead. @@ -62,7 +75,7 @@ fn a_path_gets_the_svg_written_to_it() { let written = std::fs::read(&path).unwrap(); assert_eq!(written, scene_svg(&s, sheet)); assert_eq!( - (reply["path"].as_str(), reply.get("svg"), reply["bytes"].as_u64()), + (reply["path"].as_str(), reply.get("text"), reply["bytes"].as_u64()), (Some(path.as_str()), None, Some(written.len() as u64)), "{reply}" ); @@ -106,11 +119,97 @@ fn a_failed_view_is_named_and_nothing_is_written() { let reply = run(&mut s, CMD, json!({"sheet": ids::encode(sheet)})); let statuses: Vec<_> = reply["views"].as_array().unwrap().iter().map(|v| v["status"].clone()).collect(); assert_eq!(statuses, [json!("placeholder"), json!("placeholder")], "{reply}"); - assert_eq!(reply["svg"].as_str().map(str::as_bytes), Some(scene_svg(&s, sheet).as_slice())); + assert_eq!(reply["text"].as_str().map(str::as_bytes), Some(scene_svg(&s, sheet).as_slice())); } -/// PNG and DXF aren't supported yet; a path that isn't a `.svg` file, an unknown sheet, an unknown -/// key and no drawing open are refused, and nothing is written. +/// A sheet exports as its scene's PNG, byte for byte: in the reply as base64 data, grey at the +/// sheet's own dpi when nothing says (300 for a new sheet, so A3 is 4961 x 3508 pixels: 420 and +/// 297 mm at 300 / 25.4 a millimetre, rounded; then 50 once the sheet says so), and at each colour +/// and a chosen dpi; with a path (its extension in any case) the file holds it +/// and the reply names it instead. The reply's shape is the SVG's, as its schema says. +#[test] +fn a_sheet_exports_as_its_scenes_png() { + let (mut s, sheet, _) = front_and_top(); + let id = ids::encode(sheet); + let schema = output_schema_for::(); + let reply = run(&mut s, CMD, json!({"sheet": id, "format": "png"})); + assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}"); + let png = scene_png(&s, sheet, PngOptions::default()); + assert_eq!(reply["data"].as_str().and_then(base64_decode), Some(png.clone())); + assert_eq!((reply["bytes"].as_u64(), &reply["report"]["pixels"]), (Some(png.len() as u64), &json!([4961, 3508])), "{reply}"); + assert_eq!((reply.get("text"), reply.get("path"), &reply["format"]), (None, None, &json!("png"))); + run(&mut s, "drawing.sheet.set", json!({"sheet": id, "dpi": 50})); + let reply = run(&mut s, CMD, json!({"sheet": id, "format": "png"})); + let png = scene_png(&s, sheet, PngOptions { dpi: 50.0, colour: PngColour::Grey }); + assert_eq!(reply["data"].as_str().and_then(base64_decode), Some(png), "the sheet's own dpi"); + for (colour, as_written) in + [("grey", PngColour::Grey), ("black_white", PngColour::BlackWhite), ("rgb", PngColour::Rgb), ("transparent", PngColour::Transparent)] + { + let reply = run(&mut s, CMD, json!({"sheet": id, "format": "png", "dpi": 25, "colour": colour})); + let png = scene_png(&s, sheet, PngOptions { dpi: 25.0, colour: as_written }); + assert_eq!(reply["data"].as_str().and_then(base64_decode), Some(png), "{colour}"); + assert_eq!(reply["report"]["pixels"], json!([414, 293]), "{colour}"); + } + let folder = Folder::new("drawing-export-png"); + let path = folder.path("Sheet 1.PNG"); + let reply = run(&mut s, CMD, json!({"sheet": id, "format": "png", "path": path, "dpi": 2400.0 / 32.0})); + let written = std::fs::read(&path).unwrap(); + assert_eq!(written, scene_png(&s, sheet, PngOptions { dpi: 75.0, colour: PngColour::Grey })); + assert_eq!((reply["path"].as_str(), reply.get("data"), reply["bytes"].as_u64()), (Some(path.as_str()), None, Some(written.len() as u64))); +} + +/// `paper` reaches both writers, and white is what no `paper` is, byte for byte. A blue paper's PNG +/// is rgb, asked or not; any other colour is refused by name, in place of being ignored. +#[test] +fn a_sheet_exports_on_its_paper() { + let (mut s, sheet, _) = front_and_top(); + let id = ids::encode(sheet); + let data = |reply: Value| reply["data"].as_str().and_then(base64_decode).unwrap(); + let plain = scene_svg(&s, sheet); + let reply = run(&mut s, CMD, json!({"sheet": id, "paper": "white"})); + assert_eq!(reply["text"].as_str().map(str::as_bytes), Some(plain.as_slice())); + for colour in [json!({}), json!({"colour": "rgb"}), json!({"colour": "grey"}), json!({"colour": "black_white"}), json!({"colour": "transparent"})] + { + let mut asked = json!({"sheet": id, "format": "png", "dpi": 25}); + asked.as_object_mut().unwrap().extend(colour.as_object().unwrap().clone()); + let mut white = asked.clone(); + white["paper"] = json!("white"); + assert_eq!(data(run(&mut s, CMD, white)), data(run(&mut s, CMD, asked)), "{colour}"); + } + for (name, paper, hex) in [("blueprint", PaperColour::Blueprint, "#123A76"), ("prussian_blue", PaperColour::PrussianBlue, "#003153")] { + let reply = run(&mut s, CMD, json!({"sheet": id, "paper": name})); + let text = reply["text"].as_str().unwrap(); + assert!(text.contains(&format!("fill=\"{hex}\"")) && text.contains("stroke=\"#E2EEFC\"") && !text.contains("#000"), "{name}"); + let png = scene_png(&s, sheet, PngOptions { dpi: 25.0, colour: PngColour::On(paper) }); + assert_eq!(data(run(&mut s, CMD, json!({"sheet": id, "format": "png", "dpi": 25, "paper": name}))), png, "{name}"); + assert_eq!(data(run(&mut s, CMD, json!({"sheet": id, "format": "png", "dpi": 25, "paper": name, "colour": "rgb"}))), png, "{name}"); + for colour in ["grey", "black_white", "transparent"] { + let why = refused(&mut s, json!({"sheet": id, "format": "png", "paper": name, "colour": colour})); + assert!(why.contains("a blue `paper` is rgb") && why.contains(colour), "{name}, {colour}: {why}"); + } + assert!(refused(&mut s, json!({"sheet": id, "format": "dxf", "paper": name})).contains("not supported yet: DXF"), "{name}"); + } + assert!(refused(&mut s, json!({"sheet": id, "paper": "cyan"})).contains("paper")); + assert!(refused(&mut s, json!({"sheet": id, "paper": null})).contains("paper")); +} + +/// A document held for the reply takes up to its limit and is refused past it, naming the way out. +#[test] +fn a_reply_holds_a_document_up_to_its_limit() { + let (s, sheet, _) = front_and_top(); + let options = PngOptions { dpi: 25.0, colour: PngColour::Grey }; + let png = scene_png(&s, sheet, options); + let mut exact = Held { bytes: Vec::new(), limit: png.len() }; + paper_png(&sheet_scene(&s, sheet).prepare().unwrap(), options, &NoPictures, &mut exact).unwrap(); + assert_eq!(exact.bytes, png); + let mut short = Held { bytes: Vec::new(), limit: png.len() - 1 }; + let why = paper_png(&sheet_scene(&s, sheet).prepare().unwrap(), options, &NoPictures, &mut short).unwrap_err().to_string(); + assert!(why.contains("for the reply: give a path"), "{why}"); +} + +/// DXF isn't supported yet; a path without the format's extension, a dpi outside 25 to 2400, a dpi +/// or colour on an SVG, an unknown colour, an unknown sheet, an unknown key and no drawing open are +/// refused, and nothing is written. #[test] fn what_it_cant_write_is_refused() { let (mut s, sheet, _) = front_and_top(); @@ -118,10 +217,22 @@ fn what_it_cant_write_is_refused() { let id = ids::encode(sheet); let long = format!("{}.svg", "a".repeat(MAX_PATH_BYTES)); for (p, why) in [ - (json!({"sheet": id, "format": "png"}), "not supported yet: PNG"), (json!({"sheet": id, "format": "dxf"}), "not supported yet: DXF"), + (json!({"sheet": id, "format": "dxf", "path": folder.path("sheet.dxf")}), "not supported yet: DXF"), (json!({"sheet": id, "format": "pdf"}), "format"), (json!({"sheet": id, "path": folder.path("sheet.png")}), "path must be a .svg file"), + (json!({"sheet": id, "format": "png", "path": folder.path("sheet.svg")}), "path must be a .png file"), + (json!({"sheet": id, "format": "png", "path": folder.path("sheet")}), "path must be a .png file"), + (json!({"sheet": id, "format": "png", "dpi": 24.999}), "`dpi` is 25 to 2400"), + (json!({"sheet": id, "format": "png", "dpi": 2400.001}), "`dpi` is 25 to 2400"), + (json!({"sheet": id, "format": "png", "dpi": 0}), "`dpi` is 25 to 2400"), + (json!({"sheet": id, "format": "png", "dpi": -300}), "`dpi` is 25 to 2400"), + (json!({"sheet": id, "format": "png", "dpi": 1e308}), "`dpi` is 25 to 2400"), + (json!({"sheet": id, "format": "png", "dpi": null}), "dpi"), + (json!({"sheet": id, "format": "png", "dpi": "300"}), "dpi"), + (json!({"sheet": id, "format": "png", "colour": "cmyk"}), "colour"), + (json!({"sheet": id, "format": "png", "colour": null}), "colour"), + (json!({"sheet": id, "colour": "grey"}), "`dpi` and `colour` are for png only"), (json!({"sheet": id, "path": folder.path("sheet")}), "path must be a .svg file"), (json!({"sheet": id, "path": " "}), "path must be a .svg file"), (json!({"sheet": id, "path": long}), "path must be a .svg file"), @@ -129,7 +240,8 @@ fn what_it_cant_write_is_refused() { (json!({"sheet": "Sheet 9"}), "no sheet `Sheet 9`"), (json!({"sheet": 5}), "sheet"), (json!({}), "sheet"), - (json!({"sheet": id, "dpi": 300}), "dpi"), + (json!({"sheet": id, "dpi": 300}), "`dpi` and `colour` are for png only"), + (json!({"sheet": id, "format": "png", "scale": 2}), "scale"), ] { let message = refused(&mut s, p.clone()); assert!(message.contains(why), "{p}: {message}"); @@ -139,18 +251,21 @@ fn what_it_cant_write_is_refused() { assert!(refused(&mut s, json!({"sheet": id})).contains("open a drawing first")); } -/// A sheet with shaded views exports their pictures as ``s, the same bytes twice. A picture -/// past the grid's limit is refused and nothing is written. +/// A sheet with shaded views exports their pictures as ``s, the same bytes twice, and draws +/// them in a PNG. A picture past the grid's limit is refused and nothing is written. #[test] fn a_shaded_view_exports_its_picture() { let (mut s, sheet, [front, _]) = front_and_top(); - let plain = run(&mut s, CMD, json!({"sheet": ids::encode(sheet)}))["svg"].as_str().unwrap().to_owned(); + let png = |s: &mut Session| run(s, CMD, json!({"sheet": ids::encode(sheet), "format": "png", "dpi": 25}))["data"].clone(); + let lines_only = png(&mut s); + let plain = run(&mut s, CMD, json!({"sheet": ids::encode(sheet)}))["text"].as_str().unwrap().to_owned(); assert!(!plain.contains(", + /// PNG only: its resolution in dots per inch, 25 to 2400 (the sheet's own when not given). + #[serde(default, deserialize_with = "super::present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64")] + pub dpi: Option, + /// PNG only: how it stores its pixels (grey when not given). + #[serde(default, deserialize_with = "super::present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "ExportColour")] + pub colour: Option, + /// The paper (white when not given), which the lines, dimensions and text suit. A blue paper's + /// PNG is rgb. + #[serde(default)] + pub paper: ExportPaper, } /// A sheet export's file format. @@ -34,6 +46,66 @@ pub enum ExportFormat { Dxf, } +impl ExportFormat { + /// The extension a file of this format ends in, which a path must have. + pub fn extension(self) -> &'static str { + match self { + ExportFormat::Svg => "svg", + ExportFormat::Png => "png", + ExportFormat::Dxf => "dxf", + } + } +} + +/// How a sheet PNG stores its pixels. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ExportColour { + /// 8-bit greyscale on white paper. + #[default] + Grey, + /// One bit a pixel, black or white, every line at least a pixel wide. + BlackWhite, + /// 24-bit colour on white paper. + Rgb, + /// 32-bit colour, the paper transparent. + Transparent, +} + +impl From for solidcraft_io::paper::PngColour { + fn from(colour: ExportColour) -> Self { + match colour { + ExportColour::Grey => Self::Grey, + ExportColour::BlackWhite => Self::BlackWhite, + ExportColour::Rgb => Self::Rgb, + ExportColour::Transparent => Self::Transparent, + } + } +} + +/// The paper a sheet is exported on. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ExportPaper { + /// White, or in an SVG no background at all. + #[default] + White, + /// Blue paper, `#123A76`, with `#E2EEFC` lines. + Blueprint, + /// Prussian blue paper, `#003153`, with `#E2EEFC` lines. + PrussianBlue, +} + +impl From for Option { + fn from(paper: ExportPaper) -> Self { + match paper { + ExportPaper::White => None, + ExportPaper::Blueprint => Some(solidcraft_io::paper::PaperColour::Blueprint), + ExportPaper::PrussianBlue => Some(solidcraft_io::paper::PaperColour::PrussianBlue), + } + } +} + /// What a writer did that the scene didn't say. #[derive(Debug, Serialize, JsonSchema)] pub struct ExportReport { @@ -41,6 +113,9 @@ pub struct ExportReport { pub widths_snapped: usize, /// Pieces too short for the nanometre grid, merged into the next. pub pieces_merged: usize, + /// A PNG's width and height in pixels. + #[serde(skip_serializing_if = "Option::is_none")] + pub pixels: Option<[u32; 2]>, } /// What `drawing.export` returns. @@ -53,9 +128,12 @@ pub struct ExportResult { /// The file written, when a path was given. #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, - /// The SVG document, when no path was given. + /// The document when no path was given and it is text (SVG). #[serde(skip_serializing_if = "Option::is_none")] - pub svg: Option, + pub text: Option, + /// The document as base64 when no path was given and it is binary (PNG). + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option, pub report: ExportReport, /// Each view on the sheet, in id order, as `drawing.scene` reports it. pub views: Vec, diff --git a/crates/io/src/paper.rs b/crates/io/src/paper.rs index 43a582ef9..420047111 100644 --- a/crates/io/src/paper.rs +++ b/crates/io/src/paper.rs @@ -4,4 +4,31 @@ mod png; mod svg; pub use png::{DPI, MAX_PICTURE_DPI, MAX_POINTS, PICTURE_DPI, PngColour, PngOptions, PngReport, paper_png}; -pub use svg::{SvgReport, paper_svg}; +pub use svg::{SvgReport, paper_svg, paper_svg_on}; + +/// A coloured paper a sheet can be exported on, besides the default white (#10679). It belongs to +/// the export: a sheet holds no colour, and nothing here is saved. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PaperColour { + /// The deep end of the blueprint in the macOS installer art (`make_background.py`). + Blueprint, + /// The pigment's listed value. + PrussianBlue, +} + +impl PaperColour { + /// What is drawn on either paper: lines, dimensions and text. The installer art's line colour. + pub const INK: [u8; 3] = [0xE2, 0xEE, 0xFC]; + + /// The paper, as sRGB. + pub const fn rgb(self) -> [u8; 3] { + match self { + PaperColour::Blueprint => [0x12, 0x3A, 0x76], + PaperColour::PrussianBlue => [0x00, 0x31, 0x53], + } + } +} + +#[cfg(test)] +#[path = "paper_tests.rs"] +mod tests; diff --git a/crates/io/src/paper/png.rs b/crates/io/src/paper/png.rs index a7a8ce5e0..8dc1cd3fe 100644 --- a/crates/io/src/paper/png.rs +++ b/crates/io/src/paper/png.rs @@ -4,7 +4,7 @@ //! both draw the same joints, closures and merges. Curves are flattened within 1/8 px //! ([`paper::flatten`]) and tiny-skia is given lines only: its own flattening stops at 64 lines a //! curve, more than a pixel off on a large arc at a high dpi. -//! - **Paint** as the scene says: black, strokes with butt caps and miter joins (limit 4), fills +//! - **Paint** as the scene says: black or a coloured paper's ink, strokes with butt caps and miter joins (limit 4), fills //! even-odd. Each line is stroked once, then filled band by band; a line under a pixel wide is //! drawn as tiny-skia's hairline instead, its coverage scaled by its width, so it never vanishes. //! - **Dashes:** a dashed line is cut into its dashes along the flattened line (tiny-skia's @@ -30,10 +30,13 @@ use solidcraft_geom::paper::{self, Clip, Grid, GridDashes, GridItem, GridPath, G use solidcraft_geom::pixel_grid::{GridWindow, MAX_SIDE_PX, PixelGrid, PixelGridError}; use tiny_skia::{Color, FillRule, LineCap, LineJoin, Paint, Path, PathBuilder, Pixmap, PremultipliedColorU8, Stroke, StrokeDash, Transform}; +use solidcraft_doc::drawing::{DEFAULT_DPI, MAX_DPI, MIN_DPI}; + +use super::PaperColour; use crate::{IoError, Result}; -/// The resolutions a sheet PNG may have, in dots per inch. -pub const DPI: RangeInclusive = 25.0..=2400.0; +/// The resolutions a sheet PNG may have, in dots per inch: a sheet's. +pub const DPI: RangeInclusive = MIN_DPI..=MAX_DPI; /// The most points a sheet's lines may flatten to in all. pub const MAX_POINTS: usize = 1 << 24; /// The most dots per inch a picture is asked for: above it, a coarser grid's pixels are copied. @@ -58,6 +61,8 @@ pub enum PngColour { Rgb, /// 32-bit colour, the paper transparent. Transparent, + /// 24-bit colour on a coloured paper, in its ink. + On(PaperColour), } /// A sheet PNG's resolution and colour. @@ -69,7 +74,7 @@ pub struct PngOptions { impl Default for PngOptions { fn default() -> Self { - PngOptions { dpi: 300.0, colour: PngColour::Grey } + PngOptions { dpi: DEFAULT_DPI, colour: PngColour::Grey } } } @@ -142,7 +147,7 @@ fn write(scene: &Prepared, options: PngOptions, pictures: &dyn Pictures, out: im let format = match colour { PngColour::Grey => (png::ColorType::Grayscale, png::BitDepth::Eight), PngColour::BlackWhite => (png::ColorType::Grayscale, png::BitDepth::One), - PngColour::Rgb => (png::ColorType::Rgb, png::BitDepth::Eight), + PngColour::Rgb | PngColour::On(_) => (png::ColorType::Rgb, png::BitDepth::Eight), PngColour::Transparent => (png::ColorType::Rgba, png::BitDepth::Eight), }; let mut header = encoder(out, pixels, format, dpi).write_header().map_err(png_error)?; @@ -160,13 +165,18 @@ fn write(scene: &Prepared, options: PngOptions, pictures: &dyn Pictures, out: im }) .collect(); let mut paint = Paint { anti_alias: colour != PngColour::BlackWhite, ..Paint::default() }; - paint.set_color(Color::BLACK); + paint.set_color(if matches!(colour, PngColour::On(_)) { solid(PaperColour::INK) } else { Color::BLACK }); + let paper = match colour { + PngColour::Transparent => Color::TRANSPARENT, + PngColour::On(paper) => solid(paper.rgb()), + _ => Color::WHITE, + }; let mut dithered = false; let mut row = Vec::with_capacity(width * 4); let mut top = 0; while top < pixels[1] { let n = rows.min(pixels[1] - top); - band.fill(if colour == PngColour::Transparent { Color::TRANSPARENT } else { Color::WHITE }); + band.fill(paper); let shift = Transform::from_translate(0.0, MARGIN as f32 - top as f32); for (shape, (y0, y1)) in shapes.iter().zip(&spans) { if *y1 >= top as f32 - MARGIN as f32 && *y0 <= (top + n + MARGIN) as f32 { @@ -193,7 +203,7 @@ fn write(scene: &Prepared, options: PngOptions, pictures: &dyn Pictures, out: im // Most significant bit first; 1 is white. eight.iter().enumerate().fold(0u8, |byte, (i, p)| byte | (u8::from(luma(p.red(), p.green(), p.blue()) >= 128) << (7 - i))) })), - PngColour::Rgb => row.extend(line.iter().flat_map(|p| [p.red(), p.green(), p.blue()])), + PngColour::Rgb | PngColour::On(_) => row.extend(line.iter().flat_map(|p| [p.red(), p.green(), p.blue()])), PngColour::Transparent => row.extend(line.iter().flat_map(|p| { let c = p.demultiply(); [c.red(), c.green(), c.blue(), c.alpha()] @@ -360,6 +370,11 @@ fn composite( Ok(colour == PngColour::BlackWhite) } +/// An opaque sRGB colour. +fn solid([r, g, b]: [u8; 3]) -> Color { + Color::from_rgba8(r, g, b, 255) +} + /// What a band draws for one item. enum Shape { /// A stroke's outline, filled non-zero. diff --git a/crates/io/src/paper/svg.rs b/crates/io/src/paper/svg.rs index 6177bbf39..219c0d1bf 100644 --- a/crates/io/src/paper/svg.rs +++ b/crates/io/src/paper/svg.rs @@ -10,13 +10,14 @@ //! - **Curves:** lines `L`, circular arcs `A` in the grid's pieces of at most a quarter turn (a half //! turn's centre is ill-conditioned once its ends are rounded), cubics `C`, parabolas `Q`. //! - **Paint:** strokes `stroke-width`, with butt caps, miter joins and a miter limit of 4 on the -//! root; fills black, even-odd. Text is its glyph outlines, one `` a run, filled black -//! nonzero (SVG's default), so it looks the same without the font and never reflows. One `` -//! per item, so each stays one object in an editor. +//! root; fills black, even-odd, or in a coloured paper's ink. Text is its glyph outlines, one +//! `` a run, filled in the same ink nonzero (SVG's default), so it looks the same without the +//! font and never reflows. One `` per item, so each stays one object in an editor. //! - **Dashes** are the stroke's own `stroke-dasharray`, and `stroke-dashoffset` when its phase //! isn't 0, in millimetres: SVG runs the pattern along the whole path and round a closed one. //! - **Groups** are ``: object ids repeat and start with a digit, -//! so they can't be XML ids. No background: the page stays transparent, as cutters want. +//! so they can't be XML ids. No background: the page stays transparent, as cutters want. A +//! coloured paper is one `` under everything. //! - **Pictures** (#5624 S5) are ``s holding a PNG as a data URI, on their own pixel grid //! ([`Picture::grid`]) at the picture resolution the caller gives, cropped to the pixels on the //! sheet. Their edges are the grid's, on the same nanometre grid as the lines, so they register. @@ -29,6 +30,7 @@ use solidcore_record::Vec2; use solidcraft_geom::Aabb2; use solidcraft_geom::paper::{Clip, FillRule, Grid, GridDashes, GridItem, GridPath, GridPoint, GridReport, Picture, Pictures, Piece, Prepared}; +use super::PaperColour; use super::png::{PICTURE_DPI, picture_png}; use crate::{IoError, MAX_DRAWING_BYTES, Result}; @@ -38,18 +40,27 @@ pub type SvgReport = GridReport; /// A scene's SVG document, its pictures' pixels from `pictures` at `picture_dpi`, and what /// writing it did. pub fn paper_svg(scene: &Prepared, pictures: &dyn Pictures, picture_dpi: f64) -> Result<(Vec, SvgReport)> { + paper_svg_on(scene, None, pictures, picture_dpi) +} + +/// [`paper_svg`] on a coloured paper, or on none: a picture keeps its own colours on either. +pub fn paper_svg_on(scene: &Prepared, paper: Option, pictures: &dyn Pictures, picture_dpi: f64) -> Result<(Vec, SvgReport)> { if !PICTURE_DPI.contains(&picture_dpi) { return Err(IoError::Invalid(format!("an SVG's pictures are 25 to 1200 dpi, not {picture_dpi}"))); } let on = scene.on_grid(Grid::NANOMETRE).map_err(|e| IoError::Invalid(e.to_string()))?; - let mut w = Writer { out: String::new(), height: on.size.y, clips: 0 }; + let ink = paper.map_or_else(|| "#000".to_string(), |_| hex(PaperColour::INK)); + let mut w = Writer { out: String::new(), height: on.size.y, clips: 0, ink: ink.clone() }; let (width, height) = (number(on.size.x), number(on.size.y)); w.out.push_str("\n"); let _ = writeln!( w.out, "" + fill=\"none\" stroke=\"{ink}\" stroke-linecap=\"butt\" stroke-linejoin=\"miter\" stroke-miterlimit=\"4\">" ); + if let Some(paper) = paper { + let _ = writeln!(w.out, "", hex(paper.rgb())); + } for group in &on.groups { let kind = serde_json::to_value(group.kind).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); let _ = writeln!(w.out, "", group.object); @@ -83,6 +94,11 @@ pub fn paper_svg(scene: &Prepared, pictures: &dyn Pictures, picture_dpi: f64) -> Ok((w.out.into_bytes(), on.report)) } +/// An sRGB colour as SVG writes it. +fn hex([r, g, b]: [u8; 3]) -> String { + format!("#{r:02X}{g:02X}{b:02X}") +} + /// Nanometres written as millimetres onto `out`: the integer part, then up to six decimals /// without trailing zeros. fn push_number(out: &mut String, n: i64) { @@ -110,6 +126,8 @@ struct Writer { height: i64, /// How many ``s so far: the next one's id is `clip` and one more. clips: usize, + /// What fills are painted in: black, or a coloured paper's ink. + ink: String, } /// A point on the lines' grid. @@ -118,10 +136,10 @@ fn on_lines(p: Vec2) -> Result { } impl Writer { - /// Closed `loops` as one black `` up to its `d`, filled by `rule` (nonzero is SVG's default). + /// Closed `loops` as one `` in the ink up to its `d`, filled by `rule` (nonzero is SVG's default). fn fill(&mut self, loops: &[GridPath], rule: FillRule) { let rule = if rule == FillRule::EvenOdd { " fill-rule=\"evenodd\"" } else { "" }; - let _ = write!(self.out, " Vec2 { + Vec2::new(x, y) +} + +/// A 20 x 10 mm sheet: a line whose edges fall inside pixels, and a fill. At 254 dpi a millimetre +/// is 10 pixels. +fn sheet(mut items: Vec) -> Scene { + items.push(Item::Stroke { path: vec![Seg2::Line { a: p(2.0, 5.03), b: p(18.0, 5.03) }], closed: false, width_mm: 1.0, pattern: None }); + let square = Loop2::polygon(&[p(2.0, 1.0), p(8.0, 1.0), p(8.0, 4.0), p(2.0, 4.0)]); + items.push(Item::Fill { region: Region2 { outer: square, holes: vec![] } }); + Scene::new(p(20.0, 10.0), vec![Group { object: 1, kind: ObjectKind::DrawingBorder, items }]) +} + +fn picture(source: u64, opacity: f64) -> Item { + Item::Picture(Picture { source, rect: Aabb2 { min: p(14.0, 7.0), max: p(16.0, 8.0) }, opacity }) +} + +/// [`sheet`] with text in the drawing font, a dashed line, and a picture its object's clip cuts. +fn everything() -> Scene { + use solidcraft_sketch::{TextStyle, paper_text}; + let (runs, fonts) = paper_text("Ø12 ±0.1", None, "", p(3.0, 7.5), 1.5, 0.0, &TextStyle::default()).unwrap().unwrap(); + let mut items: Vec = runs.into_iter().map(Item::Text).collect(); + let pattern = Some(Dashes { lengths_mm: vec![1.0, 0.5], phase_mm: 0.0 }); + items.push(Item::Stroke { path: vec![Seg2::Line { a: p(2.0, 9.0), b: p(12.0, 9.0) }], closed: false, width_mm: 0.35, pattern }); + let mut scene = sheet(items); + scene.groups.push(Group { object: 2, kind: ObjectKind::View, items: vec![picture(1, 1.0)] }); + Scene { fonts, clips: vec![(2, Clip::Rect { min: p(15.0, 6.0), max: p(19.0, 9.0) })], ..scene } +} + +fn svg(scene: &Scene, paper: Option) -> String { + let (bytes, _) = paper_svg_on(&scene.prepare().unwrap(), paper, &Provider::default(), 254.0).unwrap(); + String::from_utf8(bytes).unwrap() +} + +fn png(scene: &Scene, colour: PngColour) -> Image { + let mut out = Vec::new(); + paper_png(&scene.prepare().unwrap(), PngOptions { dpi: 254.0, colour }, &Provider::default(), &mut out).unwrap(); + read(&out) +} + +/// Blue paper changes only the SVG's colours and adds its rectangle, under everything: lines, fills, +/// text, dashes and a picture cut by its clip are the same paths, and a picture's `` the same +/// bytes. Without a paper, `paper_svg` is the same document. +#[test] +fn a_blue_svg_is_the_white_one_in_its_colours() { + let scene = everything(); + let white = svg(&scene, None); + assert_eq!(white.into_bytes(), paper_svg(&scene.prepare().unwrap(), &Provider::default(), 254.0).unwrap().0); + let white = svg(&scene, None); + for part in ["\n").nth(1).unwrap(); + let rect = format!("\n"); + let expected = format!("{}{rect}{}", &white[..root_end + 2], &white[root_end + 2..]).replace("#000", "#E2EEFC"); + assert_eq!(svg(&scene, Some(paper)), expected); + } +} + +/// Blue paper changes only the PNG's colours: its size and type are the RGB one's, and every pixel +/// lies between paper and ink as far as the RGB one lies between white and black, so edges blend +/// from one to the other. The line's middle is exactly the ink, the sheet's corner exactly the paper. +#[test] +fn a_blue_png_is_the_white_one_in_its_colours() { + let scene = sheet(vec![]); + let white = png(&scene, PngColour::Rgb); + let edges = white.samples.iter().filter(|s| **s != 0 && **s != 255).count(); + assert!(edges > 0, "the sheet has edges inside pixels"); + for paper in BLUES { + let blue = png(&scene, PngColour::On(paper)); + assert_eq!((blue.info.color_type, blue.info.width, blue.info.height), (white.info.color_type, white.info.width, white.info.height)); + assert_eq!(format!("{:?}", blue.info.pixel_dims), format!("{:?}", white.info.pixel_dims)); + assert_eq!(blue.at(0, 0), paper.rgb()); + assert_eq!(blue.at(100, 50), PaperColour::INK); + for (i, (b, w)) in blue.samples.iter().zip(&white.samples).enumerate() { + let (paper, ink) = (f64::from(paper.rgb()[i % 3]), f64::from(PaperColour::INK[i % 3])); + let expected = paper + (ink - paper) * (1.0 - f64::from(*w) / 255.0); + assert!((f64::from(*b) - expected).abs() <= 2.0, "sample {i}: {b}, expected {expected}"); + } + } +} + +/// A picture keeps its own colours on blue paper; what it lets through shows the paper. Lines are +/// the ink wherever a picture isn't. +#[test] +fn a_picture_keeps_its_colours_on_blue_paper() { + let paper = PaperColour::Blueprint; + let [r, g, b] = paper.rgb().map(f64::from); + let solid = png(&sheet(vec![picture(1, 1.0)]), PngColour::On(paper)); + assert_eq!(solid.at(150, 25), [255, 0, 0], "red stays red"); + let half = png(&sheet(vec![picture(1, 0.5)]), PngColour::On(paper)); + let blended = [(255.0 + r) / 2.0, g / 2.0, b / 2.0]; + assert!(half.at(150, 25).iter().zip(blended).all(|(got, want)| (f64::from(*got) - want).abs() <= 1.0), "{:?}", half.at(150, 25)); + assert_eq!(half.at(0, 0), paper.rgb()); + assert_eq!(half.at(100, 50), PaperColour::INK); +} + +/// A sheet with nothing on it is all paper, and white's `Rgb` is untouched by the blue rule. +#[test] +fn an_empty_sheet_is_all_paper() { + let empty = Scene::new(p(20.0, 10.0), vec![]); + let write = |colour| { + let mut out = Vec::new(); + paper_png(&empty.prepare().unwrap(), PngOptions { dpi: 25.4, colour }, &NoPictures, &mut out).unwrap(); + read(&out) + }; + assert!(write(PngColour::Rgb).samples.iter().all(|s| *s == 255)); + for paper in BLUES { + assert!(write(PngColour::On(paper)).samples.chunks(3).all(|c| c == paper.rgb())); + } +}