diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 11cec9b9c..1085feb96 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -3057,21 +3057,30 @@ impl Document { *self == normalized } - /// Only components' part properties (metadata and free properties) changed: nothing to + /// Only part properties changed (the fields `with_part_properties_of` names): nothing to /// evaluate. The same whole-Document proof as [`Document::differs_only_in_render`]. pub fn differs_only_in_part_properties(&self, previous: &Document) -> bool { - if self.components.len() != previous.components.len() - || self.components.iter().zip(&previous.components).any(|(a, b)| a.id != b.id) - || self.components == previous.components - { - return false; + previous.with_part_properties_of(self).is_some_and(|normalized| normalized == *self) + } + + /// This design with `other`'s part properties, or `None` when they are this design's + /// already (then nothing is copied). The part properties are the fields that change no + /// geometry: the design's metadata, and each component's metadata and free properties. A + /// field that joins them is compared and copied here, and nowhere else. + fn with_part_properties_of(&self, other: &Document) -> Option { + let same = self.metadata == other.metadata + && self.components.iter().zip(&other.components).all(|(c, o)| c.metadata == o.metadata && c.properties == o.properties); + if same { + return None; } - let mut normalized = previous.clone(); - for (n, c) in normalized.components.iter_mut().zip(&self.components) { - n.metadata = c.metadata.clone(); - n.properties = c.properties.clone(); + let mut out = self.clone(); + out.metadata.clone_from(&other.metadata); + // Paired by position: if the components themselves differ, so do the designs. + for (c, o) in out.components.iter_mut().zip(&other.components) { + c.metadata.clone_from(&o.metadata); + c.properties.clone_from(&o.properties); } - *self == normalized + Some(out) } /// The colour a body is shown and exported in (sRGB as 0–1 fractions): its appearance, diff --git a/crates/doc/src/metadata.rs b/crates/doc/src/metadata.rs index 44bbb8708..5d99c24e6 100644 --- a/crates/doc/src/metadata.rs +++ b/crates/doc/src/metadata.rs @@ -1,14 +1,17 @@ -//! Design properties (#1015): the design's optional top-level `metadata` object. +//! Design and part properties (#1015): the optional `metadata` object of the design and of each +//! component. //! //! SolidCraft reads a few well-known, unprefixed text keys from it (project, part number, -//! revision, author, organization, description, licence) and keeps every other key exactly as -//! it was through open, edit and save. Other tools keep their own data under one reverse-DNS -//! key each (`com.example.tool`), holding an object. +//! revision, author, organization, description, licence), listed once in [`KEYS`] with where +//! each may be set (the design, a component or both), how its value is checked and its label. +//! It keeps every other key exactly as it was through open, edit and save. Other tools keep +//! their own data under one reverse-DNS key each (`com.example.tool`), holding an object. //! //! Reading never validates: a well-known key holding something other than text is kept as it //! is and reads as absent, so a file another tool wrote always opens. Writing through -//! [`Metadata::set`] (the `document.metadata.set` command) checks the key, the value's kind and -//! its size, so nothing SolidCraft writes is malformed. +//! [`Metadata::set`] (the `document.metadata.set` and `component.metadata.set` commands) checks +//! the key against where it is set, the value's kind and its size, so nothing SolidCraft writes +//! is malformed. //! //! The map is stored as is: typed fields would refuse a design another tool had written //! `"author": 42` into. Everything under `metadata` is informational, never geometry, so keeping @@ -27,9 +30,67 @@ pub const ORGANIZATION: &str = "organization"; pub const DESCRIPTION: &str = "description"; pub const LICENSE: &str = "license"; -/// SolidCraft's own keys, in the order the Design Properties dialog shows them. Every other -/// unprefixed key is reserved for SolidCraft too. -pub const WELL_KNOWN: [&str; 7] = [PROJECT, PART_NUMBER, REVISION, AUTHOR, ORGANIZATION, DESCRIPTION, LICENSE]; +/// Where a key may be set: on the design, on a component, or on both. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Scope { + Design, + Component, + Both, +} + +impl Scope { + /// Whether a key of this scope may be set in `owner`'s metadata. + pub fn covers(self, owner: Owner) -> bool { + matches!((self, owner), (Scope::Both, _) | (Scope::Design, Owner::Design) | (Scope::Component, Owner::Component)) + } +} + +/// Whose metadata a change is to: the design's (`document.metadata.set`) or a component's +/// (`component.metadata.set`). [`Metadata::set`] is told which. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Owner { + Design, + Component, +} + +impl Owner { + /// What one of its properties, and several, are called in a refusal. + fn names(self) -> (&'static str, &'static str) { + match self { + Owner::Design => ("design property", "design properties"), + Owner::Component => ("part property", "part properties"), + } + } +} + +/// One of SolidCraft's own keys. +pub struct Key { + pub name: &'static str, + /// Where it may be set. + pub scope: Scope, + /// The message id of its label (the Design Properties dialog, the Bill of Materials window). + pub label: &'static str, + /// The value as it is saved (`None`: the key is removed), or why it can't be; given the key + /// to name it in the refusal. + check: fn(&str, Value) -> Result>, +} + +/// SolidCraft's own keys, in the order the Design Properties dialog shows them; a new key is one +/// row here. Every other unprefixed key is reserved for SolidCraft too. +pub static KEYS: &[Key] = &[ + Key { name: PROJECT, scope: Scope::Both, label: "ui.design_properties.project", check: text }, + Key { name: PART_NUMBER, scope: Scope::Both, label: "ui.design_properties.part_number", check: text }, + Key { name: REVISION, scope: Scope::Both, label: "ui.design_properties.revision", check: text }, + Key { name: AUTHOR, scope: Scope::Both, label: "ui.design_properties.author", check: text }, + Key { name: ORGANIZATION, scope: Scope::Both, label: "ui.design_properties.organization", check: text }, + Key { name: DESCRIPTION, scope: Scope::Both, label: "ui.design_properties.description", check: text }, + Key { name: LICENSE, scope: Scope::Both, label: "ui.design_properties.license", check: text }, +]; + +/// The keys a bill of materials lists for each part, in the order of its columns: +/// `component.metadata` returns each, `component.metadata.set` takes each as a parameter of its +/// own, and the Bill of Materials window edits them. +pub static BOM_KEYS: &[&str] = &[PART_NUMBER, DESCRIPTION, REVISION]; /// Longest key, in bytes. pub const MAX_KEY_BYTES: usize = 128; @@ -43,14 +104,29 @@ pub const MAX_VALUE_DEPTH: usize = 32; pub const MAX_KEYS: usize = 256; pub const MAX_TOTAL_BYTES: usize = 256 * 1024; -/// The design's `metadata` object. +/// A design's or a component's `metadata` object. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(transparent)] pub struct Metadata(pub Map); -/// A key SolidCraft reads as a design property. -pub fn is_well_known(key: &str) -> bool { - WELL_KNOWN.contains(&key) +/// SolidCraft's keys that may be set in `owner`'s metadata, in [`KEYS`]' order. +pub fn keys(owner: Owner) -> impl Iterator { + KEYS.iter().filter(move |k| k.scope.covers(owner)) +} + +/// The names of [`keys`]`(owner)`, as refusals list them. +pub fn key_list(owner: Owner) -> String { + keys(owner).map(|k| k.name).collect::>().join(", ") +} + +/// One of SolidCraft's keys, by name. +pub fn key(name: &str) -> Option<&'static Key> { + KEYS.iter().find(|k| k.name == name) +} + +/// A key SolidCraft reads as a design or part property. +pub fn is_well_known(name: &str) -> bool { + key(name).is_some() } /// A reverse-DNS key another tool keeps its data under: two or more dot-separated labels of @@ -61,6 +137,31 @@ pub fn is_namespaced(key: &str) -> bool { && key.split('.').all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) } +/// Text SolidCraft keeps as a property: at most [`MAX_TEXT_BYTES`], and no control characters +/// but line breaks and tabs. `what` names it in the refusal. +pub fn check_text(what: &str, text: &str) -> Result<()> { + if text.len() > MAX_TEXT_BYTES { + return Err(invalid(format!("{what} is longer than {MAX_TEXT_BYTES} bytes"))); + } + if text.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\t' | '\r')) { + return Err(invalid(format!("{what} has a control character"))); + } + Ok(()) +} + +/// A text key's check: text, which empty text (like `null`) removes. +fn text(key: &str, value: Value) -> Result> { + match value { + Value::Null => Ok(None), + Value::String(s) if s.is_empty() => Ok(None), + Value::String(s) => { + check_text(&format!("`{key}`"), &s)?; + Ok(Some(Value::String(s))) + } + _ => Err(invalid(format!("`{key}` takes text"))), + } +} + fn depth(v: &Value) -> usize { // Iterative, so a hostile value can't overflow the stack here. let mut deepest = 0; @@ -129,10 +230,10 @@ impl Metadata { self.0.iter().filter(|(k, _)| !is_well_known(k)) } - /// Set `key` to `value` after checking both; `null` (or empty text for a well-known key) - /// removes it. Returns whether the metadata changed. - pub fn set(&mut self, key: &str, value: Value) -> Result { - let value = check(key, value)?; + /// Set `key` to `value` in `owner`'s metadata, after checking both; `null` (or empty text for + /// a text key) removes it. Returns whether the metadata changed. + pub fn set(&mut self, owner: Owner, key: &str, value: Value) -> Result { + let value = check(owner, key, value)?; let Some(value) = value else { return Ok(self.remove(key)) }; if self.0.get(key) == Some(&value) { return Ok(false); @@ -146,7 +247,7 @@ impl Metadata { Some(old) => self.0.insert(key.to_string(), old), None => self.0.remove(key), }; - return Err(invalid(format!("design properties are limited to {MAX_KEYS} keys and {} KiB", MAX_TOTAL_BYTES / 1024))); + return Err(invalid(format!("{} are limited to {MAX_KEYS} keys and {} KiB", owner.names().1, MAX_TOTAL_BYTES / 1024))); } Ok(true) } @@ -157,23 +258,10 @@ impl Metadata { } } -/// `value` as `key` may hold it (`None`: remove the key), or why it can't. -fn check(key: &str, value: Value) -> Result> { - if is_well_known(key) { - return match value { - Value::Null => Ok(None), - Value::String(s) if s.is_empty() => Ok(None), - Value::String(s) => { - if s.len() > MAX_TEXT_BYTES { - return Err(invalid(format!("`{key}` is longer than {MAX_TEXT_BYTES} bytes"))); - } - if s.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\t' | '\r')) { - return Err(invalid(format!("`{key}` has a control character"))); - } - Ok(Some(Value::String(s))) - } - _ => Err(invalid(format!("`{key}` takes text"))), - }; +/// `value` as `key` may hold it in `owner`'s metadata (`None`: remove the key), or why it can't. +fn check(owner: Owner, key: &str, value: Value) -> Result> { + if let Some(k) = self::key(key).filter(|k| k.scope.covers(owner)) { + return (k.check)(key, value); } if is_namespaced(key) { return match value { @@ -193,13 +281,15 @@ fn check(key: &str, value: Value) -> Result> { } let shown: String = key.chars().take(64).collect(); Err(invalid(format!( - "`{shown}` is not a design property: SolidCraft's are {}; another tool's data goes under a reverse-DNS key such as `com.example.tool`", - WELL_KNOWN.join(", ") + "`{shown}` is not a {}: SolidCraft's are {}; another tool's data goes under a reverse-DNS key such as `com.example.tool`", + owner.names().0, + key_list(owner) ))) } #[cfg(test)] mod tests { + use super::Owner::{Component, Design}; use super::*; use serde_json::json; @@ -216,30 +306,30 @@ mod tests { #[test] fn set_checks_keys_kinds_and_sizes() { let mut m = Metadata::default(); - assert!(m.set("author", json!("Jane")).unwrap()); - assert!(!m.set("author", json!("Jane")).unwrap(), "the same value is no change"); - assert!(m.set("com.acme.tool", json!({"shop_id": 88123, "tags": ["a", null, 1.5]})).unwrap()); - assert!(m.set("author", json!(42)).is_err(), "well-known keys take text"); - assert!(m.set("author", json!("a\u{7}b")).is_err(), "no control characters"); - assert!(m.set("description", json!("two\nlines\tand a tab")).unwrap()); - assert!(m.set("com.acme.tool", json!("text")).is_err(), "a tool's key holds an object"); - assert!(m.set("colour", json!("red")).is_err(), "unprefixed keys are reserved"); - assert!(m.set("", json!({})).is_err()); + assert!(m.set(Design, "author", json!("Jane")).unwrap()); + assert!(!m.set(Design, "author", json!("Jane")).unwrap(), "the same value is no change"); + assert!(m.set(Design, "com.acme.tool", json!({"shop_id": 88123, "tags": ["a", null, 1.5]})).unwrap()); + assert!(m.set(Design, "author", json!(42)).is_err(), "well-known keys take text"); + assert!(m.set(Design, "author", json!("a\u{7}b")).is_err(), "no control characters"); + assert!(m.set(Design, "description", json!("two\nlines\tand a tab")).unwrap()); + assert!(m.set(Design, "com.acme.tool", json!("text")).is_err(), "a tool's key holds an object"); + assert!(m.set(Design, "colour", json!("red")).is_err(), "unprefixed keys are reserved"); + assert!(m.set(Design, "", json!({})).is_err()); for bad in ["com.", ".com", "com..x", "com.ex ample", "com.é", "single"] { - assert!(m.set(bad, json!({})).is_err(), "{bad}"); + assert!(m.set(Design, bad, json!({})).is_err(), "{bad}"); } - assert!(m.set("author", json!("x".repeat(MAX_TEXT_BYTES + 1))).is_err()); - assert!(m.set("org.big", json!({"a": "x".repeat(MAX_VALUE_BYTES)})).is_err()); + assert!(m.set(Design, "author", json!("x".repeat(MAX_TEXT_BYTES + 1))).is_err()); + assert!(m.set(Design, "org.big", json!({"a": "x".repeat(MAX_VALUE_BYTES)})).is_err()); let mut deep = json!({}); for _ in 0..MAX_VALUE_DEPTH { deep = json!({ "a": deep }); } - assert!(m.set("org.deep", deep).is_err()); + assert!(m.set(Design, "org.deep", deep).is_err()); assert_eq!(m.author(), Some("Jane"), "a refused value leaves the old one"); // Null and empty text remove. - assert!(m.set("author", json!("")).unwrap()); - assert!(m.set("com.acme.tool", Value::Null).unwrap()); - assert!(!m.set("com.acme.tool", Value::Null).unwrap()); + assert!(m.set(Design, "author", json!("")).unwrap()); + assert!(m.set(Design, "com.acme.tool", Value::Null).unwrap()); + assert!(!m.set(Design, "com.acme.tool", Value::Null).unwrap()); assert_eq!(m.0.keys().collect::>(), ["description"]); } @@ -247,17 +337,214 @@ mod tests { fn the_limits_refuse_growth_but_let_an_oversized_file_shrink() { let mut m = Metadata::default(); for i in 0..MAX_KEYS { - m.set(&format!("org.k{i}"), json!({})).unwrap(); + m.set(Design, &format!("org.k{i}"), json!({})).unwrap(); } - assert!(m.set("org.one_more", json!({})).is_err()); + assert!(m.set(Design, "org.one_more", json!({})).is_err()); assert_eq!(m.0.len(), MAX_KEYS); + // Each owner's refusal names its own properties. + let refusal = |owner| m.clone().set(owner, "org.one_more", json!({})).unwrap_err().to_string(); + assert_eq!(refusal(Design), "design properties are limited to 256 keys and 256 KiB"); + assert_eq!(refusal(Component), "part properties are limited to 256 keys and 256 KiB"); // A file written past the limits by another tool still opens and can be cut down. let mut big = Metadata::default(); for i in 0..MAX_KEYS + 10 { big.0.insert(format!("org.k{i}"), json!({})); } - assert!(big.set("org.k0", Value::Null).unwrap()); - assert!(big.set("author", json!("Jane")).is_err(), "still over: no new keys"); - assert!(big.set("org.k1", json!({"replaced": true})).is_ok(), "the count doesn't grow"); + assert!(big.set(Design, "org.k0", Value::Null).unwrap()); + assert!(big.set(Design, "author", json!("Jane")).is_err(), "still over: no new keys"); + assert!(big.set(Design, "org.k1", json!({"replaced": true})).is_ok(), "the count doesn't grow"); + } + + #[test] + fn each_key_is_one_row_in_the_order_the_dialog_shows() { + let names: Vec<&str> = KEYS.iter().map(|k| k.name).collect(); + assert_eq!(names, [PROJECT, PART_NUMBER, REVISION, AUTHOR, ORGANIZATION, DESCRIPTION, LICENSE]); + for (i, k) in KEYS.iter().enumerate() { + assert!(!names[..i].contains(&k.name), "`{}` has two rows", k.name); + assert!(!k.name.is_empty() && !is_namespaced(k.name), "`{}` is unprefixed", k.name); + assert!(k.label.starts_with("ui.") && !KEYS[..i].iter().any(|o| o.label == k.label), "`{}`'s label", k.name); + assert!(is_well_known(k.name) && key(k.name).is_some_and(|f| std::ptr::eq(f, k))); + } + for name in ["", "colour", "Author", "author ", "com.acme.tool"] { + assert!(!is_well_known(name), "{name:?}"); + } + // Every key SolidCraft took on the design and on a component before the table still is. + assert_eq!(key_list(Design), "project, part_number, revision, author, organization, description, license"); + assert_eq!(key_list(Component), key_list(Design)); + } + + #[test] + fn the_bill_of_materials_keys_are_rows_a_component_takes_in_column_order() { + assert_eq!(BOM_KEYS, [PART_NUMBER, DESCRIPTION, REVISION], "the bill of materials' columns"); + for name in BOM_KEYS { + assert!(key(name).is_some_and(|k| k.scope.covers(Component)), "`{name}` is a row of KEYS a component takes"); + } + } + + #[test] + fn a_key_is_taken_only_where_its_scope_covers_and_a_refusal_names_the_owner() { + let covered: Vec = + [Scope::Design, Scope::Component, Scope::Both].into_iter().flat_map(|s| [s.covers(Design), s.covers(Component)]).collect(); + assert_eq!(covered, [true, false, false, true, true, true], "design, component and both, on the design and on a component"); + for owner in [Design, Component] { + for k in KEYS { + assert_eq!(Metadata::default().set(owner, k.name, json!("x")).is_ok(), k.scope.covers(owner), "`{}` on {owner:?}", k.name); + } + assert!(Metadata::default().set(owner, "com.acme.tool", json!({"id": 1})).unwrap(), "another tool's key, on {owner:?}"); + } + let refusal = |owner, key: &str| Metadata::default().set(owner, key, json!("x")).unwrap_err().to_string(); + assert_eq!( + refusal(Design, "colour"), + "`colour` is not a design property: SolidCraft's are project, part_number, revision, author, organization, \ + description, license; another tool's data goes under a reverse-DNS key such as `com.example.tool`", + "the design's wording is as it was" + ); + assert_eq!( + refusal(Component, "colour"), + "`colour` is not a part property: SolidCraft's are project, part_number, revision, author, organization, \ + description, license; another tool's data goes under a reverse-DNS key such as `com.example.tool`" + ); + for owner in [Design, Component] { + let word = owner.names().0; + assert!(refusal(owner, "").starts_with(&format!("`` is not a {word}:")), "the empty key on {owner:?}"); + assert!(refusal(owner, "Part_Number").starts_with("`Part_Number` is not"), "keys are matched exactly"); + let long = "k".repeat(MAX_KEY_BYTES * 2); + assert!(refusal(owner, &long).starts_with(&format!("`{}` is not a {word}", "k".repeat(64))), "shown cut to 64 characters"); + } + } + + #[test] + fn a_text_key_takes_up_to_its_limit_with_line_breaks_and_tabs_only() { + for owner in [Design, Component] { + let set = |value: Value| Metadata::default().set(owner, AUTHOR, value); + assert!(set(json!("x".repeat(MAX_TEXT_BYTES))).unwrap(), "exactly the limit"); + assert!(set(json!("é".repeat(MAX_TEXT_BYTES / 2))).unwrap(), "bytes, not characters: 4096"); + let over = set(json!(format!("{}é", "x".repeat(MAX_TEXT_BYTES - 1)))).unwrap_err().to_string(); + assert_eq!(over, "`author` is longer than 4096 bytes", "one character, two bytes past the limit"); + assert!(set(json!("a\nb\r\nc\td")).unwrap(), "line breaks and tabs"); + assert!(set(json!(" ")).unwrap(), "a space is text, kept as it is"); + for c in ['\u{0}', '\u{7}', '\u{1b}', '\u{7f}', '\u{85}'] { + let refused = set(json!(format!("a{c}b"))).unwrap_err().to_string(); + assert_eq!(refused, "`author` has a control character", "{:?}", c); + } + for kind in [json!(42), json!(true), json!(["x"]), json!({"text": "x"})] { + assert_eq!(set(kind.clone()).unwrap_err().to_string(), "`author` takes text", "{kind}"); + } + // Null and empty text remove the key, and removing a missing one is no change. + let mut m = Metadata::default(); + assert!(m.set(owner, AUTHOR, json!("Jane")).unwrap()); + assert!(m.set(owner, AUTHOR, json!("")).unwrap() && m.is_empty()); + assert!(!m.set(owner, AUTHOR, Value::Null).unwrap()); + } + assert_eq!( + check_text("property `finish`", &"x".repeat(MAX_TEXT_BYTES + 1)).unwrap_err().to_string(), + "property `finish` is longer than 4096 bytes" + ); + } + + /// Every hostile key with every hostile value, on the design and on a component: no panic, + /// and a refusal leaves the metadata exactly as it was. + #[test] + fn hostile_keys_and_values_are_refused_without_a_change() { + let long_key = "k".repeat(MAX_KEY_BYTES + 1); + let long_tool = format!("com.{}", "k".repeat(MAX_KEY_BYTES)); + let keys = [ + "", + " ", + ".", + "a.", + ".a", + "a..b", + "author", + "AUTHOR", + " author", + "part_number\n", + "é", + "\u{0}", + "com.acme.tool", + long_key.as_str(), + long_tool.as_str(), + ]; + let mut deep = json!({}); + for _ in 0..MAX_VALUE_DEPTH { + deep = json!({ "a": deep }); + } + let values = [ + Value::Null, + json!(""), + json!(" "), + json!(0), + json!(-1.5e308), + json!(true), + json!([]), + json!({}), + json!("a\u{0}b"), + json!("x".repeat(MAX_TEXT_BYTES)), + json!("x".repeat(MAX_TEXT_BYTES + 1)), + json!({"a": "x".repeat(MAX_VALUE_BYTES)}), + deep, + ]; + for owner in [Design, Component] { + for key in keys { + for value in &values { + let mut m: Metadata = serde_json::from_value(json!({"author": "Jane", "com.acme.tool": {"id": 7}})).unwrap(); + let before = m.clone(); + if m.set(owner, key, value.clone()).is_err() { + assert_eq!(m, before, "{owner:?} {key:?} = {value}"); + } + } + } + } + } + + /// "Fields that change no geometry" covers each scope: the design's properties, a + /// component's, and its free properties. Each alone, and its undo, is a part-property + /// change (nothing to evaluate); anything else beside it is not. + #[test] + fn only_part_properties_changed_in_each_scope() { + let mut before = crate::Document::default(); + for (id, name) in [(1, "Plate"), (2, "Pin")] { + before.components.push(crate::Component { id, name: name.into(), ..Default::default() }); + } + let mut design = before.clone(); + design.metadata.set(Design, AUTHOR, json!("Jane")).unwrap(); + let mut part = before.clone(); + part.components[1].metadata.set(Component, PART_NUMBER, json!("PN-040")).unwrap(); + let mut free = before.clone(); + free.components[0].properties.insert("finish".into(), "zinc".into()); + let mut all = design.clone(); + all.components.clone_from(&part.components); + all.components[0].properties.clone_from(&free.components[0].properties); + for (what, after) in [("design", &design), ("component", &part), ("free property", &free), ("all three", &all)] { + assert!(after.differs_only_in_part_properties(&before), "{what}"); + assert!(before.differs_only_in_part_properties(after), "{what}, undone"); + } + assert!(!before.differs_only_in_part_properties(&before.clone()), "no change is not a part-property change"); + + let mut units = design.clone(); + units.units = "in".into(); + let mut renamed = part.clone(); + renamed.components[1].name = "Dowel".into(); + let mut added = free.clone(); + added.components.push(crate::Component { id: 3, name: "Nut".into(), ..Default::default() }); + let mut removed = part.clone(); + removed.components.remove(0); + // A part property changed on components that swapped places: the components changed too. + let mut swapped = before.clone(); + swapped.components.reverse(); + swapped.components[0].metadata.set(Component, PART_NUMBER, json!("PN-040")).unwrap(); + let mut next_id = design.clone(); + next_id.next_id += 1; + for (what, after) in [ + ("units", &units), + ("a component's name", &renamed), + ("a new component", &added), + ("a removed component", &removed), + ("swapped components", &swapped), + ("next id", &next_id), + ] { + assert!(!after.differs_only_in_part_properties(&before), "{what}"); + assert!(!before.differs_only_in_part_properties(after), "{what}, undone"); + } } } diff --git a/crates/engine/src/cmd/bom.rs b/crates/engine/src/cmd/bom.rs index e23f7dc43..ff5d6cbe8 100644 --- a/crates/engine/src/cmd/bom.rs +++ b/crates/engine/src/cmd/bom.rs @@ -1,6 +1,7 @@ //! Part properties and the bill of materials. `component.metadata` and //! `component.metadata.set` read and change a component definition's part number, description, -//! revision and free properties (shared by every occurrence, saved with the component); +//! revision and free properties (shared by every occurrence, saved with the component; the keys +//! and their checks are `solidcraft_doc::metadata`'s `KEYS`, the rows a component takes); //! `assembly.bom` counts the placed components of the design, or of one component, and lists //! them as rows, optionally written to a CSV or JSON file. With `group_children`, a part with a //! part number keeps the parts placed inside it (a bolt's washers and nut) in its own row. @@ -8,7 +9,7 @@ use std::collections::{BTreeMap, HashSet}; use serde_json::{Map, Value, json}; -use solidcraft_doc::metadata::{DESCRIPTION, MAX_KEYS, MAX_TEXT_BYTES, PART_NUMBER, REVISION, WELL_KNOWN}; +use solidcraft_doc::metadata::{BOM_KEYS, MAX_KEYS, Owner, check_text, key_list}; use super::CommandSpec; use crate::params::{bad, str_}; @@ -21,9 +22,9 @@ pub static COMMANDS: &[CommandSpec] = &[ ), CommandSpec::new("component.metadata.set", "Change Part Properties", set).icon("settings").doc_only().params( "component: id or name (not the root: use document.metadata.set); part_number?, description?, revision?: text (empty or null \ - removes); values?: {key: value} (SolidCraft's keys project, part_number, revision, author, organization, description, \ - license, or a reverse-DNS key holding an object); properties?: {name: text, …} (free properties; empty or null removes). \ - All or nothing, one undo step → component, metadata, properties, changed: [keys]", + removes); values?: {key: value} (SolidCraft's keys, as document.metadata's properties lists them, or a reverse-DNS key \ + holding an object); properties?: {name: text, …} (free properties; empty or null removes). All or nothing, one undo step \ + → component, metadata, properties, changed: [keys]", ), CommandSpec::new("assembly.bom", "Bill of Materials", bom).at("SOLID", "INSPECT").icon("bom").noundo().params( "component?: id or name (default the design); levels?: flat (default: every part at any depth, counted through its \ @@ -58,15 +59,22 @@ fn component_id(s: &Session, p: &Value, cmd: &str) -> Result { fn read(s: &mut Session, p: &Value) -> Result { let cmd = "component.metadata"; let id = component_id(s, p, cmd)?; - if id == 0 { - let m = &s.doc.metadata; - return Ok(json!({"component": 0, "name": s.doc.name, "part_number": m.part_number(), "description": m.description(), - "revision": m.revision(), "metadata": m, "properties": {}})); + // The root is the design: its own properties, and no free ones. + let (name, m, properties) = if id == 0 { + (&s.doc.name, &s.doc.metadata, json!({})) + } else { + let c = s.doc.components.iter().find(|c| c.id == id).ok_or_else(|| bad(cmd, format!("no component `{id}`")))?; + (&c.name, &c.metadata, json!(c.properties)) + }; + let mut out = Map::new(); + out.insert("component".into(), json!(id)); + out.insert("name".into(), json!(name)); + for k in BOM_KEYS { + out.insert(k.to_string(), json!(m.text(k))); } - let c = s.doc.components.iter().find(|c| c.id == id).ok_or_else(|| bad(cmd, format!("no component `{id}`")))?; - let m = &c.metadata; - Ok(json!({"component": id, "name": c.name, "part_number": m.part_number(), "description": m.description(), - "revision": m.revision(), "metadata": m, "properties": c.properties})) + out.insert("metadata".into(), json!(m)); + out.insert("properties".into(), properties); + Ok(Value::Object(out)) } /// A free property as it may be saved (`None`: remove it), or why not. @@ -83,12 +91,8 @@ fn property(name: &str, value: &Value, cmd: &str) -> Result> { Value::Bool(b) => b.to_string(), _ => return Err(bad(cmd, format!("property `{shown}` takes text"))), }; - if text.len() > MAX_TEXT_BYTES { - return Err(bad(cmd, format!("property `{shown}` is longer than {MAX_TEXT_BYTES} bytes"))); - } - if text.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\t' | '\r')) { - return Err(bad(cmd, format!("property `{shown}` has a control character"))); - } + // The same text rule as SolidCraft's keys. + check_text(&format!("property `{shown}`"), &text).map_err(|e| bad(cmd, e.to_string()))?; Ok(Some(text)) } @@ -107,8 +111,8 @@ fn set(s: &mut Session, p: &Value) -> Result { Some(Value::Object(_)) => return Err(bad(cmd, format!("`values` can hold at most {MAX_KEYS} keys"))), Some(_) => return Err(bad(cmd, "`values` must be an object: {key: value, …}")), } - for k in [PART_NUMBER, DESCRIPTION, REVISION] { - if let Some(v) = p.get(k) { + for k in BOM_KEYS { + if let Some(v) = p.get(*k) { entries.push((k.to_string(), v.clone())); } } @@ -119,11 +123,11 @@ fn set(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(cmd, "`properties` must be an object: {name: text, …}")), }; if entries.is_empty() && props.is_empty() { - return Err(bad(cmd, format!("give part_number, description, revision, values or properties ({})", WELL_KNOWN.join(", ")))); + return Err(bad(cmd, format!("give {}, values or properties ({})", BOM_KEYS.join(", "), key_list(Owner::Component)))); } let mut changed: Vec = Vec::new(); for (k, v) in entries { - if metadata.set(&k, v).map_err(|e| bad(cmd, e.to_string()))? && !changed.contains(&k) { + if metadata.set(Owner::Component, &k, v).map_err(|e| bad(cmd, e.to_string()))? && !changed.contains(&k) { changed.push(k); } } diff --git a/crates/engine/src/cmd/bom_tests.rs b/crates/engine/src/cmd/bom_tests.rs index 47df03c58..93e25e9a1 100644 --- a/crates/engine/src/cmd/bom_tests.rs +++ b/crates/engine/src/cmd/bom_tests.rs @@ -258,6 +258,73 @@ fn hostile_part_properties_are_refused_without_a_change() { assert_eq!(run(&mut s, "component.metadata", json!({"component": 0}))["part_number"], "ASM-1"); } +#[test] +fn a_components_refusals_speak_of_part_properties() { + let mut s = assembly(); + let undo = s.undo.len(); + let refusal = |s: &mut Session, p: Value| s.execute("component.metadata.set", &p).unwrap_err().to_string(); + let bogus = refusal(&mut s, json!({"component": "Pin", "values": {"bogus": "x"}})); + assert!( + bogus.ends_with( + "`bogus` is not a part property: SolidCraft's are project, part_number, revision, author, organization, description, \ + license; another tool's data goes under a reverse-DNS key such as `com.example.tool`" + ), + "{bogus}" + ); + assert!(!bogus.contains("design property"), "{bogus}"); + assert!(refusal(&mut s, json!({"component": "Pin", "values": {"": "x"}})).contains("`` is not a part property")); + // Nothing to change: the same list as before the table. + assert!(refusal(&mut s, json!({"component": "Pin"})).ends_with( + "give part_number, description, revision, values or properties (project, part_number, revision, author, organization, \ + description, license)" + )); + // Only the bill of materials' keys are parameters of their own; the others go in `values`. + assert!(refusal(&mut s, json!({"component": "Pin", "author": "Jane"})).contains("give part_number, description, revision")); + let long = refusal(&mut s, json!({"component": "Pin", "properties": {"finish": "x".repeat(5000)}})); + assert!(long.ends_with("property `finish` is longer than 4096 bytes"), "{long}"); + let bell = refusal(&mut s, json!({"component": "Pin", "properties": {"finish": "a\u{7}"}})); + assert!(bell.ends_with("property `finish` has a control character"), "{bell}"); + assert_eq!(s.undo.len(), undo, "nothing changed"); + // The design keeps its own words. + let design = s.execute("document.metadata.set", &json!({"key": "bogus", "value": "x"})).unwrap_err().to_string(); + assert!(design.contains("`bogus` is not a design property"), "{design}"); +} + +#[test] +fn every_key_a_component_took_before_is_still_taken() { + let mut s = assembly(); + let keys = ["project", "part_number", "revision", "author", "organization", "description", "license"]; + let mut values: serde_json::Map = keys.iter().map(|k| (k.to_string(), json!(format!("{k} text")))).collect(); + values.insert("com.acme.shop".into(), json!({"id": 7})); + let r = run(&mut s, "component.metadata.set", json!({"component": "Plate", "values": values})); + assert_eq!(r["changed"].as_array().map(Vec::len), Some(keys.len() + 1), "{r}"); + let plate = run(&mut s, "component.metadata", json!({"component": "Plate"})); + for k in keys { + assert_eq!(plate["metadata"][k], format!("{k} text"), "{k}"); + } + for k in ["part_number", "description", "revision"] { + assert_eq!(plate[k], format!("{k} text"), "the bill of materials' field {k}: {plate}"); + } + assert!(plate.get("author").is_none(), "the others stay in metadata: {plate}"); + // The shortcuts and the root read the same fields. + run(&mut s, "component.metadata.set", json!({"component": "Pin", "part_number": "", "description": "Pin", "revision": "D"})); + let pin = run(&mut s, "component.metadata", json!({"component": "Pin"})); + assert_eq!((&pin["part_number"], &pin["description"], &pin["revision"]), (&Value::Null, &json!("Pin"), &json!("D")), "{pin}"); + let root = run(&mut s, "component.metadata", json!({"component": 0})); + assert_eq!((&root["component"], &root["part_number"], &root["properties"]), (&json!(0), &Value::Null, &json!({})), "{root}"); +} + +#[test] +fn a_component_refused_past_its_limits_says_part_properties() { + let mut s = assembly(); + // The pin holds a part number and a description: room for this many more keys. + let room = solidcraft_doc::metadata::MAX_KEYS - 2; + let values: serde_json::Map = (0..room).map(|i| (format!("org.k{i}"), json!({}))).collect(); + run(&mut s, "component.metadata.set", json!({"component": "Pin", "values": values})); + let over = s.execute("component.metadata.set", &json!({"component": "Pin", "values": {"org.one_more": {}}})).unwrap_err().to_string(); + assert!(over.ends_with("part properties are limited to 256 keys and 256 KiB"), "{over}"); +} + /// Two hex bolts, each with a washer and a nut placed inside it, and a third bolt alone. fn bolts() -> Session { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/metadata.rs b/crates/engine/src/cmd/metadata.rs index de1b7809e..d510d051d 100644 --- a/crates/engine/src/cmd/metadata.rs +++ b/crates/engine/src/cmd/metadata.rs @@ -1,11 +1,12 @@ //! Design properties (#1015): `document.metadata` reads the design's `metadata` object, and //! `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. +//! keys SolidCraft reads, and the checks a change gets, are `solidcraft_doc::metadata`'s +//! (`KEYS`, the rows the design takes); keys other tools wrote are kept as they are. The UI's Design +//! Properties dialog, scripts and MCP agents all go through these commands. A change evaluates +//! nothing: properties are no geometry. use serde_json::{Map, Value, json}; -use solidcraft_doc::metadata::{MAX_KEYS, WELL_KNOWN}; +use solidcraft_doc::metadata::{self, MAX_KEYS, Owner}; use super::CommandSpec; use crate::params::{bad, str_}; @@ -13,13 +14,13 @@ use crate::{Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("document.metadata", "Design Properties", read).icon("settings").noundo().doc_only().params( - "→ metadata: the design's metadata object as saved (other tools' keys too); properties: project, part_number, revision, \ - author, organization, description and license, each its text or null (absent, or not text)", + "→ metadata: the design's metadata object as saved (other tools' keys too); properties: each of SolidCraft's design \ + properties (project, part number, revision…), its text or null (absent, or not text)", ), CommandSpec::new("document.metadata.set", "Change Design Properties", set).icon("settings").doc_only().params( - "key and value, or values: {key: value, …} (all or nothing, one undo step). SolidCraft's keys: project, part_number, \ - revision, author, organization, description, license (text; \"\" or null removes); another tool's data goes under its \ - reverse-DNS key such as com.example.tool (an object; null removes) → metadata, changed: [keys]", + "key and value, or values: {key: value, …} (all or nothing, one undo step). SolidCraft's keys, the ones document.metadata's \ + properties lists, take text (\"\" or null removes); another tool's data goes under its reverse-DNS key such as \ + com.example.tool (an object; null removes) → metadata, changed: [keys]", ), CommandSpec::new("document.metadata.remove", "Remove Design Property", remove) .icon("delete") @@ -29,7 +30,7 @@ pub static COMMANDS: &[CommandSpec] = &[ fn read(s: &mut Session, _: &Value) -> Result { let m = &s.doc.metadata; - let properties: Map = WELL_KNOWN.iter().map(|k| (k.to_string(), m.text(k).map_or(Value::Null, |t| json!(t)))).collect(); + let properties: Map = metadata::keys(Owner::Design).map(|k| (k.name.to_string(), json!(m.text(k.name)))).collect(); Ok(json!({"metadata": m, "properties": properties})) } @@ -48,7 +49,7 @@ fn set(s: &mut Session, p: &Value) -> Result { let mut next = s.doc.metadata.clone(); let mut changed = Vec::new(); for (key, value) in entries { - if next.set(key, value.clone()).map_err(|e| bad(cmd, e.to_string()))? { + if next.set(Owner::Design, key, value.clone()).map_err(|e| bad(cmd, e.to_string()))? { changed.push(key.to_string()); } } @@ -252,6 +253,80 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn changing_design_properties_does_not_evaluate_the_model_again() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + s.evaluations = 0; + let revision = s.revision; + run(&mut s, "document.metadata.set", json!({"values": {"author": "Jane", "com.acme.tool": {"id": 7}}})); + run(&mut s, "document.metadata.remove", json!({"key": "com.acme.tool"})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.evaluations, 0, "design properties change no geometry"); + assert!(s.revision > revision, "the views still see each change"); + assert_eq!(s.model.state().bodies.len(), 1, "the model is kept as it was"); + assert_eq!(s.doc.metadata.author(), Some("Jane")); + // Anything else still evaluates. + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5})); + assert!(s.evaluations > 0); + } + + #[test] + fn opening_a_design_that_differs_only_in_its_properties_refreshes_it() { + // Two revisions of one assembly, B held on A by a rigid joint. The open session's B was + // moved off the joint and never solved since; the file is the same design with another + // author. Opening it is no property edit: the new session's joints are solved. + let dir = scratch("revision"); + let mut s = Session::default(); + for (name, x) in [("A", 0), ("B", 20)] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})); + } + let placement = + |s: &Session, name: &str| s.doc.find_component(name).and_then(|c| s.doc.occurrence_of(c)).map(|o| (o.id, o.transform)).unwrap(); + let a = placement(&s, "A").0; + run(&mut s, "occurrence.ground", json!({"occurrence": a, "grounded": true})); + run(&mut s, "joint.create", json!({"type": "rigid", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}})); + let (b, solved) = placement(&s, "B"); + let mut unsolved = (*s.doc).clone(); + unsolved.name = "Bracket".into(); + if let Some(o) = unsolved.occurrences.iter_mut().find(|o| o.id == b) { + o.transform[3][0] += 3.0; + } + let mut s = Session::new(unsolved.clone()); + let mut revision_c = unsolved; + revision_c.metadata.set(Owner::Design, "author", json!("Jane")).unwrap(); + let path = dir.join("bracket-rev-c.json"); + std::fs::write(&path, revision_c.to_json()).unwrap(); + let (read, _) = solidcraft_io::read_design_file(path.to_str().unwrap(), None::).unwrap(); + assert!(read.differs_only_in_part_properties(&s.doc), "the two revisions differ only in their properties"); + + run(&mut s, "doc.open", json!({"path": path})); + assert_eq!(s.doc.metadata.author(), Some("Jane")); + let opened = s.doc.occurrences.iter().find(|o| o.id == b).map(|o| o.transform).unwrap(); + let off = opened.iter().flatten().zip(solved.iter().flatten()).map(|(p, q)| (p - q).abs()).fold(0.0, f64::max); + assert!(off < 1e-6, "the opened design's joint is solved: B is {off} mm off it"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn every_key_the_design_took_before_is_still_taken() { + let mut s = Session::default(); + let keys = ["project", "part_number", "revision", "author", "organization", "description", "license"]; + let values: Map = keys.iter().map(|k| (k.to_string(), json!(format!("{k} text")))).collect(); + let r = run(&mut s, "document.metadata.set", json!({ "values": values })); + assert_eq!(r["changed"].as_array().map(Vec::len), Some(keys.len()), "{r}"); + let properties = run(&mut s, "document.metadata", json!({}))["properties"].clone(); + for k in keys { + assert_eq!(properties[k], format!("{k} text"), "{k}"); + } + assert_eq!(properties.as_object().map(Map::len), Some(keys.len()), "{properties}"); + let refused = s.execute("document.metadata.set", &json!({"key": "colour", "value": "red"})).unwrap_err().to_string(); + assert!(refused.contains("`colour` is not a design property: SolidCraft's are project, part_number,"), "{refused}"); + } + #[test] fn inspect_lists_the_metadata() { let mut s = Session::default(); diff --git a/crates/engine/src/cmd/parts.rs b/crates/engine/src/cmd/parts.rs index 046dc0ead..32c6f1afe 100644 --- a/crates/engine/src/cmd/parts.rs +++ b/crates/engine/src/cmd/parts.rs @@ -387,12 +387,12 @@ fn identity(family: &str, size: &str, sh: &Shape) -> (String, String) { /// Give a standard part its part number and description; a field someone changed since the last /// size (`was`) is theirs and stays. fn set_identity(s: &mut Session, comp: u64, now: (String, String), was: Option<(String, String)>) { - use solidcraft_doc::metadata::{DESCRIPTION, PART_NUMBER}; + use solidcraft_doc::metadata::{DESCRIPTION, Owner, PART_NUMBER}; let Some(c) = s.doc.components.iter().find(|c| c.id == comp) else { return }; let mut m = c.metadata.clone(); for (k, new, old) in [(PART_NUMBER, now.0, was.as_ref().map(|w| w.0.as_str())), (DESCRIPTION, now.1, was.as_ref().map(|w| w.1.as_str()))] { if m.text(k).is_none_or(|cur| Some(cur) == old) { - let _ = m.set(k, Value::String(new)); + let _ = m.set(Owner::Component, k, Value::String(new)); } } if m != c.metadata diff --git a/crates/engine/src/cmd/script.rs b/crates/engine/src/cmd/script.rs index d5ff1f00a..d0851b053 100644 --- a/crates/engine/src/cmd/script.rs +++ b/crates/engine/src/cmd/script.rs @@ -163,7 +163,7 @@ pub(crate) fn script_steps(doc: &Document) -> Result<(Vec, Vec)> let mut properties = solidcraft_doc::Metadata::default(); let mut odd = Vec::new(); for (key, value) in &doc.metadata.0 { - if properties.set(key, value.clone()).is_err() { + if properties.set(solidcraft_doc::metadata::Owner::Design, key, value.clone()).is_err() { odd.push(key.as_str()); } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 246304821..7ae0f0c62 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -404,6 +404,10 @@ pub struct Session { /// commands are undone however long the undo history is. pub(crate) checkpoints: Vec, next_checkpoint: u64, + /// How many times [`Session::replace_design`] gave this session another design. A command + /// that did is no edit of the design before it, so [`Session::execute`] never takes it for a + /// change of render intent or part properties alone. + replacements: u64, /// Record this session's top-level commands in the crash journal (the app's own design; /// never previews or other scratch sessions). See [`crash`]. pub crash_journal: bool, @@ -556,6 +560,7 @@ impl Session { continuity: Vec::new(), checkpoints: Vec::new(), next_checkpoint: 1, + replacements: 0, saved_visibility: visibility.clone(), visibility, camera: None, @@ -584,6 +589,7 @@ impl Session { // The design on screen stays journaled for crash reports at once, not from the app's // next frame, so commands sent right after `doc.open` or `file.new` are kept. let crash_journal = self.crash_journal; + let replacements = self.replacements.wrapping_add(1); *self = fresh; self.crash_journal = crash_journal; self.auto_project = auto_project; @@ -592,6 +598,7 @@ impl Session { self.render_jobs = render_jobs; self.checkpoints = checkpoints; self.next_checkpoint = next_checkpoint; + self.replacements = replacements; } /// The design has changes not in its file: in the document, or in what is hidden. @@ -1074,6 +1081,7 @@ impl Session { }; // Where new geometry goes: not in the design, but a replay needs it (component.activate). let active_before = (self.active_component, self.active_occurrence_path.clone()); + let replacements = self.replacements; let null = Value::Object(Default::default()); let params = if params.is_null() { &null } else { params }; let given = params; @@ -1128,7 +1136,10 @@ impl Session { Ok((v, live_edit)) => { let v = if changed { self.with_created(spec.id, params, &before, v) } else { v }; if changed || hidden { - let render_only = self.render_only_change(&before); + // Another design opened, started or recovered is refreshed in full, however + // little it differs from the one before: the shortcut proves a session's own + // edit kept its model and joints valid, and a new session has had none. + let render_only = self.replacements == replacements && self.render_only_change(&before); let display_only = !changed && hidden; let previous_doc = before.doc.clone(); if spec.undoable { @@ -1288,6 +1299,7 @@ impl Session { continuity: Vec::new(), checkpoints: Vec::new(), next_checkpoint: 1, + replacements: 0, visibility: self.visibility.clone(), camera: self.camera, render_viewport: self.render_viewport.clone(), diff --git a/crates/ui-egui/src/bom_panel.rs b/crates/ui-egui/src/bom_panel.rs index a7cab4b1f..1d9242f5f 100644 --- a/crates/ui-egui/src/bom_panel.rs +++ b/crates/ui-egui/src/bom_panel.rs @@ -1,11 +1,12 @@ //! The Bill of Materials window: `assembly.bom`'s rows (flat or top level, grouped by part //! number or by definition, a part's sub-parts in its row or not), with Export CSV… and Export //! JSON…. Picking a row edits its part -//! number, description and revision through one `component.metadata.set` per definition. The -//! toolbar's Bill of Materials (`ui.start` of `assembly.bom`) opens it. +//! number, description and revision (`metadata::BOM_KEYS`) through one `component.metadata.set` +//! per definition. The toolbar's Bill of Materials (`ui.start` of `assembly.bom`) opens it. use egui::RichText; -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; +use solidcraft_engine::doc::metadata::{self, BOM_KEYS}; use crate::SolveApp; use crate::theme::Tokens; @@ -21,9 +22,9 @@ pub struct BomPanel { pub group_children: bool, /// The rows for (design revision, top, by_definition, group_children). cache: Option<(u64, [bool; 3], Value)>, - /// The picked row's index, and its fields as edited. + /// The picked row's index, and its fields as edited (one for each of [`BOM_KEYS`]). pub picked: Option, - pub fields: [String; 3], + pub fields: Vec, /// The last refusal. pub error: Option, } @@ -68,11 +69,17 @@ fn text(row: &Value, k: &str) -> String { } } +/// The label of one of [`BOM_KEYS`]. +fn field_label(key: &str) -> &str { + metadata::key(key).map_or(key, |k| crate::i18n::tr(k.label)) +} + /// Apply the picked row's fields to each of its definitions (one undo step each). fn apply(app: &mut SolveApp, d: &mut BomPanel, row: &Value) { - let [pn, desc, rev] = d.fields.clone(); + let mut params: Map = BOM_KEYS.iter().zip(&d.fields).map(|(k, v)| (k.to_string(), json!(v))).collect(); for c in row["components"].as_array().into_iter().flatten() { - let r = app.run("component.metadata.set", json!({"component": c, "part_number": pn, "description": desc, "revision": rev})); + params.insert("component".into(), c.clone()); + let r = app.run("component.metadata.set", Value::Object(params.clone())); if let Err(e) = r { d.error = Some(e); return; @@ -124,7 +131,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let picked = d.picked == Some(i); if crate::ui_kit::list_picker(ui, &i.to_string(), &text(row, "item"), picked).clicked() { d.picked = if picked { None } else { Some(i) }; - d.fields = [text(row, "part_number"), text(row, "description"), text(row, "revision")]; + d.fields = BOM_KEYS.iter().map(|k| text(row, k)).collect(); } ui.label(text(row, "part_number")); ui.label(text(row, "description")); @@ -148,10 +155,11 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { if let Some(row) = d.picked.and_then(|i| rows.get(i)) { ui.separator(); egui::Grid::new("sc_bom_edit").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { - for (label, field) in ["Part number", "Description", "Revision"].into_iter().zip(d.fields.iter_mut()) { + for (key, field) in BOM_KEYS.iter().zip(d.fields.iter_mut()) { + let label = field_label(key); ui.label(label); ui.allocate_ui(egui::vec2(280.0, crate::ui_kit::row_height()), |ui| { - crate::ui_kit::cell_editor(ui, ui.make_persistent_id(label), field, label, false); + crate::ui_kit::cell_editor(ui, ui.make_persistent_id(key), field, label, false); }); ui.end_row(); } @@ -217,6 +225,32 @@ mod tests { assert!(h.widget("PL-100").is_some(), "the list follows the change"); } + #[test] + fn a_picked_row_edits_each_bill_of_materials_key_under_its_label() { + let mut h = Harness::new(); + h.app.run("component.create", json!({"name": "Plate"})).unwrap(); + h.app.run("solid.box", json!({"length": 40, "width": 20, "height": 3})).unwrap(); + h.app.run("component.activate", json!({"component": 0})).unwrap(); + // Two placed, so the Qty cell ("2") isn't mistaken for the row's item number ("1"). + h.app.run("occurrence.copy", json!({"component": "Plate", "translate": [50, 0, 0]})).unwrap(); + h.app.run("component.metadata.set", json!({"component": "Plate", "part_number": "PL-100", "revision": "A"})).unwrap(); + h.step(&json!({"start": "assembly.bom"})).unwrap(); + h.frames(2); + // The grid's own column says "Rev"; "Revision" is the edit field's label, from the table. + assert!(h.widget("Revision").is_none()); + h.step(&json!({"widget": "1"})).unwrap(); + h.frames(2); + assert!(h.widget("Revision").is_some()); + let d = h.app.bom.as_mut().unwrap(); + assert_eq!(d.fields, ["PL-100", "", "A"], "the row's fields, in the bill of materials' order"); + d.fields[1] = "Plate, 3 mm".into(); + d.fields[2] = "B".into(); + h.frames(2); + h.step(&json!({"widget": "Apply"})).unwrap(); + let m = h.app.session.execute("component.metadata", &json!({"component": "Plate"})).unwrap(); + assert_eq!((&m["part_number"], &m["description"], &m["revision"]), (&json!("PL-100"), &json!("Plate, 3 mm"), &json!("B")), "{m}"); + } + #[test] fn sub_parts_show_under_their_part() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/design_properties.rs b/crates/ui-egui/src/design_properties.rs index 3fa2d8b19..f845fb346 100644 --- a/crates/ui-egui/src/design_properties.rs +++ b/crates/ui-egui/src/design_properties.rs @@ -8,7 +8,7 @@ //! `ui_kit::Window` cards. use serde_json::{Map, Value}; -use solidcraft_engine::doc::metadata::{DESCRIPTION, WELL_KNOWN}; +use solidcraft_engine::doc::metadata::{DESCRIPTION, Owner, keys}; use crate::SolveApp; use crate::ui_kit; @@ -20,10 +20,11 @@ const OTHERS_ROWS: f32 = 6.0; /// What is being typed; the properties themselves live in the document. pub struct DesignProperties { - /// Each well-known key's text when the window opened, in [`WELL_KNOWN`] order. - pub opened: [String; WELL_KNOWN.len()], + /// Each of SolidCraft's design properties' text when the window opened, in + /// `keys(Owner::Design)` order. + pub opened: Vec, /// The fields as edited. - pub fields: [String; WELL_KNOWN.len()], + pub fields: Vec, /// The last refusal from `document.metadata.set`. pub error: Option, } @@ -31,18 +32,17 @@ pub struct DesignProperties { impl DesignProperties { pub fn new(app: &SolveApp) -> Self { let m = &app.session.doc.metadata; - let opened = WELL_KNOWN.map(|k| m.text(k).unwrap_or_default().to_string()); + let opened: Vec = keys(Owner::Design).map(|k| m.text(k.name).unwrap_or_default().to_string()).collect(); DesignProperties { fields: opened.clone(), opened, error: None } } /// The fields that differ from what the window opened with, as `document.metadata.set` /// takes them (empty text removes the key). pub fn changes(&self) -> Map { - WELL_KNOWN - .iter() + keys(Owner::Design) .zip(self.opened.iter().zip(&self.fields)) .filter(|(_, (was, now))| was != now) - .map(|(k, (_, now))| (k.to_string(), Value::String(now.clone()))) + .map(|(k, (_, now))| (k.name.to_string(), Value::String(now.clone()))) .collect() } } @@ -67,18 +67,6 @@ fn apply(app: &mut SolveApp, d: &mut DesignProperties) -> bool { } } -fn label(key: &str) -> &'static str { - match key { - "project" => crate::i18n::tr("ui.design_properties.project"), - "part_number" => crate::i18n::tr("ui.design_properties.part_number"), - "revision" => crate::i18n::tr("ui.design_properties.revision"), - "author" => crate::i18n::tr("ui.design_properties.author"), - "organization" => crate::i18n::tr("ui.design_properties.organization"), - "description" => crate::i18n::tr("ui.design_properties.description"), - _ => crate::i18n::tr("ui.design_properties.license"), - } -} - /// A short one-line view of a value another tool keeps. fn preview(v: &Value) -> String { let text = serde_json::to_string(v).unwrap_or_default(); @@ -91,10 +79,10 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let metadata = app.session.doc.metadata.clone(); let title = crate::i18n::tr_label("Design Properties"); let (closed, action) = ui_kit::Window::new(egui::Id::new("sc_design_properties"), "settings", title).fields().show(ctx, true, |ui| { - for (i, key) in WELL_KNOWN.iter().enumerate() { - let label = label(key); + for (i, k) in keys(Owner::Design).enumerate() { + let (key, label) = (k.name, crate::i18n::tr(k.label)); let Some(field) = d.fields.get_mut(i) else { continue }; - if *key == DESCRIPTION { + if key == DESCRIPTION { ui_kit::multiline_text_field(ui, label, egui::Id::new(("sc_design_properties", key)), field); } else { ui_kit::row(ui, label, |ui| ui_kit::text_field(ui, field, "")); @@ -254,6 +242,28 @@ mod tests { assert_eq!(h.app.session.undo.len(), undo + 1); } + #[test] + fn each_field_is_labelled_from_the_table_of_keys() { + use solidcraft_engine::doc::metadata::{KEYS, Owner, keys}; + let english = crate::i18n::Locale::for_language("en"); + for k in KEYS { + assert_ne!(english.text(k.label), k.label, "`{}`'s label is in the English catalog", k.name); + } + let mut h = Harness::new(); + // A key a newer SolidCraft might read: kept as another tool's data, never labelled as one of ours. + h.app.session.doc_mut().metadata.0.insert("future_key".into(), json!("kept")); + h.step(&json!({"start": "document.metadata"})).unwrap(); + h.frames(2); + let labels: Vec<&str> = keys(Owner::Design).map(|k| english.text(k.label)).collect(); + assert_eq!(labels, ["Project", "Part number", "Revision", "Author", "Organization", "Description", "License"]); + for label in &labels { + assert!(h.widget(label).is_some(), "{label}"); + } + let d = h.app.design_properties.as_ref().unwrap(); + assert_eq!((d.opened.len(), d.fields.len()), (labels.len(), labels.len()), "a field for each key, none for others"); + assert!(h.widget("Other tools' data (1)").is_some(), "the unknown key is listed with other tools' data"); + } + #[test] fn the_file_menu_browser_and_root_component_open_the_window() { let mut h = Harness::new();