From 472a330691f89fe58e90e65665bd035927c07ca0 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Mon, 26 Oct 2026 22:05:59 +0000 Subject: [PATCH 1/3] 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/3] 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/3] 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`");