Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 43 additions & 10 deletions crates/doc/src/drawing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
//!
//! - 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.
//! - **Sources** are the designs it draws, by id: the design it is in (at most one source, with no
//! path) and other design files, each by its path ([`Source::path`]), at most [`MAX_SOURCES`] in
//! all. What a design was when the drawing last saw it is not saved here.
//! - **Sheets**: the paper, a copy of its drawing border and of its title block with the text typed
//! over its cells' values, 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 and the
Expand Down Expand Up @@ -37,9 +37,9 @@
//! damaged and refused, never patched.
//! - 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, and lists of records in a fixed order (sheets as arranged; later
//! records by id), never the order they were added in. Records listed by id read in that order
//! whatever order a file lists them in: the order means nothing, so it is never damage.
//! order, maps sorted, and lists of records in a fixed order (sheets as arranged; sources and
//! later records by id), never the order they were added in. Records listed by id read in that
//! order whatever order a file lists them in: the order means nothing, so it is never damage.
//! - A later change to the record is one file in `src/drawing/format/pending/` (its README).
//!
//! [`Drawing::from_json`] reads a drawing in this order: at most [`MAX_DRAWING_BYTES`] of text,
Expand Down Expand Up @@ -88,6 +88,8 @@ use view::{View, ViewLetters};

/// The most drawings a design may hold.
pub const MAX_DRAWINGS: usize = 1000;
/// The most designs a drawing may draw.
pub const MAX_SOURCES: usize = 64;
/// The most sheets a drawing may have.
pub const MAX_SHEETS: usize = 1000;
/// The longest name of a drawing or a sheet, in bytes.
Expand Down Expand Up @@ -130,7 +132,7 @@ pub struct Drawing {
#[serde(with = "crate::ids")]
pub id: u64,
pub name: String,
/// The designs the drawing draws: for now at most one, the design it is in.
/// The designs the drawing draws, by id ([`Source`]).
pub sources: Vec<Source>,
/// The drawing's properties and other tools' data, kept as they are, behind an `Arc` as the
/// sheets are, so an undo step shares them while they don't change.
Expand Down Expand Up @@ -268,13 +270,26 @@ impl NewerDrawing {
}
}

/// 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.
/// A design the drawing draws: the design the drawing is in (no `path`), or another design file.
/// Views, sheets and tables name it by its id.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Source {
#[serde(with = "crate::ids")]
pub id: u64,
/// The design file: whole in memory; in a file relative to the folder of the design the
/// drawing is in, with `/` (whole when the two share no root), as a component link keeps its
/// file. `None`: the design the drawing is in.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
}

/// A source's path: not empty, not only spaces, without control characters. Its length is
/// bounded by the drawing's only, as a component link's is: a design deep in folders makes it long.
pub fn check_source_path(path: &str) -> Result<()> {
require(!path.trim().is_empty() && !path.chars().any(char::is_control), || {
"a source's path is not empty, not only spaces, without control characters".into()
})
}

