From 472a330691f89fe58e90e65665bd035927c07ca0 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Mon, 26 Oct 2026 22:05:59 +0000 Subject: [PATCH 1/7] Drawings saved inside the design's file, in both forms (#3890) K3b of the drawing storage plan, after #7098: a drawing lives in the file of the design it draws (bherbruck's proposal, Cameron's choice), so the separate drawing file goes. - `Document.drawings`: the design's drawings, each its own record of the drawing family (`solidcraft-drawing/N`), each behind its own `Arc`. Every reader and writer of a design now carries them: save, Save As, autosave and recovery, crash copies, the CLI. - A design container keeps each drawing in its own entry, `drawings/.json` (Deflate), beside `document.json`, which holds nothing of them: its bytes, and the model cache keyed to them, are the same with drawings or without. A plain JSON design keeps them inline under `drawings`. - Each drawing is read by its own family's rules, taken out of the design's JSON before the design's own checks. One a build can't read (a newer number, a change it doesn't know, damage) refuses the whole design, never dropped. So does an entry under `drawings/` that isn't a drawing's, one whose record has another id, drawings inline in a container's `document.json`, two drawings with one id, or more than 1,000 (counted before any is read). A design is never saved with two drawings of one id. - Drawings are listed by name, then id: no stored order, nothing to merge when two people add drawings. - A drawing has an `id`, unique among its design's drawings (`Drawing::new` takes the ids already taken). Its source is the design it is in: at most one, an id and no path. - One pending design change, `drawings`: the last release refuses a design saved with it, so it never opens one and saves it without its drawings. One pending drawing change, `in-design`, for the record's new shape. - Gone: `read_drawing`, `read_drawing_file`, `write_drawing_container`, `file_kind`, `FileKind`, `DRAWING_EXT` and `is_drawing_path`. `read_document`, `read_design` and the container writer are as they were before #7098, with the drawings added. Tests: a design's drawings round-trip through both forms byte for byte, with `document.json` and `container.json` the same with drawings or without; their order; every refusal above; a drawing's properties kept as other tools wrote them while a sheet's number out of range is refused; the drawing's id among its objects', a new drawing's id none of the design's; a design with two drawings of one id not saved; mutation fuzz of a design with drawings in both forms. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/document.rs | 7 + crates/doc/src/drawing.rs | 100 +++++--- .../doc/src/drawing/format/pending/README.md | 4 +- .../src/drawing/format/pending/in-design.rs | 5 + crates/doc/src/drawing_tests.rs | 175 +++++++++----- crates/doc/src/format.rs | 13 ++ crates/doc/src/format/pending/drawings.rs | 5 + crates/io/src/design.rs | 84 +++---- crates/io/src/design/drawing.rs | 135 +++-------- crates/io/src/design/drawing_tests.rs | 213 ++++++++---------- crates/io/src/lib.rs | 21 +- crates/io/src/mutate.rs | 39 ++-- 12 files changed, 413 insertions(+), 388 deletions(-) create mode 100644 crates/doc/src/drawing/format/pending/in-design.rs create mode 100644 crates/doc/src/format/pending/drawings.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index a027b1b8625..f394afdf95a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2486,6 +2486,12 @@ pub struct Document { /// a document in a session leaves this empty; the session puts it back when it saves. #[serde(default, skip_serializing_if = "Visibility::is_empty")] pub visibility: Visibility, + /// The design's drawings (#3890), by name, then id ([`crate::drawing::in_design`]), each behind + /// its own `Arc`, so an undo step shares every drawing it didn't change. Each is read by its own + /// family's rules ([`crate::format::read`]), never as a field of the design; a container keeps + /// each in its own entry. + #[serde(skip_deserializing, skip_serializing_if = "Vec::is_empty")] + pub drawings: Vec>, } /// Items hidden or shown one by one. Saved with the design, but not an undo step. @@ -2686,6 +2692,7 @@ impl Document { browser_order: Default::default(), named_views: Vec::new(), visibility: Visibility::default(), + drawings: Vec::new(), } } diff --git a/crates/doc/src/drawing.rs b/crates/doc/src/drawing.rs index 2c7dfb4b957..8470552e12f 100644 --- a/crates/doc/src/drawing.rs +++ b/crates/doc/src/drawing.rs @@ -1,11 +1,14 @@ -//! A drawing (#3890): sheets of paper that draw designs saved in their own files. A drawing is a -//! file of its own, `"format": "solidcraft-drawing/N"`, versioned by the same code as designs -//! ([`DRAWING`]); format 1 is this record. +//! A drawing (#3890): sheets of paper that draw a design. A drawing lives in the file of the design +//! it draws ([`Document::drawings`](crate::Document::drawings)): a design container keeps each in +//! its own entry, a plain JSON design inline. Each is a record of its own family, +//! `"format": "solidcraft-drawing/N"`, versioned by the same code as designs ([`DRAWING`]), so a +//! change to the record is a drawing change, not a design one. //! -//! - **Sources** are the designs it draws: an id and the design file's path, relative to the -//! drawing's folder once the drawing is saved, else as given, with `/` between folders (a linked -//! design's [`DesignLink`](crate::DesignLink) rule). What a design was when the drawing last saw -//! it is not saved here. +//! - Each drawing has an **id**, unique among its design's drawings, and a design lists its +//! drawings by name, then id ([`in_design`]): nothing to merge when two people add drawings. +//! - **Sources** are the designs it draws. For now a drawing draws the design it is in: at most one +//! source, an id and nothing else. What the design was when the drawing last saw it is not saved +//! here. //! - **Sheets**: the paper, a copy of its drawing border, the resolution its pictures are rendered //! at, the component it documents, and whether it is left out of the sheet count or of printing. //! The border is a copy of the profile it was made with, never a name, so a later built-in never @@ -20,15 +23,15 @@ //! never gives a removed object's id again ([`Drawing::allocate_id`]). //! - Every reference between records is an id and must resolve: a file with one that doesn't is //! damaged and refused, never patched. -//! - 1 to [`MAX_SHEETS`] sheets and at most [`MAX_SOURCES`] sources; names of 1 to -//! [`MAX_NAME_BYTES`] bytes; paths of 1 to [`MAX_PATH_BYTES`] bytes, without NUL. +//! - 1 to [`MAX_SHEETS`] sheets; names of 1 to [`MAX_NAME_BYTES`] bytes. //! - Nothing derived is saved, and a drawing always saves as the same bytes: fields in their -//! order, maps sorted. +//! order, maps sorted, and lists of records in a fixed order (sheets as arranged; later +//! records by id), never the order they were added in. //! - A later change to the record is one file in `src/drawing/format/pending/` (its README). //! -//! [`Drawing::from_json`] reads a file in this order: at most [`MAX_DRAWING_BYTES`] of text, the -//! family's format check, every number in range, the upgrade, the typed record, then -//! [`Drawing::validate`]. +//! [`Drawing::from_json`] reads a drawing in this order: at most [`MAX_DRAWING_BYTES`] of text, +//! the family's format check, every number in range, the upgrade, the typed record, then +//! [`Drawing::validate`]; [`Drawing::from_value`] the same from the format check on. use std::collections::BTreeSet; use std::sync::Arc; @@ -41,14 +44,12 @@ use crate::format::DRAWING; use crate::ids::{self, IdSource}; use crate::{DocError, Metadata, Result, expr}; +/// The most drawings a design may hold. +pub const MAX_DRAWINGS: usize = 1000; /// The most sheets a drawing may have. pub const MAX_SHEETS: usize = 1000; -/// The most designs a drawing may draw. -pub const MAX_SOURCES: usize = 64; /// The longest name of a drawing or a sheet, in bytes. pub const MAX_NAME_BYTES: usize = 256; -/// The longest path to a design, in bytes. -pub const MAX_PATH_BYTES: usize = 4096; /// The longest language tag: what RFC 5646 asks every reader to take (§4.4.1). pub const MAX_LANGUAGE_CHARS: usize = 35; /// The largest drawing read, as JSON text. @@ -72,8 +73,11 @@ pub struct Drawing { /// otherwise. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub format_pending: Vec, + /// Unique among its design's drawings: a design container's entry for it is named by it. + #[serde(with = "crate::ids")] + pub id: u64, pub name: String, - /// The designs the drawing draws. + /// The designs the drawing draws: for now at most one, the design it is in. pub sources: Vec, /// The drawing's properties and other tools' data, kept as they are. #[serde(default, skip_serializing_if = "Metadata::is_empty")] @@ -86,15 +90,13 @@ pub struct Drawing { pub sheets: Vec>, } -/// A design the drawing draws. +/// A design the drawing draws: the design the drawing is in. Views and sheets name it by its id, +/// so a drawing of other designs can add sources of another kind later. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Source { #[serde(with = "crate::ids")] pub id: u64, - /// The design file: relative to the drawing's folder once the drawing is saved, else as given - /// (`/` separates folders). - pub path: String, } /// The length unit a drawing gives its measurements in. @@ -155,20 +157,25 @@ fn default_dpi() -> f64 { impl Drawing { /// A drawing of no designs yet, named `name` and written in `language`, with one sheet named - /// `sheet`: the paper `paper` with a copy of `border`, its id from `id_source`. + /// `sheet`: the paper `paper` with a copy of `border`. Its id, and then its sheet's, come from + /// `id_source`, the drawing's differing from every one in `taken` (its design's drawings'). pub fn new( name: &str, language: &str, sheet: &str, paper: drawing_sheet::Sheet, border: Option, + taken: &BTreeSet, id_source: &mut IdSource, ) -> Result { - let id = id_source.next(&BTreeSet::new())?; - let first = Sheet { id, name: sheet.into(), sheet: paper, border, dpi: DEFAULT_DPI, documents: None, excluded: Excluded::default() }; + let id = id_source.next(taken)?; + let sheet_id = id_source.next(&BTreeSet::from([id]))?; + let first = + Sheet { id: sheet_id, name: sheet.into(), sheet: paper, border, dpi: DEFAULT_DPI, documents: None, excluded: Excluded::default() }; let drawing = Drawing { format: DRAWING.format_string(DRAWING.current()), format_pending: DRAWING.pending_names(), + id, name: name.into(), sources: Vec::new(), properties: Metadata::default(), @@ -180,13 +187,19 @@ impl Drawing { Ok(drawing) } - /// Read a drawing file's JSON (any format this build knows; older ones are upgraded). A file + /// Read a drawing's JSON (any format this build knows; older ones are upgraded). A drawing /// that breaks a rule of the record is damaged and refused, never patched. pub fn from_json(s: &str) -> Result { if s.len() > MAX_DRAWING_BYTES { return Err(DocError::Invalid(format!("drawing too large (at most {} MiB)", MAX_DRAWING_BYTES >> 20))); } - let mut v: Value = serde_json::from_str(s).map_err(|e| DocError::Invalid(format!("not a SolidCraft drawing: {e}")))?; + let v: Value = serde_json::from_str(s).map_err(|e| DocError::Invalid(format!("not a SolidCraft drawing: {e}")))?; + Drawing::from_value(v) + } + + /// Read a drawing from its JSON value, as a plain JSON design holds it: [`Drawing::from_json`] + /// once the text is parsed. + pub fn from_value(mut v: Value) -> Result { let (version, applied) = DRAWING.take_version(&mut v)?; DRAWING.check_numbers(&v, "properties")?; DRAWING.upgrade(&mut v, version, applied.as_deref())?; @@ -214,14 +227,14 @@ impl Drawing { /// Every object's id, of every kind: what a new id must differ from. Each later kind adds its /// own here. fn ids(&self) -> impl Iterator { - self.sources.iter().map(|s| s.id).chain(self.sheets.iter().map(|s| s.id)) + std::iter::once(self.id).chain(self.sources.iter().map(|s| s.id)).chain(self.sheets.iter().map(|s| s.id)) } - /// The record's rules (the module's notes): what reading a file checks, and what every edit + /// The record's rules (the module's notes): what reading a drawing checks, and what every edit /// keeps. pub fn validate(&self) -> Result<()> { require((1..=MAX_SHEETS).contains(&self.sheets.len()), || format!("a drawing has 1 to {MAX_SHEETS} sheets"))?; - require(self.sources.len() <= MAX_SOURCES, || format!("a drawing draws at most {MAX_SOURCES} designs"))?; + require(self.sources.len() <= 1, || "a drawing draws only the design it is in".into())?; check_name(&self.name, "the drawing's")?; require(is_language_tag(&self.language), || { format!("the language is not a BCP 47 tag of 2 to {MAX_LANGUAGE_CHARS} characters (such as `en` or `en-GB`)") @@ -236,12 +249,6 @@ impl Drawing { require(id != 0, || "an object has the id 0, which is never one".into())?; require(seen.insert(id), || format!("two objects have the id {}", ids::encode(id)))?; } - for source in &self.sources { - let path = &source.path; - require(!path.is_empty() && path.len() <= MAX_PATH_BYTES && !path.contains('\0'), || { - format!("source {}: a design's path is 1 to {MAX_PATH_BYTES} bytes, without NUL", ids::encode(source.id)) - })?; - } for sheet in &self.sheets { self.check_sheet(sheet).map_err(|e| DocError::Invalid(format!("sheet {}: {e}", ids::encode(sheet.id))))?; } @@ -266,6 +273,27 @@ impl Drawing { } } +/// A design's drawings as read, each checked on its own already: in their order (by name, then id) +/// and keeping [`check_in_design`]'s rules. +pub fn in_design(mut drawings: Vec) -> Result>> { + drawings.sort_by(|a, b| (&a.name, a.id).cmp(&(&b.name, b.id))); + let drawings: Vec<_> = drawings.into_iter().map(Arc::new).collect(); + check_in_design(&drawings)?; + Ok(drawings) +} + +/// The rules for a design's drawings: at most [`MAX_DRAWINGS`], and no two with one id. +pub fn check_in_design(drawings: &[Arc]) -> Result<()> { + check_count(drawings.len())?; + let mut seen = BTreeSet::new(); + drawings.iter().try_for_each(|d| require(seen.insert(d.id), || format!("two drawings have the id {}", ids::encode(d.id)))) +} + +/// A design of `count` drawings keeps the cap: what a reader checks before it reads any of them. +pub fn check_count(count: usize) -> Result<()> { + require(count <= MAX_DRAWINGS, || format!("a design holds at most {MAX_DRAWINGS} drawings")) +} + /// `Ok` when `ok`, else the rule `broken` names. fn require(ok: bool, broken: impl FnOnce() -> String) -> Result<()> { if ok { Ok(()) } else { Err(DocError::Invalid(broken())) } diff --git a/crates/doc/src/drawing/format/pending/README.md b/crates/doc/src/drawing/format/pending/README.md index 29e16f40fca..ab38b024a78 100644 --- a/crates/doc/src/drawing/format/pending/README.md +++ b/crates/doc/src/drawing/format/pending/README.md @@ -1,7 +1,7 @@ # Pending drawing-format changes -One file per change to what a drawing file saves that no release has shipped yet. Drawings -(`"format": "solidcraft-drawing/N"`, #3890) are versioned by the same code as designs +One file per change to what a drawing saves (in its design's file) that no release has shipped +yet. Drawings (`"format": "solidcraft-drawing/N"`, #3890) are versioned by the same code as designs (`crates/doc/src/format.rs`, `Family`), from their own first format, 1. Adding a file here is the whole format bump: never edit the `DRAWING` family in `format.rs`, another change's file or a `../v/` folder. diff --git a/crates/doc/src/drawing/format/pending/in-design.rs b/crates/doc/src/drawing/format/pending/in-design.rs new file mode 100644 index 00000000000..96078e4ff2b --- /dev/null +++ b/crates/doc/src/drawing/format/pending/in-design.rs @@ -0,0 +1,5 @@ +//! A drawing lives in the file of the design it draws (#3890): it has an `id`, unique among its +//! design's drawings, and at most one source, the design it is in, which has an `id` and no `path`. +//! No step: no release saved a drawing before this, and a drawing file of its own is no longer +//! read, so an older drawing is refused as damaged. The last release refuses a design that holds a +//! drawing (the design's newer format number). diff --git a/crates/doc/src/drawing_tests.rs b/crates/doc/src/drawing_tests.rs index 12407446d94..a069c7ea4a6 100644 --- a/crates/doc/src/drawing_tests.rs +++ b/crates/doc/src/drawing_tests.rs @@ -11,18 +11,15 @@ fn own_border() -> DrawingBorderProfile { DrawingBorderProfile { filing_margin: true, trimming_mark_mm: Some([10.0, 5.0]), ..DrawingBorderProfile::iso() } } -/// Three designs on two sheets: the first sheet (A3, the ISO border) documents component 7 of the -/// first design; the second (A4 portrait, a border of its own, 600 dpi, left out of printing) -/// documents the second design. The third design is on no sheet yet. +/// The design it is in, on two sheets: the first (A3, the ISO border) documents its component 7; +/// the second (A4 portrait, a border of its own, 600 dpi, left out of printing) the design itself. fn plate() -> Drawing { let mut id_source = IdSource::seeded(SEED); let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape); - let mut d = Drawing::new("Plate assembly", "en-GB", "Assembly", a3, Some(DrawingBorderProfile::iso()), &mut id_source).unwrap(); - for path in ["plate.solidcraft", "../parts/bolt.solidcraft", "bracket.solidcraft"] { - let id = d.allocate_id(&mut id_source).unwrap(); - d.sources.push(Source { id, path: path.into() }); - } - let (plate_id, bolt_id) = (d.sources[0].id, d.sources[1].id); + let mut d = Drawing::new("Plate assembly", "en-GB", "Assembly", a3, Some(DrawingBorderProfile::iso()), &BTreeSet::new(), &mut id_source).unwrap(); + let id = d.allocate_id(&mut id_source).unwrap(); + d.sources.push(Source { id }); + let plate_id = d.sources[0].id; let id = d.allocate_id(&mut id_source).unwrap(); d.sheets.push(Arc::new(Sheet { id, @@ -30,7 +27,7 @@ fn plate() -> Drawing { sheet: drawing_sheet::Sheet::standard(PaperSize::A4, Orientation::Portrait), border: Some(own_border()), dpi: 600.0, - documents: Some(SheetComponent { source: bolt_id, component: 0 }), + documents: Some(SheetComponent { source: plate_id, component: 0 }), excluded: Excluded { count: false, print: true }, })); Arc::make_mut(&mut d.sheets[0]).documents = Some(SheetComponent { source: plate_id, component: 7 }); @@ -43,7 +40,7 @@ fn plate() -> Drawing { /// One A4 sheet that documents nothing, no sources: the base the caps grow from. fn bare() -> Drawing { let a4 = drawing_sheet::Sheet::standard(PaperSize::A4, Orientation::Landscape); - Drawing::new("Bare", "en", "Sheet", a4, None, &mut IdSource::seeded(SEED)).unwrap() + Drawing::new("Bare", "en", "Sheet", a4, None, &BTreeSet::new(), &mut IdSource::seeded(SEED)).unwrap() } fn file(d: &Drawing) -> Value { @@ -78,17 +75,14 @@ fn a_drawing_reads_back_as_saved_and_saves_the_same_bytes_again() { assert_eq!(reopened.to_json().unwrap(), saved); assert_eq!(plate().to_json().unwrap(), saved, "a seeded run makes the same drawing"); let v = file(&d); - let [plate_id, bolt_id, bracket_id] = [0, 1, 2].map(|i| ids::encode(d.sources[i].id)); + let plate_id = ids::encode(d.sources[0].id); let [assembly_id, bolt_sheet_id] = [0, 1].map(|i| ids::encode(d.sheets[i].id)); - assert_eq!(assembly_id, "1ge30wkvq38r0", "the seed's first id, as splitmix64 gives it"); + assert_eq!(v["id"], "1ge30wkvq38r0", "the seed's first id, as splitmix64 gives it"); assert_eq!(v["format"], DRAWING.format_string(DRAWING.current())); assert_eq!(v.get("format_pending").is_some(), !DRAWING.pending_names().is_empty()); assert_eq!(v.get("next_id"), None); assert_eq!((&v["name"], &v["language"]), (&json!("Plate assembly"), &json!("en-GB"))); - assert_eq!( - v["sources"], - json!([{"id": plate_id, "path": "plate.solidcraft"}, {"id": bolt_id, "path": "../parts/bolt.solidcraft"}, {"id": bracket_id, "path": "bracket.solidcraft"}]) - ); + assert_eq!(v["sources"], json!([{"id": plate_id}])); assert_eq!(v["properties"], json!({"author": "Jane Doe"})); assert_eq!(v["units"], json!({"fixed": {"unit": "in"}})); assert_eq!((&v["sheets"][0]["id"], &v["sheets"][0]["dpi"]), (&json!(assembly_id), &json!(300.0))); @@ -100,7 +94,7 @@ fn a_drawing_reads_back_as_saved_and_saves_the_same_bytes_again() { json!({ "id": bolt_sheet_id, "name": "Bolt", "sheet": {"size": {"standard": "a4"}, "orientation": "portrait"}, "border": serde_json::to_value(own_border()).unwrap(), "dpi": 600.0, - "documents": {"source": bolt_id, "component": 0}, "excluded": {"count": false, "print": true} + "documents": {"source": plate_id, "component": 0}, "excluded": {"count": false, "print": true} }) ); } @@ -111,6 +105,7 @@ fn a_drawing_reads_back_as_saved_and_saves_the_same_bytes_again() { fn a_file_may_leave_out_what_has_a_default() { let minimal = json!({ "format": DRAWING.format_string(1), + "id": "0000000000002", "name": "Bracket", "sources": [], "language": "de", @@ -125,7 +120,7 @@ fn a_file_may_leave_out_what_has_a_default() { let mut spelt = minimal.clone(); spelt["format"] = json!("solidcraft-drawing/+1"); assert_eq!(read(&spelt).unwrap().format, DRAWING.format_string(DRAWING.current())); - for key in ["name", "sources", "language", "sheets"] { + for key in ["id", "name", "sources", "language", "sheets"] { let mut v = minimal.clone(); v.as_object_mut().unwrap().remove(key); let why = refusal(&v); @@ -133,7 +128,7 @@ fn a_file_may_leave_out_what_has_a_default() { } } -/// Every cap on both sides: sheets, sources, the bytes of paths and names (two-byte characters too). +/// Every cap on both sides: sheets, sources, the bytes of names (two-byte characters too). #[test] fn every_cap_holds_on_both_sides() { let base = file(&bare()); @@ -155,18 +150,15 @@ fn every_cap_holds_on_both_sides() { for n in [0, 1001] { assert_eq!(refusal(&with("sheets", sheets(n))), "damaged drawing: a drawing has 1 to 1000 sheets", "{n} sheets"); } - // Sources from id 1: the sheet's id is the seed's, far from them. - let sources = |n: u64| Value::Array((1..=n).map(|id| json!({"id": ids::encode(id), "path": format!("part{id}.solidcraft")})).collect()); - assert_eq!(read(&with("sources", sources(64))).unwrap().sources.len(), 64); - assert_eq!(refusal(&with("sources", sources(65))), "damaged drawing: a drawing draws at most 64 designs"); - let path = |p: &str| refusal(&with("sources", json!([{"id": ids::encode(1), "path": p}]))); - for fits in ["a".repeat(4096), "é".repeat(2048), "/".into()] { - assert_eq!(path(fits.as_str()), "read", "{} bytes", fits.len()); - } - let rule = "damaged drawing: source 0000000000001: a design's path is 1 to 4096 bytes, without NUL"; - for broken in ["a".repeat(4097), "é".repeat(2048) + "a", String::new(), "plate\0.solidcraft".into()] { - assert_eq!(path(broken.as_str()), rule, "{} bytes", broken.len()); + // Sources from id 1: the drawing's and the sheet's ids are the seed's, far from them. A drawing + // draws the design it is in, by an id alone: a path is a field this build doesn't know. + let sources = |n: u64| Value::Array((1..=n).map(|id| json!({"id": ids::encode(id)})).collect()); + for n in [0, 1] { + assert_eq!(read(&with("sources", sources(n))).unwrap().sources.len(), n as usize); } + assert_eq!(refusal(&with("sources", sources(2))), "damaged drawing: a drawing draws only the design it is in"); + let with_path = refusal(&with("sources", json!([{"id": ids::encode(1), "path": "plate.solidcraft"}]))); + assert!(with_path.starts_with("damaged drawing: unknown field `path`"), "{with_path}"); let names = |name: &str| { let mut sheet_named = base.clone(); sheet_named["sheets"][0]["name"] = json!(name); @@ -253,24 +245,29 @@ fn a_border_is_saved_as_a_copy_of_its_profile() { #[test] fn damaged_files_are_refused_and_never_patched() { let d = plate(); - let plate_id = ids::encode(d.sources[0].id); + let (drawing_id, plate_id) = (ids::encode(d.id), ids::encode(d.sources[0].id)); let [assembly_id, bolt_sheet_id] = [0, 1].map(|i| ids::encode(d.sheets[i].id)); - // Two objects with one id, of one kind and of two kinds. - assert_eq!(refused(&d, |v| v["sources"][1]["id"] = json!(plate_id)), format!("damaged drawing: two objects have the id {plate_id}")); - assert_eq!(refused(&d, |v| v["sheets"][1]["id"] = json!(assembly_id)), format!("damaged drawing: two objects have the id {assembly_id}")); - assert_eq!(refused(&d, |v| v["sources"][2]["id"] = json!(bolt_sheet_id)), format!("damaged drawing: two objects have the id {bolt_sheet_id}")); + // Two objects with one id, of one kind and of two kinds, the drawing itself among them. + let two = |id: &str| format!("damaged drawing: two objects have the id {id}"); + assert_eq!(refused(&d, |v| v["sources"][0]["id"] = json!(drawing_id)), two(&drawing_id)); + assert_eq!(refused(&d, |v| v["sheets"][1]["id"] = json!(assembly_id)), two(&assembly_id)); + assert_eq!(refused(&d, |v| v["sources"][0]["id"] = json!(bolt_sheet_id)), two(&bolt_sheet_id)); + assert_eq!(refused(&d, |v| v["id"] = json!(assembly_id)), two(&assembly_id)); // An id that isn't one, where an object has it and where a reference names it; no number form, // and no counter. let not_an_id = "damaged drawing: an id is 13 characters of lowercase Crockford base32, not all 0"; for text in ["0000000000000", "FZZZZZZZZZZZZ", "000000000001", "0000000000001 ", "000000000000o", "g000000000000"] { - assert_eq!(refused(&d, |v| v["sources"][2]["id"] = json!(text)), not_an_id, "{text:?}"); + assert_eq!(refused(&d, |v| v["id"] = json!(text)), not_an_id, "{text:?}"); + assert_eq!(refused(&d, |v| v["sources"][0]["id"] = json!(text)), not_an_id, "{text:?}"); assert_eq!(refused(&d, |v| v["sheets"][1]["documents"]["source"] = json!(text)), not_an_id, "{text:?}"); } - assert!(refused(&d, |v| v["sources"][2]["id"] = json!(5)).starts_with("damaged drawing: invalid type")); + assert!(refused(&d, |v| v["sources"][0]["id"] = json!(5)).starts_with("damaged drawing: invalid type")); assert!(refused(&d, |v| v["next_id"] = json!(6)).contains("unknown field `next_id`")); - let mut in_memory = d.clone(); - in_memory.sources[2].id = 0; - assert_eq!(in_memory.validate().unwrap_err().to_string(), "an object has the id 0, which is never one"); + for zero in [|d: &mut Drawing| d.id = 0, |d: &mut Drawing| d.sources[0].id = 0] { + let mut in_memory = d.clone(); + zero(&mut in_memory); + assert_eq!(in_memory.validate().unwrap_err().to_string(), "an object has the id 0, which is never one"); + } // A reference to nothing, or to an object of another kind; a source a sheet documents removed. for missing in [ids::encode(99), assembly_id.clone()] { let expected = format!("damaged drawing: sheet {bolt_sheet_id}: it documents source {missing}, which the drawing doesn't have"); @@ -375,14 +372,14 @@ fn damaged_files_are_refused_and_never_patched() { fn a_run_never_gives_an_id_twice() { let mut id_source = IdSource::seeded(SEED); let a4 = drawing_sheet::Sheet::standard(PaperSize::A4, Orientation::Landscape); - let mut d = Drawing::new("Ids", "en", "Sheet", a4, None, &mut id_source).unwrap(); - let mut given = BTreeSet::from([d.sheets[0].id]); - for _ in 0..MAX_SOURCES { + let mut d = Drawing::new("Ids", "en", "Sheet", a4, None, &BTreeSet::new(), &mut id_source).unwrap(); + let mut given = BTreeSet::from([d.id, d.sheets[0].id]); + for _ in 0..64 { let id = d.allocate_id(&mut id_source).unwrap(); - d.sources.push(Source { id, path: "part.solidcraft".into() }); + d.sheets.push(Arc::new(Sheet { id, ..(*d.sheets[0]).clone() })); assert!(given.insert(id), "{id:#x} given twice"); } - let removed = d.sources.pop().unwrap().id; + let removed = d.sheets.pop().map_or(0, |s| s.id); for _ in 0..10_000 { let id = d.allocate_id(&mut id_source).unwrap(); assert!(id != removed && given.insert(id), "{id:#x} given twice"); @@ -420,7 +417,7 @@ fn a_drawing_too_large_to_reopen_is_not_saved() { let sheet = r#"{"id":"0000000000001","name":"S","sheet":{"size":{"standard":"a4"}}}"#; let format = DRAWING.format_string(1); format!( - r#"{{"format":"{format}","name":"A","sources":[],"language":"en","sheets":[{sheet}],"properties":{{"com.example":{{"items":[{items}]}}}}}}"# + r#"{{"format":"{format}","id":"0000000000002","name":"A","sources":[],"language":"en","sheets":[{sheet}],"properties":{{"com.example":{{"items":[{items}]}}}}}}"# ) }; // The case found in review (#3891): 2,000,000 zeros read in at about 4 MB and indent past 16 MiB. @@ -430,19 +427,24 @@ fn a_drawing_too_large_to_reopen_is_not_saved() { assert_eq!(Drawing::from_json(&small.to_json().unwrap()).unwrap(), small); } -/// A new drawing has one sheet, its id the source's first, follows its designs' units and renders -/// pictures at 300 dpi; a name, language or border that breaks the rules is refused. +/// A new drawing has one sheet, the drawing's id the source's first and the sheet's the next, +/// follows its designs' units and renders pictures at 300 dpi; its id is none of its design's other +/// drawings'; a name, language or border that breaks the rules is refused. #[test] fn a_new_drawing_has_one_sheet_and_keeps_the_rules() { let d = bare(); - let first = IdSource::seeded(SEED).next(&BTreeSet::new()).unwrap(); - assert_eq!((d.sheets.len(), d.sheets[0].id, d.sheets[0].dpi, &d.units), (1, first, DEFAULT_DPI, &Units::FollowModel)); + let mut seeded = IdSource::seeded(SEED); + let first = seeded.next(&BTreeSet::new()).unwrap(); + let second = seeded.next(&BTreeSet::new()).unwrap(); + assert_eq!((d.id, d.sheets.len(), d.sheets[0].id, d.sheets[0].dpi, &d.units), (first, 1, second, DEFAULT_DPI, &Units::FollowModel)); assert_eq!((d.format, d.format_pending), (DRAWING.format_string(DRAWING.current()), DRAWING.pending_names())); let a4 = drawing_sheet::Sheet::standard(PaperSize::A4, Orientation::Landscape); + let beside = Drawing::new("Beside", "en", "Sheet", a4, None, &BTreeSet::from([first]), &mut IdSource::seeded(SEED)).unwrap(); + assert!(beside.id != first && beside.sheets[0].id != beside.id, "the design's drawing keeps its id"); let thin = DrawingBorderProfile { drawing_border_line_mm: 0.0, ..DrawingBorderProfile::iso() }; let broken = [("", "en", "Sheet", None), ("Bare", "en_GB", "Sheet", None), ("Bare", "en", "\n", None), ("Bare", "en", "Sheet", Some(thin))]; for (name, language, sheet, border) in broken { - let made = Drawing::new(name, language, sheet, a4, border, &mut IdSource::seeded(SEED)); + let made = Drawing::new(name, language, sheet, a4, border, &BTreeSet::new(), &mut IdSource::seeded(SEED)); assert!(made.is_err(), "{name:?} {language:?} {sheet:?} {border:?}"); } } @@ -518,6 +520,75 @@ fn mutated_files_give_an_error_or_a_valid_drawing_never_a_panic() { assert!(read_back > 50, "only {read_back} mutated files read: the mutations hardly reach the record's rules"); } +/// A design holding drawings, as plain JSON: each drawing inline under `drawings`, as its own +/// record with its own format. While the change is pending the design names `drawings` in its +/// `format_pending`, so a build without it refuses the design (`format::tests`) rather than open it +/// and save it without them. They read back in their order, by name, then id, and save as the same +/// bytes; a design without drawings writes no `drawings`. +#[test] +fn a_design_keeps_its_drawings_inline_in_plain_json() { + let named = |name: &str, id: u64| Arc::new(Drawing { name: name.into(), id, ..plate() }); + let mut doc = crate::Document::new("Plate"); + doc.drawings = vec![named("Details", 7), Arc::new(plate()), named("Details", 3), named("Assembly", u64::MAX)]; + let read = crate::Document::from_json(&doc.to_json()).unwrap(); + let order: Vec<_> = read.drawings.iter().map(|d| (d.name.as_str(), d.id)).collect(); + assert_eq!(order, [("Assembly", u64::MAX), ("Details", 3), ("Details", 7), ("Plate assembly", plate().id)]); + let saved = read.to_json(); + assert_eq!(crate::Document::from_json(&saved).unwrap().to_json(), saved, "save, open, save: the same bytes"); + let v: Value = serde_json::from_str(&saved).unwrap(); + assert_eq!(v["drawings"][3], file(&plate())); + assert!(v["format_pending"].as_array().is_some_and(|names| names.contains(&json!("drawings"))), "{}", v["format_pending"]); + let empty: Value = serde_json::from_str(&crate::Document::new("Plate").to_json()).unwrap(); + assert_eq!(empty.get("drawings"), None); +} + +/// What a design refuses in its drawings, each time the whole design, never by dropping a drawing: +/// one a newer build saved (a newer number, or a change this build doesn't know), a damaged one, +/// `drawings` that isn't a list, two with one id, and more than a design may hold, counted before +/// any is read. A drawing's numbers are its own family's to check: other tools' data in its +/// properties is kept, a sheet's number out of range refused. +#[test] +fn a_drawing_a_design_cant_read_refuses_the_design() { + let mut doc = crate::Document::new("Plate"); + doc.drawings = vec![Arc::new(plate())]; + let design: Value = serde_json::from_str(&doc.to_json()).unwrap(); + let refused = |edit: &dyn Fn(&mut Value)| { + let mut v = design.clone(); + edit(&mut v); + crate::Document::from_json(&v.to_string()).map_or_else(|e| e.to_string(), |d| format!("read {}", d.drawings.len())) + }; + let (current, newer) = (DRAWING.current(), DRAWING.current() + 1); + assert_eq!( + refused(&|v| v["drawings"][0]["format"] = json!(DRAWING.format_string(newer))), + format!( + "drawing 1: this drawing was saved by a newer SolidCraft (file format {newer}; this version reads formats up to {current}): update SolidCraft to open it" + ) + ); + let later = refused(&|v| v["drawings"][0]["format_pending"] = json!(["a-later-change"])); + assert!(if DRAWING.pending_names().is_empty() { later == "read 1" } else { later.contains("newer SolidCraft") }, "{later}"); + let damaged = refused(&|v| v["drawings"][0]["language"] = json!("e")); + assert!(damaged.starts_with("drawing 1: damaged drawing: the language"), "{damaged}"); + assert_eq!(refused(&|v| v["drawings"] = json!({})), "damaged design: `drawings` is not a list"); + let twice = refused(&|v| { + let again = v["drawings"][0].clone(); + v["drawings"].as_array_mut().unwrap().push(again); + }); + assert_eq!(twice, format!("damaged design: two drawings have the id {}", ids::encode(plate().id))); + let at_cap: Vec = (1..=MAX_DRAWINGS as u64) + .map(|id| { + let mut d = file(&plate()); + d["id"] = json!(ids::encode(id)); + d + }) + .collect(); + assert_eq!(refused(&|v| v["drawings"] = Value::Array(at_cap.clone())), format!("read {MAX_DRAWINGS}")); + let over = refused(&|v| v["drawings"] = Value::Array(vec![json!({}); MAX_DRAWINGS + 1])); + assert_eq!(over, format!("damaged design: a design holds at most {MAX_DRAWINGS} drawings")); + assert_eq!(refused(&|v| v["drawings"][0]["properties"]["com.example"] = json!({"huge": 1e300})), "read 1"); + let out_of_range = refused(&|v| v["drawings"][0]["sheets"][0]["dpi"] = json!(1e300)); + assert!(out_of_range.starts_with("drawing 1: damaged drawing: the number "), "{out_of_range}"); +} + /// The number of values in `v`, itself included. fn count(v: &Value) -> usize { 1 + match v { diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index b522c93f2bc..5bf021e27ae 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -656,6 +656,8 @@ fn v2_to_v3(v: &mut Value) -> Result<()> { pub fn read(s: &str) -> Result { let mut v: Value = serde_json::from_str(s).map_err(|e| DocError::Invalid(format!("not a SolidCraft design: {e}")))?; let (version, applied) = DESIGN.take_version(&mut v)?; + // Each drawing is a record of its own family, read by its own rules, numbers and all. + let drawings = take_drawings(&mut v)?; DESIGN.check_numbers(&v, "metadata")?; crate::config::validate_rules_json(&v)?; crate::config::validate_styles_json(&v)?; @@ -768,11 +770,22 @@ pub fn read(s: &str) -> Result { // These lists used to allocate independently. Keep their existing identities, but never // let a later deletion make them available again after loading an older design. d.next_id = d.next_item_id()?; + d.drawings = crate::drawing::in_design(drawings).map_err(|e| DocError::Invalid(format!("damaged design: {e}")))?; d.format = format_string(FORMAT); d.format_pending = pending_names(); Ok(d) } +/// Take a plain JSON design's drawings out of its JSON and read each, before the design's own +/// rules see anything: a drawing this build can't read refuses the design, never dropped. +fn take_drawings(v: &mut Value) -> Result> { + let Some(list) = v.as_object_mut().and_then(|o| o.remove("drawings")) else { return Ok(Vec::new()) }; + let Value::Array(list) = list else { return Err(DocError::Invalid("damaged design: `drawings` is not a list".into())) }; + crate::drawing::check_count(list.len()).map_err(|e| DocError::Invalid(format!("damaged design: {e}")))?; + let read = |(i, d): (usize, Value)| crate::drawing::Drawing::from_value(d).map_err(|e| DocError::Invalid(format!("drawing {}: {e}", i + 1))); + list.into_iter().enumerate().map(read).collect() +} + fn all_unique(ids: impl Iterator) -> bool { let mut seen = std::collections::BTreeSet::new(); ids.into_iter().all(|id| seen.insert(id)) diff --git a/crates/doc/src/format/pending/drawings.rs b/crates/doc/src/format/pending/drawings.rs new file mode 100644 index 00000000000..1049a0e5344 --- /dev/null +++ b/crates/doc/src/format/pending/drawings.rs @@ -0,0 +1,5 @@ +//! A design holds its drawings (#3890): `drawings`, each a drawing record of its own family +//! (`solidcraft-drawing/N`, `crate::drawing`). A design container keeps each drawing in its own +//! entry, `drawings/.json`, beside `document.json`; a plain JSON design keeps them inline. +//! Older designs need no transformation: they hold no drawings. The last release refuses a design +//! saved with this (the newer format number), so it never opens one and saves it without them. diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs index 7bfdee5b682..a4b2512433f 100644 --- a/crates/io/src/design.rs +++ b/crates/io/src/design.rs @@ -8,7 +8,6 @@ use std::sync::Arc; mod drawing; mod native_cache; mod thumbnail; -pub use drawing::{FileKind, file_kind, read_drawing, read_drawing_file, write_drawing_container}; pub use native_cache::read_design_geometry; pub use thumbnail::{THUMBNAIL_SIZE, read_design_thumbnail, read_design_thumbnail_file}; @@ -74,12 +73,6 @@ struct PackageWriter { } impl PackageWriter { - fn new() -> PackageWriter { - PackageWriter { zip: zip::ZipWriter::new(Cursor::new(Vec::new())), names: BTreeSet::new(), expanded: 0, resolved: 0 } - } - fn finish(self) -> Result> { - Ok(self.zip.finish().map_err(invalid)?.into_inner()) - } fn part(&mut self, name: &str, bytes: &[u8], compressed: bool) -> Result<()> { if bytes.len() > if name.ends_with(".step") { MAX_STEP_PART } else { MAX_PART } { return Err(invalid("part too large")); @@ -228,7 +221,7 @@ fn write_container( thumbnail: Option<&[u8]>, budget: usize, ) -> Result> { - let mut writer = PackageWriter::new(); + let mut writer = PackageWriter { zip: zip::ZipWriter::new(Cursor::new(Vec::new())), names: BTreeSet::new(), expanded: 0, resolved: 0 }; let mut features = Vec::with_capacity(doc.features.len()); for feature in &doc.features { let replacements = match &feature.kind { @@ -273,10 +266,16 @@ fn write_container( value.as_object_mut().ok_or_else(|| invalid("canvas metadata"))?.insert("image_blob".into(), blob); canvases.push(value); } - let metadata = replace(doc, fields([("features", Value::Array(features)), ("canvases", Value::Array(canvases))])).map_err(invalid)?; + let replacements = fields([("features", Value::Array(features)), ("canvases", Value::Array(canvases)), ("drawings", Value::Null)]); + let mut metadata = replace(doc, replacements).map_err(invalid)?; + // The drawings have entries of their own: `document.json` is the same with them or without. + if let Some(o) = metadata.as_object_mut() { + o.remove("drawings"); + } let metadata = serde_json::to_vec(&metadata).map_err(invalid)?; writer.part("document.json", &metadata, true)?; writer.part("container.json", &serde_json::to_vec(&json!({"format": VERSION})).map_err(invalid)?, false)?; + drawing::write(&mut writer, doc)?; // The model cache is optional: one that does not fit the container is left out, never a // failed save. let cache = geometry.and_then(|g| native_cache::encode_model(g, &metadata).ok()).filter(|(manifest, data)| { @@ -302,7 +301,7 @@ fn write_container( if let Some(png) = thumbnail { thumbnail::write(&mut writer, png, &metadata)?; } - let bytes = writer.finish()?; + let bytes = writer.zip.finish().map_err(invalid)?.into_inner(); if bytes.len() > MAX_DESIGN_BYTES { return Err(invalid(format!("the design would be {} MB, over the {} MB a design file may hold", bytes.len() >> 20, MAX_DESIGN_BYTES >> 20))); } @@ -436,8 +435,9 @@ impl PackageReader { } self.document.as_ref().filter(|d| d.len() <= limit).cloned().ok_or_else(|| invalid("metadata budget")) } - fn has_part(&self, name: &str) -> bool { - self.zip.index_for_name(name).is_some() + /// Every entry's name (each was checked when the container was opened). + fn names(&self) -> Result> { + self.zip.file_names().map(|name| name.map(|n| n.into_owned()).map_err(invalid)).collect() } fn part(&mut self, name: &str) -> Result> { self.limited_part(name, if name.ends_with(".step") { MAX_STEP_PART } else { MAX_PART }) @@ -623,33 +623,6 @@ pub(super) fn read(bytes: &[u8]) -> Result { /// keeps one seekable file handle instead of buffering the complete archive. JSON continues /// through the normal migrations. pub fn read_design_file(path: &str, notify: Option) -> Result<(Document, Option)> { - let mut source = open_regular_file(path)?; - if is_container_source(&mut source)? { - let mut reader = DesignContainerReader::new(source)?; - // A design with its model opens without a picture first: the model is the session. - let model = reader.geometry(); - if let Some(notify) = notify - && model.is_none() - && let Ok(preview) = read_preview(&mut reader.reader) - { - notify(preview); - } - Ok((reader.read_document()?, model)) - } else { - let mut bytes = Vec::new(); - source.take(MAX_DESIGN_BYTES as u64 + 1).read_to_end(&mut bytes).map_err(invalid)?; - Ok((crate::read_design(&bytes)?, None)) - } -} - -#[cfg(not(target_arch = "wasm32"))] -type FileSource = std::fs::File; -#[cfg(target_arch = "wasm32")] -type FileSource = Cursor>; - -/// A file to read: inside the folders this process may use, a regular file, and at most -/// [`MAX_DESIGN_BYTES`], read from its start. -fn open_regular_file(path: &str) -> Result { #[cfg(not(target_arch = "wasm32"))] let mut source = { crate::vfs::check(path).map_err(invalid)?; @@ -673,24 +646,33 @@ fn open_regular_file(path: &str) -> Result { return Err(invalid("file too large")); } source.seek(SeekFrom::Start(0)).map_err(invalid)?; - Ok(source) -} - -/// Whether a source starts as a container does, leaving it at its start. -fn is_container_source(source: &mut FileSource) -> Result { let mut prefix = [0u8; 4]; - let size = source.seek(SeekFrom::End(0)).map_err(invalid)?; - source.seek(SeekFrom::Start(0)).map_err(invalid)?; if size >= 4 { source.read_exact(&mut prefix).map_err(invalid)?; } source.seek(SeekFrom::Start(0)).map_err(invalid)?; - Ok(is_design_container(&prefix)) + if is_design_container(&prefix) { + let mut reader = DesignContainerReader::new(source)?; + // A design with its model opens without a picture first: the model is the session. + let model = reader.geometry(); + if let Some(notify) = notify + && model.is_none() + && let Ok(preview) = read_preview(&mut reader.reader) + { + notify(preview); + } + Ok((reader.read_document()?, model)) + } else { + let mut bytes = Vec::new(); + source.take(MAX_DESIGN_BYTES as u64 + 1).read_to_end(&mut bytes).map_err(invalid)?; + Ok((crate::read_design(&bytes)?, None)) + } } fn read_document(reader: &mut PackageReader) -> Result { - if drawing::container_kind(reader)? == FileKind::Drawing { - return Err(IoError::Invalid("this file is a SolidCraft drawing, not a design: open it as a drawing".into())); + let version: Value = serde_json::from_slice(&reader.part("container.json")?).map_err(invalid)?; + if !matches!(version.get("format").and_then(Value::as_str), Some(VERSION | LEGACY_VERSION)) { + return Err(invalid("unsupported container version")); } let bytes = reader.document(MAX_DESIGN_BYTES)?; let metadata: Value = serde_json::from_slice(&bytes).map_err(invalid)?; @@ -698,6 +680,9 @@ fn read_document(reader: &mut PackageReader) -> Result(reader: &mut PackageReader) -> Result.json` (Deflate, as `document.json`), its id as [`ids::encode`] writes it and its +//! text [`Drawing::to_json`]'s. `document.json` holds nothing of them, so its bytes, and the model +//! cache keyed to them, don't change when only a drawing does. An entry under `drawings/` that +//! isn't a drawing's, or whose record has another id, is damage: the design is refused. -use std::io::{Cursor, Read, Seek}; +use std::io::{Read, Seek}; +use std::sync::Arc; -use serde::Deserialize; -use serde_json::{Value, json}; -use solidcraft_doc::drawing::{Drawing, MAX_DRAWING_BYTES}; -use solidcraft_doc::format::DRAWING; +use solidcraft_doc::drawing::{self, Drawing, MAX_DRAWING_BYTES}; +use solidcraft_doc::{Document, ids}; -use super::{PackageReader, PackageWriter, VERSION, invalid, is_design_container}; -use crate::{IoError, MAX_DESIGN_BYTES, Result}; +use super::{PackageReader, PackageWriter, invalid}; +use crate::Result; -/// The part a drawing container keeps its drawing in. -const DRAWING_PART: &str = "drawing.json"; -/// What a drawing's `container.json` says it holds. -const DRAWING_CONTENT: &str = "drawing"; +/// The folder of a container's drawing entries. +const FOLDER: &str = "drawings/"; -/// What a SolidCraft file holds. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum FileKind { - Design, - Drawing, -} - -/// Which kind of file `bytes` are, from the container's `container.json` or the JSON's `format`. -/// JSON that isn't a drawing's counts as a design, which the design reader then checks. -pub fn file_kind(bytes: &[u8]) -> Result { - if is_design_container(bytes) { - return container_kind(&mut PackageReader::new(Cursor::new(bytes))?); - } - #[derive(Deserialize)] - struct Format { - format: Option, - } - let format = serde_json::from_slice::(bytes).ok().and_then(|f| f.format); - Ok(if format.is_some_and(|f| DRAWING.version_of(&f).is_some()) { FileKind::Drawing } else { FileKind::Design }) -} - -/// What a container holds, by its `container.json`: no `content` is a design. -pub(super) fn container_kind(reader: &mut PackageReader) -> Result { - let container: Value = serde_json::from_slice(&reader.limited_part("container.json", 4096)?).map_err(invalid)?; - if !matches!(container.get("format").and_then(Value::as_str), Some(super::VERSION | super::LEGACY_VERSION)) { - return Err(invalid("unsupported container version")); - } - match container.get("content") { - None => Ok(FileKind::Design), - Some(Value::String(content)) if content == DRAWING_CONTENT => Ok(FileKind::Drawing), - Some(other) => Err(invalid(format!("this build doesn't know container content {other}"))), +/// Write each of the design's drawings to its entry. +pub(super) fn write(writer: &mut PackageWriter, doc: &Document) -> Result<()> { + drawing::check_in_design(&doc.drawings)?; + for d in &doc.drawings { + writer.part(&format!("{FOLDER}{}.json", ids::encode(d.id)), d.to_json()?.as_bytes(), true)?; } + Ok(()) } -/// The drawing as a container: the same bytes for the same drawing. -pub fn write_drawing_container(drawing: &Drawing) -> Result> { - let text = drawing.to_json()?; - let mut writer = PackageWriter::new(); - writer.part(DRAWING_PART, text.as_bytes(), true)?; - let container = json!({"format": VERSION, "content": DRAWING_CONTENT}); - writer.part("container.json", &serde_json::to_vec(&container).map_err(invalid)?, false)?; - writer.finish() -} - -/// Read a drawing file's bytes: a container or plain JSON. -pub fn read_drawing(bytes: &[u8]) -> Result { - if bytes.len() > MAX_DESIGN_BYTES { - return Err(IoError::Invalid("drawing file too large".into())); - } - if is_design_container(bytes) { - return read_container(Cursor::new(bytes)); - } - if file_kind(bytes)? == FileKind::Design { - return Err(IoError::Invalid("this file is a SolidCraft design, not a drawing: open it as a design".into())); - } - let text = std::str::from_utf8(bytes).map_err(|_| IoError::Invalid("drawing file is not UTF-8 JSON".into()))?; - Ok(Drawing::from_json(text)?) -} - -/// Read a drawing from disk (or the browser's files), a container through one seekable handle. -pub fn read_drawing_file(path: &str) -> Result { - let mut source = super::open_regular_file(path)?; - if super::is_container_source(&mut source)? { - return read_container(source); - } - let mut bytes = Vec::new(); - source.take(MAX_DRAWING_BYTES as u64 + 1).read_to_end(&mut bytes).map_err(invalid)?; - read_drawing(&bytes) -} - -fn read_container(source: R) -> Result { - let mut reader = PackageReader::new(source)?; - if container_kind(&mut reader)? == FileKind::Design { - return Err(IoError::Invalid("this file is a SolidCraft design, not a drawing: open it as a design".into())); - } - if reader.has_part("document.json") { - return Err(invalid("a drawing container also holds a design's document.json")); - } - let bytes = reader.limited_part(DRAWING_PART, MAX_DRAWING_BYTES)?; - let text = std::str::from_utf8(&bytes).map_err(invalid)?; - Ok(Drawing::from_json(text)?) +/// Read the container's drawings, in their order. +pub(super) fn read(reader: &mut PackageReader) -> Result>> { + let names: Vec = reader.names()?.into_iter().filter(|n| n.starts_with(FOLDER)).collect(); + drawing::check_count(names.len()).map_err(invalid)?; + let mut drawings = Vec::with_capacity(names.len()); + for name in names { + let id = name.strip_prefix(FOLDER).and_then(|n| n.strip_suffix(".json")).and_then(ids::decode); + let id = id.ok_or_else(|| invalid(format!("`{name}` is not a drawing's entry")))?; + let bytes = reader.limited_part(&name, MAX_DRAWING_BYTES)?; + let d = Drawing::from_json(std::str::from_utf8(&bytes).map_err(invalid)?).map_err(|e| invalid(format!("`{name}`: {e}")))?; + if d.id != id { + return Err(invalid(format!("`{name}` holds the drawing {}", ids::encode(d.id)))); + } + drawings.push(d); + } + drawing::in_design(drawings).map_err(invalid) } #[cfg(test)] diff --git a/crates/io/src/design/drawing_tests.rs b/crates/io/src/design/drawing_tests.rs index 9562bb65f9b..a5d4a643f3f 100644 --- a/crates/io/src/design/drawing_tests.rs +++ b/crates/io/src/design/drawing_tests.rs @@ -1,24 +1,28 @@ -use std::collections::BTreeMap; -use std::io::Write; +use std::collections::{BTreeMap, BTreeSet}; +use std::io::{Cursor, Write}; -use solidcraft_doc::Document; -use solidcraft_doc::drawing::Source; +use serde_json::{Value, json}; +use solidcraft_doc::drawing::{MAX_DRAWINGS, Source}; +use solidcraft_doc::format::DRAWING; use solidcraft_doc::ids::IdSource; use solidcraft_geom::drawing_sheet::{self, DrawingBorderProfile, Orientation, PaperSize}; use super::*; -use crate::{is_drawing_path, read_design, write_design, write_design_container}; +use crate::{read_design, write_design, write_design_container}; -/// A drawing of two designs on one A3 sheet. -fn drawing() -> Drawing { +/// A design with two drawings of it, each on one A3 sheet, in their order. +fn plate() -> Document { let mut ids = IdSource::seeded(3890); - let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape); - let mut d = Drawing::new("Plate assembly", "en-GB", "Assembly", a3, Some(DrawingBorderProfile::iso()), &mut ids).unwrap(); - for path in ["plate.solidcraft", "../parts/bolt.solidcraft"] { + let mut doc = Document::new("Plate"); + for name in ["Assembly", "Details"] { + let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape); + let taken: BTreeSet = doc.drawings.iter().map(|d| d.id).collect(); + let mut d = Drawing::new(name, "en-GB", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &taken, &mut ids).unwrap(); let id = d.allocate_id(&mut ids).unwrap(); - d.sources.push(Source { id, path: path.into() }); + d.sources.push(Source { id }); + doc.drawings.push(Arc::new(d)); } - d + doc } /// A container's parts by name. @@ -34,122 +38,105 @@ fn parts(bytes: &[u8]) -> BTreeMap> { .collect() } -/// A container written part by part, as a hostile or older tool might. -fn container(parts: &[(&str, &[u8])]) -> Vec { - let mut writer = PackageWriter::new(); +/// A container of these parts, as a hostile or older tool might write it. +fn container(parts: &BTreeMap>) -> Vec { + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); for (name, bytes) in parts { - writer.part(name, bytes, true).unwrap(); + zip.start_file(name.as_str(), zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(bytes).unwrap(); } - writer.finish().unwrap() + zip.finish().unwrap().into_inner() } -fn error(result: Result) -> String { - result.err().map(|e| e.to_string()).unwrap_or_else(|| panic!("accepted")) +/// The entry of the drawing with this id. +fn entry(id: u64) -> String { + format!("drawings/{}.json", ids::encode(id)) } -/// A drawing round-trips through both forms, each giving the same bytes every save; the -/// container holds `container.json` and `drawing.json`, and no `document.json`. +/// A design's drawings round-trip through both forms byte for byte. The container keeps each in its +/// own entry, holding the drawing's own text, and its `document.json` and `container.json` are the +/// same bytes with drawings or without: a drawing edit never makes the model cache, keyed to +/// `document.json`, stale. #[test] -fn a_drawing_round_trips_through_both_forms_byte_for_byte() { - let d = drawing(); - let bytes = write_drawing_container(&d).unwrap(); - assert_eq!(read_drawing(&bytes).unwrap(), d); - assert_eq!(write_drawing_container(&read_drawing(&bytes).unwrap()).unwrap(), bytes, "save, open, save: the same bytes"); +fn a_designs_drawings_round_trip_through_both_forms_byte_for_byte() { + let doc = plate(); + let bytes = write_design_container(&doc).unwrap(); + let read = read_design(&bytes).unwrap(); + assert_eq!(read.drawings, doc.drawings); + assert_eq!(write_design_container(&read).unwrap(), bytes, "save, open, save: the same bytes"); let inside = parts(&bytes); - assert_eq!(inside.keys().map(String::as_str).collect::>(), ["container.json", "drawing.json"]); - assert_eq!(inside["container.json"], br#"{"content":"drawing","format":"solidcraft-container/1"}"#); - let json = d.to_json().unwrap(); - assert_eq!(inside["drawing.json"], json.as_bytes(), "the container holds the plain form's text"); - let again = read_drawing(json.as_bytes()).unwrap(); - assert_eq!((again.to_json().unwrap(), &again), (json, &d)); -} - -/// Each file is the kind it says: a design container's `container.json` has no `content`, a -/// drawing's says `drawing`, and plain JSON is a drawing when its format is one. -#[test] -fn file_kind_tells_designs_and_drawings_apart() { - let doc = Document::new("Plate"); - let design = write_design_container(&doc).unwrap(); - assert_eq!(parts(&design)["container.json"], br#"{"format":"solidcraft-container/1"}"#, "a design's container is as it was"); - let d = drawing(); - let cases = [ - (design, FileKind::Design), - (write_design(&doc), FileKind::Design), - (write_drawing_container(&d).unwrap(), FileKind::Drawing), - (d.to_json().unwrap().into_bytes(), FileKind::Drawing), - (b"{\"format\": \"solidcraft-drawing/1\"}".to_vec(), FileKind::Drawing), - (b"{\"format\": \"solidcraft/1\"}".to_vec(), FileKind::Design), - (b"not json".to_vec(), FileKind::Design), - ]; - for (bytes, kind) in cases { - assert_eq!(file_kind(&bytes).unwrap(), kind, "{}", String::from_utf8_lossy(&bytes[..bytes.len().min(40)])); + let entries: Vec<_> = inside.keys().filter(|n| n.starts_with("drawings/")).cloned().collect(); + assert_eq!(entries, doc.drawings.iter().map(|d| entry(d.id)).collect::>().into_iter().collect::>()); + for d in &doc.drawings { + assert_eq!(inside[&entry(d.id)], d.to_json().unwrap().as_bytes()); } -} - -/// Neither reader takes the other's file, and each says what the file is. -#[test] -fn a_design_is_never_read_as_a_drawing_nor_a_drawing_as_a_design() { - let d = drawing(); - for bytes in [write_drawing_container(&d).unwrap(), d.to_json().unwrap().into_bytes()] { - assert!(error(read_design(&bytes)).contains("is a SolidCraft drawing, not a design")); - } - let doc = Document::new("Plate"); - for bytes in [write_design_container(&doc).unwrap(), write_design(&doc)] { - assert!(error(read_drawing(&bytes)).contains("is a SolidCraft design, not a drawing")); + let without = parts(&write_design_container(&Document { drawings: Vec::new(), ..doc.clone() }).unwrap()); + for part in ["document.json", "container.json"] { + assert_eq!(inside[part], without[part], "{part} is the same with drawings or without"); } + let json = write_design(&doc); + let read = read_design(&json).unwrap(); + assert_eq!(read.drawings, doc.drawings); + assert_eq!(write_design(&read), json, "the plain form too"); } -/// What a drawing container refuses: content this build doesn't know, a design's document beside -/// the drawing, a missing drawing, an unknown container version, and a damaged drawing. +/// What a container refuses in its drawings, each time the whole design: an entry under +/// `drawings/` that isn't a drawing's, one whose record has another id, a damaged drawing, one a +/// newer build saved, drawings inline in `document.json` beside the entries, and more entries than +/// a design may hold, counted before any is read. #[test] -fn a_drawing_container_refuses_what_it_cant_take() { - let text = drawing().to_json().unwrap(); - let drawing_json = |content: &str| format!(r#"{{"content":{content},"format":"solidcraft-container/1"}}"#); - let cases: [(Vec, &str); 6] = [ - (container(&[("container.json", drawing_json("\"sketch\"").as_bytes()), ("drawing.json", text.as_bytes())]), "container content \"sketch\""), - (container(&[("container.json", drawing_json("7").as_bytes()), ("drawing.json", text.as_bytes())]), "container content 7"), - ( - container(&[ - ("container.json", drawing_json("\"drawing\"").as_bytes()), - ("drawing.json", text.as_bytes()), - ("document.json", &b"{}"[..]), - ]), - "also holds a design's document.json", - ), - (container(&[("container.json", drawing_json("\"drawing\"").as_bytes())]), "required part `drawing.json`"), - ( - container(&[("container.json", &br#"{"content":"drawing","format":"solidcraft-container/9"}"#[..]), ("drawing.json", text.as_bytes())]), - "version", - ), - ( - container(&[("container.json", drawing_json("\"drawing\"").as_bytes()), ("drawing.json", text.replace("en-GB", "e").as_bytes())]), - "damaged drawing", - ), - ]; - for (bytes, says) in cases { - let e = error(read_drawing(&bytes)); - assert!(e.contains(says), "{says}: {e}"); +fn a_container_refuses_drawing_entries_it_cant_take() { + let doc = plate(); + let good = parts(&write_design_container(&doc).unwrap()); + let [first, second] = [0, 1].map(|i| doc.drawings[i].id); + let text = |i: usize| String::from_utf8(good[&entry(doc.drawings[i].id)].clone()).unwrap(); + let refusal = |edit: &dyn Fn(&mut BTreeMap>)| { + let mut parts = good.clone(); + edit(&mut parts); + read_design(&container(&parts)).map_or_else(|e| e.to_string(), |d| format!("read {}", d.drawings.len())) + }; + assert_eq!(refusal(&|_| {}), "read 2"); + for name in ["drawings/0000000000000.json", "drawings/ABCDEFGHJKMNP.json", "drawings/x/0000000000001.json", "drawings/0000000000001.svg"] { + let why = refusal(&|p| { + p.insert(name.into(), b"{}".to_vec()); + }); + assert_eq!(why, format!("design container: `{name}` is not a drawing's entry")); } - assert!(error(read_design(&container(&[("container.json", drawing_json("\"sketch\"").as_bytes())]))).contains("container content")); + let moved = refusal(&|p| { + let bytes = p.remove(&entry(first)).unwrap(); + p.insert(entry(7), bytes); + }); + assert_eq!(moved, format!("design container: `{}` holds the drawing {}", entry(7), ids::encode(first))); + let damaged = refusal(&|p| { + p.insert(entry(second), text(1).replace("en-GB", "e").into_bytes()); + }); + assert!(damaged.starts_with(&format!("design container: `{}`: damaged drawing: the language", entry(second))), "{damaged}"); + let newer = DRAWING.format_string(DRAWING.current() + 1); + let why = refusal(&|p| { + p.insert(entry(second), text(1).replace(&DRAWING.format_string(DRAWING.current()), &newer).into_bytes()); + }); + assert!(why.contains("this drawing was saved by a newer SolidCraft"), "{why}"); + let inline = refusal(&|p| { + let mut metadata: Value = serde_json::from_slice(&p["document.json"]).unwrap(); + metadata["drawings"] = json!([serde_json::from_str::(&text(0)).unwrap()]); + p.insert("document.json".into(), serde_json::to_vec(&metadata).unwrap()); + }); + assert_eq!(inline, "design container: ambiguous drawings in document.json and in their own entries"); + let over = refusal(&|p| { + for id in 1..=MAX_DRAWINGS as u64 { + p.insert(entry(id), Vec::new()); + } + }); + assert_eq!(over, format!("design container: a design holds at most {MAX_DRAWINGS} drawings")); } -/// Drawing files: the extension, and reading one from disk in either form. -#[cfg(not(target_arch = "wasm32"))] +/// A design whose drawings break the rules isn't saved: two with one id would share one entry, and +/// one of them would be lost. #[test] -fn drawing_files_open_from_disk_in_either_form() { - // The browsers' file pickers take only ASCII letters, digits, `+` and `.`, up to 16 long. - assert!(crate::DRAWING_EXT.len() < 16 && crate::DRAWING_EXT.bytes().all(|b| b.is_ascii_alphanumeric()), "{}", crate::DRAWING_EXT); - for (path, drawing) in [("a.scdwg", true), ("A.SCDWG", true), ("a.solidcraft", false), ("scdwg", false), ("a.dwg", false)] { - assert_eq!(is_drawing_path(path), drawing, "{path}"); - } - let d = drawing(); - let dir = std::env::temp_dir().join(format!("solidcraft-drawing-files-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - for (name, bytes) in [("container.scdwg", write_drawing_container(&d).unwrap()), ("plain.scdwg", d.to_json().unwrap().into_bytes())] { - let path = dir.join(name); - std::fs::File::create(&path).unwrap().write_all(&bytes).unwrap(); - assert_eq!(read_drawing_file(path.to_str().unwrap()).unwrap(), d, "{name}"); - } - assert!(error(read_drawing_file(dir.to_str().unwrap())).contains("not a regular file")); - std::fs::remove_dir_all(&dir).unwrap(); +fn a_design_with_two_drawings_of_one_id_is_not_saved() { + let mut doc = plate(); + let first = doc.drawings[0].clone(); + doc.drawings[1] = Arc::new(Drawing { name: "Details".into(), ..(*first).clone() }); + let why = write_design_container(&doc).unwrap_err().to_string(); + assert_eq!(why, format!("two drawings have the id {}", ids::encode(first.id))); } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index bd0adaf02d0..a1538fd6fb4 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -12,10 +12,9 @@ mod design_metadata; mod dxf; mod dxf_out; pub use design::{ - DesignCompression, DesignContainerReader, DesignPreview, FileKind, THUMBNAIL_SIZE, file_kind, is_design_container, read_design_file, - read_design_geometry, read_design_preview, read_design_thumbnail, read_design_thumbnail_file, read_drawing, read_drawing_file, - write_design_container, write_design_container_with_cache, write_design_container_with_compression, write_design_container_with_preview, - write_design_container_with_thumbnail, write_drawing_container, + DesignCompression, DesignContainerReader, DesignPreview, THUMBNAIL_SIZE, is_design_container, read_design_file, read_design_geometry, + read_design_preview, read_design_thumbnail, read_design_thumbnail_file, write_design_container, write_design_container_with_cache, + write_design_container_with_compression, write_design_container_with_preview, write_design_container_with_thumbnail, }; mod legacy_dir; #[cfg(test)] @@ -61,14 +60,6 @@ pub fn is_design_path(path: &str) -> bool { .and_then(|e| e.to_str()) .is_some_and(|e| DESIGN_EXTS.iter().chain(["json"].iter()).any(|x| e.eq_ignore_ascii_case(x))) } -/// Drawing file extension: a drawing is a file of its own beside the designs it draws. Short and -/// plain, as the browsers' file pickers take only ASCII letters, digits, `+` and `.`, up to 16 long. -pub const DRAWING_EXT: &str = "scdwg"; - -/// Is this a drawing file name (`.scdwg`, any case)? -pub fn is_drawing_path(path: &str) -> bool { - std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case(DRAWING_EXT)) -} /// Largest design file we read. pub const MAX_DESIGN_BYTES: usize = 256 << 20; @@ -586,11 +577,7 @@ pub fn read_design(bytes: &[u8]) -> Result { return design::read(bytes); } let s = std::str::from_utf8(bytes).map_err(|_| IoError::Invalid("design file is not UTF-8 JSON".into()))?; - // Only a file that isn't a design pays for asking whether it is a drawing. - Document::from_json(s).map_err(|e| match file_kind(bytes) { - Ok(FileKind::Drawing) => IoError::Invalid("this file is a SolidCraft drawing, not a design: open it as a drawing".into()), - _ => e.into(), - }) + Ok(Document::from_json(s)?) } /// Design file bytes. diff --git a/crates/io/src/mutate.rs b/crates/io/src/mutate.rs index 942446d7b35..48efecff52a 100644 --- a/crates/io/src/mutate.rs +++ b/crates/io/src/mutate.rs @@ -525,29 +525,30 @@ outer survives("design JSON", &mutations(&json, true, 0xde6), usize::MAX, |b| crate::read_design(b).ok().map(|d| d.features.len())); } - /// A drawing, as a container and as plain JSON: every mutation gives an error or a drawing, - /// never a panic, and `file_kind` always answers. + /// A design with two drawings, as a container and as plain JSON: every mutation gives an error + /// or a design, never a panic, and never more drawings than a design may hold. #[test] - fn drawings_survive_mutation() { + fn designs_with_drawings_survive_mutation() { + use solidcraft_doc::drawing::{Drawing, MAX_DRAWINGS, Source}; use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet}; let mut ids = solidcraft_doc::ids::IdSource::seeded(0xd4a); - let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); - let mut drawing = solidcraft_doc::drawing::Drawing::new("Fuzz", "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &mut ids).unwrap(); - let id = drawing.allocate_id(&mut ids).unwrap(); - drawing.sources.push(solidcraft_doc::drawing::Source { id, path: "plate.solidcraft".into() }); - let container = crate::write_drawing_container(&drawing).unwrap(); - assert!(crate::read_drawing(&container).is_ok()); - survives("drawing container", &mutations(&container, false, 0xd4b), usize::MAX, |b| { - let _ = crate::file_kind(b); - let _ = crate::read_design(b); - crate::read_drawing(b).ok().map(|d| d.sheets.len()) - }); - let json = drawing.to_json().unwrap().into_bytes(); - assert!(crate::read_drawing(&json).is_ok()); - survives("drawing JSON", &mutations(&json, true, 0xd4c), usize::MAX, |b| { - let _ = crate::file_kind(b); - crate::read_drawing(b).ok().map(|d| d.sheets.len()) + let mut doc = solidcraft_doc::Document::new("Fuzz"); + for name in ["Assembly", "Details"] { + let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); + let taken = doc.drawings.iter().map(|d| d.id).collect(); + let mut drawing = Drawing::new(name, "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &taken, &mut ids).unwrap(); + let id = drawing.allocate_id(&mut ids).unwrap(); + drawing.sources.push(Source { id }); + doc.drawings.push(drawing.into()); + } + let container = crate::write_design_container(&doc).unwrap(); + assert_eq!(crate::read_design(&container).unwrap().drawings, doc.drawings); + survives("design container with drawings", &mutations(&container, false, 0xd4b), MAX_DRAWINGS, |b| { + crate::read_design(b).ok().map(|d| d.drawings.len()) }); + let json = crate::write_design(&doc); + assert_eq!(crate::read_design(&json).unwrap().drawings, doc.drawings); + survives("design JSON with drawings", &mutations(&json, true, 0xd4c), MAX_DRAWINGS, |b| crate::read_design(b).ok().map(|d| d.drawings.len())); } /// A paper scene's JSON, mutated, read, prepared and written as SVG: an error or a document, From e0cb46c1ef10e84e7c6cb8bade582f9a04d209a4 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Mon, 26 Oct 2026 22:33:13 +0000 Subject: [PATCH 2/7] Drawing commands on the design's own drawings, each drawing its own undo (#3890) K4' of the drawing storage plan, on K3b (a drawing lives in its design's file): make, list, open, close and delete a design's drawings, and read and change the open one's settings and properties. It replaces #3891's drawing sessions, which held a drawing as a file of its own. - `drawing.create {name?, language?, units?}` adds a drawing of the design (one ISO A3 landscape sheet with the ISO border, the design its one source) and opens it; refused on an empty design. `drawing.list`, `drawing.open {drawing}`, `drawing.close`, `drawing.delete {drawing}`. `drawing.inspect`, `drawing.set`, `drawing.properties`, `.properties.set`, `.properties.remove` work on the open drawing. Labels in en, ja and zh. - The open drawing is the session's (`Session::open_drawing`, kept in checkpoints), and the part gate keeps the parts apart: a command says the part it works on, the model unless it says otherwise (`.in_drawing()`, `.any_part()`). While a drawing is open the model's commands wait ("a drawing is open: close it to change the model"); the drawing's run only while one is. Files, recovery, undo and redo, checkpoints, selection, diagnostics, the command list and choosing a drawing work either way. `CommandSpec::allowed` is the one check running a command, running it inside another and listing it make. - `Session::drawing` and `Session::edit_drawing` are the open drawing's one way in: an edit is kept when it changed something and still keeps the record's rules, in a new design whose other drawings are shared. - A change that only touches drawings evaluates nothing: `Document::differs_only_in_drawings` joins the render-only path, as render settings and part properties do. A model edit shares every drawing, so it pays nothing for the check. - Undo per part: a step records the part it changed (`Snapshot::part`: a drawing, or the model and its list of drawings). Undo and redo go through the open part's steps only. A drawing's step puts back only that drawing; the model's step puts back the design as it was, keeping each drawing it had as it is now. Making and deleting a drawing are the model's steps. A new step ends what could be redone in its own part only. `Snapshot::of` is the one place a step is taken. - An agent's message that changed several parts keeps their steps apart, rather than merging them into one step that would undo only one part. - `cmd::metadata`'s rules for reading, setting and removing properties are written once (`reading`, `setting`, `removing`) and used by the design's and the drawing's commands. - `drawing::sort` is the one place the drawings' order (by name, then id) is kept; `Document::put_drawing` adds or replaces one in that order. Tests: making, listing, opening, closing and deleting; what making one refuses, at the cap too; the gate both ways, inside another command and in the command list; drawing edits as undo steps that evaluate nothing over 100 rounds; undo and redo per part with model and drawing steps interleaved; redo ended per part; the order by name, then id, after renames; delete and its undo; refused changes; checkpoints; save and open in both forms; properties; hostile values for every command that runs with a drawing open, from the registry; a fuzz of the steps in any order. Co-Authored-By: Claude Opus 5.5 --- assets/locales/en.json | 10 + assets/locales/ja.json | 10 + assets/locales/zh.json | 10 + crates/doc/src/document.rs | 26 ++ crates/doc/src/drawing.rs | 12 +- crates/engine/src/cmd/diagnostics.rs | 7 +- crates/engine/src/cmd/drawing.rs | 218 ++++++++++++ crates/engine/src/cmd/drawing_tests.rs | 454 +++++++++++++++++++++++++ crates/engine/src/cmd/edit.rs | 80 ++++- crates/engine/src/cmd/file.rs | 14 +- crates/engine/src/cmd/inspect.rs | 4 +- crates/engine/src/cmd/metadata.rs | 61 ++-- crates/engine/src/cmd/mod.rs | 40 ++- crates/engine/src/lib.rs | 74 +++- crates/ui-egui/src/agent_chat/mod.rs | 7 +- crates/ui-egui/src/agent_chat/tests.rs | 6 + docs/mcp.md | 4 +- 17 files changed, 966 insertions(+), 71 deletions(-) create mode 100644 crates/engine/src/cmd/drawing.rs create mode 100644 crates/engine/src/cmd/drawing_tests.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index a2ae34bde16..4ed562c2d9c 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -563,6 +563,16 @@ "cmd.document_metadata_remove": "Remove Design Property", "cmd.document_metadata_set": "Change Design Properties", "cmd.document_units": "Change Design Units", + "cmd.drawing_close": "Close Drawing", + "cmd.drawing_create": "Create Drawing", + "cmd.drawing_delete": "Delete Drawing", + "cmd.drawing_inspect": "Inspect Drawing", + "cmd.drawing_list": "List Drawings", + "cmd.drawing_open": "Open Drawing", + "cmd.drawing_properties": "Drawing Properties", + "cmd.drawing_properties_remove": "Remove Drawing Property", + "cmd.drawing_properties_set": "Change Drawing Properties", + "cmd.drawing_set": "Drawing Settings", "cmd.edit_checkpoint": "Checkpoint", "cmd.edit_restore_checkpoint": "Restore Checkpoint", "cmd.engine_commands": "List Commands", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index b7978f85978..d4d985e6507 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -563,6 +563,16 @@ "cmd.document_metadata_remove": "デザインのプロパティを削除", "cmd.document_metadata_set": "デザインのプロパティを変更", "cmd.document_units": "デザインの単位を変更", + "cmd.drawing_close": "図面を閉じる", + "cmd.drawing_create": "図面を作成", + "cmd.drawing_delete": "図面を削除", + "cmd.drawing_inspect": "図面を確認", + "cmd.drawing_list": "図面を一覧表示", + "cmd.drawing_open": "図面を開く", + "cmd.drawing_properties": "図面のプロパティ", + "cmd.drawing_properties_remove": "図面のプロパティを削除", + "cmd.drawing_properties_set": "図面のプロパティを変更", + "cmd.drawing_set": "図面設定", "cmd.edit_checkpoint": "チェックポイント", "cmd.edit_restore_checkpoint": "チェックポイントを復元", "cmd.engine_commands": "コマンドを一覧表示", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 993a86cc6e8..14dfdb68fa3 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -563,6 +563,16 @@ "cmd.document_metadata_remove": "删除设计属性", "cmd.document_metadata_set": "更改设计属性", "cmd.document_units": "更改设计单位", + "cmd.drawing_close": "关闭绘图", + "cmd.drawing_create": "创建绘图", + "cmd.drawing_delete": "删除绘图", + "cmd.drawing_inspect": "检查绘图", + "cmd.drawing_list": "列出绘图", + "cmd.drawing_open": "打开绘图", + "cmd.drawing_properties": "绘图属性", + "cmd.drawing_properties_remove": "删除绘图属性", + "cmd.drawing_properties_set": "更改绘图属性", + "cmd.drawing_set": "绘图设置", "cmd.edit_checkpoint": "检查点", "cmd.edit_restore_checkpoint": "恢复检查点", "cmd.engine_commands": "列出命令", diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index f394afdf95a..9d87ee1c845 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2822,6 +2822,32 @@ impl Document { *self == normalized } + /// Only drawings changed: nothing to evaluate, as a drawing reads the model and never changes + /// it. The same whole-Document proof as [`Document::differs_only_in_render`]; a model edit + /// shares every drawing's `Arc`, so it costs nothing here. + pub fn differs_only_in_drawings(&self, previous: &Document) -> bool { + let shared = + self.drawings.len() == previous.drawings.len() && self.drawings.iter().zip(&previous.drawings).all(|(a, b)| std::sync::Arc::ptr_eq(a, b)); + if shared || self.drawings == previous.drawings { + return false; + } + let mut normalized = previous.clone(); + normalized.drawings = self.drawings.clone(); + *self == normalized + } + + /// The design's drawing `id`. + pub fn drawing(&self, id: u64) -> Option<&std::sync::Arc> { + self.drawings.iter().find(|d| d.id == id) + } + + /// Put `drawing` in, in place of the one with its id if there is one, in the drawings' order. + pub fn put_drawing(&mut self, drawing: std::sync::Arc) { + self.drawings.retain(|d| d.id != drawing.id); + self.drawings.push(drawing); + crate::drawing::sort(&mut self.drawings); + } + /// The colour a body is shown and exported in (sRGB as 0–1 fractions): its appearance, /// else its component's, else its material's look, else the colour it was imported with. /// (Faces may have their own: `face_looks`.) diff --git a/crates/doc/src/drawing.rs b/crates/doc/src/drawing.rs index 8470552e12f..68af7fa2072 100644 --- a/crates/doc/src/drawing.rs +++ b/crates/doc/src/drawing.rs @@ -275,13 +275,19 @@ impl Drawing { /// A design's drawings as read, each checked on its own already: in their order (by name, then id) /// and keeping [`check_in_design`]'s rules. -pub fn in_design(mut drawings: Vec) -> Result>> { - drawings.sort_by(|a, b| (&a.name, a.id).cmp(&(&b.name, b.id))); - let drawings: Vec<_> = drawings.into_iter().map(Arc::new).collect(); +pub fn in_design(drawings: Vec) -> Result>> { + let mut drawings: Vec<_> = drawings.into_iter().map(Arc::new).collect(); + sort(&mut drawings); check_in_design(&drawings)?; Ok(drawings) } +/// Put a design's drawings in their order: by name, then id. Nothing stores the order, so two +/// people adding drawings have nothing to merge. +pub fn sort(drawings: &mut [Arc]) { + drawings.sort_by(|a, b| (&a.name, a.id).cmp(&(&b.name, b.id))); +} + /// The rules for a design's drawings: at most [`MAX_DRAWINGS`], and no two with one id. pub fn check_in_design(drawings: &[Arc]) -> Result<()> { check_count(drawings.len())?; diff --git a/crates/engine/src/cmd/diagnostics.rs b/crates/engine/src/cmd/diagnostics.rs index 25a4756dcc4..bac6ec4e8fe 100644 --- a/crates/engine/src/cmd/diagnostics.rs +++ b/crates/engine/src/cmd/diagnostics.rs @@ -8,21 +8,22 @@ use crate::params::{bad, str_}; use crate::{EngineError, Result, Session, crash}; pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("diagnostics.crash_reports", "Crash Reports", list).icon("bug_report").noundo().params( + CommandSpec::new("diagnostics.crash_reports", "Crash Reports", list).any_part().icon("bug_report").noundo().params( "limit?: number (default 20). Lists this computer's crash reports, newest first: {dir, reports: [{id, kind, time, message, \ command, count, version, path, replayable}]}. kind: command_panic | panic | kernel_panic_recovered | unclean_exit. \ Read one with diagnostics.crash_report; reproduce it with `solidcraft-cli crashes replay `", ), - CommandSpec::new("diagnostics.crash_report", "Crash Report", read).icon("bug_report").noundo().params( + CommandSpec::new("diagnostics.crash_report", "Crash Report", read).any_part().icon("bug_report").noundo().params( "id: report id. The whole report: message, location, backtrace, app version and commit, system, the command that \ crashed and the recent ones, notes, and design_path / replay_path when the crash can be replayed \ (`solidcraft-cli run --in `)", ), CommandSpec::new("diagnostics.crash_reports.clear", "Delete Crash Reports", clear) + .any_part() .icon("delete") .noundo() .params("id?: one report (default: all). Returns {deleted}"), - CommandSpec::new("diagnostics.crash_test", "Crash Test", crash_test).icon("bug_report").noundo().enabled(crash_test_enabled).params( + CommandSpec::new("diagnostics.crash_test", "Crash Test", crash_test).any_part().icon("bug_report").noundo().enabled(crash_test_enabled).params( "mode: panic | kernel | abort. Checks that crash reports work: panic = an internal error in this command (caught; \ the design is unchanged), kernel = one inside the geometry kernel (caught), abort = the app ends at once (reported \ at the next start). Only when the SOLIDCRAFT_CRASH_TEST environment variable is set", diff --git a/crates/engine/src/cmd/drawing.rs b/crates/engine/src/cmd/drawing.rs new file mode 100644 index 00000000000..7d9ea52ed1b --- /dev/null +++ b/crates/engine/src/cmd/drawing.rs @@ -0,0 +1,218 @@ +//! Drawing commands (#3890, K4): make, list, open, close and delete a design's drawings, and read +//! and change the open drawing's own settings. A drawing lives in its design's file +//! ([`solidcraft_doc::Document::drawings`]); while one is open, the drawing commands change it and +//! the model's wait ([`super::Part`]). Each change of a drawing is one undo step of that drawing, +//! and evaluates nothing; making and deleting one are steps of the model, whose list of drawings +//! they change. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use serde_json::{Value, json}; +use solidcraft_doc::drawing::{self, Drawing, Source, Units}; +use solidcraft_doc::ids::{self, IdSource}; +use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet}; + +use super::CommandSpec; +use crate::params::{bad, str_}; +use crate::{Result, Session}; + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("drawing.create", "Create Drawing", create).any_part().icon("new").doc_only().params( + "name?: the drawing's name (default: the design's); language?: the drawing's content language, a BCP 47 tag (default en); units?: \"follow_model\" (default) or one length unit such as \"mm\". Adds a drawing of this design, one ISO A3 landscape sheet with the ISO border, and opens it (one undo step of the model) → as drawing.inspect", + ), + CommandSpec::new("drawing.list", "List Drawings", list) + .any_part() + .icon("list") + .noundo() + .doc_only() + .params("→ drawings: [{id, name, sheets (how many), open}], by name, then id"), + CommandSpec::new("drawing.open", "Open Drawing", open) + .any_part() + .icon("open") + .noundo() + .doc_only() + .params("drawing: id (from drawing.list) → as drawing.inspect. The drawing commands then change it; the model's wait until drawing.close"), + CommandSpec::new("drawing.close", "Close Drawing", close) + .any_part() + .icon("close") + .noundo() + .doc_only() + .params("→ closed: the drawing's id, or null when none was open"), + CommandSpec::new("drawing.delete", "Delete Drawing", delete).any_part().icon("delete").doc_only().params( + "drawing: id → deleted: its id; closed when it was open (one undo step of the model)", + ), + CommandSpec::new("drawing.inspect", "Inspect Drawing", inspect).in_drawing().icon("inspect").noundo().doc_only().params( + "→ {id, name, units, language, properties, sources: [{id}], sheets: [{id, name, size_mm, orientation, dpi, documents, excluded}]}. Read-only.", + ), + CommandSpec::new("drawing.set", "Drawing Settings", set) + .in_drawing() + .icon("settings") + .doc_only() + .params("name?, language?: a BCP 47 tag, units?: \"follow_model\" or one length unit such as \"mm\". One undo step."), + CommandSpec::new("drawing.properties", "Drawing Properties", properties).in_drawing().icon("settings").noundo().doc_only().params( + "→ metadata: the drawing's properties as saved (other tools' keys too); properties: project, part_number, revision, author, organization, description and license, each its text or null. The design properties' rules (document.metadata).", + ), + CommandSpec::new("drawing.properties.set", "Change Drawing Properties", properties_set).in_drawing().icon("settings").doc_only().params( + "key and value, or values: {key: value, …} (all or nothing, one undo step), as document.metadata.set takes them → metadata, changed: [keys]", + ), + CommandSpec::new("drawing.properties.remove", "Remove Drawing Property", properties_remove) + .in_drawing() + .icon("delete") + .doc_only() + .params("key, or keys: [keys] → metadata, removed: [keys that were there]"), +]; + +/// `units` as given: `follow_model`, or a length unit the drawing's rules check. +fn units(cmd: &str, p: &Value) -> Result> { + match p.get("units") { + None => Ok(None), + Some(Value::String(u)) if u == "follow_model" => Ok(Some(Units::FollowModel)), + Some(Value::String(u)) => Ok(Some(Units::Fixed { unit: u.clone() })), + Some(_) => Err(bad(cmd, "`units` is \"follow_model\" or a length unit such as \"mm\"")), + } +} + +/// An optional text parameter: absent, or a string. +fn text<'a>(cmd: &str, p: &'a Value, key: &str) -> Result> { + match p.get(key) { + None => Ok(None), + Some(_) => str_(p, key).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be text"))), + } +} + +/// The design's drawing `p.drawing` names, by id. +fn named(cmd: &str, s: &Session, p: &Value) -> Result { + let id = str_(p, "drawing").and_then(ids::decode).ok_or_else(|| bad(cmd, "`drawing` must be a drawing's id (drawing.list)"))?; + s.doc.drawing(id).map(|d| d.id).ok_or_else(|| bad(cmd, format!("the design has no drawing {}", ids::encode(id)))) +} + +fn create(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.create"; + if s.doc.features.is_empty() { + return Err(bad(cmd, "the design is empty: there is nothing to draw yet")); + } + drawing::check_count(s.doc.drawings.len() + 1).map_err(|e| bad(cmd, e.to_string()))?; + let name = text(cmd, p, "name")?.map_or_else(|| s.doc.name.clone(), str::to_string); + let language = text(cmd, p, "language")?.unwrap_or("en"); + // Not the id of a drawing undo or redo could bring back either. + let steps = s.undo.iter().chain(&s.redo).filter_map(|step| step.part); + let taken: BTreeSet = s.doc.drawings.iter().map(|d| d.id).chain(steps).collect(); + let mut id_source = IdSource::from_entropy(); + let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); + let fail = |e: solidcraft_doc::DocError| bad(cmd, e.to_string()); + let mut d = Drawing::new(&name, language, "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &taken, &mut id_source).map_err(fail)?; + let source = d.allocate_id(&mut id_source).map_err(fail)?; + d.sources.push(Source { id: source }); + if let Some(units) = units(cmd, p)? { + d.units = units; + } + d.validate().map_err(fail)?; + s.open_drawing = Some(d.id); + s.doc_mut().put_drawing(Arc::new(d)); + inspect(s, &Value::Null) +} + +fn list(s: &mut Session, _p: &Value) -> Result { + let listed: Vec = s + .doc + .drawings + .iter() + .map(|d| json!({"id": ids::encode(d.id), "name": d.name, "sheets": d.sheets.len(), "open": s.open_drawing == Some(d.id)})) + .collect(); + Ok(json!({"drawings": listed})) +} + +fn open(s: &mut Session, p: &Value) -> Result { + s.open_drawing = Some(named("drawing.open", s, p)?); + inspect(s, &Value::Null) +} + +fn close(s: &mut Session, _p: &Value) -> Result { + Ok(json!({"closed": s.open_drawing.take().map(ids::encode)})) +} + +fn delete(s: &mut Session, p: &Value) -> Result { + let id = named("drawing.delete", s, p)?; + if s.open_drawing == Some(id) { + s.open_drawing = None; + } + s.doc_mut().drawings.retain(|d| d.id != id); + Ok(json!({"deleted": ids::encode(id)})) +} + +/// The drawing open, as `drawing.inspect` answers, which making and opening one answer too. +fn inspect(s: &mut Session, _p: &Value) -> Result { + let cmd = "drawing.inspect"; + let d = s.drawing(cmd)?; + let mut sheets = Vec::with_capacity(d.sheets.len()); + for sheet in &d.sheets { + let size = sheet.sheet.size_mm().map_err(|e| bad(cmd, e.to_string()))?; + sheets.push(json!({ + "id": ids::encode(sheet.id), + "name": sheet.name, + "size_mm": [size.x, size.y], + "orientation": sheet.sheet.orientation, + "dpi": sheet.dpi, + "documents": sheet.documents.map(|c| json!({"source": ids::encode(c.source), "component": c.component})), + "excluded": sheet.excluded, + })); + } + Ok(json!({ + "id": ids::encode(d.id), + "name": d.name, + "units": d.units, + "language": d.language, + "properties": d.properties, + "sources": d.sources.iter().map(|source| json!({"id": ids::encode(source.id)})).collect::>(), + "sheets": sheets, + })) +} + +fn set(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.set"; + s.edit_drawing(cmd, |d| { + if let Some(name) = text(cmd, p, "name")? { + d.name = name.to_string(); + } + if let Some(language) = text(cmd, p, "language")? { + d.language = language.to_string(); + } + if let Some(units) = units(cmd, p)? { + d.units = units; + } + Ok(()) + })?; + inspect(s, &Value::Null) +} + +fn properties(s: &mut Session, _p: &Value) -> Result { + Ok(super::metadata::reading(&s.drawing("drawing.properties")?.properties)) +} + +/// The open drawing with the properties `next`, kept when they changed: one undo step. +fn keep_properties(s: &mut Session, cmd: &str, next: solidcraft_doc::Metadata) -> Result { + s.edit_drawing(cmd, |d| { + d.properties = next; + Ok(()) + })?; + Ok(json!(s.drawing(cmd)?.properties)) +} + +fn properties_set(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.properties.set"; + let (next, changed) = super::metadata::setting(cmd, &s.drawing(cmd)?.properties, p)?; + let metadata = keep_properties(s, cmd, next)?; + Ok(json!({"metadata": metadata, "changed": changed})) +} + +fn properties_remove(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.properties.remove"; + let (next, removed) = super::metadata::removing(cmd, &s.drawing(cmd)?.properties, p)?; + let metadata = keep_properties(s, cmd, next)?; + Ok(json!({"metadata": metadata, "removed": removed})) +} + +#[cfg(test)] +#[path = "drawing_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/drawing_tests.rs b/crates/engine/src/cmd/drawing_tests.rs new file mode 100644 index 00000000000..cfc7199db76 --- /dev/null +++ b/crates/engine/src/cmd/drawing_tests.rs @@ -0,0 +1,454 @@ +use super::*; +use crate::cmd::{Part, command_specs, find_command}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn refused(s: &mut Session, id: &str, p: Value) -> String { + s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("{id} accepted {p}")) +} + +/// A folder of the test's own, removed when dropped. +struct Folder(std::path::PathBuf); + +impl Folder { + fn new(name: &str) -> Folder { + let dir = solidcraft_io::vfs::temp_dir().join(format!("solidcraft-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + Folder(dir) + } + fn path(&self, file: &str) -> String { + self.0.join(file).to_str().unwrap().to_string() + } +} + +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A design with a box. +fn design() -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Plate"})); + s +} + +/// The drawing open, as the design holds it. +fn open_one(s: &Session) -> Arc { + s.drawing("test").unwrap().clone() +} + +/// The params naming drawing `id`. +fn the(id: u64) -> Value { + json!({"drawing": ids::encode(id)}) +} + +fn names(s: &Session) -> Vec<&str> { + s.doc.drawings.iter().map(|d| d.name.as_str()).collect() +} + +/// A drawing of the design: one A3 sheet with the ISO border, the design its one source, kept in +/// the design and opened. Making it is one step of the model, and evaluates nothing. +#[test] +fn a_drawing_of_the_design_is_kept_in_it_and_opened() { + let mut s = design(); + let (undo, evaluations, features) = (s.undo.len(), s.evaluations, s.doc.features.clone()); + let made = run(&mut s, "drawing.create", json!({"name": "Plate drawing", "units": "mm"})); + assert_eq!((made["name"].as_str(), made["language"].as_str()), (Some("Plate drawing"), Some("en"))); + assert_eq!(made["units"], json!({"fixed": {"unit": "mm"}})); + let sheet = &made["sheets"][0]; + assert_eq!( + (sheet["size_mm"].clone(), sheet["orientation"].clone(), sheet["dpi"].clone()), + (json!([420.0, 297.0]), json!("landscape"), json!(300.0)) + ); + assert_eq!((made["sheets"].as_array().map(Vec::len), made["sources"].as_array().map(Vec::len)), (Some(1), Some(1))); + let d = open_one(&s); + assert_eq!(made["id"], json!(ids::encode(d.id))); + assert!(d.sheets[0].border.is_some(), "the ISO border"); + assert_eq!((s.doc.drawings.len(), s.open_drawing), (1, Some(d.id))); + assert_eq!((s.undo.len(), s.undo.last().map(|u| u.part)), (undo + 1, Some(None)), "a step of the model"); + assert_eq!((s.evaluations, &s.doc.features), (evaluations, &features), "nothing evaluated, the model as it was"); + assert!(s.is_dirty()); + assert_eq!(run(&mut s, "drawing.inspect", json!({})), made); + let listed = run(&mut s, "drawing.list", json!({})); + assert_eq!(listed, json!({"drawings": [{"id": made["id"], "name": "Plate drawing", "sheets": 1, "open": true}]})); + // Its name is the design's unless given. + run(&mut s, "drawing.close", json!({})); + run(&mut s, "drawing.create", json!({})); + assert_eq!(open_one(&s).name, s.doc.name); +} + +/// What making a drawing refuses, the design unchanged: an empty design, units, a language and a +/// name the record can't take, and a design that holds the most drawings already. +#[test] +fn a_drawing_is_made_only_of_a_design_with_something_in_it() { + assert!(refused(&mut Session::default(), "drawing.create", json!({})).contains("nothing to draw")); + let mut s = design(); + let before = s.doc.clone(); + for (p, says) in [ + (json!({"units": "parsec"}), "length unit"), + (json!({"units": 3}), "follow_model"), + (json!({"language": "e"}), "BCP 47"), + (json!({"name": " "}), "name"), + (json!({"name": 7}), "must be text"), + ] { + let e = refused(&mut s, "drawing.create", p.clone()); + assert!(e.contains(says), "{p}: {e}"); + assert!(Arc::ptr_eq(&s.doc, &before) && s.open_drawing.is_none() && s.undo.len() == 1, "{p}: nothing changed"); + } + run(&mut s, "drawing.create", json!({})); + run(&mut s, "drawing.close", json!({})); + let one = s.doc.drawings[0].clone(); + s.doc_mut().drawings = (1..=drawing::MAX_DRAWINGS as u64).map(|id| Arc::new(Drawing { id, ..(*one).clone() })).collect(); + let full = s.doc.clone(); + assert!(refused(&mut s, "drawing.create", json!({})).contains("at most 1000 drawings")); + assert!(Arc::ptr_eq(&s.doc, &full)); +} + +/// While a drawing is open the model's commands wait, and the drawing's run only while one is: +/// running a command, running it inside another and listing it all say so. +#[test] +fn model_and_drawing_commands_each_run_on_their_own_part() { + let mut s = design(); + for id in ["drawing.inspect", "drawing.set", "drawing.properties", "drawing.properties.set", "drawing.properties.remove"] { + assert!(refused(&mut s, id, json!({"name": "X", "key": "author", "value": "X"})).contains("open a drawing first"), "{id}"); + } + run(&mut s, "drawing.create", json!({})); + let doc = s.doc.clone(); + let boxed = json!({"length": 5, "width": 5, "height": 5}); + let e = refused(&mut s, "solid.box", boxed.clone()); + assert!(e.contains("a drawing is open: close it to change the model (drawing.close)"), "{e}"); + assert!(find_command("solid.box").unwrap().run_nested(&mut s, &boxed).is_err(), "nor inside another command"); + assert!(Arc::ptr_eq(&s.doc, &doc)); + let enabled = |s: &mut Session, id: &str| { + let listed = run(s, "engine.commands", json!({})); + listed.as_array().unwrap().iter().find(|c| c["id"] == id).map(|c| c["enabled"] == true).unwrap() + }; + assert!(!enabled(&mut s, "solid.box") && enabled(&mut s, "drawing.set")); + for id in ["edit.undo", "file.save", "file.new", "doc.open", "select.clear", "edit.checkpoint", "drawing.list", "drawing.close"] { + assert!(find_command(id).unwrap().allowed(&s).is_ok(), "{id} runs with a drawing open"); + } + run(&mut s, "drawing.close", json!({})); + assert!(enabled(&mut s, "solid.box") && !enabled(&mut s, "drawing.set")); + run(&mut s, "solid.box", boxed); + // A new design or another opened has no drawing open. + run(&mut s, "drawing.create", json!({})); + run(&mut s, "file.new", json!({})); + assert!(s.open_drawing.is_none() && s.doc.drawings.is_empty()); +} + +/// Each change of a drawing is one undo step of that drawing: undo and redo bring back the same +/// record, and a change to the same values is no step. No model is evaluated, and the design +/// changes, so whatever follows it sees each change. +#[test] +fn drawing_edits_are_undo_steps_of_the_drawing_that_evaluate_nothing() { + let mut s = design(); + run(&mut s, "drawing.create", json!({})); + let (first, evaluations, features, steps) = (open_one(&s), s.evaluations, s.doc.features.clone(), s.undo.len()); + let (doc, revision) = (s.doc.clone(), s.revision); + run(&mut s, "drawing.set", json!({"name": "Renamed", "language": "de", "units": "in"})); + let renamed = open_one(&s); + assert_eq!((renamed.name.as_str(), renamed.language.as_str()), ("Renamed", "de")); + assert_eq!(renamed.units, Units::Fixed { unit: "in".into() }); + assert!(!Arc::ptr_eq(&s.doc, &doc) && s.revision > revision, "the design changed"); + assert_eq!((s.undo.len(), s.undo.last().map(|u| u.part)), (steps + 1, Some(Some(first.id))), "a step of the drawing"); + run(&mut s, "drawing.set", json!({"name": "Renamed"})); + assert_eq!(s.undo.len(), steps + 1, "the same value again is no step"); + for _ in 0..100 { + assert_eq!(run(&mut s, "edit.undo", json!({}))["undone"], "Drawing Settings"); + assert!(Arc::ptr_eq(&open_one(&s), &first)); + run(&mut s, "edit.redo", json!({})); + assert!(Arc::ptr_eq(&open_one(&s), &renamed)); + } + assert_eq!((s.evaluations, &s.doc.features), (evaluations, &features), "no model evaluated or changed"); +} + +/// Undo and redo go through the open part's steps only. With a drawing open, its own steps; the +/// model's stay where they are. With none open, the model's steps, which put the design back as +/// it was but keep each drawing it had as it is now. +#[test] +fn undo_and_redo_go_through_one_part_at_a_time() { + let mut s = design(); + run(&mut s, "drawing.create", json!({"name": "A"})); + let id = open_one(&s).id; + run(&mut s, "drawing.set", json!({"name": "B"})); + run(&mut s, "drawing.close", json!({})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5})); + let two = s.doc.features.len(); + run(&mut s, "drawing.open", the(id)); + run(&mut s, "drawing.set", json!({"name": "C"})); + // In the drawing: C, B, A; the model's box stays. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!((open_one(&s).name.as_str(), s.doc.features.len()), ("A", two)); + assert!(refused(&mut s, "edit.undo", json!({})).contains("nothing to undo in this drawing (close it to undo in the model)")); + // In the model: the box goes and the drawing stays as it is now (A, where the step had B); + // then the drawing goes. + run(&mut s, "drawing.close", json!({})); + let evaluations = s.evaluations; + run(&mut s, "edit.undo", json!({})); + assert_eq!((s.doc.features.len(), names(&s)), (two - 1, vec!["A"])); + assert!(s.evaluations > evaluations, "the model's step evaluates the model"); + run(&mut s, "edit.undo", json!({})); + assert!(s.doc.drawings.is_empty()); + // Redo: the drawing as it was when it went, then the box, the drawing kept. + run(&mut s, "edit.redo", json!({})); + assert_eq!((names(&s), s.open_drawing), (vec!["A"], None)); + run(&mut s, "edit.redo", json!({})); + assert_eq!((s.doc.features.len(), names(&s)), (two, vec!["A"])); + assert_eq!(refused(&mut s, "edit.redo", json!({})), "nothing to redo"); + // The drawing's own redo steps were kept all along. + run(&mut s, "drawing.open", the(id)); + run(&mut s, "edit.redo", json!({})); + run(&mut s, "edit.redo", json!({})); + assert_eq!(open_one(&s).name, "C"); + assert!(refused(&mut s, "edit.redo", json!({})).contains("nothing to redo in this drawing")); +} + +/// A new step ends what could be redone in its own part only: the others' redo steps still hold. +#[test] +fn a_new_step_ends_what_could_be_redone_in_its_part_only() { + let mut s = design(); + run(&mut s, "drawing.create", json!({"name": "A"})); + let id = open_one(&s).id; + run(&mut s, "drawing.set", json!({"name": "B"})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "drawing.close", json!({})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5})); + run(&mut s, "drawing.open", the(id)); + run(&mut s, "edit.redo", json!({})); + assert_eq!(open_one(&s).name, "B", "a model step leaves the drawing's redo"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "drawing.set", json!({"name": "Z"})); + assert!(refused(&mut s, "edit.redo", json!({})).contains("nothing to redo in this drawing"), "a drawing step ends its own"); + run(&mut s, "drawing.close", json!({})); + let features = s.doc.features.len(); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "drawing.open", the(id)); + run(&mut s, "drawing.set", json!({"name": "Q"})); + run(&mut s, "drawing.close", json!({})); + run(&mut s, "edit.redo", json!({})); + assert_eq!((s.doc.features.len(), names(&s)), (features, vec!["Q"]), "a drawing step leaves the model's redo"); +} + +/// A design lists its drawings by name, then id, whatever order they were made, renamed or +/// undone in. +#[test] +fn a_designs_drawings_are_listed_by_name_then_id() { + let mut s = design(); + for name in ["Zeta", "Alpha", "Mid", "Alpha"] { + run(&mut s, "drawing.create", json!({"name": name})); + } + assert_eq!(names(&s), ["Alpha", "Alpha", "Mid", "Zeta"]); + assert!(s.doc.drawings[0].id < s.doc.drawings[1].id); + let first = s.doc.drawings[0].id; + run(&mut s, "drawing.close", json!({})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5})); + run(&mut s, "drawing.open", the(first)); + run(&mut s, "drawing.set", json!({"name": "Zz"})); + assert_eq!(names(&s), ["Alpha", "Mid", "Zeta", "Zz"]); + let listed = run(&mut s, "drawing.list", json!({})); + let open: Vec = listed["drawings"].as_array().unwrap().iter().map(|d| d["open"] == true).collect(); + assert_eq!(open, [false, false, false, true]); + // The model's step, made before the rename, keeps the drawing renamed and in its place. + run(&mut s, "drawing.close", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), ["Alpha", "Mid", "Zeta", "Zz"]); + run(&mut s, "drawing.open", the(first)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), ["Alpha", "Alpha", "Mid", "Zeta"]); +} + +/// Deleting a drawing is a step of the model: it closes it when it was open, and undo brings it +/// back as it was, closed. What isn't a drawing of the design is refused. +#[test] +fn deleting_a_drawing_is_a_step_of_the_model() { + let mut s = design(); + run(&mut s, "drawing.create", json!({"name": "A"})); + let a = open_one(&s); + run(&mut s, "drawing.create", json!({"name": "B"})); + let b = open_one(&s); + let doc = s.doc.clone(); + for (p, says) in [(json!({}), "must be a drawing's id"), (json!({"drawing": 7}), "must be a drawing's id"), (the(1), "has no drawing")] { + let e = refused(&mut s, "drawing.delete", p.clone()); + assert!(e.contains(says), "{p}: {e}"); + assert!(Arc::ptr_eq(&s.doc, &doc) && s.open_drawing == Some(b.id)); + } + assert_eq!(run(&mut s, "drawing.delete", the(b.id)), json!({"deleted": ids::encode(b.id)})); + assert_eq!((names(&s), s.open_drawing), (vec!["A"], None)); + run(&mut s, "drawing.delete", the(a.id)); + assert!(s.doc.drawings.is_empty()); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(Arc::ptr_eq(&s.doc.drawings[0], &a) && Arc::ptr_eq(&s.doc.drawings[1], &b), "back as they were"); + assert_eq!(s.open_drawing, None); + assert!(refused(&mut s, "drawing.open", the(1)).contains("has no drawing")); +} + +/// A refused change leaves the drawing as it was, with no step, and a refused opening leaves the +/// drawing open as it was. +#[test] +fn a_refused_change_leaves_the_drawing_as_it_was() { + let mut s = design(); + run(&mut s, "drawing.create", json!({})); + let (before, steps) = (s.doc.clone(), s.undo.len()); + for p in [json!({"language": "e"}), json!({"name": ""}), json!({"units": "kg"}), json!({"name": "x".repeat(300)})] { + refused(&mut s, "drawing.set", p.clone()); + assert!(Arc::ptr_eq(&s.doc, &before) && s.undo.len() == steps, "{p}"); + } + let open = s.open_drawing; + refused(&mut s, "drawing.open", json!({"drawing": "AAAAAAAAAAAAA"})); + assert_eq!(s.open_drawing, open); +} + +/// A checkpoint brings back the design's drawings, the one open and the undo history. Going back +/// over a change of the model and of a drawing evaluates the model: it is no drawing-only change. +#[test] +fn a_checkpoint_brings_back_the_drawings_and_the_one_open() { + let mut s = design(); + run(&mut s, "drawing.create", json!({"name": "A"})); + let a = open_one(&s); + let (checkpoint, steps, features) = (run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].clone(), s.undo.len(), s.doc.features.clone()); + run(&mut s, "drawing.set", json!({"name": "B"})); + run(&mut s, "drawing.close", json!({})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + run(&mut s, "drawing.delete", the(a.id)); + run(&mut s, "drawing.create", json!({"name": "C"})); + let evaluations = s.evaluations; + run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": checkpoint})); + assert!(s.doc.drawings.len() == 1 && Arc::ptr_eq(&s.doc.drawings[0], &a)); + assert_eq!((s.open_drawing, s.undo.len(), &s.doc.features), (Some(a.id), steps, &features)); + assert!(s.evaluations > evaluations, "the model changed too, so it is evaluated"); +} + +/// A design's drawings are saved in its file and come back with it, as a container and as plain +/// JSON, with a drawing open when it is saved; a design opened has none open. +#[test] +fn a_designs_drawings_are_saved_with_it_and_come_back() { + let folder = Folder::new("drawing-saved"); + let mut s = design(); + run(&mut s, "drawing.create", json!({"name": "A", "language": "en-GB"})); + run(&mut s, "drawing.properties.set", json!({"values": {"author": "Jane Doe", "com.acme.shop": {"shop_id": 88}}})); + run(&mut s, "drawing.create", json!({"name": "B", "units": "mm"})); + let drawings = s.doc.drawings.clone(); + for file in ["plate.solidcraft", "plate.json"] { + run(&mut s, "file.save", json!({"path": folder.path(file)})); + assert!(!s.is_dirty(), "{file}"); + let mut opened = Session::default(); + run(&mut opened, "doc.open", json!({"path": folder.path(file)})); + assert_eq!(opened.doc.drawings, drawings, "{file}"); + assert!(opened.open_drawing.is_none(), "{file}"); + } +} + +/// A drawing's properties follow the design properties' rules: set, read and removed, each change +/// one undo step, other tools' keys kept, and what the design's would refuse refused. +#[test] +fn a_drawings_properties_follow_the_design_properties_rules() { + let mut s = design(); + run(&mut s, "drawing.create", json!({})); + let steps = s.undo.len(); + let set = run(&mut s, "drawing.properties.set", json!({"values": {"author": "Jane Doe", "com.acme.shop": {"shop_id": 88}}})); + assert_eq!(set["changed"], json!(["author", "com.acme.shop"])); + assert_eq!(s.undo.len(), steps + 1); + let read = run(&mut s, "drawing.properties", json!({})); + assert_eq!((read["properties"]["author"].clone(), read["metadata"]["com.acme.shop"]["shop_id"].clone()), (json!("Jane Doe"), json!(88))); + assert_eq!(read["properties"]["revision"], Value::Null); + run(&mut s, "drawing.properties.set", json!({"key": "author", "value": "Jane Doe"})); + assert_eq!(s.undo.len(), steps + 1, "the same value again is no change"); + let removed = run(&mut s, "drawing.properties.remove", json!({"keys": ["author", "missing"]})); + assert_eq!(removed["removed"], json!(["author"])); + assert_eq!((open_one(&s).properties.text("author"), s.undo.len()), (None, steps + 2)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(open_one(&s).properties.text("author"), Some("Jane Doe")); + assert!(s.doc.metadata.text("author").is_none(), "the design's own properties untouched"); + let before = open_one(&s); + for (id, p, says) in [ + ("drawing.properties.set", json!({"key": "bom_type", "value": "purchased"}), "component.metadata.set"), + ("drawing.properties.set", json!({"key": "author"}), "`value` is required"), + ("drawing.properties.set", json!({"values": {"author": 7}}), "author"), + ("drawing.properties.remove", json!({"keys": [1]}), "list of keys"), + ] { + let e = refused(&mut s, id, p.clone()); + assert!(e.contains(says), "{p}: {e}"); + assert!(Arc::ptr_eq(&open_one(&s), &before)); + } +} + +/// Hostile values for each key of every command that runs with a drawing open, from the registry, +/// and as the whole params, each on a copy of one session with a drawing open (the shared pass +/// runs with none, where the part gate refuses them): an error or a result, never a panic, and the +/// design's drawings and the one open still keeping their rules. As in the shared pass, what +/// writes files is left to its own tests; the recovery commands never read a drawing. +#[test] +fn hostile_drawing_params_never_panic() { + let mut s = design(); + run(&mut s, "drawing.create", json!({})); + run(&mut s, "drawing.create", json!({"name": "Second"})); + assert_eq!(s.scratch().open_drawing, s.open_drawing, "each copy has the drawing open"); + let keys = ["name", "language", "units", "drawing", "key", "value", "values", "keys", "checkpoint", "id"]; + let skipped = |id: &str| matches!(id, "doc.open" | "file.save" | "file.save_as") || id.starts_with("doc.recover"); + let mut internal = Vec::new(); + for spec in command_specs().iter().filter(|spec| spec.part != Part::Model && !skipped(spec.id)) { + for value in crate::tests::hostile_values() { + for p in keys.iter().map(|key| json!({ *key: value.clone() })).chain([value.clone()]) { + let mut copy = s.scratch(); + if let Err(crate::EngineError::Internal(_, msg)) = copy.execute(spec.id, &p) { + internal.push(format!("{} {p}: {msg}", spec.id)); + } + drawing::check_in_design(©.doc.drawings).unwrap(); + copy.doc.drawings.iter().for_each(|d| d.validate().unwrap()); + assert!(copy.open_drawing.is_none_or(|id| copy.doc.drawing(id).is_some()), "{} {p}", spec.id); + } + } + } + assert!(internal.is_empty(), "commands panicked with a drawing open:\n{}", internal.join("\n")); +} + +/// Making, opening, closing, changing and deleting drawings, model edits, undo, redo and +/// checkpoints in any order: never a panic, and the design's drawings and the one open always +/// keep their rules. +#[test] +fn drawing_steps_in_any_order_keep_the_rules() { + let mut state = 3890_u64; + let mut next = move |n: u64| { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (state >> 33) % n + }; + for _ in 0..12 { + let mut s = design(); + let mut checkpoints = Vec::new(); + for _ in 0..50 { + let pick = next(8) as usize; + let named = s.doc.drawings.get(pick % s.doc.drawings.len().max(1)).map_or(json!({"drawing": "AAAAAAAAAAAAA"}), |d| the(d.id)); + let (id, p) = match next(11) { + 0 => ("drawing.create", json!({"name": format!("D{}", next(4))})), + 1 => ("drawing.open", named), + 2 => ("drawing.close", json!({})), + 3 => ("drawing.set", json!({"name": format!("D{}", next(4))})), + 4 => ("drawing.delete", named), + 5 | 6 => ("edit.undo", json!({})), + 7 => ("edit.redo", json!({})), + 8 => ("solid.box", json!({"length": 1 + next(9), "width": 3, "height": 3})), + 9 => ("drawing.properties.set", json!({"key": "author", "value": format!("A{}", next(3))})), + _ => match checkpoints.pop() { + Some(checkpoint) if next(2) == 0 => ("edit.restore_checkpoint", json!({"checkpoint": checkpoint})), + _ => ("edit.checkpoint", json!({})), + }, + }; + let r = s.execute(id, &p); + if id == "edit.checkpoint" + && let Ok(v) = &r + { + checkpoints.push(v["checkpoint"].clone()); + } + assert!(!matches!(r, Err(crate::EngineError::Internal(..))), "{id} {p}: {r:?}"); + drawing::check_in_design(&s.doc.drawings).unwrap(); + assert!(s.doc.drawings.windows(2).all(|w| (&w[0].name, w[0].id) < (&w[1].name, w[1].id)), "{id}: in their order"); + assert!(s.open_drawing.is_none_or(|id| s.doc.drawing(id).is_some()), "{id}: the drawing open is the design's"); + } + } +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e9b3d7ec5ed..d5f01b11791 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1,22 +1,24 @@ //! Undo/redo, the timeline, deletion and selection. use std::collections::BTreeMap; +use std::sync::Arc; use serde_json::{Value, json}; -use solidcraft_doc::{Feature, FeatureKind}; +use solidcraft_doc::drawing::{self, Drawing}; +use solidcraft_doc::{Document, Feature, FeatureKind}; use super::CommandSpec; use crate::params::{bad, bool_, num, str_, string_list}; use crate::{EngineError, Result, Sel, Session, Snapshot}; pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("edit.undo", "Undo", undo).icon("undo").key("Ctrl+Z").noundo().doc_only(), - CommandSpec::new("edit.redo", "Redo", redo).icon("redo").key("Ctrl+Y").noundo().doc_only(), - CommandSpec::new("edit.checkpoint", "Checkpoint", checkpoint).icon("checkpoint") + CommandSpec::new("edit.undo", "Undo", undo).any_part().icon("undo").key("Ctrl+Z").noundo().doc_only(), + CommandSpec::new("edit.redo", "Redo", redo).any_part().icon("redo").key("Ctrl+Y").noundo().doc_only(), + CommandSpec::new("edit.checkpoint", "Checkpoint", checkpoint).any_part().icon("checkpoint") .noundo() .doc_only() .params("→ {checkpoint: id}: remember the design, active sketch and undo history (restore with edit.restore_checkpoint)"), - CommandSpec::new("edit.restore_checkpoint", "Restore Checkpoint", restore_checkpoint).icon("restore") + CommandSpec::new("edit.restore_checkpoint", "Restore Checkpoint", restore_checkpoint).any_part().icon("restore") .noundo() .doc_only() .params("checkpoint: id; forget?: bool (true = drop it without going back). Goes back to it, undo history included"), @@ -68,14 +70,14 @@ pub static COMMANDS: &[CommandSpec] = &[ "feature: id|name → type, definition (the fields timeline.edit's set changes, with their current values), \ inputs: [{label, param, expression, unit}] (named inputs parameters.change can also set), error, warning", ), - CommandSpec::new("select.set", "Select", select_set).icon("select") + CommandSpec::new("select.set", "Select", select_set).any_part().icon("select") .noundo() .params("items: [{type: body|edge|face|feature|sketch_curve|sketch_point|profile, …}], add?: bool"), - CommandSpec::new("select.clear", "Clear Selection", select_clear).icon("select").noundo(), + CommandSpec::new("select.clear", "Clear Selection", select_clear).any_part().icon("select").noundo(), ]; fn undo(s: &mut Session, _p: &Value) -> Result { - let Some(prev) = s.undo.pop() else { return Err(EngineError::Other("nothing to undo".into())) }; + let prev = latest(&mut s.undo, s.open_drawing).ok_or_else(|| nothing(s, "undo"))?; let now = go_to(s, prev); let label = now.label.clone(); s.redo.push(now); @@ -83,28 +85,78 @@ fn undo(s: &mut Session, _p: &Value) -> Result { } fn redo(s: &mut Session, _p: &Value) -> Result { - let Some(next) = s.redo.pop() else { return Err(EngineError::Other("nothing to redo".into())) }; + let next = latest(&mut s.redo, s.open_drawing).ok_or_else(|| nothing(s, "redo"))?; let now = go_to(s, next); let label = now.label.clone(); s.undo.push(now); Ok(json!({"redone": label})) } -/// Put the session at `snap`; returns where it was, under the same label. +/// Takes the latest of `steps` on `part` (the open drawing, else the model): undo and redo go +/// through one part's steps, and leave the others' where they are. +fn latest(steps: &mut Vec, part: Option) -> Option { + let at = steps.iter().rposition(|step| step.part == part)?; + Some(steps.remove(at)) +} + +fn nothing(s: &Session, what: &str) -> EngineError { + match s.open_drawing { + Some(_) => EngineError::Other(format!("nothing to {what} in this drawing (close it to {what} in the model)")), + None => EngineError::Other(format!("nothing to {what}")), + } +} + +/// Put the session at `snap`; returns where it was, under the same label. A drawing's step puts +/// back only that drawing. The model's step puts back the design as it was, but keeps each +/// drawing the design had as it is now: each part's steps are undone in that part only. Neither +/// opens or closes a drawing: a drawing's steps are taken while it is open, and the model's while +/// none is. fn go_to(s: &mut Session, snap: Snapshot) -> Snapshot { - let was = Snapshot { label: snap.label, doc: s.doc.clone(), active_sketch: s.active_sketch, pending_moves: s.pending_moves.clone() }; - let same = std::sync::Arc::ptr_eq(&s.doc, &snap.doc); + let was = Snapshot { part: snap.part, ..Snapshot::of(s, &snap.label) }; + let snap = match snap.part { + Some(id) => Snapshot { doc: drawing_from(&s.doc, &snap.doc, id), ..was.clone() }, + None => Snapshot { doc: drawings_from(snap.doc, &s.doc), ..snap }, + }; + let same = Arc::ptr_eq(&s.doc, &snap.doc); + let moved = s.active_sketch != snap.active_sketch || s.pending_moves != snap.pending_moves; s.doc = snap.doc; s.active_sketch = snap.active_sketch; s.pending_moves = snap.pending_moves; s.selection.clear(); - // A new document is evaluated by `execute`. - if same { + // A new document is evaluated by `execute`, and a drawing's change evaluates nothing. + if same && moved { s.refresh(); } was } +/// `doc` with its drawing `id` as `step` has it. +fn drawing_from(doc: &Arc, step: &Document, id: u64) -> Arc { + let mut doc = doc.clone(); + if let Some(then) = step.drawing(id) + && !doc.drawing(id).is_some_and(|now| Arc::ptr_eq(then, now)) + { + Arc::make_mut(&mut doc).put_drawing(then.clone()); + } + doc +} + +/// The model's step `step` with each of its drawings as `now` has it. +fn drawings_from(mut step: Arc, now: &Document) -> Arc { + let current = |d: &Arc| now.drawing(d.id).filter(|n| !Arc::ptr_eq(d, n)); + if step.drawings.iter().any(|d| current(d).is_some()) { + let mut drawings = step.drawings.clone(); + for d in &mut drawings { + if let Some(n) = current(d) { + *d = n.clone(); + } + } + drawing::sort(&mut drawings); + Arc::make_mut(&mut step).drawings = drawings; + } + step +} + fn checkpoint(s: &mut Session, _p: &Value) -> Result { Ok(json!({"checkpoint": s.checkpoint()})) } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index c39e5a09732..ba9a7816b46 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -15,8 +15,8 @@ use crate::params::{bad, bool_, num, str_, string_list}; use crate::{EngineError, Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("file.new", "New Design", new_doc).icon("new").key("Ctrl+N").noundo().params("name?"), - CommandSpec::new("doc.open", "Open", open) + CommandSpec::new("file.new", "New Design", new_doc).any_part().icon("new").key("Ctrl+N").noundo().params("name?"), + CommandSpec::new("doc.open", "Open", open).any_part() .icon("open") .key("Ctrl+O") .noundo() @@ -29,22 +29,22 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "INSERT") .icon("import") .params("path: .3mf, .stl, .obj, .glb or .gltf file (its meshes join the design as mesh bodies in a new component named after the file → component, component_name, occurrence; a glTF file's node tree becomes nested components held as one rigid group until component.unlock, a mesh placed again another occurrence, its materials the bodies' appearances, and its metres millimetres); name?; up?: z|y for a glTF file (default y: glTF has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence; z: the file's axes are kept)"), - CommandSpec::new("file.save", "Save", save) + CommandSpec::new("file.save", "Save", save).any_part() .icon("save") .key("Ctrl+S") .noundo() .params("path? (default: current file); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false)"), - CommandSpec::new("file.save_as", "Save As", save_as) + CommandSpec::new("file.save_as", "Save As", save_as).any_part() .icon("save") .noundo() .params("path; format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false)"), - CommandSpec::new("doc.recovery_list", "Recoverable Designs", recovery_list).icon("restore") + CommandSpec::new("doc.recovery_list", "Recoverable Designs", recovery_list).any_part().icon("restore") .noundo() .params("dir? (default: the recovery folder) → designs autosaved by apps that crashed or closed with unsaved changes"), - CommandSpec::new("doc.recover", "Recover Design", recover).icon("restore") + CommandSpec::new("doc.recover", "Recover Design", recover).any_part().icon("restore") .noundo() .params("id (from doc.recovery_list); dir?; discard?: bool (delete the entry once open) — opens it with its file path, unsaved"), - CommandSpec::new("doc.recovery_discard", "Discard Recovered Design", recovery_discard).icon("delete").noundo().params("id, or all: true; dir?"), + CommandSpec::new("doc.recovery_discard", "Discard Recovered Design", recovery_discard).any_part().icon("delete").noundo().params("id, or all: true; dir?"), CommandSpec::new("file.export", "Export", export) .icon("export") .noundo() diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index 76394f11349..aecc7cce53c 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -43,8 +43,8 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .doc_only() .params("→ the built-in materials, then the design's own (user: true, with their look)"), - CommandSpec::new("engine.commands", "List Commands", commands).icon("list").noundo(), - CommandSpec::new("engine.describe", "Describe Command", crate::checked!("engine.describe", DESCRIBE_CONTRACT, describe)) + CommandSpec::new("engine.commands", "List Commands", commands).any_part().icon("list").noundo(), + CommandSpec::new("engine.describe", "Describe Command", crate::checked!("engine.describe", DESCRIBE_CONTRACT, describe)).any_part() .icon("list") .noundo() .doc_only() diff --git a/crates/engine/src/cmd/metadata.rs b/crates/engine/src/cmd/metadata.rs index 9f8cdf16750..00648d38299 100644 --- a/crates/engine/src/cmd/metadata.rs +++ b/crates/engine/src/cmd/metadata.rs @@ -2,9 +2,11 @@ //! `document.metadata.set` and `document.metadata.remove` change it, each in one undo step. The //! keys SolidCraft reads, and the checks a change gets, are `solidcraft_doc::metadata`'s; keys //! other tools wrote are kept as they are. The UI's Design Properties dialog, scripts and MCP -//! agents all go through these commands. +//! agents all go through these commands. A drawing's properties are read and changed by the +//! same rules ([`reading`], [`setting`], [`removing`]), through `drawing.properties`. use serde_json::{Map, Value, json}; +use solidcraft_doc::Metadata; use solidcraft_doc::metadata::{BOM_TYPE, MAX_KEYS, WELL_KNOWN}; use super::CommandSpec; @@ -27,14 +29,16 @@ pub static COMMANDS: &[CommandSpec] = &[ .params("key, or keys: [keys] (any key, also one another tool wrote) → metadata, removed: [keys that were there]"), ]; -fn read(s: &mut Session, _: &Value) -> Result { - let m = &s.doc.metadata; +/// What reading `m` answers: the object as saved, and SolidCraft's properties, each its text or +/// null. +pub(super) fn reading(m: &Metadata) -> Value { let properties: Map = WELL_KNOWN.iter().map(|k| (k.to_string(), m.text(k).map_or(Value::Null, |t| json!(t)))).collect(); - Ok(json!({"metadata": m, "properties": properties})) + json!({"metadata": m, "properties": properties}) } -fn set(s: &mut Session, p: &Value) -> Result { - let cmd = "document.metadata.set"; +/// `m` with a call's `key` and `value`, or its `values`, set (all or nothing), and the keys that +/// changed. +pub(super) fn setting(cmd: &str, m: &Metadata, p: &Value) -> Result<(Metadata, Vec)> { let entries: Vec<(&str, &Value)> = match (p.get("values"), p.get("key")) { (Some(Value::Object(values)), None) if values.len() <= MAX_KEYS => values.iter().map(|(k, v)| (k.as_str(), v)).collect(), (Some(Value::Object(_)), None) => return Err(bad(cmd, format!("`values` can hold at most {MAX_KEYS} keys"))), @@ -45,7 +49,7 @@ fn set(s: &mut Session, p: &Value) -> Result { } _ => return Err(bad(cmd, "give `key` and `value`, or `values`: {key: value, …}")), }; - let mut next = s.doc.metadata.clone(); + let mut next = m.clone(); let mut changed = Vec::new(); for (key, value) in entries { if key == BOM_TYPE { @@ -55,15 +59,11 @@ fn set(s: &mut Session, p: &Value) -> Result { changed.push(key.to_string()); } } - // Only a real change touches the design (an undo step, unsaved changes). - if next != s.doc.metadata { - s.doc_mut().metadata = next; - } - Ok(json!({"metadata": s.doc.metadata, "changed": changed})) + Ok((next, changed)) } -fn remove(s: &mut Session, p: &Value) -> Result { - let cmd = "document.metadata.remove"; +/// `m` with a call's `key`, or its `keys`, removed, and the keys that were there. +pub(super) fn removing(cmd: &str, m: &Metadata, p: &Value) -> Result<(Metadata, Vec)> { let keys: Vec<&str> = match (p.get("keys"), p.get("key")) { (Some(Value::Array(keys)), None) if keys.len() <= MAX_KEYS => { keys.iter().map(Value::as_str).collect::>().ok_or_else(|| bad(cmd, "`keys` must be a list of keys"))? @@ -71,17 +71,36 @@ fn remove(s: &mut Session, p: &Value) -> Result { (None, Some(_)) => vec![str_(p, "key").ok_or_else(|| bad(cmd, "`key` must be text"))?], _ => return Err(bad(cmd, format!("give `key`, or `keys`: a list of at most {MAX_KEYS} keys"))), }; - let mut removed: Vec<&str> = Vec::new(); + let mut removed: Vec = Vec::new(); for k in keys { - if s.doc.metadata.get(k).is_some() && !removed.contains(&k) { - removed.push(k); + if m.get(k).is_some() && !removed.iter().any(|r| r == k) { + removed.push(k.to_string()); } } + let mut next = m.clone(); + for k in &removed { + next.remove(k); + } + Ok((next, removed)) +} + +fn read(s: &mut Session, _: &Value) -> Result { + Ok(reading(&s.doc.metadata)) +} + +fn set(s: &mut Session, p: &Value) -> Result { + let (next, changed) = setting("document.metadata.set", &s.doc.metadata, p)?; + // Only a real change touches the design (an undo step, unsaved changes). + if next != s.doc.metadata { + s.doc_mut().metadata = next; + } + Ok(json!({"metadata": s.doc.metadata, "changed": changed})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let (next, removed) = removing("document.metadata.remove", &s.doc.metadata, p)?; if !removed.is_empty() { - let m = &mut s.doc_mut().metadata; - for k in &removed { - m.remove(k); - } + s.doc_mut().metadata = next; } Ok(json!({"metadata": s.doc.metadata, "removed": removed})) } diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index b26c54e8658..b659d0eaf7e 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -31,6 +31,7 @@ mod component_clone_assembly; mod construct; mod delete; mod diagnostics; +mod drawing; mod edit; mod face; mod features; @@ -102,6 +103,16 @@ pub type LiveRun = fn(&mut Session, &Value) -> Result<(Value, Option std::result::Result<(), String>; pub type SchemaFn = fn() -> schemars::Schema; +/// The part of the design a command works on (#3890): the model (most commands), the open +/// drawing, or either (files, undo, selection, diagnostics, choosing a drawing). +/// [`CommandSpec::allowed`] checks it before the command's own `enabled`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Part { + Model, + Drawing, + Any, +} + pub struct CommandSpec { pub id: &'static str, pub label: &'static str, @@ -130,6 +141,8 @@ pub struct CommandSpec { pub contract: Option<&'static dyn crate::schema::Contract>, /// The JSON Schema of a successful result; `None` until described. pub output: Option, + /// The part of the design it works on: the model unless it says otherwise. + pub part: Part, } impl CommandSpec { @@ -150,6 +163,7 @@ impl CommandSpec { planned: None, contract: None, output: None, + part: Part::Model, } } /// Not built yet; `issue` tracks building it. @@ -202,14 +216,33 @@ impl CommandSpec { self.undoable = false; self } - /// Run inside another command: when it is enabled, its `run` (the caller's command owns the + /// Works with a drawing open or with none. + pub const fn any_part(mut self) -> Self { + self.part = Part::Any; + self + } + /// Works on the open drawing. + pub const fn in_drawing(mut self) -> Self { + self.part = Part::Drawing; + self + } + /// Whether the command can run in `s` now: on the part open, and enabled. The one check + /// running a command, running it inside another and listing it make. + pub fn allowed(&self, s: &Session) -> std::result::Result<(), String> { + match (self.part, s.open_drawing.is_some()) { + (Part::Model, true) => Err("a drawing is open: close it to change the model (drawing.close)".into()), + (Part::Drawing, false) => Err("open a drawing first (drawing.open, or drawing.create)".into()), + _ => (self.enabled)(s), + } + } + /// Run inside another command: when it is allowed, its `run` (the caller's command owns the /// undo step and the evaluation). pub(crate) fn run_nested(&self, s: &mut Session, p: &Value) -> Result { - (self.enabled)(s).map_err(|why| crate::EngineError::Disabled(self.id.to_string(), why))?; + self.allowed(s).map_err(|why| crate::EngineError::Disabled(self.id.to_string(), why))?; (self.run)(s, p) } pub fn info(&self, s: &Session) -> CommandInfo { - let e = (self.enabled)(s); + let e = self.allowed(s); CommandInfo { id: self.id, label: self.label, @@ -303,6 +336,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(section::COMMANDS.iter()); v.extend(view_navigation::COMMANDS.iter()); v.extend(view_dxf::COMMANDS.iter()); + v.extend(drawing::COMMANDS.iter()); v.extend(diagnostics::COMMANDS.iter()); v.extend(render::COMMANDS.iter()); v diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 942e6b385f0..8a9ed5d6a50 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -164,6 +164,17 @@ pub struct Snapshot { pub doc: Arc, pub active_sketch: Option, pub pending_moves: std::collections::BTreeMap, + /// The part of the design the step changed: a drawing (by id), or the model and the list of + /// drawings (`None`). Undo and redo go through one part's steps (`edit.undo`). + pub part: Option, +} + +impl Snapshot { + /// The session as it is now, as a step of the model, under `label`: the one place a step is + /// taken. + pub fn of(s: &Session, label: &str) -> Snapshot { + Snapshot { label: label.to_string(), doc: s.doc.clone(), active_sketch: s.active_sketch, pending_moves: s.pending_moves.clone(), part: None } + } } /// A copy of a session that evaluates commands ahead of it ([`Session::ahead`]). @@ -243,6 +254,9 @@ pub struct Session { pub redo: Vec, /// Sketch feature being edited (sketch mode). pub active_sketch: Option, + /// The drawing open (by id): drawing commands change it, and the model's wait until it is + /// closed ([`cmd::Part`]). + pub open_drawing: Option, pub selection: Vec, pub path: Option, /// One-shot display-only notification during doc.open, before authoritative evaluation. @@ -321,12 +335,13 @@ pub struct LiveEdit { pub report: solidcraft_sketch::SolveReport, } -/// The design, active sketch, pending positions and undo history at an `edit.checkpoint`. +/// The design, active sketch, open drawing, pending positions and undo history at an `edit.checkpoint`. #[derive(Clone, Debug)] pub(crate) struct Checkpoint { pub id: u64, pub doc: Arc, pub active_sketch: Option, + pub open_drawing: Option, pub pending_moves: std::collections::BTreeMap, pub undo: Vec, pub redo: Vec, @@ -415,6 +430,7 @@ impl Session { undo: Vec::new(), redo: Vec::new(), active_sketch: None, + open_drawing: None, selection: Vec::new(), path: None, open_preview: None, @@ -557,6 +573,28 @@ impl Session { Arc::make_mut(&mut self.doc) } + /// The drawing open, for `cmd`. + pub fn drawing(&self, cmd: &str) -> Result<&Arc> { + self.open_drawing.and_then(|id| self.doc.drawing(id)).ok_or_else(|| params::bad(cmd, "open a drawing first (drawing.open)")) + } + + /// Change the drawing open, for `cmd`: kept when it still keeps the record's rules, and only + /// when it changed (one undo step of the drawing, through `execute`; the design's other + /// drawings shared). + pub fn edit_drawing(&mut self, cmd: &str, change: impl FnOnce(&mut solidcraft_doc::drawing::Drawing) -> Result) -> Result { + let open = self.drawing(cmd)?; + let mut d = (**open).clone(); + let out = change(&mut d)?; + if d.id != open.id { + return Err(params::bad(cmd, "a drawing keeps its id")); + } + d.validate().map_err(|e| params::bad(cmd, e.to_string()))?; + if d != **open { + self.doc_mut().put_drawing(Arc::new(d)); + } + Ok(out) + } + /// Prepared placements only: optional save caches must not compute a cold world. pub(crate) fn cached_world_state(&self) -> Option> { let state = self.model.state(); @@ -708,12 +746,14 @@ impl Session { Some((old, new)) } - /// Only persistent render intent, or only part properties, changed. Never evaluate or clear - /// a stale model here. + /// Only persistent render intent, part properties or drawings changed. Never evaluate or + /// clear a stale model here. fn render_only_change(&self, before: &Snapshot) -> bool { self.active_sketch == before.active_sketch && self.pending_moves == before.pending_moves - && (self.doc.differs_only_in_render(&before.doc) || self.doc.differs_only_in_part_properties(&before.doc)) + && (self.doc.differs_only_in_render(&before.doc) + || self.doc.differs_only_in_part_properties(&before.doc) + || self.doc.differs_only_in_drawings(&before.doc)) } fn refresh_render(&mut self, previous: &Arc) { @@ -789,13 +829,9 @@ impl Session { if live.is_none() && spec.reads_model && self.model.is_stale() { self.refresh(); } - (spec.enabled)(self).map_err(|why| EngineError::Disabled(spec.id.to_string(), why))?; - let before = Snapshot { - label: spec.label.to_string(), - doc: self.doc.clone(), - active_sketch: self.active_sketch, - pending_moves: self.pending_moves.clone(), - }; + spec.allowed(self).map_err(|why| EngineError::Disabled(spec.id.to_string(), why))?; + let open_drawing = self.open_drawing; + let before = Snapshot { part: open_drawing.filter(|_| spec.part == cmd::Part::Drawing), ..Snapshot::of(self, spec.label) }; let null = Value::Object(Default::default()); let params = if params.is_null() { &null } else { params }; let given = params; @@ -834,6 +870,7 @@ impl Session { let changed = !Arc::ptr_eq(&self.doc, &before.doc) || self.active_sketch != before.active_sketch || self.pending_moves != before.pending_moves + || self.open_drawing != open_drawing || spec.id.starts_with("select."); crash::command_done(self.crash_journal, changed, &before.doc, after, spec.id, given, failed.map_or(Ok(()), Err)); } @@ -845,11 +882,14 @@ impl Session { let render_only = self.render_only_change(&before); let previous_doc = before.doc.clone(); if spec.undoable { + // A new step ends what could be redone in its part; the other parts' redo + // steps still hold, as undo puts back only the part a step changed. + let part = before.part; self.undo.push(before); if self.undo.len() > MAX_UNDO { self.undo.remove(0); } - self.redo.clear(); + self.redo.retain(|step| step.part != part); } match live_edit { Some(edit) => self.refresh_live(edit), @@ -860,6 +900,7 @@ impl Session { Ok(v) } Err(e) => { + self.open_drawing = open_drawing; if changed || self.pending_moves != before.pending_moves { self.doc = before.doc; self.active_sketch = before.active_sketch; @@ -892,7 +933,8 @@ impl Session { v } - /// Remember the design, active sketch, pending positions and undo history; returns the checkpoint's id. + /// Remember the design, active sketch, open drawing, pending positions and undo history; + /// returns the checkpoint's id. pub fn checkpoint(&mut self) -> u64 { let id = self.next_checkpoint; self.next_checkpoint += 1; @@ -900,6 +942,7 @@ impl Session { id, doc: self.doc.clone(), active_sketch: self.active_sketch, + open_drawing: self.open_drawing, undo: self.undo.clone(), pending_moves: self.pending_moves.clone(), redo: self.redo.clone(), @@ -915,10 +958,10 @@ impl Session { pub fn restore_checkpoint(&mut self, id: u64) -> Result<()> { let i = self.checkpoints.iter().position(|c| c.id == id).ok_or_else(|| EngineError::Other(format!("no checkpoint {id}")))?; let Some(c) = self.checkpoints.drain(i..).next() else { return Err(EngineError::Other(format!("no checkpoint {id}"))) }; - let before = - Snapshot { label: String::new(), doc: self.doc.clone(), active_sketch: self.active_sketch, pending_moves: self.pending_moves.clone() }; + let before = Snapshot::of(self, ""); self.doc = c.doc; self.active_sketch = c.active_sketch; + self.open_drawing = c.open_drawing; self.pending_moves = c.pending_moves; self.undo = c.undo; self.redo = c.redo; @@ -947,6 +990,7 @@ impl Session { undo: Vec::new(), redo: Vec::new(), active_sketch: self.active_sketch, + open_drawing: self.open_drawing, selection: self.selection.clone(), path: None, open_preview: None, diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index e73f401faea..dc434a299e4 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -1270,7 +1270,8 @@ fn end_turn(app: &mut SolveApp) { } /// Merge the undo steps made since `start_doc` (at depth `start_undo`) into one, labelled `label`; -/// how many steps it took in (0: none were made, or the history no longer reaches that far). +/// how many steps it took in (0: none were made, the history no longer reaches that far, or they +/// changed several parts of the design, whose steps are each undone in their own part). fn merge_undo( undo: &mut Vec, start_doc: &Arc, @@ -1282,6 +1283,10 @@ fn merge_undo( let Some(first) = (0..undo.len().min(start_undo + 1)).rev().find(|&i| undo.get(i).is_some_and(|s| Arc::ptr_eq(&s.doc, start_doc))) else { return 0; }; + let part = undo.get(first).map(|s| s.part); + if undo.iter().skip(first).any(|s| Some(s.part) != part) { + return 0; + } let steps = undo.len() - first; undo.truncate(first + 1); if let Some(s) = undo.get_mut(first) { diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 04c215735b5..d2db1ffcc50 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -175,6 +175,7 @@ fn merging_finds_the_turns_start_when_the_history_was_trimmed() { doc: d.clone(), active_sketch: None, pending_moves: Default::default(), + part: None, }; let docs: Vec<_> = (0..6).map(doc).collect(); // The turn began at depth 3 with docs[3]; the history then lost its oldest step. @@ -186,6 +187,11 @@ fn merging_finds_the_turns_start_when_the_history_was_trimmed() { let mut undo: Vec<_> = docs[1..6].iter().map(snap).collect(); assert_eq!(merge_undo(&mut undo, &doc(9), 3, "Agent"), 0); assert_eq!(undo.len(), 5); + // A drawing's step among the model's: each part keeps its own steps. + let mut undo: Vec<_> = docs[1..6].iter().map(snap).collect(); + undo[3].part = Some(7); + assert_eq!(merge_undo(&mut undo, &docs[3], 3, "Agent"), 0); + assert_eq!(undo.len(), 5); } /// People who don't want AI never see it: with "Show AI features" off there is no button, the diff --git a/docs/mcp.md b/docs/mcp.md index 5741e169542..6ffd967bb4d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -200,8 +200,8 @@ Errors: an unknown tool or arguments that don't match the tool's schema are JSON result with `isError: true` and the engine's message, which the model can read and correct. `batch` rollback goes back to an engine checkpoint (`edit.checkpoint`) taken before the first -step: the design, the active sketch and the undo history are restored exactly as they were, -however long the history is. Batches that call `file.new` or `doc.open` get the design back, +step: the design (its drawings too), the active sketch, the drawing open and the undo history +are restored exactly as they were, however long the history is. Batches that call `file.new` or `doc.open` get the design back, not its file path. (An older app without checkpoints falls back to undoing as many steps as the batch added to the undo history.) From 36cf48a3f64c530a128f5d794f37b7cfa24cc3ab Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Tue, 27 Oct 2026 03:37:32 +0000 Subject: [PATCH 3/7] Unknown-command tests: the closest id first (#3890) drawing.open now joins doc.open in the suggestion for `file.open`, as the rule says: both end in the same word. The engine's and the CLI's tests check that doc.open comes first and let other close ids follow, as the `solid.extrud` line beside them already does. Co-Authored-By: Claude Opus 5.5 --- apps/solidcraft-cli/tests/run_results.rs | 5 +++-- crates/engine/src/tests.rs | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/apps/solidcraft-cli/tests/run_results.rs b/apps/solidcraft-cli/tests/run_results.rs index c5709904fdc..80fa1b24448 100644 --- a/apps/solidcraft-cli/tests/run_results.rs +++ b/apps/solidcraft-cli/tests/run_results.rs @@ -172,12 +172,13 @@ fn snapshot_runs_its_script_on_the_in_design() { } } -/// An unknown command's error suggests the id that was meant. +/// An unknown command's error suggests the id that was meant first; other close ids (such as +/// `drawing.open`) may follow it. #[test] fn unknown_command_suggests_the_closest_id() { let output = cli().args(["exec", "file.open"]).output().unwrap(); assert_eq!(output.status.code(), Some(1)); - assert!(String::from_utf8_lossy(&output.stderr).contains("did you mean `doc.open`?"), "{}", String::from_utf8_lossy(&output.stderr)); + assert!(String::from_utf8_lossy(&output.stderr).contains("did you mean `doc.open`"), "{}", String::from_utf8_lossy(&output.stderr)); } /// #1833: `--timings` reports each command's time instead of the measurement, `--profile` adds diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f2d8cf46a3f..14eeeaf5a4d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -892,12 +892,12 @@ fn only_own_ids_name_commands() { } /// An unknown command's error names the ids it was probably meant to be: a typo's, or the -/// command that ends in the same word. +/// commands that end in the same word, the nearest first. #[test] fn unknown_commands_suggest_the_closest_ids() { let mut s = Session::default(); let mut msg = |id: &str| s.execute(id, &serde_json::json!({})).unwrap_err().to_string(); - assert_eq!(msg("file.open"), "unknown command `file.open` (did you mean `doc.open`?)"); + assert!(msg("file.open").starts_with("unknown command `file.open` (did you mean `doc.open`"), "{}", msg("file.open")); assert!(msg("solid.extrud").starts_with("unknown command `solid.extrud` (did you mean `solid.extrude`"), "{}", msg("solid.extrud")); assert!(msg("Extrude").contains("`solid.extrude`"), "{}", msg("Extrude")); assert_eq!(msg("FusionFilletEdgesCommand"), "unknown command `FusionFilletEdgesCommand`"); From 30906de7910176063c51e7eb5b13d5fc15e089e4 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Sun, 25 Oct 2026 18:16:22 +0000 Subject: [PATCH 4/7] Model bodies: their extents seen on a plane, for a drawing view's size (#5866) ModelBody::mesh_bounds_in(plane) is the box of a body's mesh in a plane's own coordinates (Plane::to_local), beside mesh_bounds and in the same way: a body meshed already is measured from its own mesh, and a placement of a part from its definition's shared mesh, with the placement folded into the plane's two axes once (two dot products a point), so no moved copy is made. W07's drawing.view measures a view's extents with it. Tests: a 100 x 50 x 20 block seen on the three principal pairs of axes and from an isometric corner (150/sqrt(2) by 190/sqrt(6), worked by hand), a plane away from the origin, and every placement in the shared-mesh test against its moved mesh, still without a moved copy, and the same again from its own mesh once it is meshed. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/eval.rs | 17 ++++++++++++++++ crates/doc/src/placed_mesh.rs | 38 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 4eba4b2dd86..1e083ac059c 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -198,6 +198,23 @@ impl ModelBody { }) } + /// The box of [`ModelBody::mesh`] seen on a plane, in the plane's own coordinates + /// ([`Plane::to_local`]): a drawing view's extents (W07), again without making a placement's + /// moved copy. + pub fn mesh_bounds_in(&self, plane: &Plane) -> solidcraft_geom::Aabb2 { + let (mesh, m) = match self.cached_mesh() { + Some(mesh) => (mesh, crate::IDENTITY), + None => self.mesh_in_place(), + }; + // The placement folded into each of the plane's axes: a mesh point p lands at + // p · axis + offset, with no moved copy of the point made first. + let [c0, c1, c2, t] = m.map(|r| Vec3::new(r[0], r[1], r[2])); + let offset = t - plane.origin; + let axis = |a: Vec3| (Vec3::new(c0.dot(a), c1.dot(a), c2.dot(a)), offset.dot(a)); + let ((ax, ox), (ay, oy)) = (axis(plane.x), axis(plane.y)); + mesh.positions.iter().map(|p| Vec2::new(p.dot(ax) + ox, p.dot(ay) + oy)).collect() + } + /// [`ModelBody::plan_mesh_at`] as a shared mesh and the move that places it, as /// [`ModelBody::mesh_in_place`] does for the reference mesh. pub fn plan_mesh_in_place_at(&self, q: crate::display_quality::DisplayQuality) -> Option<(Arc, crate::Mat)> { diff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rs index 2131f89db86..130b302a57b 100644 --- a/crates/doc/src/placed_mesh.rs +++ b/crates/doc/src/placed_mesh.rs @@ -133,6 +133,8 @@ fn proper_rigid(m: &crate::Mat) -> bool { } #[cfg(test)] mod tests { + use solidcraft_geom::{Plane, Vec2}; + use super::*; #[test] @@ -162,6 +164,32 @@ mod tests { assert!(Arc::ptr_eq(&mesh, &nested.mesh())); } + /// A block 100 x 50 x 20 mm seen on a view's plane measures as worked by hand: its size along + /// each principal pair of axes, and from an isometric corner (150/sqrt(2) wide, 190/sqrt(6) + /// high; the box's extremes are its corners, so the mesh gives them exactly). A body meshed + /// already is measured from its own mesh. + #[test] + fn a_bodys_bounds_on_a_plane_are_its_mesh_seen_on_it() { + let block = ModelBody::new("Block".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(100., 50., 20.)).unwrap(), 1); + let plane = |x: Vec3, y: Vec3| Plane { origin: Vec3::ZERO, x, y }; + let iso_x = Vec3::new(1., 1., 0.) * (1. / 2f64.sqrt()); + let iso_y = Vec3::new(-1., 1., 2.) * (1. / 6f64.sqrt()); + let views = [ + (plane(Vec3::X, Vec3::Z), (100., 20.)), + (plane(Vec3::X, Vec3::Y), (100., 50.)), + (plane(Vec3::Y, Vec3::Z), (50., 20.)), + (plane(iso_x, iso_y), (150. / 2f64.sqrt(), 190. / 6f64.sqrt())), + ]; + for (basis, (w, h)) in views { + let size = block.mesh_bounds_in(&basis).size(); + assert!((size.x - w).abs() < 1e-9 && (size.y - h).abs() < 1e-9, "{basis:?}: {size:?}"); + } + assert!(block.cached_mesh().is_some(), "an unplaced body measures its own mesh"); + let moved = Plane { origin: Vec3::new(30., 0., 5.), ..plane(Vec3::X, Vec3::Z) }; + let b = block.mesh_bounds_in(&moved); + assert!(b.min.dist(Vec2::new(-30., -5.)) < 1e-9 && b.max.dist(Vec2::new(70., 15.)) < 1e-9, "{b:?}"); + } + /// A placement hands out its definition's own meshes and its move without making the moved /// copy: every placement of a part gives the same mesh, and that mesh moved is the /// placement's own. @@ -185,13 +213,23 @@ mod tests { let (mesh, m) = p.mesh_in_place(); assert!(Arc::ptr_eq(&mesh, &own), "the definition's mesh, not a copy"); let bounds = p.mesh_bounds(); + let tilted = Plane { origin: Vec3::new(1., 2., 3.), x: Vec3::new(0.6, 0.8, 0.), y: Vec3::Z }; + let seen = p.mesh_bounds_in(&tilted); assert!(p.cached_mesh().is_none(), "no moved copy is made"); let (plan_mesh, pm) = p.plan_mesh_in_place_at(q).unwrap(); assert!(Arc::ptr_eq(&plan_mesh, &source.plan_mesh_at(q).unwrap())); assert_eq!(pm, m); let moved = p.mesh(); + assert!(p.cached_mesh().is_some()); + let cached = p.mesh_bounds_in(&tilted); + assert!(cached.min.dist(seen.min) < 1e-9 && cached.max.dist(seen.max) < 1e-9, "a meshed placement measures its own mesh the same"); let exact = moved.bounds(); assert!(bounds.min.dist(exact.min) < 1e-9 && bounds.max.dist(exact.max) < 1e-9, "{bounds:?} vs {exact:?}"); + let on_plane = moved.positions.iter().fold(solidcraft_geom::Aabb2::EMPTY, |mut b, q| { + b.add(tilted.to_local(*q)); + b + }); + assert!(seen.min.dist(on_plane.min) < 1e-9 && seen.max.dist(on_plane.max) < 1e-9, "{seen:?} vs {on_plane:?}"); for (a, b) in mesh.positions.iter().zip(&moved.positions) { assert!(crate::apply_point(&m, *a).dist(*b) < 1e-9); } From bedae91868d6fe6b05ee0060a894f1f1a0da4ca0 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Mon, 26 Oct 2026 13:36:25 +0000 Subject: [PATCH 5/7] Drawing views: projected views in first or third angle, lined up with their parent (#4816, W17a) W17a's second slice: the principal views derived from a base view. - `ProjectedSide` (left, right, above, below): the side of its parent a projected view sits on. - `projected_basis(parent, side, projection)`: in third angle a view shows the side of the model it sits on (one to the right looks from the right), in first angle the side away from it (ISO 5456-2). It's the parent's basis turned a quarter turn about one of its paper axes, through its origin, with no -0. From the front view it gives exactly the named views: right, left, top and bottom in third angle; left, right, bottom and top in first. - `ViewFrame::aligned(side, projection, centre, position_mm)`: a projected view at its parent's scale, lined up with it, so it moves only along the free axis. - The projection is S2's `cell::Projection`, the value the title block's symbol reads, so a drawing has one first-or-third setting. Tests: the front view's projections are the named views in both angles, with no -0; from every named view and a leaning one, a projected view looks from its side and keeps the parent's other axis and origin, four turns or a turn and its opposite bring the parent back; a box's corners line up across aligned views in both angles; hostile parents, centres and positions refused. Corner (isometric) projected views wait for one convention check on first angle. The derivation graph (projected from, aligned to, cycles refused) moves to the view record in the drawing file, where the view ids live. Co-Authored-By: Claude Opus 5.5 --- crates/geom/src/drawing_view.rs | 63 +++++++++++++++ crates/geom/src/drawing_view_tests.rs | 112 ++++++++++++++++++++++++++ 2 files changed, 175 insertions(+) diff --git a/crates/geom/src/drawing_view.rs b/crates/geom/src/drawing_view.rs index 4459c10db32..3d310a85555 100644 --- a/crates/geom/src/drawing_view.rs +++ b/crates/geom/src/drawing_view.rs @@ -6,6 +6,9 @@ //! `x × y` toward the viewer. [`NamedView`] gives the principal views and the four upper //! isometric corners exactly, never from a camera, which tilts a top view by its pitch clamp; //! [`basis_looking`] gives any other view from its direction and up. +//! - A **projected view** sits on one side of its parent ([`ProjectedSide`]) and looks from that +//! side in third angle, from the side away from it in first ([`projected_basis`]); its frame +//! lines up with the parent's ([`ViewFrame::aligned`]). //! - A **[`Scale`]** is a ratio of two numbers from 0.000001 to 1000000, written `"1:2"` (paper : //! model), from 1:100000 to 1000:1. [`Scale::fit`] picks the largest of ISO 5455's preset //! scales at which a view fits a space. @@ -18,6 +21,7 @@ use std::str::FromStr; use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use crate::cell::Projection; use crate::paper::MAX_SIDE_MM; use crate::section::{CurveAccuracy, MAX_NUMBER, validate_plane}; use crate::{Aabb2, Plane, Seg2, Similarity2, Vec2, Vec3}; @@ -119,6 +123,51 @@ pub fn basis_looking(direction: Vec3, up: Vec3, origin: Vec3) -> Result { Ok(basis) } +/// The side of its parent a projected view sits on. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ProjectedSide { + Left, + Right, + Above, + Below, +} + +impl ProjectedSide { + pub const ALL: [ProjectedSide; 4] = [ProjectedSide::Left, ProjectedSide::Right, ProjectedSide::Above, ProjectedSide::Below]; +} + +/// The basis of the view projected from `parent` onto `side` of it, in `projection` (ISO 5456-2): +/// in third angle a view shows the side of the model it sits on (one to the right looks from the +/// right), and in first angle the side away from it. It is the parent's basis turned a quarter +/// turn about one of its paper axes, through the parent's origin, with no rounding beyond the +/// parent's normal (a principal view's projections are exact), and it lines up with the parent: a +/// view to the left or right keeps the parent's paper y, one above or below its paper x. +pub fn projected_basis(parent: &Plane, side: ProjectedSide, projection: Projection) -> Result { + validate_plane(parent).map_err(|_| Invalid("a view's basis is finite and orthonormal"))?; + // 1 when the view looks from the side it sits on, -1 when from the side away from it. + let from = match projection { + Projection::Third => 1.0, + Projection::First => -1.0, + }; + // The normal, toward the parent's viewer, becomes the paper axis the turn doesn't keep. + let normal = parent.x.cross(parent.y); + let (x, y) = match side { + ProjectedSide::Right => (normal * -from, parent.y), + ProjectedSide::Left => (normal * from, parent.y), + ProjectedSide::Above => (parent.x, normal * -from), + ProjectedSide::Below => (parent.x, normal * from), + }; + Ok(Plane { origin: parent.origin, x: positive_zeros(x), y: positive_zeros(y) }) +} + +/// `v` with any -0 made 0 (turning by a sign makes a zero component -0), so a view's axes write +/// out as `[0.0, 1.0, 0.0]`, never `[-0.0, 1.0, -0.0]`. +fn positive_zeros(v: Vec3) -> Vec3 { + let positive = |c: f64| if c == 0.0 { 0.0 } else { c }; + Vec3::new(positive(v.x), positive(v.y), positive(v.z)) +} + /// Paper x and y for an isometric view from the upper corner `(cx, cy, 1)`: x is horizontal, the /// view direction × Z, and y = x × direction, so the normal points back at the corner. fn iso(cx: f64, cy: f64) -> (Vec3, Vec3) { @@ -245,6 +294,20 @@ impl ViewFrame { Ok(ViewFrame { basis, scale, map }) } + /// The view projected from this one onto `side` of it in `projection`, at this view's scale and + /// lined up with it: the point `centre` of its plane lands at `position_mm` along the free axis + /// (paper x for a view to the left or right, y above or below), and on this view's line along + /// the other, so each point of the model sits as high in both views (or as far across). + pub fn aligned(&self, side: ProjectedSide, projection: Projection, centre: Vec2, position_mm: Vec2) -> Result { + let basis = projected_basis(&self.basis, side, projection)?; + // The kept axis's coordinate of `centre` is the same in this view's plane. + let position = match side { + ProjectedSide::Left | ProjectedSide::Right => Vec2::new(position_mm.x, self.map.apply(Vec2::new(0.0, centre.y)).y), + ProjectedSide::Above | ProjectedSide::Below => Vec2::new(self.map.apply(Vec2::new(centre.x, 0.0)).x, position_mm.y), + }; + ViewFrame::new(basis, self.scale, centre, position) + } + pub fn basis(&self) -> Plane { self.basis } diff --git a/crates/geom/src/drawing_view_tests.rs b/crates/geom/src/drawing_view_tests.rs index 75228a89b70..e725b4df80d 100644 --- a/crates/geom/src/drawing_view_tests.rs +++ b/crates/geom/src/drawing_view_tests.rs @@ -248,6 +248,118 @@ fn the_fitted_scale_is_the_largest_preset_that_fits() { } } +/// Whether any component of `v` is -0. +fn negative_zero(v: Vec3) -> bool { + [v.x, v.y, v.z].iter().any(|c| *c == 0.0 && c.is_sign_negative()) +} + +/// Projected from the front view, each side is exactly a named view: in third angle the side the +/// view sits on (right of the front, the right view), in first angle the side away from it, as +/// ISO 5456-2 places them. Their axes are exact, with no -0, and the names read as written. +#[test] +fn projected_views_of_the_front_are_the_named_views_in_either_angle() { + use ProjectedSide::{Above, Below, Left, Right}; + let front = NamedView::Front.basis(); + let sides = [ + (Right, NamedView::Right, NamedView::Left), + (Left, NamedView::Left, NamedView::Right), + (Above, NamedView::Top, NamedView::Bottom), + (Below, NamedView::Bottom, NamedView::Top), + ]; + for (side, third, first) in sides { + for (projection, named) in [(Projection::Third, third), (Projection::First, first)] { + let view = projected_basis(&front, side, projection).unwrap(); + assert_eq!(view, named.basis(), "{side:?} in {projection:?}"); + assert!(!negative_zero(view.x) && !negative_zero(view.y), "{side:?} in {projection:?}: {view:?}"); + } + } + let names: Vec<_> = ProjectedSide::ALL.iter().map(|s| serde_json::to_value(s).unwrap()).collect(); + assert_eq!(names, [serde_json::json!("left"), serde_json::json!("right"), serde_json::json!("above"), serde_json::json!("below")]); + assert!(serde_json::from_value::(serde_json::json!("top")).is_err()); +} + +/// From any view: the projected view looks from its side's paper axis (or the opposite one in +/// first angle), keeps the parent's other axis and origin, and is a basis; four quarter turns the +/// same way bring the parent back, and so does a turn and its opposite. +#[test] +fn a_projected_view_is_its_parent_turned_a_quarter_turn() { + use ProjectedSide::{Above, Below, Left, Right}; + let leaning = basis_looking(Vec3::new(0.3, 1.0, -0.2), Vec3::new(0.1, 0.2, 1.0), Vec3::new(5.0, -7.0, 2.0)).unwrap(); + for parent in NamedView::ALL.map(NamedView::basis).into_iter().chain([leaning]) { + for projection in [Projection::Third, Projection::First] { + let from = if projection == Projection::Third { 1.0 } else { -1.0 }; + for side in ProjectedSide::ALL { + let view = projected_basis(&parent, side, projection).unwrap(); + validate_plane(&view).unwrap(); + assert_eq!(view.origin, parent.origin); + let (toward_viewer, kept, kept_by) = match side { + Right => (parent.x * from, view.y, parent.y), + Left => (parent.x * -from, view.y, parent.y), + Above => (parent.y * from, view.x, parent.x), + Below => (parent.y * -from, view.x, parent.x), + }; + assert!(close(view.normal(), toward_viewer) && kept == kept_by, "{parent:?} {side:?} {projection:?}: {view:?}"); + } + let turned = |mut b: Plane, side, n: usize| { + for _ in 0..n { + b = projected_basis(&b, side, projection).unwrap(); + } + b + }; + for side in ProjectedSide::ALL { + let back = turned(parent, side, 4); + assert!(close(back.x, parent.x) && close(back.y, parent.y), "{parent:?}: four turns {side:?}"); + } + for (side, opposite) in [(Right, Left), (Above, Below)] { + let back = turned(turned(parent, side, 1), opposite, 1); + assert!(close(back.x, parent.x) && close(back.y, parent.y), "{parent:?}: {side:?} then {opposite:?}"); + } + } + // The principal views' projections stay exact, with no -0. + if parent.x.x.fract() == 0.0 && parent.x.y.fract() == 0.0 && parent.x.z.fract() == 0.0 { + for (side, projection) in ProjectedSide::ALL.into_iter().flat_map(|s| [(s, Projection::Third), (s, Projection::First)]) { + let view = projected_basis(&parent, side, projection).unwrap(); + assert!(!negative_zero(view.x) && !negative_zero(view.y), "{parent:?} {side:?} {projection:?}"); + } + } + } + let skewed = Plane { x: Vec3::new(1.0, 0.1, 0.0), ..NamedView::Front.basis() }; + let not_finite = Plane { origin: Vec3::new(f64::NAN, 0.0, 0.0), ..NamedView::Front.basis() }; + for parent in [skewed, not_finite] { + assert_eq!(projected_basis(&parent, Right, Projection::Third), Err(Invalid("a view's basis is finite and orthonormal"))); + } +} + +/// An aligned projected view takes its parent's scale and lines up with it: every corner of a box +/// sits as high in the front view and the views to its left and right, and as far across in the +/// views above and below it; the projected view's centre lands at the position asked for along the +/// free axis. A position past the paper's limit is refused. +#[test] +fn an_aligned_view_lines_up_with_its_parent() { + let corners: Vec = + (0..8).map(|i| Vec3::new(f64::from(i & 1) * 100.0, f64::from((i >> 1) & 1) * 50.0, f64::from((i >> 2) & 1) * 20.0)).collect(); + let front = ViewFrame::new(NamedView::Front.basis(), "1:2".parse().unwrap(), Vec2::new(50.0, 10.0), Vec2::new(150.0, 150.0)).unwrap(); + for projection in [Projection::Third, Projection::First] { + for side in ProjectedSide::ALL { + let centre = Vec2::new(25.0, -10.0); + let view = front.aligned(side, projection, centre, Vec2::new(300.0, 60.0)).unwrap(); + assert_eq!(view.scale(), front.scale()); + let across = matches!(side, ProjectedSide::Above | ProjectedSide::Below); + for p in &corners { + let (a, b) = (front.to_paper(*p), view.to_paper(*p)); + let lined_up = if across { (a.x - b.x).abs() } else { (a.y - b.y).abs() }; + assert!(lined_up < EPS, "{side:?} {projection:?}: {p:?} at {a:?} and {b:?}"); + } + let at = view.paper_map().apply(centre); + let free = if across { (at.y - 60.0).abs() } else { (at.x - 300.0).abs() }; + assert!(free < EPS, "{side:?} {projection:?}: centre at {at:?}"); + } + } + let right = front.aligned(ProjectedSide::Right, Projection::Third, Vec2::ZERO, Vec2::new(5000.001, 0.0)); + assert!(right.is_err(), "past the paper's limit"); + assert!(front.aligned(ProjectedSide::Above, Projection::Third, Vec2::new(f64::NAN, 0.0), Vec2::ZERO).is_err(), "a centre not finite"); +} + /// What a frame refuses: a basis that isn't orthonormal or finite, a centre that isn't finite, and /// a position past the paper's limit. #[test] From cfa5602b4fe5ed78a8a1bfe9aa8be2277c410ca5 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Mon, 26 Oct 2026 17:42:37 +0000 Subject: [PATCH 6/7] Drawing dimensions: measurement on view frames (#4896, W19a) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `geom::drawing_measure` is what a dimension on a view reads, in model mm or radians, from model points and edges and the view's basis: one rule for every dimension. The view's scale and place on the sheet never enter. - `linear`: horizontal and vertical along the view's paper x and y, aligned as the view shows the segment, or along a direction picked on the view; a true reading is the segment's own length (aligned only). - `angle`: from the view's horizontal or vertical, a model axis as the view shows it, or another edge, from 0 to π as each line is oriented; a true reading is between model lines. - `foreshortened` says a measured line isn't parallel to the view's plane. - Refused with a reason: points that aren't finite or are past 1e12 mm, an invalid basis, a zero-length segment, a line seen end-on, a zero direction, a zero reading, parallel lines, and a true reading where there is none. `drawing_view`'s `PARALLEL` and `require` are shared. Co-Authored-By: Claude Opus 5.5 --- crates/geom/src/drawing_measure.rs | 132 ++++++++++++++ crates/geom/src/drawing_measure_tests.rs | 209 +++++++++++++++++++++++ crates/geom/src/drawing_view.rs | 4 +- crates/geom/src/lib.rs | 1 + 4 files changed, 344 insertions(+), 2 deletions(-) create mode 100644 crates/geom/src/drawing_measure.rs create mode 100644 crates/geom/src/drawing_measure_tests.rs diff --git a/crates/geom/src/drawing_measure.rs b/crates/geom/src/drawing_measure.rs new file mode 100644 index 00000000000..ca48ac71653 --- /dev/null +++ b/crates/geom/src/drawing_measure.rs @@ -0,0 +1,132 @@ +//! Measurement on drawing views (W19a, #4896): what a dimension on a view reads, in model +//! millimetres or radians, from model points and edges and the view's basis. One rule for every +//! dimension: the dimension record (W19b) keeps what to measure, and W09 formats the number. +//! +//! A value is **projected** (as the view shows it) or **true** (as the model has it); +//! `foreshortened` says a measured line isn't parallel to the view's plane, so the two differ. The +//! view's scale and place on the sheet never change a measurement. + +use crate::drawing_view::{Invalid, PARALLEL, require}; +use crate::section::{MAX_NUMBER, validate_plane}; +use crate::{EPS, Plane, Vec2, Vec3}; + +type Result = std::result::Result; + +/// Which way a linear dimension measures on its view. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum LinearDirection { + /// Along the view's horizontal (paper x). + Horizontal, + /// Along the view's vertical (paper y). + Vertical, + /// Along the segment as the view shows it. + Aligned, + /// Along a direction on the view, in its plane's coordinates (any length but zero): a rotated + /// dimension, or one along a picked edge. + Along(Vec2), +} + +/// What a dimension reads: the length or angle as the view shows it, or as the model has it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reading { + Projected, + True, +} + +/// The line an angle is measured from. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum AngleFrom { + /// The view's horizontal, pointing right (paper +x). + Horizontal, + /// The view's vertical, pointing up (paper +y). + Vertical, + /// A model direction, such as the part's axis, as the view shows it. + ModelAxis(Vec3), + /// Another edge, from its first point to its second. + Edge(Vec3, Vec3), +} + +/// What a dimension reads, and whether a measured line is out of the view's plane. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Measured { + /// Model millimetres, or radians for an angle. + pub value: f64, + /// A measured line isn't parallel to the view's plane, so its projected value differs from + /// the model's. + pub foreshortened: bool, +} + +/// The distance from `a` to `b` (model points) that a linear dimension measuring `direction` on +/// the view through `basis` reads. A true reading is the segment's own length, so it goes with +/// [`LinearDirection::Aligned`] only: a true horizontal has no one meaning in a tilted view. +pub fn linear(basis: &Plane, a: Vec3, b: Vec3, direction: LinearDirection, reading: Reading) -> Result { + let d = segment(basis, a, b)?; + let shown = Vec2::new(d.dot(basis.x), d.dot(basis.y)); + let value = match (direction, reading) { + (LinearDirection::Aligned, Reading::True) => d.len(), + (_, Reading::True) => return Err(Invalid("a true length is along the segment: measure it aligned")), + (LinearDirection::Horizontal, Reading::Projected) => shown.x.abs(), + (LinearDirection::Vertical, Reading::Projected) => shown.y.abs(), + (LinearDirection::Aligned, Reading::Projected) => shown.len(), + (LinearDirection::Along(along), Reading::Projected) => { + let along = along.normalized().ok_or(Invalid("the direction to measure along is zero or not finite"))?; + shown.dot(along).abs() + } + }; + require(value > EPS, "the dimension would read 0: the points line up across the direction it measures")?; + Ok(Measured { value, foreshortened: out_of_plane(basis, d) }) +} + +/// The angle from the line `from` to `edge` (model points, from its first to its second) on the +/// view through `basis`, from 0 to π: each line goes the way its caller gives it (from the vertex +/// outwards), so the other side of the angle reads π minus it. A true reading is the angle +/// between the model lines, so it isn't given from the view's horizontal or vertical. +pub fn angle(basis: &Plane, edge: (Vec3, Vec3), from: AngleFrom, reading: Reading) -> Result { + let d = segment(basis, edge.0, edge.1)?; + let (reference, model_line) = match from { + AngleFrom::Horizontal => (basis.x, false), + AngleFrom::Vertical => (basis.y, false), + AngleFrom::ModelAxis(axis) => (axis.normalized().ok_or(Invalid("the model axis is zero or not finite"))?, true), + AngleFrom::Edge(a, b) => (segment(basis, a, b)?, true), + }; + let value = match reading { + Reading::True if model_line => between(d, reference)?, + Reading::True => return Err(Invalid("a true angle is between two model lines, not from the view's horizontal or vertical")), + Reading::Projected => between(on_view(basis, d)?, on_view(basis, reference)?)?, + }; + Ok(Measured { value, foreshortened: out_of_plane(basis, d) || (model_line && out_of_plane(basis, reference)) }) +} + +/// `b - a`, both finite model points within 1e12 mm of the origin, the segment not of zero length, +/// on a valid basis. +fn segment(basis: &Plane, a: Vec3, b: Vec3) -> Result { + validate_plane(basis).map_err(|_| Invalid("a view's basis is finite and orthonormal"))?; + let point = |p: Vec3| p.is_finite() && [p.x, p.y, p.z].iter().all(|v| v.abs() <= MAX_NUMBER); + require(point(a) && point(b), "a model point is finite and within 1e12 mm of the origin")?; + let d = b - a; + require(d.len() > EPS, "a segment or edge has no length")?; + Ok(d) +} + +/// `d` as the view shows it, in its plane's coordinates: refused when the view sees it end-on. +fn on_view(basis: &Plane, d: Vec3) -> Result { + let shown = Vec3::new(d.dot(basis.x), d.dot(basis.y), 0.0); + require(shown.len() > PARALLEL * d.len(), "a line is seen end-on in this view: it has no direction there")?; + Ok(shown) +} + +/// The angle between `u` and `v`, from 0 to π: refused when they are parallel either way. +fn between(u: Vec3, v: Vec3) -> Result { + let sine = u.cross(v).len(); + require(sine > PARALLEL * u.len() * v.len(), "the lines are parallel: there is no angle between them")?; + Ok(sine.atan2(u.dot(v))) +} + +/// Whether `d` leaves the view's plane: the sine of its angle to the plane is over [`PARALLEL`]. +fn out_of_plane(basis: &Plane, d: Vec3) -> bool { + d.dot(basis.normal()).abs() > PARALLEL * d.len() +} + +#[cfg(test)] +#[path = "drawing_measure_tests.rs"] +mod tests; diff --git a/crates/geom/src/drawing_measure_tests.rs b/crates/geom/src/drawing_measure_tests.rs new file mode 100644 index 00000000000..ac32c21d1b9 --- /dev/null +++ b/crates/geom/src/drawing_measure_tests.rs @@ -0,0 +1,209 @@ +use super::*; +use crate::drawing_view::{NamedView, basis_looking}; + +use AngleFrom::{Edge, ModelAxis}; +use LinearDirection::{Aligned, Along, Horizontal, Vertical}; +use Reading::{Projected, True}; + +/// Paper x along X, y along Z. +fn front() -> Plane { + NamedView::Front.basis() +} + +/// From the (1, -1, 1) corner. +fn iso() -> Plane { + NamedView::IsoFrontRight.basis() +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() <= 1e-12 * b.abs().max(1.0) +} + +fn reads(m: Result) -> (f64, bool) { + let m = m.unwrap(); + (m.value, m.foreshortened) +} + +fn degrees(m: Result) -> f64 { + m.unwrap().value.to_degrees() +} + +fn refused(result: Result, says: &str) { + match result { + Err(Invalid(message)) => assert!(message.contains(says), "{message:?} doesn't say {says:?}"), + other => panic!("expected a refusal saying {says:?}, got {other:?}"), + } +} + +/// From (0, 0, 0) to (30, 0, 40) in the front view: 30 across, 40 up, 50 aligned, 70/√2 along +/// (1, 1), 30 along (-2, 0); none foreshortened, and the true length is 50 too. +#[test] +fn a_segment_in_the_views_plane_reads_its_lengths() { + let (a, b) = (Vec3::ZERO, Vec3::new(30.0, 0.0, 40.0)); + let cases = [ + (Horizontal, 30.0), + (Vertical, 40.0), + (Aligned, 50.0), + (Along(Vec2::new(1.0, 1.0)), 70.0 / 2f64.sqrt()), + (Along(Vec2::new(-2.0, 0.0)), 30.0), + ]; + for (direction, value) in cases { + let (v, foreshortened) = reads(linear(&front(), a, b, direction, Projected)); + assert!(close(v, value) && !foreshortened, "{direction:?}: {v}"); + } + assert_eq!(reads(linear(&front(), a, b, Aligned, True)), (50.0, false)); +} + +/// The same segment 20 mm deeper at one end, to (30, 20, 40): still 30, 40 and 50 as the view +/// shows it, now foreshortened; its true length √2900. Scale and place don't enter: a view moved +/// along its normal reads the same. +#[test] +fn a_segment_out_of_the_views_plane_is_foreshortened() { + let (a, b) = (Vec3::ZERO, Vec3::new(30.0, 20.0, 40.0)); + for (direction, value) in [(Horizontal, 30.0), (Vertical, 40.0), (Aligned, 50.0)] { + let (v, foreshortened) = reads(linear(&front(), a, b, direction, Projected)); + assert!(close(v, value) && foreshortened, "{direction:?}: {v}"); + } + let (v, foreshortened) = reads(linear(&front(), a, b, Aligned, True)); + assert!(close(v, 2900f64.sqrt()) && foreshortened); + let moved = Plane { origin: Vec3::new(5.0, -300.0, 7.0), ..front() }; + let (v, foreshortened) = reads(linear(&moved, a, b, Aligned, Projected)); + assert!(close(v, 50.0) && foreshortened, "{v}"); +} + +/// A 50 mm cube edge along X in the front-right isometric view: 50·√(2/3) as drawn, 50 true, +/// foreshortened either way. +#[test] +fn a_cube_edge_in_an_isometric_view() { + let edge = (Vec3::ZERO, Vec3::new(50.0, 0.0, 0.0)); + let (drawn, foreshortened) = reads(linear(&iso(), edge.0, edge.1, Aligned, Projected)); + assert!(close(drawn, 50.0 * (2.0f64 / 3.0).sqrt()) && foreshortened, "{drawn}"); + let (true_length, foreshortened) = reads(linear(&iso(), edge.0, edge.1, Aligned, True)); + assert!(close(true_length, 50.0) && foreshortened); +} + +/// A 30° bevel in the front view, from its low end: 30° to the horizontal, 60° to the vertical, +/// 30° to the X axis and 60° to a vertical edge, none foreshortened; from its high end it reads +/// the other side, 150° to the horizontal. The true angle to X is 30° too; to an axis leaning out +/// of the view, (1, 1, 0), it is 30° as drawn and foreshortened. The Y axis is seen end-on in +/// this view, so an angle to it is refused. +#[test] +fn a_bevel_reads_its_angles_to_the_view_and_the_model() { + let rise = 30f64.to_radians(); + let bevel = (Vec3::ZERO, Vec3::new(rise.cos(), 0.0, rise.sin()) * 10.0); + let upright = Edge(Vec3::ZERO, Vec3::new(0.0, 0.0, 10.0)); + for (from, value) in [(AngleFrom::Horizontal, 30.0), (AngleFrom::Vertical, 60.0), (ModelAxis(Vec3::X), 30.0), (upright, 60.0)] { + let m = angle(&front(), bevel, from, Projected).unwrap(); + assert!(close(m.value.to_degrees(), value) && !m.foreshortened, "{from:?}: {}", m.value.to_degrees()); + } + assert!(close(degrees(angle(&front(), (bevel.1, bevel.0), AngleFrom::Horizontal, Projected)), 150.0)); + assert!(close(degrees(angle(&front(), bevel, ModelAxis(Vec3::X), True)), 30.0)); + let leaning = angle(&front(), bevel, ModelAxis(Vec3::new(1.0, 1.0, 0.0)), Projected).unwrap(); + assert!(close(leaning.value.to_degrees(), 30.0) && leaning.foreshortened, "an axis leaning out of the view: {leaning:?}"); + refused(angle(&front(), bevel, ModelAxis(Vec3::Y), Projected), "end-on"); +} + +/// The X and Z axes in the front-right isometric view (both toward the viewer) are 120° apart as +/// drawn and 90° in the model, foreshortened; X and Y, one away from the viewer, are 60° as drawn. +#[test] +fn model_axes_in_an_isometric_view() { + let x = (Vec3::ZERO, Vec3::X * 50.0); + let drawn = angle(&iso(), x, ModelAxis(Vec3::Z), Projected).unwrap(); + assert!(close(drawn.value.to_degrees(), 120.0) && drawn.foreshortened, "{drawn:?}"); + assert!(close(degrees(angle(&iso(), x, ModelAxis(Vec3::Z), True)), 90.0)); + assert!(close(degrees(angle(&iso(), x, Edge(Vec3::ZERO, Vec3::Y), Projected)), 60.0)); +} + +/// What can't be measured, each refused with its reason. +#[test] +fn what_cant_be_measured_is_refused() { + let (a, b) = (Vec3::ZERO, Vec3::new(30.0, 0.0, 40.0)); + for p in [Vec3::new(f64::NAN, 0.0, 0.0), Vec3::new(0.0, f64::INFINITY, 0.0), Vec3::new(0.0, 0.0, 1.000_000_1e12)] { + refused(linear(&front(), a, p, Aligned, Projected), "model point"); + refused(angle(&front(), (p, b), AngleFrom::Horizontal, Projected), "model point"); + } + linear(&front(), Vec3::new(-1e12, 0.0, 0.0), Vec3::new(1e12, 0.0, 0.0), Horizontal, Projected).unwrap(); + refused(linear(&front(), a, a, Aligned, True), "no length"); + refused(linear(&front(), a, a + Vec3::X * 1e-10, Horizontal, Projected), "no length"); + let skewed = Plane { x: Vec3::new(2.0, 0.0, 0.0), ..front() }; + refused(linear(&skewed, a, b, Horizontal, Projected), "basis"); + refused(angle(&skewed, (a, b), AngleFrom::Horizontal, Projected), "basis"); + for along in [Vec2::ZERO, Vec2::new(f64::NAN, 1.0), Vec2::new(f64::INFINITY, 0.0)] { + refused(linear(&front(), a, b, Along(along), Projected), "direction to measure along"); + } + refused(linear(&front(), a, Vec3::new(0.0, 0.0, 40.0), Horizontal, Projected), "would read 0"); + refused(linear(&front(), a, Vec3::new(0.0, 25.0, 0.0), Aligned, Projected), "would read 0"); + for direction in [Horizontal, Vertical, Along(Vec2::X)] { + refused(linear(&front(), a, b, direction, True), "true length"); + } + let edge = (a, b); + refused(angle(&front(), edge, Edge(a, b * 2.0), Projected), "parallel"); + refused(angle(&front(), edge, Edge(b, a), Projected), "parallel"); + refused(angle(&front(), edge, Edge(b, a), True), "parallel"); + refused(angle(&front(), (a, Vec3::new(0.0, 25.0, 0.0)), AngleFrom::Horizontal, Projected), "end-on"); + refused(angle(&front(), edge, AngleFrom::Horizontal, True), "true angle"); + refused(angle(&front(), edge, AngleFrom::Vertical, True), "true angle"); + for axis in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0), Vec3::new(1e308, 1e308, 0.0)] { + refused(angle(&front(), edge, ModelAxis(axis), Projected), "model axis"); + } + refused(angle(&front(), edge, Edge(a, a), Projected), "no length"); +} + +fn random(state: &mut u64) -> u64 { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + *state +} + +/// Points, edges, bases and directions, three cases in four tidy (the named views and views +/// looking any way, points within a metre) and the rest hostile (non-finite, huge, repeated, +/// along the view's normal), 20,000 seeded cases: nothing panics; across² + up² = aligned²; a +/// projected aligned length is never more than the true one; every angle is from 0 to π, and a +/// true angle and its projection agree in a view square to both lines. +#[test] +fn measurements_seeded_never_panic_and_keep_their_rules() { + let mut seed = 0x4896_19a0_d1e5_7c3b; + let hostile = [0.0, -0.0, 1e-10, 1e12, 1.1e12, f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300, -5.0]; + let (mut lengths, mut angles) = (0, 0); + for case in 0..20_000 { + let tidy = !random(&mut seed).is_multiple_of(4); + let number = |seed: &mut u64| { + if tidy { + (random(seed) % 2_001) as f64 / 2.0 - 500.0 + } else { + hostile.get((random(seed) % hostile.len() as u64) as usize).copied().unwrap_or(0.0) + } + }; + let point = |seed: &mut u64| Vec3::new(number(seed), number(seed), number(seed)); + let basis = match random(&mut seed) % 3 { + 0 => NamedView::ALL.get((random(&mut seed) % 10) as usize).map(|v| v.basis()).unwrap_or_else(front), + 1 => basis_looking(point(&mut seed), Vec3::Z, Vec3::ZERO).unwrap_or_else(|_| iso()), + _ => Plane { origin: point(&mut seed), x: point(&mut seed), y: point(&mut seed) }, + }; + let (a, b, c, d) = (point(&mut seed), point(&mut seed), point(&mut seed), point(&mut seed)); + let along = Vec2::new(number(&mut seed), number(&mut seed)); + let read = |direction| linear(&basis, a, b, direction, Projected).map(|m| m.value); + if let (Ok(h), Ok(v), Ok(aligned)) = (read(Horizontal), read(Vertical), read(Aligned)) { + lengths += 1; + assert!((h * h + v * v - aligned * aligned).abs() <= 1e-9 * aligned * aligned, "case {case}"); + let true_length = linear(&basis, a, b, Aligned, True).map(|m| m.value); + assert!(true_length.is_ok_and(|t| aligned <= t * (1.0 + 1e-12)), "case {case}"); + } + let _ = linear(&basis, a, b, Along(along), Projected); + for from in [AngleFrom::Horizontal, AngleFrom::Vertical, ModelAxis(c - d), Edge(c, d)] { + for reading in [Projected, True] { + if let Ok(m) = angle(&basis, (a, b), from, reading) { + angles += 1; + assert!(m.value > 0.0 && m.value < std::f64::consts::PI, "case {case}: {m:?}"); + } + } + } + if let (Ok(drawn), Ok(model)) = (angle(&basis, (a, b), Edge(c, d), Projected), angle(&basis, (a, b), Edge(c, d), True)) + && !drawn.foreshortened + { + assert!((drawn.value - model.value).abs() <= 1e-6, "case {case}: {drawn:?} {model:?}"); + } + } + assert!(lengths > 5_000 && angles > 20_000, "lengths {lengths}, angles {angles}"); +} diff --git a/crates/geom/src/drawing_view.rs b/crates/geom/src/drawing_view.rs index 3d310a85555..24a3518a624 100644 --- a/crates/geom/src/drawing_view.rs +++ b/crates/geom/src/drawing_view.rs @@ -41,12 +41,12 @@ pub struct Invalid(pub &'static str); type Result = std::result::Result; -fn require(condition: bool, message: &'static str) -> Result<()> { +pub(crate) fn require(condition: bool, message: &'static str) -> Result<()> { if condition { Ok(()) } else { Err(Invalid(message)) } } /// Two directions closer to parallel than this (the sine of their angle) give no view. -const PARALLEL: f64 = 1e-9; +pub(crate) const PARALLEL: f64 = 1e-9; /// A view with a name: the six principal views and the isometric views from the four upper /// corners. Each looks at the model from where its name says; `iso` reads as the front-right one. diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 0c60fbe722c..e1a2d37548e 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -18,6 +18,7 @@ mod bvh; pub mod cell; mod chain; pub mod compare; +pub mod drawing_measure; pub mod drawing_sheet; pub mod drawing_view; pub mod env; From cce39b40d1cb177baad320ddede0e153452fce90 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Sun, 25 Oct 2026 18:16:22 +0000 Subject: [PATCH 7/7] drawing.view.snapshot: a view's scale, place and boundary on its sheet (#5866, W07 V2) The first slice of W07: one orthographic view of the design, worked out and returned as data, before any line is drawn, so scripts can lay views out by their boundaries. - `drawing.view.snapshot` takes the view's settings, the sheet it goes on (A3 landscape at 300 dpi when not given) and where its centre goes (the sheet's centre when not given). With no scale it takes the largest ISO 5455 scale at which the view, centred there, lies inside the sheet's drawing border. It returns the resolved view, the scale (and whether it was fitted), the extents on the view's plane, the boundary on the sheet and what it was drawn from. Read-only and not undoable; it opens nothing and saves nothing. - Every body the design places is in the view, wherever its occurrences place it; the browser's eye counts for nothing (`engine::drawing_view::extents`, from P2's `mesh_bounds_in`). A design whose assembly walk stops at its limits (deeper than 64 levels, or past 100,000 placements) is refused rather than drawn with parts left out: `Document::placements_complete`, beside the walk, says whether every placement it holds had its occurrences walked. - `doc::drawing_view::ViewSettings` is the view's one parameter set: the view (named, or a direction and an up), the scale, the two visual styles, the reference settings and tangent edges. A saved view (W12) keeps the same fields; no scale is written as none, not null, so what it writes reads back as the snapshot's parameters. - `render::VisualStyle` names the five styles: visible, visible_hidden, shaded, shaded_visible and shaded_visible_hidden. The shaded ones are refused as not supported yet until the drawing renderer (#5624). - The command has a typed contract (input and output schemas). Its handler reads the contract's own type through `schema::read`, in the contract check's own words, so the check's levels give one message for one mistake and an unknown field is refused by name. The reply includes the sheet, its defaults filled in. Tests: the 100 x 50 x 20 block's boundary in the front, top, right and isometric views at 1:2, worked by hand; the fitted scale on A3 and A4 and near the border; scale, position and margin; the browser's eye ignored; the design untouched; each hostile setting refused; the walk's depth limit one level either side; the contract's keys the same as the settings' own. Co-Authored-By: Claude Opus 5.5 --- assets/locales/en.json | 1 + assets/locales/ja.json | 1 + assets/locales/zh.json | 1 + crates/doc/src/assembly.rs | 13 + crates/doc/src/drawing_view.rs | 108 ++++++++ crates/doc/src/drawing_view_tests.rs | 55 ++++ crates/doc/src/lib.rs | 1 + crates/engine/src/cmd/drawing_view.rs | 120 +++++++++ crates/engine/src/cmd/drawing_view_tests.rs | 174 ++++++++++++ crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/drawing_view.rs | 29 ++ crates/engine/src/lib.rs | 1 + crates/engine/src/schema/check.rs | 6 + crates/engine/src/schema/drawing_view.rs | 248 ++++++++++++++++++ .../engine/src/schema/drawing_view_tests.rs | 47 ++++ crates/engine/src/schema/mod.rs | 2 + crates/engine/src/tests.rs | 8 + crates/render/src/lib.rs | 2 + crates/render/src/visual_style.rs | 59 +++++ 19 files changed, 878 insertions(+) create mode 100644 crates/doc/src/drawing_view.rs create mode 100644 crates/doc/src/drawing_view_tests.rs create mode 100644 crates/engine/src/cmd/drawing_view.rs create mode 100644 crates/engine/src/cmd/drawing_view_tests.rs create mode 100644 crates/engine/src/drawing_view.rs create mode 100644 crates/engine/src/schema/drawing_view.rs create mode 100644 crates/engine/src/schema/drawing_view_tests.rs create mode 100644 crates/render/src/visual_style.rs diff --git a/assets/locales/en.json b/assets/locales/en.json index 4ed562c2d9c..1e76537b5cf 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -573,6 +573,7 @@ "cmd.drawing_properties_remove": "Remove Drawing Property", "cmd.drawing_properties_set": "Change Drawing Properties", "cmd.drawing_set": "Drawing Settings", + "cmd.drawing_view_snapshot": "Drawing View Snapshot", "cmd.edit_checkpoint": "Checkpoint", "cmd.edit_restore_checkpoint": "Restore Checkpoint", "cmd.engine_commands": "List Commands", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index d4d985e6507..3d4ee0b2c64 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -573,6 +573,7 @@ "cmd.drawing_properties_remove": "図面のプロパティを削除", "cmd.drawing_properties_set": "図面のプロパティを変更", "cmd.drawing_set": "図面設定", + "cmd.drawing_view_snapshot": "図面ビューのスナップショット", "cmd.edit_checkpoint": "チェックポイント", "cmd.edit_restore_checkpoint": "チェックポイントを復元", "cmd.engine_commands": "コマンドを一覧表示", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 14dfdb68fa3..f4485f7136c 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -573,6 +573,7 @@ "cmd.drawing_properties_remove": "删除绘图属性", "cmd.drawing_properties_set": "更改绘图属性", "cmd.drawing_set": "绘图设置", + "cmd.drawing_view_snapshot": "绘图视图快照", "cmd.edit_checkpoint": "检查点", "cmd.edit_restore_checkpoint": "恢复检查点", "cmd.engine_commands": "列出命令", diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs index 838231dfb5f..b19c2edcb8a 100644 --- a/crates/doc/src/assembly.rs +++ b/crates/doc/src/assembly.rs @@ -325,6 +325,19 @@ impl Document { out } + /// Whether [`Document::placements`] reaches every placement. Its walk stops at + /// [`MAX_PLACEMENTS`], and a branch past [`MAX_PLACEMENT_DEPTH`] levels, so a placement it + /// holds may have occurrences it never walked; the walk is whole when none does. + pub fn placements_complete(&self) -> bool { + let mut children = std::collections::HashMap::::new(); + for o in &self.occurrences { + *children.entry(o.parent).or_default() += 1; + } + let walk = self.placements(); + let reached = walk.iter().fold(0usize, |n, (c, _, _)| n.saturating_add(children.get(c).copied().unwrap_or(0))); + walk.len() == reached.saturating_add(1) + } + /// Every body as the world shows it: its world name ("Body1", or "Body1 (Occ:2)" for a /// further instance), its component, the occurrence path, and the transform from the frame /// its geometry is in to the world. diff --git a/crates/doc/src/drawing_view.rs b/crates/doc/src/drawing_view.rs new file mode 100644 index 00000000000..3d4cd91e461 --- /dev/null +++ b/crates/doc/src/drawing_view.rs @@ -0,0 +1,108 @@ +//! A drawing view's settings (W07, #5866): which way it looks, its scale and how it draws. +//! `drawing.view.snapshot` takes them whole; a saved view (W12) keeps the same fields, each one +//! optional so that a projected view can follow its parent. + +use serde::{Deserialize, Deserializer, Serialize}; +use solidcraft_geom::Plane; +use solidcraft_geom::drawing_view::{Invalid, NamedView, Scale, basis_looking}; +use solidcraft_render::VisualStyle; + +/// The largest reference margin, in model millimetres. +pub const MAX_REFERENCE_MARGIN_MM: f64 = 1e5; + +/// Which way a view looks: by name, or along any direction with an up. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ViewDirection { + Named(NamedView), + Looking(Looking), +} + +/// A view along `direction` with `up` toward the top of the paper, through `origin` (the world +/// origin when not given). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Looking { + pub direction: [f64; 3], + pub up: [f64; 3], + #[serde(default)] + pub origin: [f64; 3], +} + +impl<'de> Deserialize<'de> for ViewDirection { + /// One message for anything that is neither, rather than serde's "did not match any variant". + fn deserialize>(d: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Either { + Named(NamedView), + Looking(Looking), + } + let message = "view is front, back, top, bottom, left, right, iso, iso_front_right, iso_front_left, iso_back_right, iso_back_left, or {direction, up, origin?}"; + Ok(match Either::deserialize(d).map_err(|_| serde::de::Error::custom(message))? { + Either::Named(view) => ViewDirection::Named(view), + Either::Looking(looking) => ViewDirection::Looking(looking), + }) + } +} + +impl Default for ViewDirection { + fn default() -> Self { + ViewDirection::Named(NamedView::Front) + } +} + +impl ViewDirection { + /// The view's basis: a named view's exact one, or one built from the direction and up. + pub fn basis(&self) -> Result { + match *self { + ViewDirection::Named(view) => Ok(view.basis()), + ViewDirection::Looking(Looking { direction, up, origin }) => basis_looking(direction.into(), up.into(), origin.into()), + } + } +} + +/// Tangent edges, where faces meet smoothly: left out (the default) or drawn. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TangentEdges { + #[default] + Hide, + Show, +} + +/// What a view shows and how. Every field has a default: the front view at the scale that fits +/// its page, visible lines only, tangent edges hidden. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ViewSettings { + pub view: ViewDirection, + /// None: the largest preset scale at which the view fits its page ([`Scale::fit`]). Not + /// written when None: a snapshot refuses a null scale. + #[serde(skip_serializing_if = "Option::is_none")] + pub scale: Option, + pub display_style: VisualStyle, + /// How reference parts draw (bill of materials type `reference`). + pub reference_style: VisualStyle, + /// Whether reference parts hide the model's lines behind them. + pub reference_hides_model: bool, + /// Model millimetres added on every side of the view's extents, so reference parts around the + /// model show inside its boundary: 0 to [`MAX_REFERENCE_MARGIN_MM`]. + pub reference_margin_mm: f64, + pub tangent_edges: TangentEdges, +} + +impl ViewSettings { + /// What reading alone can't check: the margin's range and the view's basis. + pub fn validate(&self) -> Result { + let margin = self.reference_margin_mm; + if !(margin.is_finite() && (0.0..=MAX_REFERENCE_MARGIN_MM).contains(&margin)) { + return Err(Invalid("reference_margin_mm is a number of model millimetres from 0 to 100000")); + } + self.view.basis() + } +} + +#[cfg(test)] +#[path = "drawing_view_tests.rs"] +mod tests; diff --git a/crates/doc/src/drawing_view_tests.rs b/crates/doc/src/drawing_view_tests.rs new file mode 100644 index 00000000000..00f3d5c85f7 --- /dev/null +++ b/crates/doc/src/drawing_view_tests.rs @@ -0,0 +1,55 @@ +use serde_json::json; +use solidcraft_geom::Vec3; + +use super::*; + +/// Every field has its default, and the settings read and write back the same. +#[test] +fn view_settings_default_to_a_front_view_that_fits_its_page() { + let settings: ViewSettings = serde_json::from_value(json!({})).unwrap(); + assert_eq!(settings, ViewSettings::default()); + assert_eq!(settings.view, ViewDirection::Named(NamedView::Front)); + assert_eq!((settings.scale, settings.display_style, settings.tangent_edges), (None, VisualStyle::Visible, TangentEdges::Hide)); + assert_eq!(settings.validate().unwrap(), NamedView::Front.basis()); + assert_eq!(serde_json::to_value(settings).unwrap().get("scale"), None, "no scale is written, not null"); + let full = json!({ + "view": {"direction": [0.0, 1.0, 0.0], "up": [0.0, 0.0, 1.0], "origin": [1.0, 2.0, 3.0]}, + "scale": "1:2", "display_style": "visible_hidden", "reference_style": "shaded", + "reference_hides_model": true, "reference_margin_mm": 5.0, "tangent_edges": "show", + }); + let read: ViewSettings = serde_json::from_value(full.clone()).unwrap(); + assert_eq!(serde_json::to_value(read).unwrap(), full); + assert_eq!(read.validate().unwrap().origin, Vec3::new(1.0, 2.0, 3.0)); + let iso: ViewSettings = serde_json::from_value(json!({"view": "iso"})).unwrap(); + assert_eq!(iso.view, ViewDirection::Named(NamedView::IsoFrontRight)); +} + +/// What the settings refuse: unknown fields, unknown names, a basis that can't be built and a +/// margin out of range. +#[test] +fn view_settings_refuse_what_they_cant_draw() { + for not_settings in [ + json!({"scael": "1:2"}), + json!({"view": 3}), + json!({"view": "Front"}), + json!({"view": {"direction": [0, 1, 0]}}), + json!({"view": {"direction": [0, 1, 0], "up": [0, 0, 1], "roll": 1}}), + json!({"scale": 0.5}), + json!({"display_style": "hidden"}), + json!({"tangent_edges": "thin"}), + ] { + assert!(serde_json::from_value::(not_settings.clone()).is_err(), "{not_settings}"); + } + let refused = [ + json!({"view": {"direction": [0, 0, 0], "up": [0, 0, 1]}}), + json!({"view": {"direction": [0, 0, 1], "up": [0, 0, -1]}}), + json!({"reference_margin_mm": -0.001}), + json!({"reference_margin_mm": 100000.001}), + ]; + for settings in refused { + let read: ViewSettings = serde_json::from_value(settings.clone()).unwrap(); + assert!(read.validate().is_err(), "{settings}"); + } + let edge: ViewSettings = serde_json::from_value(json!({"reference_margin_mm": 100000.0})).unwrap(); + assert!(edge.validate().is_ok()); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c68da3053aa..2a40409dfba 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -20,6 +20,7 @@ pub mod display_quality; pub mod display_units; mod document; pub mod drawing; +pub mod drawing_view; mod eval; pub mod expr; pub mod face_anchor; diff --git a/crates/engine/src/cmd/drawing_view.rs b/crates/engine/src/cmd/drawing_view.rs new file mode 100644 index 00000000000..99060a8f995 --- /dev/null +++ b/crates/engine/src/cmd/drawing_view.rs @@ -0,0 +1,120 @@ +//! `drawing.view.snapshot` (W07, #5866): one orthographic view of the design, worked out and +//! returned without saving anything. It reads the evaluated model and changes nothing. +//! +//! The view's settings are `doc::drawing_view::ViewSettings`; its basis, scale and map onto +//! paper are `geom::drawing_view`'s. Without a scale it takes the largest ISO 5455 scale at +//! which the view, centred where it goes, lies inside the sheet's drawing border. + +use serde::Serialize; +use serde_json::Value; +use solidcraft_doc::drawing_view::ViewDirection; +use solidcraft_doc::{MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS}; +use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Sheet}; +use solidcraft_geom::drawing_view::{PRESETS, Scale, ViewFrame}; +use solidcraft_geom::paper::MAX_COORDINATE_MM; +use solidcraft_geom::{Aabb2, Vec2}; + +use super::CommandSpec; +use crate::params::bad; +use crate::schema::drawing_view::{BoxResult, DPI_RANGE, ExtentsResult, ScaleResult, SnapshotParams, SnapshotResult, SourceResult, ViewResult}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{Result, Session}; + +const CMD: &str = "drawing.view.snapshot"; +const CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Drawing View Snapshot", crate::checked!("drawing.view.snapshot", CONTRACT, snapshot)) + .icon("export") + .noundo() + .contract(&CONTRACT) + .output(output_schema_for::) + .params("view?: front (default), back, top, bottom, left, right, iso (= iso_front_right), iso_front_left, iso_back_right, iso_back_left, or {direction, up, origin?}; scale?: \"paper:model\" such as \"1:2\" (default: the largest ISO 5455 scale that fits the sheet's drawing area); position_mm?: [x, y] for the view's centre on the sheet (default the sheet's centre); sheet?: {size: {standard: a3} or {custom: {sides_mm: [w, h]}}, orientation?: landscape|portrait, dpi?: 25..2400} (default A3 landscape, 300 dpi); display_style?, reference_style?: visible (default) or visible_hidden (the shaded styles aren't supported yet); reference_hides_model?: false; reference_margin_mm?: 0..100000 model mm on every side; tangent_edges?: hide (default) or show. Every body the design places, whatever the browser shows. Returns {view, scale: {text, factor, fitted}, position_mm, sheet, extents (model mm on the view's plane), boundary_mm (on the sheet), source}. Read-only: saves nothing.")]; + +fn snapshot(s: &mut Session, p: &Value) -> Result { + let request: SnapshotParams = crate::schema::read(CMD, p)?; + let settings = request.settings(); + let basis = settings.validate().map_err(|e| bad(CMD, e.to_string()))?; + if settings.display_style.is_shaded() || settings.reference_style.is_shaded() { + return Err(bad(CMD, "not supported yet: shaded views need the drawing renderer (#5624)")); + } + if !(request.sheet.dpi.is_finite() && DPI_RANGE.contains(&request.sheet.dpi)) { + return Err(bad(CMD, format!("sheet.dpi is a number from {} to {}", DPI_RANGE.start(), DPI_RANGE.end()))); + } + let sheet = Sheet { size: request.sheet.size, orientation: request.sheet.orientation }; + let paper = sheet.size_mm().map_err(|e| bad(CMD, e.to_string()))?; + let border = DrawingBorderProfile::iso().layout(&sheet).map_err(|e| bad(CMD, e.to_string()))?.drawing_border; + + if !s.doc.placements_complete() { + let limits = format!("deeper than {MAX_PLACEMENT_DEPTH} levels or has more than {MAX_PLACEMENTS} placements"); + return Err(bad(CMD, format!("the assembly is {limits}: a view of it would leave parts out"))); + } + let extents = crate::drawing_view::extents(s, &basis); + if extents.model.is_empty() { + return Err(bad(CMD, "the view's source has no bodies")); + } + let shown = extents.model.inflated(settings.reference_margin_mm); + let position = request.position_mm.map_or(paper * 0.5, |p| p.0); + let (scale, fitted) = match settings.scale { + Some(scale) => (scale, false), + None => (fit(shown.size(), position, border)?, true), + }; + let frame = ViewFrame::new(basis, scale, shown.center(), position).map_err(|e| bad(CMD, e.to_string()))?; + let boundary = frame.boundary(&shown).map_err(|e| bad(CMD, e.to_string()))?; + let on_paper = [boundary.min, boundary.max].iter().all(|c| c.is_finite() && c.x.abs() <= MAX_COORDINATE_MM && c.y.abs() <= MAX_COORDINATE_MM); + if !on_paper { + return Err(bad(CMD, format!("at scale {scale} the view reaches past ±{MAX_COORDINATE_MM} mm on paper: choose a smaller scale"))); + } + + let named = match settings.view { + ViewDirection::Named(view) => Some(snake_name(view)), + ViewDirection::Looking(_) => None, + }; + let reply = SnapshotResult { + view: ViewResult { + named, + // The line of sight, -(x × y), written so no component reads -0. + direction: basis.y.cross(basis.x).into(), + x: basis.x.into(), + y: basis.y.into(), + origin: basis.origin.into(), + }, + scale: ScaleResult { text: scale.to_string(), factor: scale.factor(), fitted }, + position_mm: position.into(), + sheet: request.sheet, + display_style: snake_name(settings.display_style), + reference_style: snake_name(settings.reference_style), + extents: ExtentsResult { + min: extents.model.min.into(), + max: extents.model.max.into(), + error_mm: extents.error_mm, + status: "approximate", + provenance: "display_mesh", + }, + boundary_mm: BoxResult { min: boundary.min.into(), max: boundary.max.into() }, + source: SourceResult { bodies: extents.bodies, timeline_at_end: s.doc.marker.is_none() }, + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| crate::EngineError::Other(e.to_string())) +} + +/// The largest preset scale at which a view `size` (model mm), centred at `position`, lies inside +/// the drawing border: the room is twice the distance from the position to the nearer side, +/// each way. +fn fit(size: Vec2, position: Vec2, border: Aabb2) -> Result { + let room = + Vec2::new(2.0 * (position.x - border.min.x).min(border.max.x - position.x), 2.0 * (position.y - border.min.y).min(border.max.y - position.y)); + Scale::fit(size, room).ok_or_else(|| { + let name = |s: Option<&Scale>| s.map(|s| s.to_string()).unwrap_or_default(); + let presets = format!("from {} to {}", name(PRESETS.first()), name(PRESETS.last())); + bad(CMD, format!("the view fits the sheet's drawing area at no preset scale {presets} here: give a scale, a position or a larger sheet")) + }) +} + +/// A unit enum's name as it reads and writes (`iso_front_right`, `visible_hidden`). +fn snake_name(value: impl Serialize) -> String { + serde_json::to_value(value).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default() +} + +#[cfg(test)] +#[path = "drawing_view_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/drawing_view_tests.rs b/crates/engine/src/cmd/drawing_view_tests.rs new file mode 100644 index 00000000000..5aaaccba434 --- /dev/null +++ b/crates/engine/src/cmd/drawing_view_tests.rs @@ -0,0 +1,174 @@ +use serde_json::json; + +use super::*; + +const EPS: f64 = 1e-9; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap() +} + +/// A block 100 x 50 x 20 mm along X, Y and Z, from the origin. +fn block() -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 100, "width": 50, "height": 20, "body_name": "Block"})); + s +} + +fn snap(s: &mut Session, p: Value) -> Value { + run(s, CMD, p) +} + +fn refused(s: &mut Session, p: Value) -> String { + s.execute(CMD, &p).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("accepted: {p}")) +} + +fn point(v: &Value) -> Vec2 { + Vec2::new(v[0].as_f64().unwrap(), v[1].as_f64().unwrap()) +} + +/// The boundary's size and centre on the sheet. +fn boundary(v: &Value) -> (Vec2, Vec2) { + let (min, max) = (point(&v["boundary_mm"]["min"]), point(&v["boundary_mm"]["max"])); + (max - min, (min + max) * 0.5) +} + +/// The block's boundary in each view at 1:2, worked by hand: front 50 x 10, top 50 x 25, right +/// 25 x 10, and from an isometric corner (100 + 50)/sqrt(2)/2 by (100 + 50 + 2 x 20)/sqrt(6)/2. +/// The centre lands on the position, and the extents are the model's own millimetres. +#[test] +fn a_blocks_boundary_in_each_view_is_its_size_at_the_scale() { + let mut s = block(); + let views = [ + (json!("front"), (50.0, 10.0)), + (json!("top"), (50.0, 25.0)), + (json!("right"), (25.0, 10.0)), + (json!("iso"), (150.0 / 2f64.sqrt() / 2.0, 190.0 / 6f64.sqrt() / 2.0)), + (json!({"direction": [0, 1, 0], "up": [0, 0, 1]}), (50.0, 10.0)), + ]; + for (view, (w, h)) in views { + let v = snap(&mut s, json!({"view": view, "scale": "1:2", "position_mm": [100, 120]})); + let (size, centre) = boundary(&v); + assert!((size - Vec2::new(w, h)).len() < EPS, "{view}: {size:?}"); + assert!((centre - Vec2::new(100.0, 120.0)).len() < EPS, "{view}: {centre:?}"); + assert_eq!((v["scale"]["text"].as_str(), v["scale"]["fitted"].as_bool()), (Some("1:2"), Some(false))); + } + let front = snap(&mut s, json!({"scale": "1:2"})); + assert_eq!(front["view"]["named"], "front"); + assert_eq!((front["view"]["direction"].clone(), front["view"]["x"].clone()), (json!([0.0, 1.0, 0.0]), json!([1.0, 0.0, 0.0]))); + assert!((point(&front["extents"]["min"]) - Vec2::ZERO).len() < EPS && (point(&front["extents"]["max"]) - Vec2::new(100.0, 20.0)).len() < EPS); + assert_eq!((front["extents"]["status"].as_str(), front["source"]["bodies"].as_u64()), (Some("approximate"), Some(1))); + assert_eq!(front["source"]["timeline_at_end"], true); + let iso = snap(&mut s, json!({"view": "iso", "scale": "1:2"})); + assert_eq!(iso["view"]["named"], "iso_front_right"); +} + +/// With no scale the view takes the largest preset scale that fits the sheet's drawing border, +/// centred on the sheet: the 100 x 20 front view on A3 landscape at 2:1 (5:1 would be 500 mm +/// wide), boundary 110..310 x 128.5..168.5. A scale given is used as it is, even when it overhangs. +#[test] +fn without_a_scale_the_view_fits_and_centres_on_its_sheet() { + let mut s = block(); + let v = snap(&mut s, json!({})); + assert_eq!((v["scale"]["text"].as_str(), v["scale"]["fitted"].as_bool()), (Some("2:1"), Some(true))); + assert!((point(&v["boundary_mm"]["min"]) - Vec2::new(110.0, 128.5)).len() < EPS, "{v}"); + assert!((point(&v["boundary_mm"]["max"]) - Vec2::new(310.0, 168.5)).len() < EPS, "{v}"); + let a4 = snap(&mut s, json!({"sheet": {"size": {"standard": "a4"}, "orientation": "portrait"}})); + assert_eq!(a4["scale"]["text"], "1:1", "A4 portrait has 95 mm to the border each side: 190 mm of room, so 2:1 (200 mm) doesn't fit"); + let near_the_left = snap(&mut s, json!({"position_mm": [80, 148.5]})); + assert_eq!(near_the_left["scale"]["text"], "1:1", "70 mm to the left border: 140 mm of room"); + let overhanging = snap(&mut s, json!({"scale": "5:1"})); + assert!((boundary(&overhanging).0 - Vec2::new(500.0, 100.0)).len() < EPS); + let off_the_border = refused(&mut s, json!({"position_mm": [5, 148.5]})); + assert!(off_the_border.contains("no preset scale from 50:1 to 1:10000"), "{off_the_border}"); + assert_eq!(a4["sheet"], json!({"size": {"standard": "a4"}, "orientation": "portrait", "dpi": 300.0}), "the sheet, its defaults filled in"); +} + +/// Scale and position only scale and move the boundary; the margin grows each side by the +/// margin times the scale; the browser's eye counts for nothing; nothing in the design changes. +#[test] +fn scale_position_and_margin_set_the_boundary_and_the_design_is_untouched() { + let mut s = block(); + let (undo, doc) = (s.undo.len(), s.doc.clone()); + let dirty = s.is_dirty(); + let one = boundary(&snap(&mut s, json!({"scale": "1:1", "position_mm": [0, 0]}))); + let half = boundary(&snap(&mut s, json!({"scale": "1:2", "position_mm": [0, 0]}))); + assert!((one.0 - half.0 * 2.0).len() < EPS && one.1.len() < EPS && half.1.len() < EPS); + let margin = boundary(&snap(&mut s, json!({"scale": "1:2", "position_mm": [0, 0], "reference_margin_mm": 5}))); + assert!((margin.0 - (half.0 + Vec2::new(5.0, 5.0))).len() < EPS, "2.5 mm a side at 1:2: {margin:?}"); + let first = snap(&mut s, json!({"view": "top"})); + assert_eq!(snap(&mut s, json!({"view": "top"})), first, "the same call gives the same answer"); + assert_eq!((s.undo.len(), s.is_dirty()), (undo, dirty)); + assert!(std::sync::Arc::ptr_eq(&doc, &s.doc), "nothing in the design changes"); + run(&mut s, "browser.visibility", json!({"items": ["Block"], "visible": false})); + assert_eq!(snap(&mut s, json!({"view": "top"}))["boundary_mm"], first["boundary_mm"], "a hidden body is still drawn"); +} + +/// What the snapshot refuses, each with nothing changed: bad settings, the shaded styles until +/// the drawing renderer, the sheet's resolution out of range, an empty design, a position off +/// the sheet's limit, and a view that would reach past the paper's coordinates. +#[test] +fn hostile_snapshots_are_refused() { + let mut s = block(); + let doc = s.doc.clone(); + let cases = [ + (json!({"scale": "0:1"}), "scale"), + (json!({"scale": "-1:2"}), "scale"), + (json!({"scale": "1e400:1"}), "scale"), + (json!({"scale": "1:2:3"}), "scale"), + (json!({"scale": 2}), "scale"), + (json!({"scale": null}), "scale"), + (json!({"view": "Front"}), "view is"), + (json!({"view": {"direction": [0, 0, 0], "up": [0, 0, 1]}}), "direction"), + (json!({"view": {"direction": [1e308, 1e308, 0], "up": [0, 0, 1]}}), "direction"), + (json!({"view": {"direction": [0, 0, 1], "up": [0, 0, 2]}}), "along the view direction"), + (json!({"display_style": "shaded"}), "not supported yet"), + (json!({"reference_style": "shaded_visible"}), "not supported yet"), + (json!({"display_style": "Shaded"}), "unknown variant"), + (json!({"sheet": {"dpi": 24.9}}), "dpi"), + (json!({"sheet": {"dpi": 2400.1}}), "dpi"), + (json!({"sheet": {"size": {"custom": {"sides_mm": [0, 10]}}}}), "sheet"), + (json!({"reference_margin_mm": -1}), "reference_margin_mm"), + (json!({"position_mm": [1e308, 0]}), "point"), + (json!({"position_mm": [5000.1, 0], "scale": "1:1"}), "position"), + (json!({"scael": "1:2"}), "scael"), + ]; + for (p, says) in cases { + let e = refused(&mut s, p.clone()); + assert!(e.contains(says), "{p}: {e}"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.doc), "{p}"); + } + let mut big = Session::default(); + run(&mut big, "solid.box", json!({"length": 300, "width": 10, "height": 10})); + let e = refused(&mut big, json!({"scale": "1000:1"})); + assert!(e.contains("past ±100000 mm"), "{e}"); + let e = refused(&mut Session::default(), json!({})); + assert!(e.contains("no bodies"), "{e}"); +} + +/// A view shows every body the design places, so a design whose assembly walk stops at its depth +/// limit before some occurrences is refused, and one that ends at the limit is drawn: a chain of +/// components one inside the next, one level at a time across the limit. +#[test] +fn a_view_of_an_assembly_past_the_walks_limit_is_refused() { + let mut s = block(); + let nest = |s: &mut Session, level: u64| { + let (component, parent) = (1000 + level, if level == 0 { 0 } else { 1000 + level - 1 }); + let doc = s.doc_mut(); + doc.components.push(solidcraft_doc::Component { id: component, name: format!("L{level}"), parent, ..Default::default() }); + let name = format!("L{level}"); + // From JSON, so a field another change adds to occurrences takes its default here. + let occurrence = json!({"id": 5000 + level, "component": component, "parent": parent, "name": name}); + doc.occurrences.push(serde_json::from_value(occurrence).unwrap()); + }; + // The deepest occurrence's path is MAX_PLACEMENT_DEPTH + 1 long: walked, its children not. + for level in 0..=MAX_PLACEMENT_DEPTH as u64 { + nest(&mut s, level); + } + assert!(s.doc.placements_complete()); + snap(&mut s, json!({"scale": "1:1"})); + nest(&mut s, MAX_PLACEMENT_DEPTH as u64 + 1); + assert!(!s.doc.placements_complete()); + let e = refused(&mut s, json!({"scale": "1:1"})); + assert!(e.contains("deeper than 64 levels or has more than 100000 placements"), "{e}"); +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index b659d0eaf7e..667c32e212d 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -32,6 +32,7 @@ mod construct; mod delete; mod diagnostics; mod drawing; +mod drawing_view; mod edit; mod face; mod features; @@ -337,6 +338,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(view_navigation::COMMANDS.iter()); v.extend(view_dxf::COMMANDS.iter()); v.extend(drawing::COMMANDS.iter()); + v.extend(drawing_view::COMMANDS.iter()); v.extend(diagnostics::COMMANDS.iter()); v.extend(render::COMMANDS.iter()); v diff --git a/crates/engine/src/drawing_view.rs b/crates/engine/src/drawing_view.rs new file mode 100644 index 00000000000..23d0636e4ff --- /dev/null +++ b/crates/engine/src/drawing_view.rs @@ -0,0 +1,29 @@ +//! Drawing views of the session's model (W07, #5866): what a view shows and how far it reaches. +//! The snapshot command uses it now; saved views (W14) and their pictures (W17b) will too. +//! +//! A view shows every body the design places, where its occurrences place it. The browser's eye +//! counts for nothing: hiding a part in the model never changes a drawing. + +use solidcraft_geom::{Aabb2, Plane}; + +use crate::Session; + +/// How far a view reaches on its own plane, in model millimetres. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Extents { + /// The bodies' box in the plane's own coordinates ([`Plane::to_local`]); empty with no bodies. + pub model: Aabb2, + /// How far a curved face may lie outside its display mesh: the largest display tolerance. + pub error_mm: f64, + pub bodies: usize, +} + +/// The extents of every body the design places, seen on `basis`. +pub fn extents(s: &Session, basis: &Plane) -> Extents { + let st = s.world_state(); + st.bodies.iter().fold(Extents { model: Aabb2::EMPTY, error_mm: 0.0, bodies: 0 }, |e, body| Extents { + model: e.model.union(&body.mesh_bounds_in(basis)), + error_mm: e.error_mm.max(body.display_tol()), + bodies: e.bodies + 1, + }) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8a9ed5d6a50..f2e14b63393 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,7 @@ pub mod capture; pub mod cmd; pub mod control_auth; pub mod crash; +pub mod drawing_view; pub mod frames; pub mod fuzz; pub mod licences; diff --git a/crates/engine/src/schema/check.rs b/crates/engine/src/schema/check.rs index 251bb780681..864a6f74692 100644 --- a/crates/engine/src/schema/check.rs +++ b/crates/engine/src/schema/check.rs @@ -223,6 +223,12 @@ fn nearest(key: &str, allowed: &BTreeSet) -> Option { .map(|(_, a)| a.clone()) } +/// The command `cmd`'s parameters `p` as its contract type `P`, refused in the words the contract +/// check uses, so the handler and the check say the same thing about the same mistake. +pub(crate) fn read(cmd: &str, p: &Value) -> Result

{ + serde_path_to_error::deserialize(p).map_err(|e| bad(cmd, parse_issue(&e).message)) +} + /// A deserialization failure as an issue, in the engine's style. pub(crate) fn parse_issue(e: &serde_path_to_error::Error) -> Issue { let path = error_path(e); diff --git a/crates/engine/src/schema/drawing_view.rs b/crates/engine/src/schema/drawing_view.rs new file mode 100644 index 00000000000..a3ab5c4cd21 --- /dev/null +++ b/crates/engine/src/schema/drawing_view.rs @@ -0,0 +1,248 @@ +//! Contracts and result types for the commands in `cmd/drawing_view.rs`. +//! +//! The view's own settings are `solidcraft_doc::drawing_view::ViewSettings`, which a saved view +//! (W12) keeps too. The contract lists the same fields, each read by that type's own reader, and +//! `the_contract_lists_the_view_settings` keeps the two lists the same. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use solidcraft_doc::drawing_view::{TangentEdges, ViewDirection, ViewSettings}; +use solidcraft_geom::drawing_sheet::{Orientation, PaperSize, SheetSize}; +use solidcraft_geom::drawing_view::{NamedView, Scale}; +use solidcraft_render::VisualStyle; + +use super::Point2; + +/// The lowest and highest picture resolution a sheet takes, in dots per inch. +pub const DPI_RANGE: std::ops::RangeInclusive = 25.0..=2400.0; + +/// What `drawing.view.snapshot` takes: the view's settings, the page it fits on, and where its +/// centre goes. +#[derive(Debug, Default, Deserialize, JsonSchema)] +#[serde(default, deny_unknown_fields)] +#[schemars(deny_unknown_fields)] +pub struct SnapshotParams { + pub view: ViewParam, + #[serde(deserialize_with = "super::present")] + #[schemars(with = "ScaleParam")] + pub scale: Option, + pub display_style: StyleParam, + pub reference_style: StyleParam, + /// Whether reference parts hide the model's lines behind them (false when not given). + pub reference_hides_model: bool, + /// Model millimetres added on every side of the view's extents, so reference parts around + /// the model show inside its boundary: 0 to 100000 (0 when not given). + pub reference_margin_mm: f64, + pub tangent_edges: TangentEdgesParam, + pub sheet: SheetParam, + /// Where the view's centre goes on the sheet, in paper millimetres from its lower-left + /// corner (the sheet's centre when not given). + #[serde(deserialize_with = "super::present")] + #[schemars(with = "Point2")] + pub position_mm: Option, +} + +impl SnapshotParams { + pub fn settings(&self) -> ViewSettings { + ViewSettings { + view: self.view.0, + scale: self.scale.map(|s| s.0), + display_style: self.display_style.0, + reference_style: self.reference_style.0, + reference_hides_model: self.reference_hides_model, + reference_margin_mm: self.reference_margin_mm, + tangent_edges: self.tangent_edges.0, + } + } +} + +// Each parameter type below reads as the type it wraps, so the contract accepts exactly what the +// view's settings do; it is there for its schema. + +/// Which way the view looks. +#[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize)] +#[serde(transparent)] +pub struct ViewParam(pub ViewDirection); + +impl JsonSchema for ViewParam { + fn schema_name() -> Cow<'static, str> { + "DrawingView".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let names: Vec = NamedView::ALL.iter().filter_map(|v| serde_json::to_value(v).ok()).chain([json!("iso")]).collect(); + let vector = json!({"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}); + json_schema!({ + "description": "Which way the view looks: a named view (front when not given; iso is iso_front_right), or {direction, up, origin?}: the line of sight, the way up the paper (not along the direction) and the point the view's plane passes through (the world origin when not given).", + "anyOf": [ + {"type": "string", "enum": names}, + {"type": "object", "properties": {"direction": vector, "up": vector, "origin": vector}, "required": ["direction", "up"], "additionalProperties": false} + ] + }) + } +} + +/// A drawing scale, paper:model. +#[derive(Clone, Copy, Debug, PartialEq, Deserialize)] +#[serde(transparent)] +pub struct ScaleParam(pub Scale); + +impl JsonSchema for ScaleParam { + fn schema_name() -> Cow<'static, str> { + "DrawingScale".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "The scale as paper:model text, such as \"1:2\" or \"5:1\", from 1:100000 to 1000:1. When not given, the largest ISO 5455 scale at which the view fits the sheet's drawing area.", + "type": "string", + "pattern": "^[0-9]+(\\.[0-9]+)?:[0-9]+(\\.[0-9]+)?$" + }) + } +} + +/// How the model draws. +#[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize)] +#[serde(transparent)] +pub struct StyleParam(pub VisualStyle); + +impl JsonSchema for StyleParam { + fn schema_name() -> Cow<'static, str> { + "VisualStyle".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let names: Vec = VisualStyle::ALL.iter().filter_map(|s| serde_json::to_value(s).ok()).collect(); + json_schema!({ + "description": "How the model draws: visible (the default), visible_hidden, shaded, shaded_visible or shaded_visible_hidden.", + "type": "string", + "enum": names + }) + } +} + +/// Tangent edges hidden or shown. +#[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize)] +#[serde(transparent)] +pub struct TangentEdgesParam(pub TangentEdges); + +impl JsonSchema for TangentEdgesParam { + fn schema_name() -> Cow<'static, str> { + "TangentEdges".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"description": "Edges where faces meet smoothly: hide (the default) or show.", "type": "string", "enum": ["hide", "show"]}) + } +} + +/// The page the view fits on: its size, the way it lies and its picture resolution. +#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)] +#[serde(default, deny_unknown_fields)] +pub struct SheetParam { + pub size: SheetSize, + pub orientation: Orientation, + pub dpi: f64, +} + +impl Default for SheetParam { + fn default() -> Self { + SheetParam { size: SheetSize::Standard(PaperSize::A3), orientation: Orientation::Landscape, dpi: 300.0 } + } +} + +impl JsonSchema for SheetParam { + fn schema_name() -> Cow<'static, str> { + "SnapshotSheet".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let papers: Vec = PaperSize::ALL.iter().filter_map(|p| serde_json::to_value(p).ok()).collect(); + let sides = json!({"type": "array", "items": {"type": "number", "exclusiveMinimum": 0}, "minItems": 2, "maxItems": 2}); + let standard = json!({"type": "object", "properties": {"standard": {"type": "string", "enum": papers}}, "required": ["standard"], "additionalProperties": false}); + let custom = json!({ + "type": "object", + "properties": {"custom": {"type": "object", "properties": {"sides_mm": sides}, "required": ["sides_mm"], "additionalProperties": false}}, + "required": ["custom"], + "additionalProperties": false + }); + json_schema!({ + "description": "The page the view fits and centres on (A3 landscape at 300 dpi when not given).", + "type": "object", + "properties": { + "size": {"anyOf": [standard, custom]}, + "orientation": {"type": "string", "enum": ["landscape", "portrait"]}, + "dpi": {"type": "number", "minimum": *DPI_RANGE.start(), "maximum": *DPI_RANGE.end()} + }, + "additionalProperties": false + }) + } +} + +/// A view's extents on its own plane, in model millimetres. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ExtentsResult { + pub min: [f64; 2], + pub max: [f64; 2], + /// How far the display mesh may lie inside a curved face: the largest display tolerance. + pub error_mm: f64, + /// `approximate`: measured on the display mesh. + pub status: &'static str, + pub provenance: &'static str, +} + +/// A box on the sheet, in paper millimetres. +#[derive(Debug, Serialize, JsonSchema)] +pub struct BoxResult { + pub min: [f64; 2], + pub max: [f64; 2], +} + +/// The scale the view was drawn at. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ScaleResult { + pub text: String, + pub factor: f64, + /// Whether the scale was worked out to fit the sheet rather than given. + pub fitted: bool, +} + +/// The view's basis as resolved: its name when it has one, the line of sight and the paper axes. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ViewResult { + #[serde(skip_serializing_if = "Option::is_none")] + pub named: Option, + pub direction: [f64; 3], + pub x: [f64; 3], + pub y: [f64; 3], + pub origin: [f64; 3], +} + +/// What the view was drawn from. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SourceResult { + pub bodies: usize, + /// Whether the timeline marker is at the end; otherwise the view shows the rolled-back model. + pub timeline_at_end: bool, +} + +/// What `drawing.view.snapshot` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SnapshotResult { + pub view: ViewResult, + pub scale: ScaleResult, + pub position_mm: [f64; 2], + /// The sheet the view is placed on, its defaults filled in. + pub sheet: SheetParam, + pub display_style: String, + pub reference_style: String, + pub extents: ExtentsResult, + /// The view's box on the sheet: `position_mm` at its centre, the extents at the scale. + pub boundary_mm: BoxResult, + pub source: SourceResult, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "drawing_view_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/drawing_view_tests.rs b/crates/engine/src/schema/drawing_view_tests.rs new file mode 100644 index 00000000000..e4efdb50da6 --- /dev/null +++ b/crates/engine/src/schema/drawing_view_tests.rs @@ -0,0 +1,47 @@ +use serde_json::json; +use solidcraft_doc::drawing_view::ViewSettings; + +use super::SnapshotParams; +use crate::schema::input_schema_for; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors}; + +#[test] +fn schemas_and_the_key_check_agree() { + let keys = [ + "display_style", + "position_mm", + "reference_hides_model", + "reference_margin_mm", + "reference_style", + "scale", + "sheet", + "tangent_edges", + "view", + ]; + assert_keys(input_schema_for::(), &keys); +} + +/// The contract takes the view's settings field for field, plus the sheet and the position, so +/// the snapshot and a saved view (W12) keep one parameter set. +#[test] +fn the_contract_lists_the_view_settings() { + // With a scale: none is left out when written. + let settings = serde_json::to_value(ViewSettings { scale: "1:2".parse().ok(), ..ViewSettings::default() }).unwrap_or_default(); + let mut theirs: Vec = settings.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(); + theirs.extend(["position_mm".to_string(), "sheet".to_string()]); + theirs.sort(); + let schema = input_schema_for::(); + let mut ours: Vec = schema.as_value()["properties"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(); + ours.sort(); + assert_eq!(ours, theirs); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("drawing.view.snapshot", json!({"scale": "0:1"})), + ("drawing.view.snapshot", json!({"view": "Front"})), + ("drawing.view.snapshot", json!({"display_style": "shaded"})), + ("drawing.view.snapshot", json!({"sheet": {"dpi": 1e9}})), + ]); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 266d5fa87c2..81f993b6ff7 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -46,9 +46,11 @@ mod types; mod tests; // The contracts, by command file. +pub mod drawing_view; pub mod features; pub mod inspect; +pub(crate) use check::read; pub use check::{Contract, Issue, ParamCheck, TypedContract, input_schema_for, output_schema_for, run_checked}; pub use types::*; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 14eeeaf5a4d..d265b802314 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -822,6 +822,14 @@ fn hostile_params_never_panic() { "keep_with", "stitch", "extend", + "view", + "display_style", + "reference_style", + "reference_hides_model", + "reference_margin_mm", + "tangent_edges", + "sheet", + "position_mm", ]; // Commands are independent; worker threads take them one at a time (their costs vary a lot). let ids: Vec<&str> = command_specs() diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4f9e70be790..fbf44448445 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -20,6 +20,7 @@ pub mod texture_input; pub mod texture_interpolation; pub mod texture_lod; pub mod texture_sampling; +mod visual_style; pub use analysis::{AnalysisColors, AnalysisMode, SceneAnalysis}; pub use backend::{ @@ -33,3 +34,4 @@ pub use gif::gif; pub use product::{FaceAppearance, ProductMesh, ProductScene}; pub use raster::{Canvas, render, render_png, render_transparent}; pub use scene::{MIN_ALPHA, Rgb, SECTION_CAP, SEE_THROUGH, Scene, SceneLine, SceneMesh, png}; +pub use visual_style::VisualStyle; diff --git a/crates/render/src/visual_style.rs b/crates/render/src/visual_style.rs new file mode 100644 index 00000000000..eced8480ebb --- /dev/null +++ b/crates/render/src/visual_style.rs @@ -0,0 +1,59 @@ +//! How a view draws the model: its lines, its shading, or both. One list for drawing views +//! (W07, W17b) and the viewport's styles (#5219, #5307) to map to. + +use serde::{Deserialize, Serialize}; + +/// A view's visual style. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum VisualStyle { + /// The visible lines only. + #[default] + Visible, + /// The visible lines and the hidden ones. + VisibleHidden, + /// The shaded model with no lines. + Shaded, + /// The shaded model under its visible lines. + ShadedVisible, + /// The shaded model under its visible and hidden lines. + ShadedVisibleHidden, +} + +impl VisualStyle { + pub const ALL: [VisualStyle; 5] = + [VisualStyle::Visible, VisualStyle::VisibleHidden, VisualStyle::Shaded, VisualStyle::ShadedVisible, VisualStyle::ShadedVisibleHidden]; + + /// Whether the model is drawn as a picture. + pub fn is_shaded(self) -> bool { + matches!(self, VisualStyle::Shaded | VisualStyle::ShadedVisible | VisualStyle::ShadedVisibleHidden) + } + + /// Whether hidden lines are drawn. + pub fn draws_hidden(self) -> bool { + matches!(self, VisualStyle::VisibleHidden | VisualStyle::ShadedVisibleHidden) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The five styles, by their snake-case names, and what each draws. + #[test] + fn each_style_reads_by_its_name_and_says_what_it_draws() { + let names = ["visible", "visible_hidden", "shaded", "shaded_visible", "shaded_visible_hidden"]; + for (style, name) in VisualStyle::ALL.into_iter().zip(names) { + assert_eq!(serde_json::to_value(style).unwrap(), serde_json::json!(name)); + assert_eq!(serde_json::from_value::(serde_json::json!(name)).unwrap(), style); + } + let shaded: Vec = VisualStyle::ALL.iter().map(|s| s.is_shaded()).collect(); + let hidden: Vec = VisualStyle::ALL.iter().map(|s| s.draws_hidden()).collect(); + assert_eq!(shaded, [false, false, true, true, true]); + assert_eq!(hidden, [false, true, false, false, true]); + assert_eq!(VisualStyle::default(), VisualStyle::Visible); + for not_a_style in ["Shaded", "hidden", "", "visible-hidden"] { + assert!(serde_json::from_value::(serde_json::json!(not_a_style)).is_err(), "{not_a_style}"); + } + } +}