Skip to content
Closed
5 changes: 3 additions & 2 deletions apps/solidcraft-cli/tests/run_results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions assets/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,17 @@
"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.drawing_view_snapshot": "Drawing View Snapshot",
"cmd.edit_checkpoint": "Checkpoint",
"cmd.edit_restore_checkpoint": "Restore Checkpoint",
"cmd.engine_commands": "List Commands",
Expand Down
11 changes: 11 additions & 0 deletions assets/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,17 @@
"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.drawing_view_snapshot": "図面ビューのスナップショット",
"cmd.edit_checkpoint": "チェックポイント",
"cmd.edit_restore_checkpoint": "チェックポイントを復元",
"cmd.engine_commands": "コマンドを一覧表示",
Expand Down
11 changes: 11 additions & 0 deletions assets/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,17 @@
"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.drawing_view_snapshot": "绘图视图快照",
"cmd.edit_checkpoint": "检查点",
"cmd.edit_restore_checkpoint": "恢复检查点",
"cmd.engine_commands": "列出命令",
Expand Down
13 changes: 13 additions & 0 deletions crates/doc/src/assembly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,19 @@ impl Document {
out
}

/// Whether [`Document::placements`] reaches every placement. Its walk stops at
/// [`MAX_PLACEMENTS`], and a branch past [`MAX_PLACEMENT_DEPTH`] levels, so a placement it
/// holds may have occurrences it never walked; the walk is whole when none does.
pub fn placements_complete(&self) -> bool {
let mut children = std::collections::HashMap::<u64, usize>::new();
for o in &self.occurrences {
*children.entry(o.parent).or_default() += 1;
}
let walk = self.placements();
let reached = walk.iter().fold(0usize, |n, (c, _, _)| n.saturating_add(children.get(c).copied().unwrap_or(0)));
walk.len() == reached.saturating_add(1)
}

/// Every body as the world shows it: its world name ("Body1", or "Body1 (Occ:2)" for a
/// further instance), its component, the occurrence path, and the transform from the frame
/// its geometry is in to the world.
Expand Down
33 changes: 33 additions & 0 deletions crates/doc/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::sync::Arc<crate::drawing::Drawing>>,
}

/// Items hidden or shown one by one. Saved with the design, but not an undo step.
Expand Down Expand Up @@ -2686,6 +2692,7 @@ impl Document {
browser_order: Default::default(),
named_views: Vec::new(),
visibility: Visibility::default(),
drawings: Vec::new(),
}
}

Expand Down Expand Up @@ -2815,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<crate::drawing::Drawing>> {
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<crate::drawing::Drawing>) {
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`.)
Expand Down
106 changes: 70 additions & 36 deletions crates/doc/src/drawing.rs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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;
Expand All @@ -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.
Expand All @@ -72,8 +73,11 @@ pub struct Drawing {
/// otherwise.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub format_pending: Vec<String>,
/// 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<Source>,
/// The drawing's properties and other tools' data, kept as they are.
#[serde(default, skip_serializing_if = "Metadata::is_empty")]
Expand All @@ -86,15 +90,13 @@ pub struct Drawing {
pub sheets: Vec<Arc<Sheet>>,
}

/// 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.
Expand Down Expand Up @@ -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<DrawingBorderProfile>,
taken: &BTreeSet<u64>,
id_source: &mut IdSource,
) -> Result<Drawing> {
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(),
Expand All @@ -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<Drawing> {
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<Drawing> {
let (version, applied) = DRAWING.take_version(&mut v)?;
DRAWING.check_numbers(&v, "properties")?;
DRAWING.upgrade(&mut v, version, applied.as_deref())?;
Expand Down Expand Up @@ -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<Item = u64> {
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`)")
Expand All @@ -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))))?;
}
Expand All @@ -266,6 +273,33 @@ 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(drawings: Vec<Drawing>) -> Result<Vec<Arc<Drawing>>> {
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<Drawing>]) {
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<Drawing>]) -> 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())) }
Expand Down
4 changes: 2 additions & 2 deletions crates/doc/src/drawing/format/pending/README.md
Original file line number Diff line number Diff line change
@@ -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<N>/` folder.
Expand Down
5 changes: 5 additions & 0 deletions crates/doc/src/drawing/format/pending/in-design.rs
Original file line number Diff line number Diff line change
@@ -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).
Loading