/// The length unit a drawing gives its measurements in.
Expand Down Expand Up @@ -493,6 +508,7 @@ impl Drawing {
DRAWING.check_numbers(&v, "properties")?;
DRAWING.upgrade(&mut v, version, applied)?;
let mut d: Drawing = serde_json::from_value(v).map_err(damaged)?;
d.sources.sort_by_key(|s| s.id);
let (views, dimensions) = (std::mem::take(&mut d.views), std::mem::take(&mut d.dimensions));
d.add_views(views);
d.add_dimensions(dimensions);
Expand Down Expand Up @@ -671,7 +687,7 @@ impl Drawing {
/// 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() <= 1, || "a drawing draws only the design it is in".into())?;
self.check_sources()?;
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`)")
Expand Down Expand Up @@ -705,6 +721,23 @@ impl Drawing {
self.check_symbols()
}

/// The sources' rules: at most [`MAX_SOURCES`], by id, the design the drawing is in at most once,
/// and each path keeping [`check_source_path`]. Whether two paths name one file is not judged
/// here: only the file system can say (`a/../p.sc` and `p.sc`), so the engine refuses one file
/// twice when a source is added, and a record holding it still opens and can be edited.
fn check_sources(&self) -> Result<()> {
require(self.sources.len() <= MAX_SOURCES, || format!("a drawing draws at most {MAX_SOURCES} designs"))?;
require(self.sources.is_sorted_by_key(|s| s.id), || "a drawing lists its sources by id".into())?;
let own = self.sources.iter().filter(|s| s.path.is_none()).count();
require(own <= 1, || "a drawing draws the design it is in at most once".into())?;
self.sources.iter().filter_map(|s| s.path.as_deref()).try_for_each(check_source_path)
}

/// The source that is the design the drawing is in, if it draws it.
pub fn own_source(&self) -> Option<u64> {
self.sources.iter().find(|s| s.path.is_none()).map(|s| s.id)
}

/// A sheet's own rules, and that the source it documents is one of the drawing's.
fn check_sheet(&self, sheet: &Sheet) -> Result<()> {
check_name(&sheet.name, "its")?;
Expand Down
2 changes: 1 addition & 1 deletion crates/doc/src/drawing/balloon_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn ballooned() -> (Drawing, [u64; 2]) {
let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape);
let mut d = Drawing::new("Bolted", "en", "Sheet 1", a3, None, &BTreeSet::new(), &mut id_source).unwrap();
let source = d.allocate_id(&mut id_source).unwrap();
d.sources.push(Source { id: source });
d.sources.push(Source { id: source, path: None });
let (view, sheet) = (d.allocate_id(&mut id_source).unwrap(), d.sheets[0].id);
let kind = ViewKind::Base { source, view: ViewDirection::Named(NamedView::Front) };
d.add_views([Arc::new(View {
Expand Down
2 changes: 1 addition & 1 deletion crates/doc/src/drawing/dimension_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ fn measured() -> (Drawing, [u64; 3]) {
let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape);
let mut d = Drawing::new("Box", "en", "Sheet 1", a3, None, &BTreeSet::new(), &mut id_source).unwrap();
let source = d.allocate_id(&mut id_source).unwrap();
d.sources.push(Source { id: source });
d.sources.push(Source { id: source, path: None });
let (view, sheet) = (d.allocate_id(&mut id_source).unwrap(), d.sheets[0].id);
let kind = ViewKind::Base { source, view: ViewDirection::Named(NamedView::Front) };
let settings = ViewOverrides { scale: Some("1:2".parse().unwrap()), ..ViewOverrides::default() };
Expand Down
2 changes: 1 addition & 1 deletion crates/doc/src/drawing/fields_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ fn a_sheets_scale_is_the_one_its_base_views_share() {
assert_eq!(scale(&d), ["", "", ""]);
let mut ids = IdSource::seeded(13059);
let source = d.allocate_id(&mut ids).unwrap();
d.sources.push(DrawingSource { id: source });
d.sources.push(DrawingSource { id: source, path: None });
let [side, front, other, top] = [(); 4].map(|()| d.allocate_id(&mut ids).unwrap());
let (first, second) = (d.sheets[0].id, d.sheets[1].id);
let view = |id, sheet, kind, scale: &str| {
Expand Down
10 changes: 10 additions & 0 deletions crates/doc/src/drawing/format/pending/source-paths.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//! A drawing's source can name another design file (#3890): `sources: [{id, path}]`, `path` relative
//! to the folder of the design the drawing is in, with `/` (whole when the two share no root). A
//! source without `path` is the design the drawing is in, at most one of them; at most 64 sources,
//! listed by id. This replaces `in-design.rs`'s "at most one source, which has no `path`". No step:
//! an older drawing's sources have no path and read as they are. The last release doesn't know
//! drawings: it opens the design with a warning about its newer format and keeps the drawings, paths
//! and all, as it keeps any part it can't read (read in its code, not tried). A build with drawings
//! from before this change opens a drawing with such a source, keeps it and writes it back, unless
//! its views, sheets or tables name it: then it refuses the design as saved by a newer SolidCraft,
//! rather than drop the drawing.
2 changes: 1 addition & 1 deletion crates/doc/src/drawing/note_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fn noted() -> (Drawing, [u64; 3]) {
let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape);
let mut d = Drawing::new("Noted", "en", "Sheet 1", a3, None, &BTreeSet::new(), &mut id_source).unwrap();
let source = d.allocate_id(&mut id_source).unwrap();
d.sources.push(DrawingSource { id: source });
d.sources.push(DrawingSource { id: source, path: None });
let (view, sheet) = (d.allocate_id(&mut id_source).unwrap(), d.sheets[0].id);
let kind = ViewKind::Base { source, view: ViewDirection::Named(NamedView::Front) };
d.add_views([Arc::new(View {
Expand Down
2 changes: 1 addition & 1 deletion crates/doc/src/drawing/table_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ fn tabled() -> (Drawing, u64) {
let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape);
let mut d = Drawing::new("Bolted", "en", "Sheet 1", a3, None, &BTreeSet::new(), &mut id_source).unwrap();
let source = d.allocate_id(&mut id_source).unwrap();
d.sources.push(DrawingSource { id: source });
d.sources.push(DrawingSource { id: source, path: None });
let sheet = d.sheets[0].id;
let list = Kind::PartsList(PartsList {
of: SheetComponent { source, component: 0 },
Expand Down
2 changes: 1 addition & 1 deletion crates/doc/src/drawing/view_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ fn front() -> (Drawing, IdSource, u64) {
let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape);
let mut d = Drawing::new("Plate", "en", "Sheet 1", a3, None, &BTreeSet::new(), &mut id_source).unwrap();
let source = d.allocate_id(&mut id_source).unwrap();
d.sources.push(Source { id: source });
d.sources.push(Source { id: source, path: None });
let front = ViewKind::Base { source, view: ViewDirection::Named(NamedView::Front) };
let id = add(&mut d, &mut id_source, front, ViewPlace::At([150.0, 150.0]), scaled("1:2"));
(d, id_source, id)
Expand Down
66 changes: 57 additions & 9 deletions crates/doc/src/drawing_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub(crate) fn plate() -> Drawing {
let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape);
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 });
d.sources.push(Source { id, path: None });
let plate_id = d.sources[0].id;
let id = d.allocate_id(&mut id_source).unwrap();
d.sheets.push(Arc::new(Sheet {
Expand Down Expand Up @@ -221,15 +221,31 @@ 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 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);
// Sources from id 1: the drawing's and the sheet's ids are the seed's, far from them. Each names
// another design's file by its path, but at most one: the design the drawing is in, by an id alone.
let linked = |n: u64| Value::Array((1..=n).map(|id| json!({"id": ids::encode(id), "path": format!("parts/{id}.sc")})).collect());
for n in [0, 1, 64] {
assert_eq!(read(&with("sources", linked(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}");
assert_eq!(refusal(&with("sources", linked(65))), "damaged drawing: a drawing draws at most 64 designs");
let own = |id: u64| json!({"id": ids::encode(id)});
let both = json!([own(1), {"id": ids::encode(2), "path": "plate.sc"}]);
assert_eq!(read(&with("sources", both)).unwrap().own_source(), Some(1));
assert_eq!(refusal(&with("sources", json!([own(1), own(2)]))), "damaged drawing: a drawing draws the design it is in at most once");
for broken in ["", " ", "a\0b.sc", "a\nb.sc"] {
let one = json!([{"id": ids::encode(1), "path": broken}]);
let rule = "damaged drawing: a source's path is not empty, not only spaces, without control characters";
assert_eq!(refusal(&with("sources", one)), rule, "{broken:?}");
}
// One file named twice still reads: only the file system can say two paths are one file, so
// the engine refuses it when a source is added, never the record.
let twice = json!([{"id": ids::encode(1), "path": "plate.sc"}, {"id": ids::encode(2), "path": "plate.sc"}]);
assert_eq!(read(&with("sources", twice)).unwrap().sources.len(), 2);
// No cap on a path's bytes but the drawing's own: a design deep in folders keeps its sources'
// whole paths in memory, as a component link keeps its file's.
let long = "é".repeat(3000) + ".sc";
let deep = read(&with("sources", json!([{"id": ids::encode(1), "path": long}]))).unwrap();
assert_eq!(deep.sources[0].path.as_deref(), Some(long.as_str()));
let names = |name: &str| {
let mut sheet_named = base.clone();
sheet_named["sheets"][0]["name"] = json!(name);
Expand All @@ -246,6 +262,25 @@ fn every_cap_holds_on_both_sides() {
}
}

/// Sources read in id order whatever order a file lists them in, and a drawing that draws another
/// design's file saves the same bytes again: on its own (a design container's entry for it) and
/// inline in a design's JSON. A `null` path reads as none and is never written.
#[test]
fn sources_read_in_id_order_and_save_the_same_bytes() {
let mut v = file(&bare());
v["sources"] = json!([{"id": ids::encode(9), "path": "../parts/plate.sc"}, {"id": ids::encode(3), "path": null}]);
let d = read(&v).unwrap();
assert_eq!(d.sources, [Source { id: 3, path: None }, Source { id: 9, path: Some("../parts/plate.sc".into()) }]);
let saved = d.to_json().unwrap();
assert_eq!(Drawing::from_json(&saved).unwrap().to_json().unwrap(), saved, "save, open, save: the same bytes");
let written: Value = serde_json::from_str(&saved).unwrap();
assert_eq!(written["sources"], json!([{"id": ids::encode(3)}, {"id": ids::encode(9), "path": "../parts/plate.sc"}]));
let mut doc = crate::Document::new("Case");
doc.drawings = vec![Arc::new(d)];
let inline = doc.to_json();
assert_eq!(crate::Document::from_json(&inline).unwrap().to_json(), inline);
}

/// The content language is a well-formed BCP 47 tag of 2 to 35 characters.
#[test]
fn the_language_is_a_bcp_47_tag_of_2_to_35_characters() {
Expand Down Expand Up @@ -928,4 +963,17 @@ fn a_newer_builds_drawing_opens_and_keeps_what_it_cant_read() {
assert_eq!(again["future_views"], file["future_views"]);
assert_eq!(again["sheets"].as_array().unwrap().len(), d.sheets.len() + 1);
assert_eq!(again["format"], json!(newer));
// A source of another design's file reads; one it can't read (a field a later build adds) stays
// out, named by its path, and goes back.
let nut = json!({"id": ids::encode(2), "path": "parts/nut.sc"});
let bolt = json!({"id": ids::encode(1), "path": "parts/bolt.sc", "future_digest": "ab"});
file["sources"].as_array_mut().unwrap().extend([nut, bolt.clone()]);
let opened = Drawing::from_json(&file.to_string()).unwrap();
let nut = Source { id: 2, path: Some("parts/nut.sc".into()) };
assert_eq!(opened.sources, [&[nut][..], &d.sources[..]].concat());
assert_eq!(opened.own_source(), Some(d.sources[0].id));
let said = &opened.newer_file.as_ref().unwrap().not_understood;
assert!(said.iter().any(|what| what.contains("parts/bolt.sc")), "{said:?}");
let again: Value = serde_json::from_str(&opened.to_json().unwrap()).unwrap();
assert_eq!(again["sources"].as_array().unwrap().last(), Some(&bolt));
}
19 changes: 12 additions & 7 deletions crates/engine/src/cmd/component_link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,11 @@ fn link_refused(design: Option<&str>, link: &str) -> Result<()> {
solidcraft_io::vfs::check_design_path(&file.to_string_lossy(), design).map_err(|e| EngineError::Other(e.to_string()))
}

/// Resolve a design's component links against its original file, before opening it from a
/// different location (for example a recovery file) or keeping it in session history.
/// Resolve a design's links (its component links and its drawings' sources) against its original
/// file, before opening it from a different location (for example a recovery file) or keeping it
/// in session history.
pub fn resolve_design_links(doc: &mut Document, from: Option<&str>) {
for link in doc.links.values_mut() {
link.path = absolute(&resolve(from, &link.path)).to_string_lossy().into_owned();
}
super::design_link::located(doc, from);
}

/// The bodies of a linked design: its name, the Import feature that holds them and the names
Expand Down Expand Up @@ -1575,8 +1574,9 @@ mod tests {

/// Every place that reaches a file through a link path goes through the design-path rule
/// (`vfs::check_design_path` / `read_design_path` / `design_path_is_file` / `link_refusal`):
/// no plain file call on a link's path in the link commands, and the font file a design's text
/// names is checked before it is read.
/// no plain file call on a link's path in the link commands, a drawing's source path judged by the
/// rule before `same_file` canonicalises it, and the font file a design's text names is checked
/// before it is read.
#[test]
fn every_link_path_goes_through_the_design_path_rule() {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
Expand Down Expand Up @@ -1609,6 +1609,11 @@ mod tests {
assert!(rule < at, "{file}: canonicalize before check_design_path");
}
}
// A drawing's source path: the rule judges its text before `same_file` canonicalises it (a network touch).
let drawing = code("src/cmd/drawing.rs");
let source = &drawing[drawing.find("fn linked_source(").unwrap()..];
let rule = source.find("check_design_path(given").expect("linked_source goes through the design-path rule");
assert!(rule < source.find("same_file(").unwrap(), "src/cmd/drawing.rs: same_file before check_design_path");
let fonts = std::fs::read_to_string(root.join("../sketch/src/fonts.rs")).unwrap();
let (check, read) = (fonts.find("FILE_CHECK.get()").unwrap(), fonts.find("read_font(&path)").unwrap());
assert!(check < read, "a font file named by a design is checked before it is read");
Expand Down
Loading
Loading