diff --git a/apps/solidcraft-cli/src/crashes.rs b/apps/solidcraft-cli/src/crashes.rs index 01288fbfdcf..581eb3a0b9c 100644 --- a/apps/solidcraft-cli/src/crashes.rs +++ b/apps/solidcraft-cli/src/crashes.rs @@ -60,6 +60,10 @@ fn replay(report: &Value) -> Result<(), String> { Some(d) => super::load(d)?, None => solidcraft_engine::Session::default(), }; + // The ids the session drew from there, so the commands give the same objects the same ids. + if let Some(seed) = script["ids"].as_u64() { + s.seed_ids(seed); + } std::panic::set_hook(Box::new(|info| { let loc = info.location().map_or_else(|| "(unknown)".to_string(), |l| format!("{}:{}", l.file(), l.line())); let msg = info.payload_as_str().unwrap_or("(not a text message)").to_string(); diff --git a/apps/solidcraft-cli/tests/run_results.rs b/apps/solidcraft-cli/tests/run_results.rs index c5709904fdc..80fa1b24448 100644 --- a/apps/solidcraft-cli/tests/run_results.rs +++ b/apps/solidcraft-cli/tests/run_results.rs @@ -172,12 +172,13 @@ fn snapshot_runs_its_script_on_the_in_design() { } } -/// An unknown command's error suggests the id that was meant. +/// An unknown command's error suggests the id that was meant first; other close ids (such as +/// `drawing.open`) may follow it. #[test] fn unknown_command_suggests_the_closest_id() { let output = cli().args(["exec", "file.open"]).output().unwrap(); assert_eq!(output.status.code(), Some(1)); - assert!(String::from_utf8_lossy(&output.stderr).contains("did you mean `doc.open`?"), "{}", String::from_utf8_lossy(&output.stderr)); + assert!(String::from_utf8_lossy(&output.stderr).contains("did you mean `doc.open`"), "{}", String::from_utf8_lossy(&output.stderr)); } /// #1833: `--timings` reports each command's time instead of the measurement, `--profile` adds diff --git a/assets/locales/de.json b/assets/locales/de.json index f50159cfa32..2185110fac0 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -992,6 +992,7 @@ "pick a hole to seat it, or OK places it at the origin": "Wählen Sie eine Bohrung zum Einsetzen, oder OK platziert es im Ursprung", "pick one or two vertices, edges or faces": "Wählen Sie ein oder zwei Ecken, Kanten oder Flächen", "prefs.cpu": "CPU (Software)", + "prefs.drawings": "Zeichnungen", "prefs.minutes_suffix": " min", "properties.title": "Eigenschaften: {name}", "recovery.days_ago": "vor {count} Tagen", @@ -1486,6 +1487,7 @@ "ui.findInTimeline": "In der Zeitleiste suchen", "ui.findInWindow": "Im Fenster suchen", "ui.finish_sketch": "Skizze beenden", + "ui.first_angle": "Erster Winkel", "ui.fit": "Einpassen", "ui.fix_unfix": "Fixieren/Lösen", "ui.flat": "Flach", @@ -1706,6 +1708,7 @@ "ui.profiles": "Profile", "ui.project": "Projizieren", "ui.project_face_edges_sketch": "Flächenkanten in neue Skizzen projizieren", + "ui.projection_of_new_drawings": "Projektion neuer Zeichnungen", "ui.properties": "Eigenschaften", "ui.pull_direction": "Entformungsrichtung", "ui.quantity": "Anzahl", @@ -1878,6 +1881,7 @@ "ui.text": "Text", "ui.theme": "Design", "ui.thickness": "Dicke", + "ui.third_angle": "Dritter Winkel", "ui.thread": "Gewinde", "ui.tie_ends": "Verknüpfen", "ui.tie_ends_tip": "Alle unverknüpften Enden mit Abhängigkeiten versehen", diff --git a/assets/locales/en.json b/assets/locales/en.json index a2ae34bde16..506babd0638 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -563,6 +563,25 @@ "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_sheet_add": "Add Sheet", + "cmd.drawing_sheet_delete": "Delete Sheet", + "cmd.drawing_sheet_reorder": "Reorder Sheets", + "cmd.drawing_sheet_set": "Sheet Settings", + "cmd.drawing_view_copy_to_sheet": "Copy View to Sheet", + "cmd.drawing_view_edit": "Edit Drawing View", + "cmd.drawing_view_inspect": "Inspect Drawing View", + "cmd.drawing_view_move_to_sheet": "Move View to Sheet", + "cmd.drawing_view_snapshot": "Drawing View Snapshot", "cmd.edit_checkpoint": "Checkpoint", "cmd.edit_restore_checkpoint": "Restore Checkpoint", "cmd.engine_commands": "List Commands", @@ -1075,6 +1094,7 @@ "prefs.design_note": "What new designs start with. Open designs keep their own.", "prefs.devices": "3D mouse", "prefs.display": "Display", + "prefs.drawings": "Drawings", "prefs.edges": "Edges and shading", "prefs.extend": "Extend", "prefs.extra_navigation": "Ctrl+left drag on empty space orbits; hold Space to pan.", @@ -1663,6 +1683,7 @@ "ui.findInTimeline": "Find in Timeline", "ui.findInWindow": "Find in Window", "ui.finish_sketch": "Finish Sketch", + "ui.first_angle": "First angle", "ui.fit": "Fit", "ui.fix_unfix": "Fix/Unfix", "ui.flat": "Flat", @@ -1890,6 +1911,7 @@ "ui.profiles": "Profiles", "ui.project": "Project", "ui.project_face_edges_sketch": "Project face edges into new sketches", + "ui.projection_of_new_drawings": "Projection of new drawings", "ui.properties": "Properties", "ui.pull_direction": "Pull direction", "ui.quantity": "Quantity", @@ -2062,6 +2084,7 @@ "ui.text": "Text", "ui.theme": "Theme", "ui.thickness": "Thickness", + "ui.third_angle": "Third angle", "ui.thread": "Thread", "ui.tie_ends": "Tie", "ui.tie_ends_tip": "Constrain all untied ends", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index b7978f85978..f5c7025a2a4 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -563,6 +563,25 @@ "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_sheet_add": "シートを追加", + "cmd.drawing_sheet_delete": "シートを削除", + "cmd.drawing_sheet_reorder": "シートを並べ替え", + "cmd.drawing_sheet_set": "シート設定", + "cmd.drawing_view_copy_to_sheet": "ビューをシートにコピー", + "cmd.drawing_view_edit": "図面ビューを編集", + "cmd.drawing_view_inspect": "図面ビューを確認", + "cmd.drawing_view_move_to_sheet": "ビューをシートに移動", + "cmd.drawing_view_snapshot": "図面ビューのスナップショット", "cmd.edit_checkpoint": "チェックポイント", "cmd.edit_restore_checkpoint": "チェックポイントを復元", "cmd.engine_commands": "コマンドを一覧表示", @@ -1075,6 +1094,7 @@ "prefs.design_note": "新しいデザインの初期設定です。開いているデザインはそれぞれの設定を保持します。", "prefs.devices": "3D マウス", "prefs.display": "表示", + "prefs.drawings": "図面", "prefs.edges": "エッジと陰影", "prefs.extend": "拡張", "prefs.extra_navigation": "何もない場所でCtrl+左ドラッグすると回転し、Spaceを押しながらドラッグすると移動します。", @@ -1663,6 +1683,7 @@ "ui.findInTimeline": "タイムラインで検索", "ui.findInWindow": "ウィンドウで検索", "ui.finish_sketch": "スケッチを終了", + "ui.first_angle": "第一角法", "ui.fit": "フィット", "ui.fix_unfix": "固定/固定解除", "ui.flat": "展開", @@ -1890,6 +1911,7 @@ "ui.profiles": "プロファイル", "ui.project": "投影", "ui.project_face_edges_sketch": "新規スケッチに面のエッジを自動投影", + "ui.projection_of_new_drawings": "新規図面の投影法", "ui.properties": "プロパティ", "ui.pull_direction": "抜き方向", "ui.quantity": "数量", @@ -2062,6 +2084,7 @@ "ui.text": "テキスト", "ui.theme": "テーマ", "ui.thickness": "厚さ", + "ui.third_angle": "第三角法", "ui.thread": "ねじ", "ui.tie_ends": "拘束", "ui.tie_ends_tip": "未拘束をすべて拘束", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index f76a724ae9f..ed8f89bf528 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -992,6 +992,7 @@ "pick a hole to seat it, or OK places it at the origin": "안착시킬 구멍을 선택하거나, 확인을 누르면 원점에 배치됩니다", "pick one or two vertices, edges or faces": "꼭짓점, 모서리 또는 면을 하나나 두 개 선택하세요", "prefs.cpu": "CPU (소프트웨어)", + "prefs.drawings": "도면", "prefs.minutes_suffix": " min", "properties.title": "속성: {name}", "recovery.days_ago": "{count}일 전", @@ -1486,6 +1487,7 @@ "ui.findInTimeline": "타임라인에서 찾기", "ui.findInWindow": "창에서 찾기", "ui.finish_sketch": "스케치 종료", + "ui.first_angle": "제1각법", "ui.fit": "맞춤", "ui.fix_unfix": "고정/고정 해제", "ui.flat": "플랫", @@ -1706,6 +1708,7 @@ "ui.profiles": "프로파일", "ui.project": "투영", "ui.project_face_edges_sketch": "면 모서리를 새 스케치로 투영", + "ui.projection_of_new_drawings": "새 도면의 투상법", "ui.properties": "속성", "ui.pull_direction": "빼기 방향", "ui.quantity": "수량", @@ -1878,6 +1881,7 @@ "ui.text": "텍스트", "ui.theme": "테마", "ui.thickness": "두께", + "ui.third_angle": "제3각법", "ui.thread": "나사산", "ui.tie_ends": "연결", "ui.tie_ends_tip": "연결되지 않은 모든 끝점 구속", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 993a86cc6e8..1ef96941ca4 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -563,6 +563,25 @@ "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_sheet_add": "添加图纸", + "cmd.drawing_sheet_delete": "删除图纸", + "cmd.drawing_sheet_reorder": "重新排列图纸", + "cmd.drawing_sheet_set": "图纸设置", + "cmd.drawing_view_copy_to_sheet": "将视图复制到图纸", + "cmd.drawing_view_edit": "编辑绘图视图", + "cmd.drawing_view_inspect": "检查绘图视图", + "cmd.drawing_view_move_to_sheet": "将视图移至图纸", + "cmd.drawing_view_snapshot": "绘图视图快照", "cmd.edit_checkpoint": "检查点", "cmd.edit_restore_checkpoint": "恢复检查点", "cmd.engine_commands": "列出命令", @@ -1075,6 +1094,7 @@ "prefs.design_note": "新建设计的初始设置。已打开的设计保留各自的设置。", "prefs.devices": "3D 鼠标", "prefs.display": "显示", + "prefs.drawings": "绘图", "prefs.edges": "边缘与着色", "prefs.extend": "扩展", "prefs.extra_navigation": "在空白处按住Ctrl并用鼠标左键拖动可旋转;按住空格键可平移。", @@ -1663,6 +1683,7 @@ "ui.findInTimeline": "在时间线中查找", "ui.findInWindow": "在窗口中查找", "ui.finish_sketch": "完成草图", + "ui.first_angle": "第一角投影", "ui.fit": "适合", "ui.fix_unfix": "固定/取消固定", "ui.flat": "平面", @@ -1890,6 +1911,7 @@ "ui.profiles": "轮廓", "ui.project": "投影", "ui.project_face_edges_sketch": "将面的边投影到新草图", + "ui.projection_of_new_drawings": "新绘图的投影法", "ui.properties": "属性", "ui.pull_direction": "拔模方向", "ui.quantity": "数量", @@ -2062,6 +2084,7 @@ "ui.text": "文本", "ui.theme": "主题", "ui.thickness": "厚度", + "ui.third_angle": "第三角投影", "ui.thread": "螺纹", "ui.tie_ends": "约束", "ui.tie_ends_tip": "约束全部未约束端点", diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs index 838231dfb5f..b19c2edcb8a 100644 --- a/crates/doc/src/assembly.rs +++ b/crates/doc/src/assembly.rs @@ -325,6 +325,19 @@ impl Document { out } + /// Whether [`Document::placements`] reaches every placement. Its walk stops at + /// [`MAX_PLACEMENTS`], and a branch past [`MAX_PLACEMENT_DEPTH`] levels, so a placement it + /// holds may have occurrences it never walked; the walk is whole when none does. + pub fn placements_complete(&self) -> bool { + let mut children = std::collections::HashMap::::new(); + for o in &self.occurrences { + *children.entry(o.parent).or_default() += 1; + } + let walk = self.placements(); + let reached = walk.iter().fold(0usize, |n, (c, _, _)| n.saturating_add(children.get(c).copied().unwrap_or(0))); + walk.len() == reached.saturating_add(1) + } + /// Every body as the world shows it: its world name ("Body1", or "Body1 (Occ:2)" for a /// further instance), its component, the occurrence path, and the transform from the frame /// its geometry is in to the world. diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index a027b1b8625..9d87ee1c845 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2486,6 +2486,12 @@ pub struct Document { /// a document in a session leaves this empty; the session puts it back when it saves. #[serde(default, skip_serializing_if = "Visibility::is_empty")] pub visibility: Visibility, + /// The design's drawings (#3890), by name, then id ([`crate::drawing::in_design`]), each behind + /// its own `Arc`, so an undo step shares every drawing it didn't change. Each is read by its own + /// family's rules ([`crate::format::read`]), never as a field of the design; a container keeps + /// each in its own entry. + #[serde(skip_deserializing, skip_serializing_if = "Vec::is_empty")] + pub drawings: Vec>, } /// Items hidden or shown one by one. Saved with the design, but not an undo step. @@ -2686,6 +2692,7 @@ impl Document { browser_order: Default::default(), named_views: Vec::new(), visibility: Visibility::default(), + drawings: Vec::new(), } } @@ -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> { + self.drawings.iter().find(|d| d.id == id) + } + + /// Put `drawing` in, in place of the one with its id if there is one, in the drawings' order. + pub fn put_drawing(&mut self, drawing: std::sync::Arc) { + self.drawings.retain(|d| d.id != drawing.id); + self.drawings.push(drawing); + crate::drawing::sort(&mut self.drawings); + } + /// The colour a body is shown and exported in (sRGB as 0–1 fractions): its appearance, /// else its component's, else its material's look, else the colour it was imported with. /// (Faces may have their own: `face_looks`.) diff --git a/crates/doc/src/drawing.rs b/crates/doc/src/drawing.rs index 2c7dfb4b957..21140c03fa6 100644 --- a/crates/doc/src/drawing.rs +++ b/crates/doc/src/drawing.rs @@ -1,11 +1,14 @@ -//! A drawing (#3890): sheets of paper that draw designs saved in their own files. A drawing is a -//! file of its own, `"format": "solidcraft-drawing/N"`, versioned by the same code as designs -//! ([`DRAWING`]); format 1 is this record. +//! A drawing (#3890): sheets of paper that draw a design. A drawing lives in the file of the design +//! it draws ([`Document::drawings`](crate::Document::drawings)): a design container keeps each in +//! its own entry, a plain JSON design inline. Each is a record of its own family, +//! `"format": "solidcraft-drawing/N"`, versioned by the same code as designs ([`DRAWING`]), so a +//! change to the record is a drawing change, not a design one. //! -//! - **Sources** are the designs it draws: an id and the design file's path, relative to the -//! drawing's folder once the drawing is saved, else as given, with `/` between folders (a linked -//! design's [`DesignLink`](crate::DesignLink) rule). What a design was when the drawing last saw -//! it is not saved here. +//! - Each drawing has an **id**, unique among its design's drawings, and a design lists its +//! drawings by name, then id ([`in_design`]): nothing to merge when two people add drawings. +//! - **Sources** are the designs it draws. For now a drawing draws the design it is in: at most one +//! source, an id and nothing else. What the design was when the drawing last saw it is not saved +//! here. //! - **Sheets**: the paper, a copy of its drawing border, the resolution its pictures are rendered //! at, the component it documents, and whether it is left out of the sheet count or of printing. //! The border is a copy of the profile it was made with, never a name, so a later built-in never @@ -13,6 +16,8 @@ //! - **Units** follow each view's design or are one length unit for the whole drawing. The //! **language** is the content's, a BCP 47 tag chosen when the drawing is made, whatever the //! interface's is. **Properties** follow [`Metadata`]'s rules. +//! - **Views** of its designs on its sheets, base and projected ([`view`]), and the **projection** +//! (first or third angle) every projected view follows. //! //! The rules, which every later kind of record (views, annotations, tables) keeps too: //! - Every object has an id of [`crate::ids`]: random, so objects added side by side never take @@ -20,35 +25,39 @@ //! 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; use serde::{Deserialize, Serialize}; use serde_json::Value; +use solidcraft_geom::cell::Projection; use solidcraft_geom::drawing_sheet::{self, DrawingBorderProfile}; +use solidcraft_geom::{Aabb2, Vec2}; use crate::format::DRAWING; use crate::ids::{self, IdSource}; use crate::{DocError, Metadata, Result, expr}; +pub mod view; + +use view::View; + +/// The most drawings a design may hold. +pub const MAX_DRAWINGS: usize = 1000; /// The most sheets a drawing may have. pub const MAX_SHEETS: usize = 1000; -/// The most designs a drawing may draw. -pub const MAX_SOURCES: usize = 64; /// The longest name of a drawing or a sheet, in bytes. pub const MAX_NAME_BYTES: usize = 256; -/// The longest path to a design, in bytes. -pub const MAX_PATH_BYTES: usize = 4096; /// The longest language tag: what RFC 5646 asks every reader to take (§4.4.1). pub const MAX_LANGUAGE_CHARS: usize = 35; /// The largest drawing read, as JSON text. @@ -72,29 +81,37 @@ pub struct Drawing { /// otherwise. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub format_pending: Vec, + /// Unique among its design's drawings: a design container's entry for it is named by it. + #[serde(with = "crate::ids")] + pub id: u64, pub name: String, - /// The designs the drawing draws. + /// The designs the drawing draws: for now at most one, the design it is in. pub sources: Vec, - /// The drawing's properties and other tools' data, kept as they are. - #[serde(default, skip_serializing_if = "Metadata::is_empty")] - pub properties: Metadata, + /// 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. + #[serde(default, skip_serializing_if = "no_properties")] + pub properties: Arc, #[serde(default)] pub units: Units, + /// First or third angle: what every projected view shows, and the title block's symbol. + #[serde(default)] + pub projection: Projection, /// The language of the drawing's content, a BCP 47 tag (`en-GB`). pub language: String, /// In order, each behind its own `Arc`, so an undo step shares every sheet it didn't change. pub sheets: Vec>, + /// In order, each behind its own `Arc`, as the sheets are. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub views: Vec>, } -/// A design the drawing draws. +/// A design the drawing draws: the design the drawing is in. Views and sheets name it by its id, +/// so a drawing of other designs can add sources of another kind later. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Source { #[serde(with = "crate::ids")] pub id: u64, - /// The design file: relative to the drawing's folder once the drawing is saved, else as given - /// (`/` separates folders). - pub path: String, } /// The length unit a drawing gives its measurements in. @@ -149,44 +166,69 @@ pub struct Excluded { pub print: bool, } +impl Sheet { + /// Where the sheet's drawing goes, in paper millimetres: inside its drawing border, or the + /// whole paper when it has none. Nothing on a sheet is saved against its border, so a change + /// of paper regrows the border and its zones by itself. + pub fn drawing_space(&self) -> Result { + match &self.border { + Some(border) => Ok(border.layout(&self.sheet).map_err(from_sheet)?.drawing_border), + None => Ok(Aabb2 { min: Vec2::ZERO, max: self.sheet.size_mm().map_err(from_sheet)? }), + } + } +} + fn default_dpi() -> f64 { DEFAULT_DPI } impl Drawing { /// A drawing of no designs yet, named `name` and written in `language`, with one sheet named - /// `sheet`: the paper `paper` with a copy of `border`, its id from `id_source`. + /// `sheet`: the paper `paper` with a copy of `border`. Its id, and then its sheet's, come from + /// `id_source`, the drawing's differing from every one in `taken` (its design's drawings'). pub fn new( name: &str, language: &str, sheet: &str, paper: drawing_sheet::Sheet, border: Option, + taken: &BTreeSet, id_source: &mut IdSource, ) -> Result { - let id = id_source.next(&BTreeSet::new())?; - let first = Sheet { id, name: sheet.into(), sheet: paper, border, dpi: DEFAULT_DPI, documents: None, excluded: Excluded::default() }; + let id = id_source.next(taken)?; + let sheet_id = id_source.next(&BTreeSet::from([id]))?; + let first = + Sheet { id: sheet_id, name: sheet.into(), sheet: paper, border, dpi: DEFAULT_DPI, documents: None, excluded: Excluded::default() }; let drawing = Drawing { format: DRAWING.format_string(DRAWING.current()), format_pending: DRAWING.pending_names(), + id, name: name.into(), sources: Vec::new(), - properties: Metadata::default(), + properties: Arc::default(), units: Units::default(), + projection: Projection::default(), language: language.into(), sheets: vec![Arc::new(first)], + views: Vec::new(), }; drawing.validate()?; Ok(drawing) } - /// Read a drawing file's JSON (any format this build knows; older ones are upgraded). A file + /// Read a drawing's JSON (any format this build knows; older ones are upgraded). A drawing /// that breaks a rule of the record is damaged and refused, never patched. pub fn from_json(s: &str) -> Result { if s.len() > MAX_DRAWING_BYTES { return Err(DocError::Invalid(format!("drawing too large (at most {} MiB)", MAX_DRAWING_BYTES >> 20))); } - let mut v: Value = serde_json::from_str(s).map_err(|e| DocError::Invalid(format!("not a SolidCraft drawing: {e}")))?; + let v: Value = serde_json::from_str(s).map_err(|e| DocError::Invalid(format!("not a SolidCraft drawing: {e}")))?; + Drawing::from_value(v) + } + + /// Read a drawing from its JSON value, as a plain JSON design holds it: [`Drawing::from_json`] + /// once the text is parsed. + pub fn from_value(mut v: Value) -> Result { let (version, applied) = DRAWING.take_version(&mut v)?; DRAWING.check_numbers(&v, "properties")?; DRAWING.upgrade(&mut v, version, applied.as_deref())?; @@ -211,17 +253,33 @@ impl Drawing { id_source.next(&self.ids().collect()) } + /// The position of the sheet `named` names: by id, else by a name only one sheet has. + pub fn sheet_index(&self, named: &str) -> Result { + if let Some(i) = ids::decode(named).and_then(|id| self.sheets.iter().position(|s| s.id == id)) { + return Ok(i); + } + let mut called = self.sheets.iter().enumerate().filter(|(_, s)| s.name == named).map(|(i, _)| i); + match (called.next(), called.next()) { + (Some(i), None) => Ok(i), + (Some(_), Some(_)) => Err(DocError::Invalid(format!("more than one sheet is called `{named}`: give its id"))), + (None, _) => Err(DocError::Invalid(format!("no sheet `{named}`"))), + } + } + /// Every object's id, of every kind: what a new id must differ from. Each later kind adds its /// own here. fn ids(&self) -> impl Iterator { - self.sources.iter().map(|s| s.id).chain(self.sheets.iter().map(|s| s.id)) + std::iter::once(self.id) + .chain(self.sources.iter().map(|s| s.id)) + .chain(self.sheets.iter().map(|s| s.id)) + .chain(self.views.iter().map(|v| v.id)) } - /// The record's rules (the module's notes): what reading a file checks, and what every edit + /// The record's rules (the module's notes): what reading a drawing checks, and what every edit /// keeps. pub fn validate(&self) -> Result<()> { require((1..=MAX_SHEETS).contains(&self.sheets.len()), || format!("a drawing has 1 to {MAX_SHEETS} sheets"))?; - require(self.sources.len() <= MAX_SOURCES, || format!("a drawing draws at most {MAX_SOURCES} designs"))?; + require(self.sources.len() <= 1, || "a drawing draws only the design it is in".into())?; check_name(&self.name, "the drawing's")?; require(is_language_tag(&self.language), || { format!("the language is not a BCP 47 tag of 2 to {MAX_LANGUAGE_CHARS} characters (such as `en` or `en-GB`)") @@ -236,24 +294,20 @@ 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))))?; } - Ok(()) + self.check_views() } /// 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")?; sheet.sheet.size_mm().map_err(from_sheet)?; + // The border must lay out on the sheet: the one rule, as drawing it uses it. A few small + // lists per sheet, so every edit's check stays cheap. if let Some(border) = &sheet.border { - border.validate().map_err(from_sheet)?; + border.layout(&sheet.sheet).map_err(from_sheet)?; } require((MIN_DPI..=MAX_DPI).contains(&sheet.dpi), || format!("its pictures are {MIN_DPI} to {MAX_DPI} dpi"))?; match sheet.documents { @@ -266,6 +320,38 @@ 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) -> Result>> { + let mut drawings: Vec<_> = drawings.into_iter().map(Arc::new).collect(); + sort(&mut drawings); + check_in_design(&drawings)?; + Ok(drawings) +} + +/// Put a design's drawings in their order: by name, then id. Nothing stores the order, so two +/// people adding drawings have nothing to merge. +pub fn sort(drawings: &mut [Arc]) { + drawings.sort_by(|a, b| (&a.name, a.id).cmp(&(&b.name, b.id))); +} + +/// The rules for a design's drawings: at most [`MAX_DRAWINGS`], and no two with one id. +pub fn check_in_design(drawings: &[Arc]) -> Result<()> { + check_count(drawings.len())?; + 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")) +} + +/// Whether the drawing has no properties, so its file leaves them out. +fn no_properties(properties: &Arc) -> bool { + properties.is_empty() +} + /// `Ok` when `ok`, else the rule `broken` names. fn require(ok: bool, broken: impl FnOnce() -> String) -> Result<()> { if ok { Ok(()) } else { Err(DocError::Invalid(broken())) } diff --git a/crates/doc/src/drawing/format/pending/README.md b/crates/doc/src/drawing/format/pending/README.md index 29e16f40fca..ab38b024a78 100644 --- a/crates/doc/src/drawing/format/pending/README.md +++ b/crates/doc/src/drawing/format/pending/README.md @@ -1,7 +1,7 @@ # Pending drawing-format changes -One file per change to what a drawing file saves that no release has shipped yet. Drawings -(`"format": "solidcraft-drawing/N"`, #3890) are versioned by the same code as designs +One file per change to what a drawing saves (in its design's file) that no release has shipped +yet. Drawings (`"format": "solidcraft-drawing/N"`, #3890) are versioned by the same code as designs (`crates/doc/src/format.rs`, `Family`), from their own first format, 1. Adding a file here is the whole format bump: never edit the `DRAWING` family in `format.rs`, another change's file or a `../v/` folder. diff --git a/crates/doc/src/drawing/format/pending/in-design.rs b/crates/doc/src/drawing/format/pending/in-design.rs new file mode 100644 index 00000000000..96078e4ff2b --- /dev/null +++ b/crates/doc/src/drawing/format/pending/in-design.rs @@ -0,0 +1,5 @@ +//! A drawing lives in the file of the design it draws (#3890): it has an `id`, unique among its +//! design's drawings, and at most one source, the design it is in, which has an `id` and no `path`. +//! No step: no release saved a drawing before this, and a drawing file of its own is no longer +//! read, so an older drawing is refused as damaged. The last release refuses a design that holds a +//! drawing (the design's newer format number). diff --git a/crates/doc/src/drawing/format/pending/sheet-views.rs b/crates/doc/src/drawing/format/pending/sheet-views.rs new file mode 100644 index 00000000000..b4bcdf6b4e1 --- /dev/null +++ b/crates/doc/src/drawing/format/pending/sheet-views.rs @@ -0,0 +1,5 @@ +//! Drawings save their views (`views`, #4816): base views of their designs and the views projected +//! from them, on their sheets, each with the settings it sets itself; and the projection every +//! projected view follows (`projection`: `first` or `third` angle). An older drawing has no views, +//! and its projection is third angle. The last release refuses a drawing saved with them, as a +//! newer format. diff --git a/crates/doc/src/drawing/view.rs b/crates/doc/src/drawing/view.rs new file mode 100644 index 00000000000..20f6bc197dd --- /dev/null +++ b/crates/doc/src/drawing/view.rs @@ -0,0 +1,247 @@ +//! A drawing's views (W17a, #4816): each a view of one of the drawing's designs, on one of its +//! sheets. A **base view** draws a source from a direction ([`ViewDirection`]). A **projected +//! view** sits on one side of its parent and looks from that side, or from the side away from it +//! in first angle ([`Drawing::projection`], [`projected_basis`]); lined up with its parent, it saves +//! only its place along the free axis, as the other comes from the parent ([`Drawing::view_centre`]). +//! +//! What a view sets itself is in [`ViewOverrides`]: each setting it leaves out follows its parent, +//! then the default, and [`Drawing::resolve_view`] is that one rule for every reader. A projected +//! view's source and basis come from its chain of parents, so neither is saved. +//! +//! The rules, beside the record's: a view is on one of the drawing's sheets; a base view draws one +//! of its sources, has a scale and looks from a direction that makes a view; every parent is a view +//! of the drawing, no chain of parents loops, and a chain is at most [`MAX_VIEW_DEPTH`] views; a +//! view lined up with its parent is on the parent's sheet; a view's place is on paper +//! ([`is_paper_coordinate`]); at most [`MAX_VIEWS`] views. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use solidcraft_geom::drawing_view::{ProjectedSide, Scale, is_paper_coordinate, projected_basis}; +use solidcraft_geom::paper::MAX_SIDE_MM; +use solidcraft_geom::{Plane, Vec2}; +use solidcraft_render::VisualStyle; + +use super::{Drawing, require}; +use crate::drawing_view::{MAX_REFERENCE_MARGIN_MM, TangentEdges, ViewDirection, ViewOverrides, ViewSettings}; +use crate::{DocError, Result, ids}; + +/// The most views a drawing may have. +pub const MAX_VIEWS: usize = 4096; +/// The most views in a chain, from a base view down through the views projected from it. +pub const MAX_VIEW_DEPTH: usize = 32; + +/// One view of a drawing. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct View { + #[serde(with = "crate::ids")] + pub id: u64, + /// The sheet it is on. + #[serde(with = "crate::ids")] + pub sheet: u64, + pub kind: ViewKind, + /// Where its centre sits on its sheet. + pub place: ViewPlace, + /// What it sets itself; each setting left out follows its parent, then the default. + #[serde(default, skip_serializing_if = "ViewOverrides::is_empty")] + pub settings: ViewOverrides, + /// Model millimetres added on every side of its extents, so reference parts around the model + /// show inside its boundary: 0 to [`MAX_REFERENCE_MARGIN_MM`], each view its own. + #[serde(default, skip_serializing_if = "is_zero")] + pub reference_margin_mm: f64, +} + +/// What a view draws, and from where. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", deny_unknown_fields)] +pub enum ViewKind { + /// The design of `source`, seen from `view`. + Base { + #[serde(with = "crate::ids")] + source: u64, + view: ViewDirection, + }, + /// Projected from `parent`, on `side` of it. + Projected { + #[serde(with = "crate::ids")] + parent: u64, + side: ProjectedSide, + }, +} + +/// Where a view's centre sits on its sheet, in paper millimetres. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", deny_unknown_fields)] +pub enum ViewPlace { + /// At this point of the sheet. + At([f64; 2]), + /// Lined up with its parent, this far along the free axis: across for a view to the left or + /// right of it, up for one above or below. A projected view only. + Aligned(f64), +} + +/// Who gave a resolved setting its value. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SetBy { + /// The view itself. + This, + /// The parent of this id, the nearest that sets it. + Parent(u64), + /// No view of the chain: the default. + Default, +} + +/// A setting's value and who gave it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Setting { + pub value: T, + pub set_by: SetBy, +} + +/// A view as it draws: the source it draws, which way it looks, and each setting with who gave it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ResolvedView { + pub source: u64, + pub basis: Plane, + pub scale: Setting, + pub display_style: Setting, + pub reference_style: Setting, + pub reference_hides_model: Setting, + pub tangent_edges: Setting, + pub reference_margin_mm: f64, +} + +fn is_zero(v: &f64) -> bool { + *v == 0.0 +} + +/// The views from `id` up to its base view, nearest first, each found by `find`: refused when a +/// parent isn't one, the chain loops, or it is longer than [`MAX_VIEW_DEPTH`]. +fn chain<'a>(id: u64, find: impl Fn(u64) -> Option<&'a View>) -> Result> { + let mut chain: Vec<&View> = Vec::new(); + let mut at = id; + loop { + let view = find(at).ok_or_else(|| match chain.last() { + None => DocError::Invalid(format!("the drawing has no view {}", ids::encode(at))), + Some(_) => DocError::Invalid(format!("its parent {} isn't one of the drawing's views", ids::encode(at))), + })?; + require(chain.iter().all(|v| v.id != at), || "its chain of parents loops".into())?; + chain.push(view); + match view.kind { + ViewKind::Base { .. } => return Ok(chain), + ViewKind::Projected { parent, .. } => at = parent, + } + require(chain.len() < MAX_VIEW_DEPTH, || format!("a chain of views is at most {MAX_VIEW_DEPTH} views"))?; + } +} + +/// The nearest view of `chain` (the view first) that sets a setting `field` reads, with its value. +fn inherited(chain: &[&View], field: impl Fn(&ViewOverrides) -> Option) -> Option> { + chain.iter().enumerate().find_map(|(i, view)| { + let set_by = if i == 0 { SetBy::This } else { SetBy::Parent(view.id) }; + field(&view.settings).map(|value| Setting { value, set_by }) + }) +} + +/// [`inherited`], or the default `value` when no view of the chain sets it. +fn or_default(chain: &[&View], field: impl Fn(&ViewOverrides) -> Option, value: T) -> Setting { + inherited(chain, field).unwrap_or(Setting { value, set_by: SetBy::Default }) +} + +impl Drawing { + /// The views' rules (the module's notes). + pub(super) fn check_views(&self) -> Result<()> { + require(self.views.len() <= MAX_VIEWS, || format!("a drawing has at most {MAX_VIEWS} views"))?; + let views: BTreeMap = self.views.iter().map(|v| (v.id, &**v)).collect(); + for view in &self.views { + self.check_view(view, &views).map_err(|e| DocError::Invalid(format!("view {}: {e}", ids::encode(view.id))))?; + } + Ok(()) + } + + fn check_view(&self, view: &View, views: &BTreeMap) -> Result<()> { + let on = |sheet: u64| format!("it is on sheet {}, which the drawing doesn't have", ids::encode(sheet)); + require(self.sheets.iter().any(|s| s.id == view.sheet), || on(view.sheet))?; + let margin = view.reference_margin_mm; + require(margin.is_finite() && (0.0..=MAX_REFERENCE_MARGIN_MM).contains(&margin), || { + format!("its reference margin is 0 to {MAX_REFERENCE_MARGIN_MM} model millimetres") + })?; + let place = match view.place { + ViewPlace::At([x, y]) => is_paper_coordinate(x) && is_paper_coordinate(y), + ViewPlace::Aligned(along) => is_paper_coordinate(along), + }; + require(place, || format!("its place is at most {MAX_SIDE_MM} mm from the sheet's origin"))?; + match view.kind { + ViewKind::Base { source, view: direction } => { + let drawn = || format!("it draws source {}, which the drawing doesn't have", ids::encode(source)); + require(self.sources.iter().any(|s| s.id == source), drawn)?; + require(view.settings.scale.is_some(), || "a base view has a scale".into())?; + require(matches!(view.place, ViewPlace::At(_)), || "a base view is placed at a point: it has no parent to line up with".into())?; + direction.basis().map(|_| ()).map_err(|e| DocError::Invalid(e.to_string())) + } + ViewKind::Projected { parent, .. } => { + chain(view.id, |id| views.get(&id).copied())?; + let parent_sheet = views.get(&parent).map(|p| p.sheet); + let lined_up = matches!(view.place, ViewPlace::Aligned(_)); + require(!lined_up || parent_sheet == Some(view.sheet), || "a view lined up with its parent is on its parent's sheet".into()) + } + } + } + + /// View `id` as it draws: its base view's source, its basis turned down its chain of parents + /// ([`projected_basis`], in the drawing's projection), and each setting from the nearest view + /// of the chain that sets it, then the default. One rule for every reader of a view. + pub fn resolve_view(&self, id: u64) -> Result { + let chain = self.chain_of(id)?; + let Some(ViewKind::Base { source, view: direction }) = chain.last().map(|base| base.kind) else { + return Err(DocError::Invalid(format!("view {} has no base view", ids::encode(id)))); + }; + let mut basis = direction.basis().map_err(|e| DocError::Invalid(e.to_string()))?; + for view in chain.iter().rev() { + if let ViewKind::Projected { side, .. } = view.kind { + basis = projected_basis(&basis, side, self.projection).map_err(|e| DocError::Invalid(e.to_string()))?; + } + } + let scale = inherited(&chain, |s| s.scale).ok_or_else(|| DocError::Invalid(format!("view {} has no scale", ids::encode(id))))?; + let defaults = ViewSettings::default(); + Ok(ResolvedView { + source, + basis, + scale, + display_style: or_default(&chain, |s| s.display_style, defaults.display_style), + reference_style: or_default(&chain, |s| s.reference_style, defaults.reference_style), + reference_hides_model: or_default(&chain, |s| s.reference_hides_model, defaults.reference_hides_model), + tangent_edges: or_default(&chain, |s| s.tangent_edges, defaults.tangent_edges), + reference_margin_mm: chain.first().map_or(0.0, |view| view.reference_margin_mm), + }) + } + + /// Where view `id`'s centre sits on its sheet, in paper millimetres. A view placed at a point + /// is there. One lined up with its parent takes its own place along the free axis and its + /// parent's centre across it ([`ProjectedSide::on_free_axis`]): both draw the same model, so + /// their extents share that axis's middle, and they line up whatever their scales. + pub fn view_centre(&self, id: u64) -> Result { + let mut centre = Vec2::ZERO; + // From the base view down to this one, each lined up with the one before or placed apart. + for view in self.chain_of(id)?.iter().rev() { + centre = match (view.place, view.kind) { + (ViewPlace::At([x, y]), _) => Vec2::new(x, y), + (ViewPlace::Aligned(along), ViewKind::Projected { side, .. }) => side.on_free_axis(centre, along), + (ViewPlace::Aligned(_), ViewKind::Base { .. }) => { + return Err(DocError::Invalid(format!("base view {} isn't placed at a point", ids::encode(view.id)))); + } + }; + } + Ok(centre) + } + + /// The views from `id` up to its base view, nearest first ([`chain`]). + fn chain_of(&self, id: u64) -> Result> { + chain(id, |id| self.views.iter().find(|v| v.id == id).map(|v| &**v)) + } +} + +#[cfg(test)] +#[path = "view_tests.rs"] +mod tests; diff --git a/crates/doc/src/drawing/view_tests.rs b/crates/doc/src/drawing/view_tests.rs new file mode 100644 index 00000000000..1d6276f95ef --- /dev/null +++ b/crates/doc/src/drawing/view_tests.rs @@ -0,0 +1,275 @@ +use std::collections::BTreeSet; +use std::sync::Arc; + +use serde_json::{Value, json}; +use solidcraft_geom::Vec3; +use solidcraft_geom::cell::Projection; +use solidcraft_geom::drawing_sheet::{self, Orientation, PaperSize}; +use solidcraft_geom::drawing_view::NamedView; + +use super::*; +use crate::drawing::{Excluded, Sheet, Source}; +use crate::format::DRAWING; +use crate::ids::IdSource; + +const SEED: u64 = 4816; + +/// A drawing of one design on one A3 sheet, its front view at 1:2 centred at (150, 150), and the +/// id source that made it. +fn front() -> (Drawing, IdSource, u64) { + let mut id_source = IdSource::seeded(SEED); + 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 }); + 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) +} + +/// A view on the drawing's first sheet, with no reference margin. +fn add(d: &mut Drawing, id_source: &mut IdSource, kind: ViewKind, place: ViewPlace, settings: ViewOverrides) -> u64 { + let id = d.allocate_id(id_source).unwrap(); + let sheet = d.sheets[0].id; + d.views.push(Arc::new(View { id, sheet, kind, place, settings, reference_margin_mm: 0.0 })); + id +} + +fn projected(parent: u64, side: ProjectedSide) -> ViewKind { + ViewKind::Projected { parent, side } +} + +fn scaled(scale: &str) -> ViewOverrides { + ViewOverrides { scale: Some(scale.parse().unwrap()), ..ViewOverrides::default() } +} + +fn styled(style: VisualStyle) -> ViewOverrides { + ViewOverrides { display_style: Some(style), ..ViewOverrides::default() } +} + +/// The front view, its right view lined up with it and drawing hidden lines too, and the right +/// view's top view placed apart. +fn three() -> (Drawing, IdSource, [u64; 3]) { + let (mut d, mut id_source, front) = front(); + let hidden = styled(VisualStyle::VisibleHidden); + let right = add(&mut d, &mut id_source, projected(front, ProjectedSide::Right), ViewPlace::Aligned(320.0), hidden); + let top = add(&mut d, &mut id_source, projected(right, ProjectedSide::Above), ViewPlace::At([320.0, 250.0]), ViewOverrides::default()); + d.validate().unwrap(); + (d, id_source, [front, right, top]) +} + +fn file(d: &Drawing) -> Value { + serde_json::from_str(&d.to_json().unwrap()).unwrap() +} + +/// Why `d`'s file, changed by `edit`, is refused, or "read". +fn refused(d: &Drawing, edit: impl FnOnce(&mut Value)) -> String { + let mut v = file(d); + edit(&mut v); + Drawing::from_json(&v.to_string()).map_or_else(|e| e.to_string(), |_| "read".into()) +} + +/// A view saves its kind, its place and what it sets itself, and nothing it leaves out; the +/// drawing saves its projection. It reads back as saved, the same bytes again, and an older +/// drawing reads with no views, in third angle. +#[test] +fn views_save_what_they_set_and_read_back_as_saved() { + let (d, _, [front, right, top]) = three(); + let v = file(&d); + let [front_id, right_id, top_id, sheet, source] = [front, right, top, d.sheets[0].id, d.sources[0].id].map(ids::encode); + assert_eq!(v["projection"], json!("third")); + assert_eq!( + v["views"], + json!([ + {"id": front_id, "sheet": sheet, "kind": {"base": {"source": source, "view": "front"}}, "place": {"at": [150.0, 150.0]}, "settings": {"scale": "1:2"}}, + {"id": right_id, "sheet": sheet, "kind": {"projected": {"parent": front_id, "side": "right"}}, "place": {"aligned": 320.0}, "settings": {"display_style": "visible_hidden"}}, + {"id": top_id, "sheet": sheet, "kind": {"projected": {"parent": right_id, "side": "above"}}, "place": {"at": [320.0, 250.0]}}, + ]) + ); + let reopened = Drawing::from_json(&d.to_json().unwrap()).unwrap(); + assert_eq!(reopened, d); + assert_eq!(reopened.to_json().unwrap(), d.to_json().unwrap()); + let mut first = v.clone(); + first["projection"] = json!("first"); + assert_eq!(Drawing::from_json(&first.to_string()).unwrap().projection, Projection::First); + let older = json!({ + "format": DRAWING.format_string(1), "id": "0000000000002", "name": "Old", "sources": [], "language": "en", + "sheets": [{"id": "0000000000001", "name": "S", "sheet": {"size": {"standard": "a4"}}}] + }); + let old = Drawing::from_json(&older.to_string()).unwrap(); + assert!(old.views.is_empty() && old.projection == Projection::Third); + assert_eq!(file(&old).get("views"), None, "no views, none written"); +} + +/// What reading refuses, each rule by name: where a view is and what it draws, its parents, its +/// place and margin, its settings, its id, and how many views there are. +#[test] +fn the_views_rules_are_kept_on_reading() { + let (mut d, mut id_source, [front, right, top]) = three(); + let [front_id, right_id, top_id] = [front, right, top].map(ids::encode); + let nothing = ids::encode(99); + let rule = |id: &str, rule: &str| format!("damaged drawing: view {id}: {rule}"); + // Where it is and what it draws. + let on = format!("it is on sheet {nothing}, which the drawing doesn't have"); + assert_eq!(refused(&d, |v| v["views"][1]["sheet"] = json!(nothing)), rule(&right_id, &on)); + let draws = format!("it draws source {nothing}, which the drawing doesn't have"); + assert_eq!(refused(&d, |v| v["views"][0]["kind"]["base"]["source"] = json!(nothing)), rule(&front_id, &draws)); + let no_scale = refused(&d, |v| { + v["views"][0].as_object_mut().unwrap().remove("settings"); + }); + assert_eq!(no_scale, rule(&front_id, "a base view has a scale")); + let lined_up = refused(&d, |v| v["views"][0]["place"] = json!({"aligned": 10.0})); + assert_eq!(lined_up, rule(&front_id, "a base view is placed at a point: it has no parent to line up with")); + let looking = |direction: Value| refused(&d, |v| v["views"][0]["kind"]["base"]["view"] = json!({"direction": direction, "up": [0.0, 0.0, 1.0]})); + assert_eq!(looking(json!([0.0, 1.0, 0.0])), "read"); + assert_eq!(looking(json!([0.0, 0.0, 0.0])), rule(&front_id, "drawing view: the view direction is zero or not finite")); + assert_eq!(looking(json!([0.0, 0.0, -1.0])), rule(&front_id, "drawing view: `up` lies along the view direction: give another up")); + // Its parents: one that isn't a view, itself, and loops of two and three views. + let parent = |view: usize, parent: &str| { + let parent = parent.to_string(); + move |v: &mut Value| v["views"][view]["kind"] = json!({"projected": {"parent": parent, "side": "left"}}) + }; + let missing = format!("its parent {nothing} isn't one of the drawing's views"); + assert_eq!(refused(&d, parent(1, ¬hing)), rule(&right_id, &missing)); + assert_eq!(refused(&d, parent(1, &front_id)), "read"); + assert_eq!(refused(&d, parent(1, &right_id)), rule(&right_id, "its chain of parents loops")); + assert_eq!(refused(&d, parent(0, &right_id)), rule(&front_id, "its chain of parents loops"), "two views"); + assert_eq!(refused(&d, parent(0, &top_id)), rule(&front_id, "its chain of parents loops"), "three views"); + // A view lined up with its parent is on its parent's sheet; one placed apart may be on any. + let other = d.allocate_id(&mut id_source).unwrap(); + let a4 = drawing_sheet::Sheet::standard(PaperSize::A4, Orientation::Landscape); + d.sheets.push(Arc::new(Sheet { + id: other, + name: "Other".into(), + sheet: a4, + border: None, + dpi: 300.0, + documents: None, + excluded: Excluded::default(), + })); + let other_id = ids::encode(other); + assert_eq!( + refused(&d, |v| v["views"][1]["sheet"] = json!(other_id)), + rule(&right_id, "a view lined up with its parent is on its parent's sheet") + ); + assert_eq!(refused(&d, |v| v["views"][2]["sheet"] = json!(other_id)), "read"); + // Its place and its reference margin. + let off_paper = "its place is at most 5000 mm from the sheet's origin"; + assert_eq!(refused(&d, |v| v["views"][2]["place"] = json!({"at": [5000.0, -5000.0]})), "read"); + assert_eq!(refused(&d, |v| v["views"][2]["place"] = json!({"at": [5000.001, 0.0]})), rule(&top_id, off_paper)); + assert_eq!(refused(&d, |v| v["views"][1]["place"] = json!({"aligned": -5000.001})), rule(&right_id, off_paper)); + for (margin, read) in [(0.0, true), (100_000.0, true), (-0.001, false), (100_000.001, false)] { + let why = refused(&d, |v| v["views"][2]["reference_margin_mm"] = json!(margin)); + let expected = if read { "read".to_string() } else { rule(&top_id, "its reference margin is 0 to 100000 model millimetres") }; + assert_eq!(why, expected, "{margin}"); + } + // Its settings and its fields, only those it knows; a resolution is the sheet's, not a view's. + let unknown: [fn(&mut Value); 5] = [ + |v| v["views"][0]["label"] = json!("A"), + |v| v["views"][0]["settings"]["dpi"] = json!(300.0), + |v| v["views"][0]["kind"]["base"]["scale"] = json!("1:1"), + |v| v["views"][1]["kind"]["projected"]["aligned"] = json!(true), + |v| v["views"][0]["place"] = json!({"at": [1.0, 2.0], "aligned": 3.0}), + ]; + for (i, edit) in unknown.into_iter().enumerate() { + assert!(refused(&d, edit).starts_with("damaged drawing: "), "{i}"); + } + assert!(refused(&d, |v| v["views"][0]["settings"]["scale"] = json!("1:0")).starts_with("damaged drawing: ")); + // Its id is the drawing's: never another object's. + let sheet_id = ids::encode(d.sheets[0].id); + assert_eq!(refused(&d, |v| v["views"][2]["id"] = json!(front_id)), format!("damaged drawing: two objects have the id {front_id}")); + assert_eq!(refused(&d, |v| v["views"][2]["id"] = json!(sheet_id)), format!("damaged drawing: two objects have the id {sheet_id}")); + // At most MAX_VIEWS views. + let many = |n: usize| { + let mut v = file(&d); + let one = v["views"][0].clone(); + v["views"] = Value::Array( + (1..=n as u64) + .map(|i| { + let mut view = one.clone(); + view["id"] = json!(ids::encode(i)); + view + }) + .collect(), + ); + Drawing::from_json(&v.to_string()).map(|d| d.views.len()).map_err(|e| e.to_string()) + }; + assert_eq!(many(MAX_VIEWS), Ok(MAX_VIEWS)); + assert_eq!(many(MAX_VIEWS + 1), Err(format!("damaged drawing: a drawing has at most {MAX_VIEWS} views"))); +} + +/// A chain of views is at most MAX_VIEW_DEPTH views, the base view one of them. +#[test] +fn a_chain_of_views_is_at_most_its_depth() { + let (mut d, mut id_source, front) = front(); + let mut last = front; + for _ in 1..MAX_VIEW_DEPTH { + last = add(&mut d, &mut id_source, projected(last, ProjectedSide::Right), ViewPlace::At([10.0, 10.0]), ViewOverrides::default()); + } + assert_eq!(d.views.len(), MAX_VIEW_DEPTH); + d.validate().unwrap(); + let deepest = add(&mut d, &mut id_source, projected(last, ProjectedSide::Right), ViewPlace::At([10.0, 10.0]), ViewOverrides::default()); + let why = d.validate().unwrap_err().to_string(); + assert_eq!(why, format!("view {}: a chain of views is at most {MAX_VIEW_DEPTH} views", ids::encode(deepest))); +} + +/// A view resolves through its chain of parents: its basis turned down the chain in the drawing's +/// projection, each setting from the nearest view that sets it, then the default, saying who gave +/// it, and its own reference margin. +#[test] +fn a_view_resolves_through_its_chain() { + let (mut d, _, [front, right, top]) = three(); + let view = Arc::make_mut(&mut d.views[2]); + view.settings.tangent_edges = Some(TangentEdges::Show); + view.reference_margin_mm = 2.0; + let resolved = d.resolve_view(top).unwrap(); + assert_eq!(resolved.source, d.sources[0].id); + let right_basis = projected_basis(&NamedView::Front.basis(), ProjectedSide::Right, Projection::Third).unwrap(); + assert_eq!(resolved.basis, projected_basis(&right_basis, ProjectedSide::Above, Projection::Third).unwrap()); + assert_eq!(resolved.scale, Setting { value: "1:2".parse().unwrap(), set_by: SetBy::Parent(front) }); + assert_eq!(resolved.display_style, Setting { value: VisualStyle::VisibleHidden, set_by: SetBy::Parent(right) }); + assert_eq!(resolved.tangent_edges, Setting { value: TangentEdges::Show, set_by: SetBy::This }); + assert_eq!(resolved.reference_style, Setting { value: VisualStyle::Visible, set_by: SetBy::Default }); + assert_eq!(resolved.reference_hides_model, Setting { value: false, set_by: SetBy::Default }); + assert_eq!(resolved.reference_margin_mm, 2.0); + // The base view gives its own; its projected views follow the drawing's projection. + let base = d.resolve_view(front).unwrap(); + assert_eq!((base.basis, base.scale.set_by, base.display_style.set_by), (NamedView::Front.basis(), SetBy::This, SetBy::Default)); + assert_eq!(d.resolve_view(right).unwrap().basis, NamedView::Right.basis()); + d.projection = Projection::First; + assert_eq!(d.resolve_view(right).unwrap().basis, NamedView::Left.basis()); + // A view's own setting wins over its parent's. + Arc::make_mut(&mut d.views[2]).settings.display_style = Some(VisualStyle::Visible); + assert_eq!(d.resolve_view(top).unwrap().display_style, Setting { value: VisualStyle::Visible, set_by: SetBy::This }); + // Four quarter turns the same way bring the front view back. + let (mut d, mut id_source, front) = self::front(); + let mut last = front; + for _ in 0..4 { + last = add(&mut d, &mut id_source, projected(last, ProjectedSide::Right), ViewPlace::At([10.0, 10.0]), ViewOverrides::default()); + } + let turned = d.resolve_view(last).unwrap().basis; + let close = |a: Vec3, b: Vec3| (a - b).len() < 1e-12; + assert!(close(turned.x, Vec3::X) && close(turned.y, Vec3::Z), "{turned:?}"); + assert_eq!(d.resolve_view(99).unwrap_err().to_string(), format!("the drawing has no view {}", ids::encode(99))); +} + +/// A view placed at a point is there; one lined up with its parent takes its own place along the +/// free axis and its parent's centre across it, down a chain, and follows when the parent moves; +/// one placed apart stays. A base view lined up with nothing has no place, nor its views. +#[test] +fn a_views_centre_is_its_point_or_lined_up_with_its_parent() { + let (mut d, mut id_source, [front, right, top]) = three(); + let back = add(&mut d, &mut id_source, projected(right, ProjectedSide::Right), ViewPlace::Aligned(450.0), ViewOverrides::default()); + let below = add(&mut d, &mut id_source, projected(right, ProjectedSide::Below), ViewPlace::Aligned(60.0), ViewOverrides::default()); + d.validate().unwrap(); + let centres = |d: &Drawing| [front, right, top, back, below].map(|id| d.view_centre(id).unwrap()); + let at = |x, y| Vec2::new(x, y); + assert_eq!(centres(&d), [at(150.0, 150.0), at(320.0, 150.0), at(320.0, 250.0), at(450.0, 150.0), at(320.0, 60.0)]); + Arc::make_mut(&mut d.views[0]).place = ViewPlace::At([140.0, 130.0]); + assert_eq!(centres(&d), [at(140.0, 130.0), at(320.0, 130.0), at(320.0, 250.0), at(450.0, 130.0), at(320.0, 60.0)]); + Arc::make_mut(&mut d.views[0]).place = ViewPlace::Aligned(10.0); + for id in [front, right, top, back, below] { + assert_eq!(d.view_centre(id).unwrap_err().to_string(), format!("base view {} isn't placed at a point", ids::encode(front))); + } + assert_eq!(d.view_centre(99).unwrap_err().to_string(), format!("the drawing has no view {}", ids::encode(99))); +} diff --git a/crates/doc/src/drawing_tests.rs b/crates/doc/src/drawing_tests.rs index 12407446d94..93378801585 100644 --- a/crates/doc/src/drawing_tests.rs +++ b/crates/doc/src/drawing_tests.rs @@ -1,5 +1,11 @@ use serde_json::json; use solidcraft_geom::drawing_sheet::{Margins, Orientation, PaperSize, SheetSize}; +use solidcraft_geom::drawing_view::{NamedView, ProjectedSide}; + +use solidcraft_render::VisualStyle; + +use crate::drawing_view::{TangentEdges, ViewDirection, ViewOverrides}; +use view::{ViewKind, ViewPlace}; use super::*; @@ -11,18 +17,18 @@ fn own_border() -> DrawingBorderProfile { DrawingBorderProfile { filing_margin: true, trimming_mark_mm: Some([10.0, 5.0]), ..DrawingBorderProfile::iso() } } -/// Three designs on two sheets: the first sheet (A3, the ISO border) documents component 7 of the -/// first design; the second (A4 portrait, a border of its own, 600 dpi, left out of printing) -/// documents the second design. The third design is on no sheet yet. +/// The design it is in, on two sheets: the first (A3, the ISO border) documents its component 7; +/// the second (A4 portrait, a border of its own, 600 dpi, left out of printing) the design itself. +/// On the first sheet, the front view at 1:2, its right view lined up with it and drawing hidden +/// lines too, and the right view's top view placed apart; on the second, an iso view at 1:1, +/// tangent edges shown, with a 5 mm reference margin. fn plate() -> Drawing { let mut id_source = IdSource::seeded(SEED); let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape); - let mut d = Drawing::new("Plate assembly", "en-GB", "Assembly", a3, Some(DrawingBorderProfile::iso()), &mut id_source).unwrap(); - for path in ["plate.solidcraft", "../parts/bolt.solidcraft", "bracket.solidcraft"] { - let id = d.allocate_id(&mut id_source).unwrap(); - d.sources.push(Source { id, path: path.into() }); - } - let (plate_id, bolt_id) = (d.sources[0].id, d.sources[1].id); + let mut d = Drawing::new("Plate assembly", "en-GB", "Assembly", a3, Some(DrawingBorderProfile::iso()), &BTreeSet::new(), &mut id_source).unwrap(); + let id = d.allocate_id(&mut id_source).unwrap(); + d.sources.push(Source { id }); + let plate_id = d.sources[0].id; let id = d.allocate_id(&mut id_source).unwrap(); d.sheets.push(Arc::new(Sheet { id, @@ -30,12 +36,29 @@ fn plate() -> Drawing { sheet: drawing_sheet::Sheet::standard(PaperSize::A4, Orientation::Portrait), border: Some(own_border()), dpi: 600.0, - documents: Some(SheetComponent { source: bolt_id, component: 0 }), + documents: Some(SheetComponent { source: plate_id, component: 0 }), excluded: Excluded { count: false, print: true }, })); Arc::make_mut(&mut d.sheets[0]).documents = Some(SheetComponent { source: plate_id, component: 7 }); - d.properties.set("author", json!("Jane Doe")).unwrap(); + Arc::make_mut(&mut d.properties).set("author", json!("Jane Doe")).unwrap(); d.units = Units::Fixed { unit: "in".into() }; + let (assembly, bolt_sheet) = (d.sheets[0].id, d.sheets[1].id); + let mut add = |d: &mut Drawing, sheet, kind, place, settings, reference_margin_mm| { + let id = d.allocate_id(&mut id_source).unwrap(); + d.views.push(Arc::new(View { id, sheet, kind, place, settings, reference_margin_mm })); + id + }; + let half = ViewOverrides { scale: Some("1:2".parse().unwrap()), ..ViewOverrides::default() }; + let front = ViewKind::Base { source: plate_id, view: ViewDirection::Named(NamedView::Front) }; + let front = add(&mut d, assembly, front, ViewPlace::At([150.0, 150.0]), half, 0.0); + let hidden = ViewOverrides { display_style: Some(VisualStyle::VisibleHidden), ..ViewOverrides::default() }; + let right = ViewKind::Projected { parent: front, side: ProjectedSide::Right }; + let right = add(&mut d, assembly, right, ViewPlace::Aligned(320.0), hidden, 0.0); + let top = ViewKind::Projected { parent: right, side: ProjectedSide::Above }; + add(&mut d, assembly, top, ViewPlace::At([320.0, 250.0]), ViewOverrides::default(), 0.0); + let iso = ViewKind::Base { source: plate_id, view: ViewDirection::Named(NamedView::IsoFrontRight) }; + let full_size = ViewOverrides { scale: Some("1:1".parse().unwrap()), tangent_edges: Some(TangentEdges::Show), ..ViewOverrides::default() }; + add(&mut d, bolt_sheet, iso, ViewPlace::At([105.0, 148.5]), full_size, 5.0); d.validate().unwrap(); d } @@ -43,7 +66,7 @@ fn plate() -> Drawing { /// One A4 sheet that documents nothing, no sources: the base the caps grow from. fn bare() -> Drawing { let a4 = drawing_sheet::Sheet::standard(PaperSize::A4, Orientation::Landscape); - Drawing::new("Bare", "en", "Sheet", a4, None, &mut IdSource::seeded(SEED)).unwrap() + Drawing::new("Bare", "en", "Sheet", a4, None, &BTreeSet::new(), &mut IdSource::seeded(SEED)).unwrap() } fn file(d: &Drawing) -> Value { @@ -78,17 +101,14 @@ fn a_drawing_reads_back_as_saved_and_saves_the_same_bytes_again() { assert_eq!(reopened.to_json().unwrap(), saved); assert_eq!(plate().to_json().unwrap(), saved, "a seeded run makes the same drawing"); let v = file(&d); - let [plate_id, bolt_id, bracket_id] = [0, 1, 2].map(|i| ids::encode(d.sources[i].id)); + let plate_id = ids::encode(d.sources[0].id); let [assembly_id, bolt_sheet_id] = [0, 1].map(|i| ids::encode(d.sheets[i].id)); - assert_eq!(assembly_id, "1ge30wkvq38r0", "the seed's first id, as splitmix64 gives it"); + assert_eq!(v["id"], "1ge30wkvq38r0", "the seed's first id, as splitmix64 gives it"); assert_eq!(v["format"], DRAWING.format_string(DRAWING.current())); assert_eq!(v.get("format_pending").is_some(), !DRAWING.pending_names().is_empty()); assert_eq!(v.get("next_id"), None); assert_eq!((&v["name"], &v["language"]), (&json!("Plate assembly"), &json!("en-GB"))); - assert_eq!( - v["sources"], - json!([{"id": plate_id, "path": "plate.solidcraft"}, {"id": bolt_id, "path": "../parts/bolt.solidcraft"}, {"id": bracket_id, "path": "bracket.solidcraft"}]) - ); + assert_eq!(v["sources"], json!([{"id": plate_id}])); assert_eq!(v["properties"], json!({"author": "Jane Doe"})); assert_eq!(v["units"], json!({"fixed": {"unit": "in"}})); assert_eq!((&v["sheets"][0]["id"], &v["sheets"][0]["dpi"]), (&json!(assembly_id), &json!(300.0))); @@ -100,7 +120,7 @@ fn a_drawing_reads_back_as_saved_and_saves_the_same_bytes_again() { json!({ "id": bolt_sheet_id, "name": "Bolt", "sheet": {"size": {"standard": "a4"}, "orientation": "portrait"}, "border": serde_json::to_value(own_border()).unwrap(), "dpi": 600.0, - "documents": {"source": bolt_id, "component": 0}, "excluded": {"count": false, "print": true} + "documents": {"source": plate_id, "component": 0}, "excluded": {"count": false, "print": true} }) ); } @@ -111,6 +131,7 @@ fn a_drawing_reads_back_as_saved_and_saves_the_same_bytes_again() { fn a_file_may_leave_out_what_has_a_default() { let minimal = json!({ "format": DRAWING.format_string(1), + "id": "0000000000002", "name": "Bracket", "sources": [], "language": "de", @@ -125,7 +146,7 @@ fn a_file_may_leave_out_what_has_a_default() { let mut spelt = minimal.clone(); spelt["format"] = json!("solidcraft-drawing/+1"); assert_eq!(read(&spelt).unwrap().format, DRAWING.format_string(DRAWING.current())); - for key in ["name", "sources", "language", "sheets"] { + for key in ["id", "name", "sources", "language", "sheets"] { let mut v = minimal.clone(); v.as_object_mut().unwrap().remove(key); let why = refusal(&v); @@ -133,7 +154,7 @@ fn a_file_may_leave_out_what_has_a_default() { } } -/// Every cap on both sides: sheets, sources, the bytes of paths and names (two-byte characters too). +/// Every cap on both sides: sheets, sources, the bytes of names (two-byte characters too). #[test] fn every_cap_holds_on_both_sides() { let base = file(&bare()); @@ -155,18 +176,15 @@ fn every_cap_holds_on_both_sides() { for n in [0, 1001] { assert_eq!(refusal(&with("sheets", sheets(n))), "damaged drawing: a drawing has 1 to 1000 sheets", "{n} sheets"); } - // Sources from id 1: the sheet's id is the seed's, far from them. - let sources = |n: u64| Value::Array((1..=n).map(|id| json!({"id": ids::encode(id), "path": format!("part{id}.solidcraft")})).collect()); - assert_eq!(read(&with("sources", sources(64))).unwrap().sources.len(), 64); - assert_eq!(refusal(&with("sources", sources(65))), "damaged drawing: a drawing draws at most 64 designs"); - let path = |p: &str| refusal(&with("sources", json!([{"id": ids::encode(1), "path": p}]))); - for fits in ["a".repeat(4096), "é".repeat(2048), "/".into()] { - assert_eq!(path(fits.as_str()), "read", "{} bytes", fits.len()); - } - let rule = "damaged drawing: source 0000000000001: a design's path is 1 to 4096 bytes, without NUL"; - for broken in ["a".repeat(4097), "é".repeat(2048) + "a", String::new(), "plate\0.solidcraft".into()] { - assert_eq!(path(broken.as_str()), rule, "{} bytes", broken.len()); + // Sources from id 1: the drawing's and the sheet's ids are the seed's, far from them. A drawing + // draws the design it is in, by an id alone: a path is a field this build doesn't know. + let sources = |n: u64| Value::Array((1..=n).map(|id| json!({"id": ids::encode(id)})).collect()); + for n in [0, 1] { + assert_eq!(read(&with("sources", sources(n))).unwrap().sources.len(), n as usize); } + assert_eq!(refusal(&with("sources", sources(2))), "damaged drawing: a drawing draws only the design it is in"); + let with_path = refusal(&with("sources", json!([{"id": ids::encode(1), "path": "plate.solidcraft"}]))); + assert!(with_path.starts_with("damaged drawing: unknown field `path`"), "{with_path}"); let names = |name: &str| { let mut sheet_named = base.clone(); sheet_named["sheets"][0]["name"] = json!(name); @@ -248,29 +266,49 @@ fn a_border_is_saved_as_a_copy_of_its_profile() { assert_eq!(read(&edited).unwrap().sheets[0].border, None, "no drawing border"); } +/// A sheet's drawing goes inside its drawing border: 10 mm in from each edge with the ISO border, +/// 20 mm on the left with a filing margin, and the whole paper with no border. +#[test] +fn a_sheets_drawing_space_is_inside_its_border_or_the_whole_paper() { + let d = plate(); + let space = |sheet: &Sheet| sheet.drawing_space().map(|b| (b.min, b.max)).unwrap(); + assert_eq!(space(&d.sheets[0]), (Vec2::new(10.0, 10.0), Vec2::new(410.0, 287.0)), "A3 landscape, ISO"); + assert_eq!(space(&d.sheets[1]), (Vec2::new(20.0, 10.0), Vec2::new(200.0, 287.0)), "A4 portrait, filing margin"); + let bare = Sheet { border: None, ..(*d.sheets[0]).clone() }; + assert_eq!(space(&bare), (Vec2::ZERO, Vec2::new(420.0, 297.0)), "no border"); + let low = drawing_sheet::Sheet { size: SheetSize::Custom { sides_mm: [20.5, 297.0] }, ..d.sheets[0].sheet }; + let narrow = Sheet { sheet: low, ..(*d.sheets[0]).clone() }; + assert!(narrow.drawing_space().is_err(), "margins that leave no drawing space"); +} + /// What reading refuses: each damage the rules name, refused rather than patched, and files this /// build can't read. #[test] fn damaged_files_are_refused_and_never_patched() { let d = plate(); - let plate_id = ids::encode(d.sources[0].id); + let (drawing_id, plate_id) = (ids::encode(d.id), ids::encode(d.sources[0].id)); let [assembly_id, bolt_sheet_id] = [0, 1].map(|i| ids::encode(d.sheets[i].id)); - // Two objects with one id, of one kind and of two kinds. - assert_eq!(refused(&d, |v| v["sources"][1]["id"] = json!(plate_id)), format!("damaged drawing: two objects have the id {plate_id}")); - assert_eq!(refused(&d, |v| v["sheets"][1]["id"] = json!(assembly_id)), format!("damaged drawing: two objects have the id {assembly_id}")); - assert_eq!(refused(&d, |v| v["sources"][2]["id"] = json!(bolt_sheet_id)), format!("damaged drawing: two objects have the id {bolt_sheet_id}")); + // Two objects with one id, of one kind and of two kinds, the drawing itself among them. + let two = |id: &str| format!("damaged drawing: two objects have the id {id}"); + assert_eq!(refused(&d, |v| v["sources"][0]["id"] = json!(drawing_id)), two(&drawing_id)); + assert_eq!(refused(&d, |v| v["sheets"][1]["id"] = json!(assembly_id)), two(&assembly_id)); + assert_eq!(refused(&d, |v| v["sources"][0]["id"] = json!(bolt_sheet_id)), two(&bolt_sheet_id)); + assert_eq!(refused(&d, |v| v["id"] = json!(assembly_id)), two(&assembly_id)); // An id that isn't one, where an object has it and where a reference names it; no number form, // and no counter. let not_an_id = "damaged drawing: an id is 13 characters of lowercase Crockford base32, not all 0"; for text in ["0000000000000", "FZZZZZZZZZZZZ", "000000000001", "0000000000001 ", "000000000000o", "g000000000000"] { - assert_eq!(refused(&d, |v| v["sources"][2]["id"] = json!(text)), not_an_id, "{text:?}"); + assert_eq!(refused(&d, |v| v["id"] = json!(text)), not_an_id, "{text:?}"); + assert_eq!(refused(&d, |v| v["sources"][0]["id"] = json!(text)), not_an_id, "{text:?}"); assert_eq!(refused(&d, |v| v["sheets"][1]["documents"]["source"] = json!(text)), not_an_id, "{text:?}"); } - assert!(refused(&d, |v| v["sources"][2]["id"] = json!(5)).starts_with("damaged drawing: invalid type")); + assert!(refused(&d, |v| v["sources"][0]["id"] = json!(5)).starts_with("damaged drawing: invalid type")); assert!(refused(&d, |v| v["next_id"] = json!(6)).contains("unknown field `next_id`")); - let mut in_memory = d.clone(); - in_memory.sources[2].id = 0; - assert_eq!(in_memory.validate().unwrap_err().to_string(), "an object has the id 0, which is never one"); + for zero in [|d: &mut Drawing| d.id = 0, |d: &mut Drawing| d.sources[0].id = 0] { + let mut in_memory = d.clone(); + zero(&mut in_memory); + assert_eq!(in_memory.validate().unwrap_err().to_string(), "an object has the id 0, which is never one"); + } // A reference to nothing, or to an object of another kind; a source a sheet documents removed. for missing in [ids::encode(99), assembly_id.clone()] { let expected = format!("damaged drawing: sheet {bolt_sheet_id}: it documents source {missing}, which the drawing doesn't have"); @@ -282,7 +320,15 @@ fn damaged_files_are_refused_and_never_patched() { assert_eq!(without_plate, format!("damaged drawing: sheet {assembly_id}: it documents source {plate_id}, which the drawing doesn't have")); // The paper, its border and its resolution, through the sheet's own rules. let custom = |sides: Value| refused(&d, |v| v["sheets"][0]["sheet"]["size"] = json!({"custom": {"sides_mm": sides}})); - assert_eq!(custom(json!([5000.0, 0.5])), "read"); + assert_eq!(custom(json!([5000.0, 100.0])), "read"); + // A side the border's margins fill leaves no drawing space; without a border it is paper. + let no_space = format!("damaged drawing: sheet {assembly_id}: drawing sheet: the margins leave no drawing space"); + assert_eq!(custom(json!([5000.0, 0.5])), no_space); + let bare = refused(&d, |v| { + v["sheets"][0]["sheet"]["size"] = json!({"custom": {"sides_mm": [5000.0, 0.5]}}); + v["sheets"][0]["border"] = Value::Null; + }); + assert_eq!(bare, "read"); for sides in [json!([5000.1, 100.0]), json!([0.0, 100.0]), json!([-1.0, 100.0])] { let expected = format!("damaged drawing: sheet {assembly_id}: drawing sheet: a custom side is finite, above 0 and at most 5000 mm"); assert_eq!(custom(sides), expected); @@ -312,7 +358,7 @@ fn damaged_files_are_refused_and_never_patched() { assert!(in_memory.validate().unwrap_err().to_string().starts_with(&format!("sheet {bolt_sheet_id}: drawing sheet: a custom side"))); // An unknown field anywhere. let unknown: [fn(&mut Value); 8] = [ - |v| v["views"] = json!([]), + |v| v["annotations"] = json!([]), |v| v["sources"][0]["name"] = json!("Plate"), |v| v["sheets"][0]["scale"] = json!(1), |v| v["sheets"][0]["sheet"]["colour"] = json!("white"), @@ -330,7 +376,7 @@ fn damaged_files_are_refused_and_never_patched() { let (current, newer) = (DRAWING.current(), DRAWING.current() + 1); let why = refused(&d, |v| { v["format"] = json!(DRAWING.format_string(newer)); - v["views"] = json!([]); + v["annotations"] = json!([]); v["sheets"][0]["dpi"] = json!(1e10); }); assert_eq!( @@ -360,8 +406,8 @@ fn damaged_files_are_refused_and_never_patched() { assert_eq!(Drawing::from_json("[]").unwrap_err().to_string(), "not a SolidCraft drawing (expected a JSON object)"); assert!(Drawing::from_json("").unwrap_err().to_string().starts_with("not a SolidCraft drawing: ")); let deep: Value = serde_json::from_str(&format!("{}1{}", "[".repeat(100), "]".repeat(100))).unwrap(); - assert_eq!(refused(&d, |v| v["views"] = deep), "damaged drawing: nested too deeply"); - let deeper = format!("{{\"format\": \"{drawing_format}\", \"views\": {}1{}}}", "[".repeat(200), "]".repeat(200)); + assert_eq!(refused(&d, |v| v["annotations"] = deep), "damaged drawing: nested too deeply"); + let deeper = format!("{{\"format\": \"{drawing_format}\", \"annotations\": {}1{}}}", "[".repeat(200), "]".repeat(200)); assert!(Drawing::from_json(&deeper).unwrap_err().to_string().starts_with("not a SolidCraft drawing: ")); let text = d.to_json().unwrap(); let at_cap = text.clone() + &" ".repeat(MAX_DRAWING_BYTES - text.len()); @@ -375,14 +421,14 @@ fn damaged_files_are_refused_and_never_patched() { fn a_run_never_gives_an_id_twice() { let mut id_source = IdSource::seeded(SEED); let a4 = drawing_sheet::Sheet::standard(PaperSize::A4, Orientation::Landscape); - let mut d = Drawing::new("Ids", "en", "Sheet", a4, None, &mut id_source).unwrap(); - let mut given = BTreeSet::from([d.sheets[0].id]); - for _ in 0..MAX_SOURCES { + let mut d = Drawing::new("Ids", "en", "Sheet", a4, None, &BTreeSet::new(), &mut id_source).unwrap(); + let mut given = BTreeSet::from([d.id, d.sheets[0].id]); + for _ in 0..64 { let id = d.allocate_id(&mut id_source).unwrap(); - d.sources.push(Source { id, path: "part.solidcraft".into() }); + d.sheets.push(Arc::new(Sheet { id, ..(*d.sheets[0]).clone() })); assert!(given.insert(id), "{id:#x} given twice"); } - let removed = d.sources.pop().unwrap().id; + let removed = d.sheets.pop().map_or(0, |s| s.id); for _ in 0..10_000 { let id = d.allocate_id(&mut id_source).unwrap(); assert!(id != removed && given.insert(id), "{id:#x} given twice"); @@ -420,7 +466,7 @@ fn a_drawing_too_large_to_reopen_is_not_saved() { let sheet = r#"{"id":"0000000000001","name":"S","sheet":{"size":{"standard":"a4"}}}"#; let format = DRAWING.format_string(1); format!( - r#"{{"format":"{format}","name":"A","sources":[],"language":"en","sheets":[{sheet}],"properties":{{"com.example":{{"items":[{items}]}}}}}}"# + r#"{{"format":"{format}","id":"0000000000002","name":"A","sources":[],"language":"en","sheets":[{sheet}],"properties":{{"com.example":{{"items":[{items}]}}}}}}"# ) }; // The case found in review (#3891): 2,000,000 zeros read in at about 4 MB and indent past 16 MiB. @@ -430,19 +476,24 @@ fn a_drawing_too_large_to_reopen_is_not_saved() { assert_eq!(Drawing::from_json(&small.to_json().unwrap()).unwrap(), small); } -/// A new drawing has one sheet, its id the source's first, follows its designs' units and renders -/// pictures at 300 dpi; a name, language or border that breaks the rules is refused. +/// A new drawing has one sheet, the drawing's id the source's first and the sheet's the next, +/// follows its designs' units and renders pictures at 300 dpi; its id is none of its design's other +/// drawings'; a name, language or border that breaks the rules is refused. #[test] fn a_new_drawing_has_one_sheet_and_keeps_the_rules() { let d = bare(); - let first = IdSource::seeded(SEED).next(&BTreeSet::new()).unwrap(); - assert_eq!((d.sheets.len(), d.sheets[0].id, d.sheets[0].dpi, &d.units), (1, first, DEFAULT_DPI, &Units::FollowModel)); + let mut seeded = IdSource::seeded(SEED); + let first = seeded.next(&BTreeSet::new()).unwrap(); + let second = seeded.next(&BTreeSet::new()).unwrap(); + assert_eq!((d.id, d.sheets.len(), d.sheets[0].id, d.sheets[0].dpi, &d.units), (first, 1, second, DEFAULT_DPI, &Units::FollowModel)); assert_eq!((d.format, d.format_pending), (DRAWING.format_string(DRAWING.current()), DRAWING.pending_names())); let a4 = drawing_sheet::Sheet::standard(PaperSize::A4, Orientation::Landscape); + let beside = Drawing::new("Beside", "en", "Sheet", a4, None, &BTreeSet::from([first]), &mut IdSource::seeded(SEED)).unwrap(); + assert!(beside.id != first && beside.sheets[0].id != beside.id, "the design's drawing keeps its id"); let thin = DrawingBorderProfile { drawing_border_line_mm: 0.0, ..DrawingBorderProfile::iso() }; let broken = [("", "en", "Sheet", None), ("Bare", "en_GB", "Sheet", None), ("Bare", "en", "\n", None), ("Bare", "en", "Sheet", Some(thin))]; for (name, language, sheet, border) in broken { - let made = Drawing::new(name, language, sheet, a4, border, &mut IdSource::seeded(SEED)); + let made = Drawing::new(name, language, sheet, a4, border, &BTreeSet::new(), &mut IdSource::seeded(SEED)); assert!(made.is_err(), "{name:?} {language:?} {sheet:?} {border:?}"); } } @@ -518,6 +569,75 @@ fn mutated_files_give_an_error_or_a_valid_drawing_never_a_panic() { assert!(read_back > 50, "only {read_back} mutated files read: the mutations hardly reach the record's rules"); } +/// A design holding drawings, as plain JSON: each drawing inline under `drawings`, as its own +/// record with its own format. While the change is pending the design names `drawings` in its +/// `format_pending`, so a build without it refuses the design (`format::tests`) rather than open it +/// and save it without them. They read back in their order, by name, then id, and save as the same +/// bytes; a design without drawings writes no `drawings`. +#[test] +fn a_design_keeps_its_drawings_inline_in_plain_json() { + let named = |name: &str, id: u64| Arc::new(Drawing { name: name.into(), id, ..plate() }); + let mut doc = crate::Document::new("Plate"); + doc.drawings = vec![named("Details", 7), Arc::new(plate()), named("Details", 3), named("Assembly", u64::MAX)]; + let read = crate::Document::from_json(&doc.to_json()).unwrap(); + let order: Vec<_> = read.drawings.iter().map(|d| (d.name.as_str(), d.id)).collect(); + assert_eq!(order, [("Assembly", u64::MAX), ("Details", 3), ("Details", 7), ("Plate assembly", plate().id)]); + let saved = read.to_json(); + assert_eq!(crate::Document::from_json(&saved).unwrap().to_json(), saved, "save, open, save: the same bytes"); + let v: Value = serde_json::from_str(&saved).unwrap(); + assert_eq!(v["drawings"][3], file(&plate())); + assert!(v["format_pending"].as_array().is_some_and(|names| names.contains(&json!("drawings"))), "{}", v["format_pending"]); + let empty: Value = serde_json::from_str(&crate::Document::new("Plate").to_json()).unwrap(); + assert_eq!(empty.get("drawings"), None); +} + +/// What a design refuses in its drawings, each time the whole design, never by dropping a drawing: +/// one a newer build saved (a newer number, or a change this build doesn't know), a damaged one, +/// `drawings` that isn't a list, two with one id, and more than a design may hold, counted before +/// any is read. A drawing's numbers are its own family's to check: other tools' data in its +/// properties is kept, a sheet's number out of range refused. +#[test] +fn a_drawing_a_design_cant_read_refuses_the_design() { + let mut doc = crate::Document::new("Plate"); + doc.drawings = vec![Arc::new(plate())]; + let design: Value = serde_json::from_str(&doc.to_json()).unwrap(); + let refused = |edit: &dyn Fn(&mut Value)| { + let mut v = design.clone(); + edit(&mut v); + crate::Document::from_json(&v.to_string()).map_or_else(|e| e.to_string(), |d| format!("read {}", d.drawings.len())) + }; + let (current, newer) = (DRAWING.current(), DRAWING.current() + 1); + assert_eq!( + refused(&|v| v["drawings"][0]["format"] = json!(DRAWING.format_string(newer))), + format!( + "drawing 1: this drawing was saved by a newer SolidCraft (file format {newer}; this version reads formats up to {current}): update SolidCraft to open it" + ) + ); + let later = refused(&|v| v["drawings"][0]["format_pending"] = json!(["a-later-change"])); + assert!(if DRAWING.pending_names().is_empty() { later == "read 1" } else { later.contains("newer SolidCraft") }, "{later}"); + let damaged = refused(&|v| v["drawings"][0]["language"] = json!("e")); + assert!(damaged.starts_with("drawing 1: damaged drawing: the language"), "{damaged}"); + assert_eq!(refused(&|v| v["drawings"] = json!({})), "damaged design: `drawings` is not a list"); + let twice = refused(&|v| { + let again = v["drawings"][0].clone(); + v["drawings"].as_array_mut().unwrap().push(again); + }); + assert_eq!(twice, format!("damaged design: two drawings have the id {}", ids::encode(plate().id))); + let at_cap: Vec = (1..=MAX_DRAWINGS as u64) + .map(|id| { + let mut d = file(&plate()); + d["id"] = json!(ids::encode(id)); + d + }) + .collect(); + assert_eq!(refused(&|v| v["drawings"] = Value::Array(at_cap.clone())), format!("read {MAX_DRAWINGS}")); + let over = refused(&|v| v["drawings"] = Value::Array(vec![json!({}); MAX_DRAWINGS + 1])); + assert_eq!(over, format!("damaged design: a design holds at most {MAX_DRAWINGS} drawings")); + assert_eq!(refused(&|v| v["drawings"][0]["properties"]["com.example"] = json!({"huge": 1e300})), "read 1"); + let out_of_range = refused(&|v| v["drawings"][0]["sheets"][0]["dpi"] = json!(1e300)); + assert!(out_of_range.starts_with("drawing 1: damaged drawing: the number "), "{out_of_range}"); +} + /// The number of values in `v`, itself included. fn count(v: &Value) -> usize { 1 + match v { diff --git a/crates/doc/src/drawing_view.rs b/crates/doc/src/drawing_view.rs new file mode 100644 index 00000000000..8f63bf9f6c4 --- /dev/null +++ b/crates/doc/src/drawing_view.rs @@ -0,0 +1,132 @@ +//! A drawing view's settings (W07, #5866): which way it looks, its scale and how it draws. +//! `drawing.view.snapshot` takes them whole; a saved view (W12) keeps the same fields, each one +//! optional so that a projected view can follow its parent. + +use serde::{Deserialize, Deserializer, Serialize}; +use solidcraft_geom::Plane; +use solidcraft_geom::drawing_view::{Invalid, NamedView, Scale, basis_looking}; +use solidcraft_render::VisualStyle; + +/// The largest reference margin, in model millimetres. +pub const MAX_REFERENCE_MARGIN_MM: f64 = 1e5; + +/// Which way a view looks: by name, or along any direction with an up. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(untagged)] +pub enum ViewDirection { + Named(NamedView), + Looking(Looking), +} + +/// A view along `direction` with `up` toward the top of the paper, through `origin` (the world +/// origin when not given). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Looking { + pub direction: [f64; 3], + pub up: [f64; 3], + #[serde(default)] + pub origin: [f64; 3], +} + +impl<'de> Deserialize<'de> for ViewDirection { + /// One message for anything that is neither, rather than serde's "did not match any variant". + fn deserialize>(d: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Either { + Named(NamedView), + Looking(Looking), + } + let message = "view is front, back, top, bottom, left, right, iso, iso_front_right, iso_front_left, iso_back_right, iso_back_left, or {direction, up, origin?}"; + Ok(match Either::deserialize(d).map_err(|_| serde::de::Error::custom(message))? { + Either::Named(view) => ViewDirection::Named(view), + Either::Looking(looking) => ViewDirection::Looking(looking), + }) + } +} + +impl Default for ViewDirection { + fn default() -> Self { + ViewDirection::Named(NamedView::Front) + } +} + +impl ViewDirection { + /// The view's basis: a named view's exact one, or one built from the direction and up. + pub fn basis(&self) -> Result { + match *self { + ViewDirection::Named(view) => Ok(view.basis()), + ViewDirection::Looking(Looking { direction, up, origin }) => basis_looking(direction.into(), up.into(), origin.into()), + } + } +} + +/// Tangent edges, where faces meet smoothly: left out (the default) or drawn. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TangentEdges { + #[default] + Hide, + Show, +} + +/// What a view shows and how. Every field has a default: the front view at the scale that fits +/// its page, visible lines only, tangent edges hidden. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ViewSettings { + pub view: ViewDirection, + /// None: the largest preset scale at which the view fits its page ([`Scale::fit`]). Not + /// written when None: a snapshot refuses a null scale. + #[serde(skip_serializing_if = "Option::is_none")] + pub scale: Option, + pub display_style: VisualStyle, + /// How reference parts draw (bill of materials type `reference`). + pub reference_style: VisualStyle, + /// Whether reference parts hide the model's lines behind them. + pub reference_hides_model: bool, + /// Model millimetres added on every side of the view's extents, so reference parts around the + /// model show inside its boundary: 0 to [`MAX_REFERENCE_MARGIN_MM`]. + pub reference_margin_mm: f64, + pub tangent_edges: TangentEdges, +} + +/// The settings a saved view sets itself, each on its own: one left out follows the view's parent, +/// then [`ViewSettings`]'s default ([`crate::drawing::Drawing::resolve_view`]). None is written. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ViewOverrides { + #[serde(skip_serializing_if = "Option::is_none")] + pub scale: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub display_style: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reference_style: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reference_hides_model: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub tangent_edges: Option, +} + +impl ViewOverrides { + /// Sets nothing: every setting follows. + pub fn is_empty(&self) -> bool { + *self == ViewOverrides::default() + } +} + +impl ViewSettings { + /// What reading alone can't check: the margin's range and the view's basis. + pub fn validate(&self) -> Result { + let margin = self.reference_margin_mm; + if !(margin.is_finite() && (0.0..=MAX_REFERENCE_MARGIN_MM).contains(&margin)) { + return Err(Invalid("reference_margin_mm is a number of model millimetres from 0 to 100000")); + } + self.view.basis() + } +} + +#[cfg(test)] +#[path = "drawing_view_tests.rs"] +mod tests; diff --git a/crates/doc/src/drawing_view_tests.rs b/crates/doc/src/drawing_view_tests.rs new file mode 100644 index 00000000000..00f3d5c85f7 --- /dev/null +++ b/crates/doc/src/drawing_view_tests.rs @@ -0,0 +1,55 @@ +use serde_json::json; +use solidcraft_geom::Vec3; + +use super::*; + +/// Every field has its default, and the settings read and write back the same. +#[test] +fn view_settings_default_to_a_front_view_that_fits_its_page() { + let settings: ViewSettings = serde_json::from_value(json!({})).unwrap(); + assert_eq!(settings, ViewSettings::default()); + assert_eq!(settings.view, ViewDirection::Named(NamedView::Front)); + assert_eq!((settings.scale, settings.display_style, settings.tangent_edges), (None, VisualStyle::Visible, TangentEdges::Hide)); + assert_eq!(settings.validate().unwrap(), NamedView::Front.basis()); + assert_eq!(serde_json::to_value(settings).unwrap().get("scale"), None, "no scale is written, not null"); + let full = json!({ + "view": {"direction": [0.0, 1.0, 0.0], "up": [0.0, 0.0, 1.0], "origin": [1.0, 2.0, 3.0]}, + "scale": "1:2", "display_style": "visible_hidden", "reference_style": "shaded", + "reference_hides_model": true, "reference_margin_mm": 5.0, "tangent_edges": "show", + }); + let read: ViewSettings = serde_json::from_value(full.clone()).unwrap(); + assert_eq!(serde_json::to_value(read).unwrap(), full); + assert_eq!(read.validate().unwrap().origin, Vec3::new(1.0, 2.0, 3.0)); + let iso: ViewSettings = serde_json::from_value(json!({"view": "iso"})).unwrap(); + assert_eq!(iso.view, ViewDirection::Named(NamedView::IsoFrontRight)); +} + +/// What the settings refuse: unknown fields, unknown names, a basis that can't be built and a +/// margin out of range. +#[test] +fn view_settings_refuse_what_they_cant_draw() { + for not_settings in [ + json!({"scael": "1:2"}), + json!({"view": 3}), + json!({"view": "Front"}), + json!({"view": {"direction": [0, 1, 0]}}), + json!({"view": {"direction": [0, 1, 0], "up": [0, 0, 1], "roll": 1}}), + json!({"scale": 0.5}), + json!({"display_style": "hidden"}), + json!({"tangent_edges": "thin"}), + ] { + assert!(serde_json::from_value::(not_settings.clone()).is_err(), "{not_settings}"); + } + let refused = [ + json!({"view": {"direction": [0, 0, 0], "up": [0, 0, 1]}}), + json!({"view": {"direction": [0, 0, 1], "up": [0, 0, -1]}}), + json!({"reference_margin_mm": -0.001}), + json!({"reference_margin_mm": 100000.001}), + ]; + for settings in refused { + let read: ViewSettings = serde_json::from_value(settings.clone()).unwrap(); + assert!(read.validate().is_err(), "{settings}"); + } + let edge: ViewSettings = serde_json::from_value(json!({"reference_margin_mm": 100000.0})).unwrap(); + assert!(edge.validate().is_ok()); +} diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 4eba4b2dd86..1e083ac059c 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -198,6 +198,23 @@ impl ModelBody { }) } + /// The box of [`ModelBody::mesh`] seen on a plane, in the plane's own coordinates + /// ([`Plane::to_local`]): a drawing view's extents (W07), again without making a placement's + /// moved copy. + pub fn mesh_bounds_in(&self, plane: &Plane) -> solidcraft_geom::Aabb2 { + let (mesh, m) = match self.cached_mesh() { + Some(mesh) => (mesh, crate::IDENTITY), + None => self.mesh_in_place(), + }; + // The placement folded into each of the plane's axes: a mesh point p lands at + // p · axis + offset, with no moved copy of the point made first. + let [c0, c1, c2, t] = m.map(|r| Vec3::new(r[0], r[1], r[2])); + let offset = t - plane.origin; + let axis = |a: Vec3| (Vec3::new(c0.dot(a), c1.dot(a), c2.dot(a)), offset.dot(a)); + let ((ax, ox), (ay, oy)) = (axis(plane.x), axis(plane.y)); + mesh.positions.iter().map(|p| Vec2::new(p.dot(ax) + ox, p.dot(ay) + oy)).collect() + } + /// [`ModelBody::plan_mesh_at`] as a shared mesh and the move that places it, as /// [`ModelBody::mesh_in_place`] does for the reference mesh. pub fn plan_mesh_in_place_at(&self, q: crate::display_quality::DisplayQuality) -> Option<(Arc, crate::Mat)> { diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index b522c93f2bc..5bf021e27ae 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -656,6 +656,8 @@ fn v2_to_v3(v: &mut Value) -> Result<()> { pub fn read(s: &str) -> Result { let mut v: Value = serde_json::from_str(s).map_err(|e| DocError::Invalid(format!("not a SolidCraft design: {e}")))?; let (version, applied) = DESIGN.take_version(&mut v)?; + // Each drawing is a record of its own family, read by its own rules, numbers and all. + let drawings = take_drawings(&mut v)?; DESIGN.check_numbers(&v, "metadata")?; crate::config::validate_rules_json(&v)?; crate::config::validate_styles_json(&v)?; @@ -768,11 +770,22 @@ pub fn read(s: &str) -> Result { // These lists used to allocate independently. Keep their existing identities, but never // let a later deletion make them available again after loading an older design. d.next_id = d.next_item_id()?; + d.drawings = crate::drawing::in_design(drawings).map_err(|e| DocError::Invalid(format!("damaged design: {e}")))?; d.format = format_string(FORMAT); d.format_pending = pending_names(); Ok(d) } +/// Take a plain JSON design's drawings out of its JSON and read each, before the design's own +/// rules see anything: a drawing this build can't read refuses the design, never dropped. +fn take_drawings(v: &mut Value) -> Result> { + let Some(list) = v.as_object_mut().and_then(|o| o.remove("drawings")) else { return Ok(Vec::new()) }; + let Value::Array(list) = list else { return Err(DocError::Invalid("damaged design: `drawings` is not a list".into())) }; + crate::drawing::check_count(list.len()).map_err(|e| DocError::Invalid(format!("damaged design: {e}")))?; + let read = |(i, d): (usize, Value)| crate::drawing::Drawing::from_value(d).map_err(|e| DocError::Invalid(format!("drawing {}: {e}", i + 1))); + list.into_iter().enumerate().map(read).collect() +} + fn all_unique(ids: impl Iterator) -> bool { let mut seen = std::collections::BTreeSet::new(); ids.into_iter().all(|id| seen.insert(id)) diff --git a/crates/doc/src/format/pending/drawings.rs b/crates/doc/src/format/pending/drawings.rs new file mode 100644 index 00000000000..1049a0e5344 --- /dev/null +++ b/crates/doc/src/format/pending/drawings.rs @@ -0,0 +1,5 @@ +//! A design holds its drawings (#3890): `drawings`, each a drawing record of its own family +//! (`solidcraft-drawing/N`, `crate::drawing`). A design container keeps each drawing in its own +//! entry, `drawings/.json`, beside `document.json`; a plain JSON design keeps them inline. +//! Older designs need no transformation: they hold no drawings. The last release refuses a design +//! saved with this (the newer format number), so it never opens one and saves it without them. diff --git a/crates/doc/src/ids.rs b/crates/doc/src/ids.rs index 2e741ff2eaf..d3146bd6f79 100644 --- a/crates/doc/src/ids.rs +++ b/crates/doc/src/ids.rs @@ -51,6 +51,12 @@ impl IdSource { IdSource::seeded(RandomState::new().hash_one((nanos, MADE.fetch_add(1, Ordering::Relaxed)))) } + /// Where the source stands: [`IdSource::seeded`] with it gives the ids this one gives next + /// (a replay's start). + pub fn seed(&self) -> u64 { + self.state + } + /// The next id that isn't 0 and isn't `in_use`. A run never draws a number twice, so at most /// one draw per id in use, and one 0, come before a free one. pub fn next(&mut self, in_use: &BTreeSet) -> Result { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c68da3053aa..2a40409dfba 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -20,6 +20,7 @@ pub mod display_quality; pub mod display_units; mod document; pub mod drawing; +pub mod drawing_view; mod eval; pub mod expr; pub mod face_anchor; diff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rs index 2131f89db86..130b302a57b 100644 --- a/crates/doc/src/placed_mesh.rs +++ b/crates/doc/src/placed_mesh.rs @@ -133,6 +133,8 @@ fn proper_rigid(m: &crate::Mat) -> bool { } #[cfg(test)] mod tests { + use solidcraft_geom::{Plane, Vec2}; + use super::*; #[test] @@ -162,6 +164,32 @@ mod tests { assert!(Arc::ptr_eq(&mesh, &nested.mesh())); } + /// A block 100 x 50 x 20 mm seen on a view's plane measures as worked by hand: its size along + /// each principal pair of axes, and from an isometric corner (150/sqrt(2) wide, 190/sqrt(6) + /// high; the box's extremes are its corners, so the mesh gives them exactly). A body meshed + /// already is measured from its own mesh. + #[test] + fn a_bodys_bounds_on_a_plane_are_its_mesh_seen_on_it() { + let block = ModelBody::new("Block".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(100., 50., 20.)).unwrap(), 1); + let plane = |x: Vec3, y: Vec3| Plane { origin: Vec3::ZERO, x, y }; + let iso_x = Vec3::new(1., 1., 0.) * (1. / 2f64.sqrt()); + let iso_y = Vec3::new(-1., 1., 2.) * (1. / 6f64.sqrt()); + let views = [ + (plane(Vec3::X, Vec3::Z), (100., 20.)), + (plane(Vec3::X, Vec3::Y), (100., 50.)), + (plane(Vec3::Y, Vec3::Z), (50., 20.)), + (plane(iso_x, iso_y), (150. / 2f64.sqrt(), 190. / 6f64.sqrt())), + ]; + for (basis, (w, h)) in views { + let size = block.mesh_bounds_in(&basis).size(); + assert!((size.x - w).abs() < 1e-9 && (size.y - h).abs() < 1e-9, "{basis:?}: {size:?}"); + } + assert!(block.cached_mesh().is_some(), "an unplaced body measures its own mesh"); + let moved = Plane { origin: Vec3::new(30., 0., 5.), ..plane(Vec3::X, Vec3::Z) }; + let b = block.mesh_bounds_in(&moved); + assert!(b.min.dist(Vec2::new(-30., -5.)) < 1e-9 && b.max.dist(Vec2::new(70., 15.)) < 1e-9, "{b:?}"); + } + /// A placement hands out its definition's own meshes and its move without making the moved /// copy: every placement of a part gives the same mesh, and that mesh moved is the /// placement's own. @@ -185,13 +213,23 @@ mod tests { let (mesh, m) = p.mesh_in_place(); assert!(Arc::ptr_eq(&mesh, &own), "the definition's mesh, not a copy"); let bounds = p.mesh_bounds(); + let tilted = Plane { origin: Vec3::new(1., 2., 3.), x: Vec3::new(0.6, 0.8, 0.), y: Vec3::Z }; + let seen = p.mesh_bounds_in(&tilted); assert!(p.cached_mesh().is_none(), "no moved copy is made"); let (plan_mesh, pm) = p.plan_mesh_in_place_at(q).unwrap(); assert!(Arc::ptr_eq(&plan_mesh, &source.plan_mesh_at(q).unwrap())); assert_eq!(pm, m); let moved = p.mesh(); + assert!(p.cached_mesh().is_some()); + let cached = p.mesh_bounds_in(&tilted); + assert!(cached.min.dist(seen.min) < 1e-9 && cached.max.dist(seen.max) < 1e-9, "a meshed placement measures its own mesh the same"); let exact = moved.bounds(); assert!(bounds.min.dist(exact.min) < 1e-9 && bounds.max.dist(exact.max) < 1e-9, "{bounds:?} vs {exact:?}"); + let on_plane = moved.positions.iter().fold(solidcraft_geom::Aabb2::EMPTY, |mut b, q| { + b.add(tilted.to_local(*q)); + b + }); + assert!(seen.min.dist(on_plane.min) < 1e-9 && seen.max.dist(on_plane.max) < 1e-9, "{seen:?} vs {on_plane:?}"); for (a, b) in mesh.positions.iter().zip(&moved.positions) { assert!(crate::apply_point(&m, *a).dist(*b) < 1e-9); } diff --git a/crates/engine/src/cmd/diagnostics.rs b/crates/engine/src/cmd/diagnostics.rs index 25a4756dcc4..bac6ec4e8fe 100644 --- a/crates/engine/src/cmd/diagnostics.rs +++ b/crates/engine/src/cmd/diagnostics.rs @@ -8,21 +8,22 @@ use crate::params::{bad, str_}; use crate::{EngineError, Result, Session, crash}; pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("diagnostics.crash_reports", "Crash Reports", list).icon("bug_report").noundo().params( + CommandSpec::new("diagnostics.crash_reports", "Crash Reports", list).any_part().icon("bug_report").noundo().params( "limit?: number (default 20). Lists this computer's crash reports, newest first: {dir, reports: [{id, kind, time, message, \ command, count, version, path, replayable}]}. kind: command_panic | panic | kernel_panic_recovered | unclean_exit. \ Read one with diagnostics.crash_report; reproduce it with `solidcraft-cli crashes replay `", ), - CommandSpec::new("diagnostics.crash_report", "Crash Report", read).icon("bug_report").noundo().params( + CommandSpec::new("diagnostics.crash_report", "Crash Report", read).any_part().icon("bug_report").noundo().params( "id: report id. The whole report: message, location, backtrace, app version and commit, system, the command that \ crashed and the recent ones, notes, and design_path / replay_path when the crash can be replayed \ (`solidcraft-cli run --in `)", ), CommandSpec::new("diagnostics.crash_reports.clear", "Delete Crash Reports", clear) + .any_part() .icon("delete") .noundo() .params("id?: one report (default: all). Returns {deleted}"), - CommandSpec::new("diagnostics.crash_test", "Crash Test", crash_test).icon("bug_report").noundo().enabled(crash_test_enabled).params( + CommandSpec::new("diagnostics.crash_test", "Crash Test", crash_test).any_part().icon("bug_report").noundo().enabled(crash_test_enabled).params( "mode: panic | kernel | abort. Checks that crash reports work: panic = an internal error in this command (caught; \ the design is unchanged), kernel = one inside the geometry kernel (caught), abort = the app ends at once (reported \ at the next start). Only when the SOLIDCRAFT_CRASH_TEST environment variable is set", diff --git a/crates/engine/src/cmd/drawing.rs b/crates/engine/src/cmd/drawing.rs new file mode 100644 index 00000000000..7894014c0a1 --- /dev/null +++ b/crates/engine/src/cmd/drawing.rs @@ -0,0 +1,230 @@ +//! Drawing commands (#3890, K4): make, list, open, close and delete a design's drawings, and read +//! and change the open drawing's own settings. A drawing lives in its design's file +//! ([`solidcraft_doc::Document::drawings`]); while one is open, the drawing commands change it and +//! the model's wait ([`super::Part`]). Each change of a drawing is one undo step of that drawing, +//! and evaluates nothing; making and deleting one are steps of the model, whose list of drawings +//! they change. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use serde_json::{Value, json}; +use solidcraft_doc::drawing::{self, Drawing, Source, Units}; +use solidcraft_doc::ids; +use solidcraft_geom::cell::Projection; +use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet}; + +use super::CommandSpec; +use crate::params::{bad, str_}; +use crate::{Result, Session}; + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("drawing.create", "Create Drawing", create).any_part().icon("new").doc_only().params( + "name?: the drawing's name (default: the design's); language?: the drawing's content language, a BCP 47 tag (default en); units?: \"follow_model\" (default) or one length unit such as \"mm\". Adds a drawing of this design, one ISO A3 landscape sheet with the ISO border, and opens it (one undo step of the model) → as drawing.inspect", + ), + CommandSpec::new("drawing.list", "List Drawings", list) + .any_part() + .icon("list") + .noundo() + .doc_only() + .params("→ drawings: [{id, name, sheets (how many), open}], by name, then id"), + CommandSpec::new("drawing.open", "Open Drawing", open) + .any_part() + .icon("open") + .noundo() + .doc_only() + .params("drawing: id (from drawing.list) → as drawing.inspect. The drawing commands then change it; the model's wait until drawing.close"), + CommandSpec::new("drawing.close", "Close Drawing", close) + .any_part() + .icon("close") + .noundo() + .doc_only() + .params("→ closed: the drawing's id, or null when none was open"), + CommandSpec::new("drawing.delete", "Delete Drawing", delete).any_part().icon("delete").doc_only().params( + "drawing: id → deleted: its id; closed when it was open (one undo step of the model)", + ), + CommandSpec::new("drawing.inspect", "Inspect Drawing", inspect).in_drawing().icon("inspect").noundo().doc_only().params( + "→ {id, name, units, projection, language, properties, sources: [{id}], sheets: [{id, name, size_mm, orientation, dpi, documents, excluded}]}. Read-only.", + ), + CommandSpec::new("drawing.set", "Drawing Settings", set) + .in_drawing() + .icon("settings") + .doc_only() + .params("name?, language?: a BCP 47 tag, units?: \"follow_model\" or one length unit such as \"mm\", projection?: first or third (angle), which every projected view follows. One undo step."), + CommandSpec::new("drawing.properties", "Drawing Properties", properties).in_drawing().icon("settings").noundo().doc_only().params( + "→ metadata: the drawing's properties as saved (other tools' keys too); properties: project, part_number, revision, author, organization, description and license, each its text or null. The design properties' rules (document.metadata).", + ), + CommandSpec::new("drawing.properties.set", "Change Drawing Properties", properties_set).in_drawing().icon("settings").doc_only().params( + "key and value, or values: {key: value, …} (all or nothing, one undo step), as document.metadata.set takes them → metadata, changed: [keys]", + ), + CommandSpec::new("drawing.properties.remove", "Remove Drawing Property", properties_remove) + .in_drawing() + .icon("delete") + .doc_only() + .params("key, or keys: [keys] → metadata, removed: [keys that were there]"), +]; + +/// `units` as given: `follow_model`, or a length unit the drawing's rules check. +fn units(cmd: &str, p: &Value) -> Result> { + match p.get("units") { + None => Ok(None), + Some(Value::String(u)) if u == "follow_model" => Ok(Some(Units::FollowModel)), + Some(Value::String(u)) => Ok(Some(Units::Fixed { unit: u.clone() })), + Some(_) => Err(bad(cmd, "`units` is \"follow_model\" or a length unit such as \"mm\"")), + } +} + +/// `projection` as given: first or third angle. +fn projection(cmd: &str, p: &Value) -> Result> { + match p.get("projection") { + None => Ok(None), + Some(v) => serde_json::from_value(v.clone()).map(Some).map_err(|_| bad(cmd, "`projection` is first or third (angle)")), + } +} + +/// An optional text parameter: absent, or a string. +fn text<'a>(cmd: &str, p: &'a Value, key: &str) -> Result> { + match p.get(key) { + None => Ok(None), + Some(_) => str_(p, key).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be text"))), + } +} + +/// The design's drawing `p.drawing` names, by id. +fn named(cmd: &str, s: &Session, p: &Value) -> Result { + let id = str_(p, "drawing").and_then(ids::decode).ok_or_else(|| bad(cmd, "`drawing` must be a drawing's id (drawing.list)"))?; + s.doc.drawing(id).map(|d| d.id).ok_or_else(|| bad(cmd, format!("the design has no drawing {}", ids::encode(id)))) +} + +fn create(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.create"; + if s.doc.features.is_empty() { + return Err(bad(cmd, "the design is empty: there is nothing to draw yet")); + } + drawing::check_count(s.doc.drawings.len() + 1).map_err(|e| bad(cmd, e.to_string()))?; + let name = text(cmd, p, "name")?.map_or_else(|| s.doc.name.clone(), str::to_string); + let language = text(cmd, p, "language")?.unwrap_or("en"); + // Not the id of a drawing undo or redo could bring back either. + let steps = s.undo.iter().chain(&s.redo).filter_map(|step| step.part); + let taken: BTreeSet = s.doc.drawings.iter().map(|d| d.id).chain(steps).collect(); + let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); + let fail = |e: solidcraft_doc::DocError| bad(cmd, e.to_string()); + let mut d = Drawing::new(&name, language, "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &taken, &mut s.ids).map_err(fail)?; + let source = d.allocate_id(&mut s.ids).map_err(fail)?; + d.sources.push(Source { id: source }); + if let Some(units) = units(cmd, p)? { + d.units = units; + } + d.validate().map_err(fail)?; + s.open_drawing = Some(d.id); + s.doc_mut().put_drawing(Arc::new(d)); + inspect(s, &Value::Null) +} + +fn list(s: &mut Session, _p: &Value) -> Result { + let listed: Vec = s + .doc + .drawings + .iter() + .map(|d| json!({"id": ids::encode(d.id), "name": d.name, "sheets": d.sheets.len(), "open": s.open_drawing == Some(d.id)})) + .collect(); + Ok(json!({"drawings": listed})) +} + +fn open(s: &mut Session, p: &Value) -> Result { + s.open_drawing = Some(named("drawing.open", s, p)?); + inspect(s, &Value::Null) +} + +fn close(s: &mut Session, _p: &Value) -> Result { + Ok(json!({"closed": s.open_drawing.take().map(ids::encode)})) +} + +fn delete(s: &mut Session, p: &Value) -> Result { + let id = named("drawing.delete", s, p)?; + if s.open_drawing == Some(id) { + s.open_drawing = None; + } + s.doc_mut().drawings.retain(|d| d.id != id); + Ok(json!({"deleted": ids::encode(id)})) +} + +/// The drawing open, as `drawing.inspect` answers, which making and opening one answer too. +fn inspect(s: &mut Session, _p: &Value) -> Result { + let cmd = "drawing.inspect"; + let d = s.drawing(cmd)?; + let mut sheets = Vec::with_capacity(d.sheets.len()); + for sheet in &d.sheets { + let size = sheet.sheet.size_mm().map_err(|e| bad(cmd, e.to_string()))?; + sheets.push(json!({ + "id": ids::encode(sheet.id), + "name": sheet.name, + "size_mm": [size.x, size.y], + "orientation": sheet.sheet.orientation, + "dpi": sheet.dpi, + "documents": sheet.documents.map(|c| json!({"source": ids::encode(c.source), "component": c.component})), + "excluded": sheet.excluded, + })); + } + Ok(json!({ + "id": ids::encode(d.id), + "name": d.name, + "units": d.units, + "projection": d.projection, + "language": d.language, + "properties": d.properties, + "sources": d.sources.iter().map(|source| json!({"id": ids::encode(source.id)})).collect::>(), + "sheets": sheets, + })) +} + +fn set(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.set"; + s.edit_drawing(cmd, |d| { + if let Some(name) = text(cmd, p, "name")? { + d.name = name.to_string(); + } + if let Some(language) = text(cmd, p, "language")? { + d.language = language.to_string(); + } + if let Some(units) = units(cmd, p)? { + d.units = units; + } + if let Some(projection) = projection(cmd, p)? { + d.projection = projection; + } + Ok(()) + })?; + inspect(s, &Value::Null) +} + +fn properties(s: &mut Session, _p: &Value) -> Result { + Ok(super::metadata::reading(&s.drawing("drawing.properties")?.properties)) +} + +/// The open drawing with the properties `next`, kept when they changed: one undo step. +fn keep_properties(s: &mut Session, cmd: &str, next: solidcraft_doc::Metadata) -> Result { + s.edit_drawing(cmd, |d| { + d.properties = Arc::new(next); + Ok(()) + })?; + Ok(json!(s.drawing(cmd)?.properties)) +} + +fn properties_set(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.properties.set"; + let (next, changed) = super::metadata::setting(cmd, &s.drawing(cmd)?.properties, p)?; + let metadata = keep_properties(s, cmd, next)?; + Ok(json!({"metadata": metadata, "changed": changed})) +} + +fn properties_remove(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.properties.remove"; + let (next, removed) = super::metadata::removing(cmd, &s.drawing(cmd)?.properties, p)?; + let metadata = keep_properties(s, cmd, next)?; + Ok(json!({"metadata": metadata, "removed": removed})) +} + +#[cfg(test)] +#[path = "drawing_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/drawing_sheet.rs b/crates/engine/src/cmd/drawing_sheet.rs new file mode 100644 index 00000000000..fac0e58e5ff --- /dev/null +++ b/crates/engine/src/cmd/drawing_sheet.rs @@ -0,0 +1,196 @@ +//! A drawing's sheets (#3875, W18 S4): add, change, reorder and delete them, each one undo step of +//! the drawing (none when nothing changes). A sheet is named by its id or, when only one has it, +//! its name. +//! +//! A new sheet takes the paper, border and resolution of the sheet it follows, so a drawing's +//! sheets match unless told otherwise. Changing a sheet's paper regrows its border and zones, +//! which nothing on it is saved against, and moves nothing (S5): the answer lists the sheet's views +//! whose boundary the new paper leaves outside its drawing space. + +use std::sync::Arc; + +use serde_json::Value; +use solidcraft_doc::drawing::{Drawing, Excluded, Sheet, SheetComponent}; +use solidcraft_doc::ids; +use solidcraft_geom::drawing_sheet::{Orientation, SheetSize}; + +use super::CommandSpec; +use crate::params::{bad, num, str_}; +use crate::schema::drawing_sheet::{SheetAddParams, SheetDeleteParams, SheetName, SheetReorderParams, SheetSetParams, SheetsResult}; +use crate::schema::drawing_view::OutsideResult; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{EngineError, Result, Session}; + +const ADD: TypedContract = TypedContract::new(); +const SET: TypedContract = TypedContract::new(); +const REORDER: TypedContract = TypedContract::new(); +const DELETE: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("drawing.sheet.add", "Add Sheet", crate::checked!("drawing.sheet.add", ADD, add)) + .icon("new") + .in_drawing() + .doc_only() + .contract(&ADD) + .output(output_schema_for::) + .params( + "after?: a sheet (id or name; default the last); name?; size?: {standard: a3} or {custom: {sides_mm: [w, h]}}; \ + orientation?: landscape|portrait; dpi?: 25..2400 (each defaulting to the sheet it follows); documents?: {source: id, \ + component: id (0 the design)}; excluded?: {count?, print?} (none unless given) → sheet: the new sheet's id, sheets. \ + One undo step.", + ), + CommandSpec::new("drawing.sheet.set", "Sheet Settings", crate::checked!("drawing.sheet.set", SET, set)) + .icon("settings") + .in_drawing() + .doc_only() + .contract(&SET) + .output(output_schema_for::) + .params( + "sheet: id or name; name?, size?, orientation?, dpi?; documents?: {source: id, component: id (0 the design)} or null; \ + excluded?: {count?, print?} → the drawing's sheets, and after a change of paper `outside`: the sheet's views whose \ + boundary leaves its drawing space (none is moved). One undo step, none when nothing changes.", + ), + CommandSpec::new("drawing.sheet.reorder", "Reorder Sheets", crate::checked!("drawing.sheet.reorder", REORDER, reorder)) + .icon("reorder") + .in_drawing() + .doc_only() + .contract(&REORDER) + .output(output_schema_for::) + .params("sheets: every sheet's id, in the new order → the drawing's sheets. One undo step, none for the same order."), + CommandSpec::new("drawing.sheet.delete", "Delete Sheet", crate::checked!("drawing.sheet.delete", DELETE, delete)) + .icon("delete") + .in_drawing() + .doc_only() + .contract(&DELETE) + .output(output_schema_for::) + .params("sheet: id or name (a drawing keeps at least one) → the drawing's sheets. One undo step."), +]; + +/// The drawing's sheets, as each command answers (`sheet`: the one `drawing.sheet.add` made; +/// `outside`: the views `drawing.sheet.set`'s paper leaves outside). +fn answer(s: &Session, cmd: &str, sheet: Option, outside: Vec) -> Result { + let sheets = s.drawing(cmd)?.sheets.iter().map(|sheet| SheetName { id: ids::encode(sheet.id), name: sheet.name.clone() }).collect(); + let reply = SheetsResult { sheet: sheet.map(ids::encode), sheets, outside, param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + +/// The position of the sheet `p[key]` names ([`Drawing::sheet_index`]). +fn sheet_at(cmd: &str, d: &Drawing, p: &Value, key: &str) -> Result { + let named = str_(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be a sheet's id or name")))?; + d.sheet_index(named).map_err(|e| bad(cmd, e.to_string())) +} + +/// The settings `p` gives a sheet, over the ones it has. +fn apply(cmd: &str, sheet: &mut Sheet, p: &Value) -> Result<()> { + if let Some(name) = p.get("name") { + sheet.name = name.as_str().ok_or_else(|| bad(cmd, "`name` must be text"))?.to_string(); + } + if let Some(size) = p.get("size") { + sheet.sheet.size = serde_json::from_value::(size.clone()) + .map_err(|_| bad(cmd, "`size` is {\"standard\": \"a3\"} or {\"custom\": {\"sides_mm\": [w, h]}}"))?; + } + if let Some(orientation) = p.get("orientation") { + sheet.sheet.orientation = + serde_json::from_value::(orientation.clone()).map_err(|_| bad(cmd, "`orientation` is landscape or portrait"))?; + } + if p.get("dpi").is_some() { + sheet.dpi = num(p, "dpi").ok_or_else(|| bad(cmd, "`dpi` must be a number"))?; + } + match p.get("documents") { + None => {} + Some(Value::Null) => sheet.documents = None, + Some(documents) => { + let source = str_(documents, "source").and_then(ids::decode).ok_or_else(|| bad(cmd, "`documents.source` must be a source's id"))?; + let component = + documents.get("component").map_or(Some(0), Value::as_u64).ok_or_else(|| bad(cmd, "`documents.component` must be a component id"))?; + sheet.documents = Some(SheetComponent { source, component }); + } + } + if let Some(excluded) = p.get("excluded") { + // An object of the two flags: anything else (a mistyped key) would change nothing unseen. + let shape = || bad(cmd, "`excluded` is {count?: true|false, print?: true|false}"); + let excluded = excluded.as_object().filter(|o| o.keys().all(|k| matches!(k.as_str(), "count" | "print"))).ok_or_else(shape)?; + let flag = |key: &str, was: bool| match excluded.get(key) { + None => Ok(was), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(bad(cmd, format!("`excluded.{key}` is true or false"))), + }; + sheet.excluded = Excluded { count: flag("count", sheet.excluded.count)?, print: flag("print", sheet.excluded.print)? }; + } + Ok(()) +} + +fn add(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.sheet.add"; + let record = s.drawing(cmd)?.clone(); + let id = record.allocate_id(&mut s.ids).map_err(|e| bad(cmd, e.to_string()))?; + s.edit_drawing(cmd, |d| { + let after = if p.get("after").is_some() { sheet_at(cmd, d, p, "after")? } else { d.sheets.len().saturating_sub(1) }; + let model = d.sheets.get(after).ok_or_else(|| bad(cmd, "the drawing has no sheet to follow"))?; + let free = (d.sheets.len() + 1..).map(|n| format!("Sheet {n}")).find(|name| d.sheets.iter().all(|s| s.name != *name)).unwrap_or_default(); + let mut sheet = Sheet { id, name: free, documents: None, excluded: Excluded::default(), ..(**model).clone() }; + apply(cmd, &mut sheet, p)?; + d.sheets.insert(after + 1, Arc::new(sheet)); + Ok(()) + })?; + answer(s, cmd, Some(id), Vec::new()) +} + +fn set(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.sheet.set"; + let (id, paper) = s.edit_drawing(cmd, |d| { + let at = sheet_at(cmd, d, p, "sheet")?; + let sheet = Arc::make_mut(d.sheets.get_mut(at).ok_or_else(|| bad(cmd, "no such sheet"))?); + let was = sheet.sheet; + apply(cmd, sheet, p)?; + Ok((sheet.id, sheet.sheet != was)) + })?; + // Only a change of paper moves the drawing space; each view measured once. + let d = s.drawing(cmd)?; + let on: Vec = if paper { d.views.iter().filter(|v| v.sheet == id).map(|v| v.id).collect() } else { Vec::new() }; + let outside = super::drawing_view::outside_results(crate::drawing_view::outside(s, d, &on, cmd)?); + answer(s, cmd, None, outside) +} + +fn reorder(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.sheet.reorder"; + s.edit_drawing(cmd, |d| { + let every = || bad(cmd, "`sheets` must list every sheet's id once"); + let order: Vec = p + .get("sheets") + .and_then(Value::as_array) + .ok_or_else(every)? + .iter() + .map(|v| v.as_str().and_then(ids::decode)) + .collect::>() + .ok_or_else(every)?; + let mut sheets = Vec::with_capacity(order.len()); + for id in &order { + let at = d.sheets.iter().position(|s| s.id == *id).ok_or_else(every)?; + sheets.push(d.sheets.remove(at)); + } + if !d.sheets.is_empty() { + return Err(every()); + } + d.sheets = sheets; + Ok(()) + })?; + answer(s, cmd, None, Vec::new()) +} + +fn delete(s: &mut Session, p: &Value) -> Result { + let cmd = "drawing.sheet.delete"; + s.edit_drawing(cmd, |d| { + let at = sheet_at(cmd, d, p, "sheet")?; + if d.sheets.len() <= 1 { + return Err(bad(cmd, "a drawing keeps at least one sheet")); + } + d.sheets.remove(at); + Ok(()) + })?; + answer(s, cmd, None, Vec::new()) +} + +#[cfg(test)] +#[path = "drawing_sheet_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/drawing_sheet_tests.rs b/crates/engine/src/cmd/drawing_sheet_tests.rs new file mode 100644 index 00000000000..3e5564cdc81 --- /dev/null +++ b/crates/engine/src/cmd/drawing_sheet_tests.rs @@ -0,0 +1,178 @@ +use serde_json::json; + +use super::*; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn refused(s: &mut Session, id: &str, p: Value) -> String { + s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("{id} accepted {p}")) +} + +/// A box's drawing, open, with its one A3 sheet. +fn drawing_session() -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10})); + run(&mut s, "drawing.create", json!({})); + s +} + +fn sheets(s: &Session) -> Vec> { + s.drawing("test").unwrap().sheets.clone() +} + +fn names(s: &Session) -> Vec { + sheets(s).iter().map(|sheet| sheet.name.clone()).collect() +} + +/// A new sheet follows the last, or the one named, with its paper, border and resolution and a +/// name of its own; each add is one undo step. +#[test] +fn a_new_sheet_takes_the_paper_of_the_sheet_it_follows() { + let mut s = drawing_session(); + let steps = s.undo.len(); + run(&mut s, "drawing.sheet.set", json!({"sheet": "Sheet 1", "dpi": 600, "size": {"standard": "a2"}})); + let added = run(&mut s, "drawing.sheet.add", json!({})); + let all = sheets(&s); + assert_eq!(added["sheet"], json!(ids::encode(all[1].id))); + assert_eq!((all[1].name.as_str(), all[1].dpi, all[1].sheet), ("Sheet 2", 600.0, all[0].sheet)); + assert_eq!(all[1].border, all[0].border); + run(&mut s, "drawing.sheet.add", json!({"after": "Sheet 1", "name": "Details", "orientation": "portrait"})); + assert_eq!(names(&s), ["Sheet 1", "Details", "Sheet 2"]); + assert_eq!(sheets(&s)[1].sheet.orientation, Orientation::Portrait); + assert_eq!(s.undo.len(), steps + 3); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), ["Sheet 1", "Sheet 2"]); + // After a sheet by id; an unknown one is refused. + let first = ids::encode(sheets(&s)[0].id); + run(&mut s, "drawing.sheet.add", json!({"after": first, "name": "Second"})); + assert_eq!(names(&s), ["Sheet 1", "Second", "Sheet 2"]); + assert!(refused(&mut s, "drawing.sheet.add", json!({"after": "Nowhere"})).contains("no sheet `Nowhere`")); + // A new sheet documents nothing and leaves nothing out unless told, whatever the one it follows does. + let source = ids::encode(s.drawing("test").unwrap().sources[0].id); + run(&mut s, "drawing.sheet.set", json!({"sheet": "Sheet 2", "documents": {"source": source}, "excluded": {"count": true}})); + run(&mut s, "drawing.sheet.add", json!({"after": "Sheet 2"})); + let added = sheets(&s).last().cloned().unwrap(); + assert_eq!((added.documents, added.excluded.count, added.excluded.print), (None, false, false)); + let told = json!({"documents": {"source": source, "component": 0}, "excluded": {"print": true}}); + let id = run(&mut s, "drawing.sheet.add", told)["sheet"].clone(); + let added = sheets(&s).into_iter().find(|sheet| json!(ids::encode(sheet.id)) == id).unwrap(); + assert!(added.documents.is_some() && added.excluded.print && !added.excluded.count); +} + +/// A sheet's id comes from the session's id source: two sessions seeded alike and run alike give +/// the same ids (where a crash replay starts), another seed others, and a failed add draws none. +#[test] +fn sheet_ids_come_from_the_sessions_seed() { + let made = |seed: u64, fail: bool| { + let mut s = Session::default(); + s.seed_ids(seed); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10})); + run(&mut s, "drawing.create", json!({})); + if fail { + refused(&mut s, "drawing.sheet.add", json!({"after": "Nowhere"})); + } + run(&mut s, "drawing.sheet.add", json!({})); + let record = s.drawing("test").unwrap().clone(); + record.sheets.iter().map(|sheet| sheet.id).chain(record.sources.iter().map(|source| source.id)).collect::>() + }; + assert_eq!(made(7, false), made(7, false)); + assert_eq!(made(7, true), made(7, false), "the failed add drew none"); + assert_ne!(made(7, false), made(8, false)); +} + +/// 1000 sheets at most: the 1000th is added, the 1001st refused with nothing changed. +#[test] +fn a_drawing_has_at_most_1000_sheets() { + let mut s = drawing_session(); + for _ in 1..solidcraft_doc::drawing::MAX_SHEETS { + run(&mut s, "drawing.sheet.add", json!({})); + } + assert_eq!(sheets(&s).len(), 1000); + let before = s.drawing("test").unwrap().clone(); + assert!(refused(&mut s, "drawing.sheet.add", json!({})).contains("1 to 1000 sheets")); + assert!(Arc::ptr_eq(s.drawing("test").unwrap(), &before)); +} + +/// A sheet's settings change one at a time, the rest kept; what the sheet's rules refuse is +/// refused with the drawing unchanged. +#[test] +fn a_sheets_settings_change_and_keep_its_rules() { + let mut s = drawing_session(); + let source = ids::encode(s.drawing("test").unwrap().sources[0].id); + let id = ids::encode(sheets(&s)[0].id); + run( + &mut s, + "drawing.sheet.set", + json!({"sheet": id, "name": "Assembly", "documents": {"source": source, "component": 0}, "excluded": {"print": true}}), + ); + let sheet = sheets(&s)[0].clone(); + assert_eq!(sheet.name, "Assembly"); + assert_eq!(sheet.documents.map(|d| d.component), Some(0)); + assert_eq!((sheet.excluded.count, sheet.excluded.print), (false, true)); + run(&mut s, "drawing.sheet.set", json!({"sheet": "Assembly", "excluded": {"count": true}, "documents": null})); + let sheet = sheets(&s)[0].clone(); + assert_eq!((sheet.excluded.count, sheet.excluded.print, sheet.documents), (true, true, None), "the other flag kept"); + let before = s.drawing("test").unwrap().clone(); + for (p, says) in [ + (json!({"sheet": "Assembly", "dpi": 24}), "dpi"), + (json!({"sheet": "Assembly", "size": {"standard": "b7"}}), "`size`"), + (json!({"sheet": "Assembly", "size": {"custom": {"sides_mm": [0, 100]}}}), "a custom side is finite, above 0 and at most 5000 mm"), + (json!({"sheet": "Assembly", "size": {"custom": {"sides_mm": [15, 15]}}}), "the margins leave no drawing space"), + (json!({"sheet": "Assembly", "dpi": 2400.001}), "dpi"), + (json!({"sheet": "Assembly", "excluded": true}), "`excluded` is {count?"), + (json!({"sheet": "Assembly", "excluded": {"cuont": true}}), "`excluded` is {count?"), + (json!({"sheet": "Assembly", "orientation": "upright"}), "landscape or portrait"), + (json!({"sheet": "Assembly", "name": ""}), "name"), + (json!({"sheet": "Assembly", "documents": {"source": "0000000000001"}}), "documents source"), + (json!({"sheet": "Assembly", "excluded": {"count": "yes"}}), "true or false"), + (json!({"sheet": "Nowhere"}), "no sheet `Nowhere`"), + (json!({}), "`sheet`"), + ] { + let e = refused(&mut s, "drawing.sheet.set", p.clone()); + assert!(e.contains(says), "{p}: {e}"); + assert!(Arc::ptr_eq(s.drawing("test").unwrap(), &before), "{p}"); + } + // The resolution's bounds are in; the same settings again are no step; a name two sheets + // share is allowed, and then the sheet is named by id. + let steps = s.undo.len(); + for dpi in [25.0, 2400.0] { + run(&mut s, "drawing.sheet.set", json!({"sheet": "Assembly", "dpi": dpi})); + assert_eq!(sheets(&s)[0].dpi, dpi); + } + run(&mut s, "drawing.sheet.set", json!({"sheet": "Assembly", "dpi": 2400})); + assert_eq!(s.undo.len(), steps + 2, "no change, no step"); + run(&mut s, "drawing.sheet.add", json!({})); + let second = ids::encode(sheets(&s)[1].id); + run(&mut s, "drawing.sheet.set", json!({"sheet": second, "name": "Assembly"})); + assert!(refused(&mut s, "drawing.sheet.set", json!({"sheet": "Assembly", "dpi": 300})).contains("give its id")); +} + +/// Sheets reorder by every id once, a name shared by two is refused in favour of the id, and the +/// last sheet can't be deleted. +#[test] +fn sheets_reorder_and_delete_but_one_always_stays() { + let mut s = drawing_session(); + run(&mut s, "drawing.sheet.add", json!({})); + run(&mut s, "drawing.sheet.add", json!({"name": "Sheet 1"})); + let ids: Vec = sheets(&s).iter().map(|sheet| ids::encode(sheet.id)).collect(); + assert!(refused(&mut s, "drawing.sheet.delete", json!({"sheet": "Sheet 1"})).contains("give its id")); + let steps = s.undo.len(); + run(&mut s, "drawing.sheet.reorder", json!({"sheets": [ids[0], ids[1], ids[2]]})); + assert_eq!(s.undo.len(), steps, "the same order is no step"); + run(&mut s, "drawing.sheet.reorder", json!({"sheets": [ids[2], ids[0], ids[1]]})); + assert_eq!(sheets(&s).iter().map(|sheet| ids::encode(sheet.id)).collect::>(), [ids[2].clone(), ids[0].clone(), ids[1].clone()]); + for order in [json!([ids[0], ids[1]]), json!([ids[0], ids[0], ids[1]]), json!([ids[0], ids[1], ids[2], "0000000000001"]), json!("all")] { + let e = refused(&mut s, "drawing.sheet.reorder", json!({"sheets": order})); + assert!(e.contains("every sheet's id once"), "{order}: {e}"); + } + run(&mut s, "drawing.sheet.delete", json!({"sheet": ids[0]})); + // An undone delete puts the sheet back where it was. + run(&mut s, "edit.undo", json!({})); + assert_eq!(sheets(&s).iter().map(|sheet| ids::encode(sheet.id)).collect::>(), [ids[2].clone(), ids[0].clone(), ids[1].clone()]); + run(&mut s, "drawing.sheet.delete", json!({"sheet": ids[0]})); + run(&mut s, "drawing.sheet.delete", json!({"sheet": ids[1]})); + assert!(refused(&mut s, "drawing.sheet.delete", json!({"sheet": ids[2]})).contains("at least one sheet")); + assert_eq!(sheets(&s).len(), 1); +} diff --git a/crates/engine/src/cmd/drawing_tests.rs b/crates/engine/src/cmd/drawing_tests.rs new file mode 100644 index 00000000000..408df78dd46 --- /dev/null +++ b/crates/engine/src/cmd/drawing_tests.rs @@ -0,0 +1,480 @@ +use super::*; +use crate::cmd::{Part, command_specs, find_command}; +use crate::tests::Folder; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn refused(s: &mut Session, id: &str, p: Value) -> String { + s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("{id} accepted {p}")) +} + +/// A design with a box. +fn design() -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Plate"})); + s +} + +/// The drawing open, as the design holds it. +fn open_one(s: &Session) -> Arc { + s.drawing("test").unwrap().clone() +} + +/// The params naming drawing `id`. +fn the(id: u64) -> Value { + json!({"drawing": ids::encode(id)}) +} + +fn names(s: &Session) -> Vec<&str> { + s.doc.drawings.iter().map(|d| d.name.as_str()).collect() +} + +/// A drawing of the design: one A3 sheet with the ISO border, the design its one source, kept in +/// the design and opened. Making it is one step of the model, and evaluates nothing. +#[test] +fn a_drawing_of_the_design_is_kept_in_it_and_opened() { + let mut s = design(); + let (undo, evaluations, features) = (s.undo.len(), s.evaluations, s.doc.features.clone()); + let made = run(&mut s, "drawing.create", json!({"name": "Plate drawing", "units": "mm"})); + assert_eq!((made["name"].as_str(), made["language"].as_str()), (Some("Plate drawing"), Some("en"))); + assert_eq!(made["units"], json!({"fixed": {"unit": "mm"}})); + let sheet = &made["sheets"][0]; + assert_eq!( + (sheet["size_mm"].clone(), sheet["orientation"].clone(), sheet["dpi"].clone()), + (json!([420.0, 297.0]), json!("landscape"), json!(300.0)) + ); + assert_eq!((made["sheets"].as_array().map(Vec::len), made["sources"].as_array().map(Vec::len)), (Some(1), Some(1))); + let d = open_one(&s); + assert_eq!(made["id"], json!(ids::encode(d.id))); + assert!(d.sheets[0].border.is_some(), "the ISO border"); + assert_eq!((s.doc.drawings.len(), s.open_drawing), (1, Some(d.id))); + assert_eq!((s.undo.len(), s.undo.last().map(|u| u.part)), (undo + 1, Some(None)), "a step of the model"); + assert_eq!((s.evaluations, &s.doc.features), (evaluations, &features), "nothing evaluated, the model as it was"); + assert!(s.is_dirty()); + assert_eq!(run(&mut s, "drawing.inspect", json!({})), made); + let listed = run(&mut s, "drawing.list", json!({})); + assert_eq!(listed, json!({"drawings": [{"id": made["id"], "name": "Plate drawing", "sheets": 1, "open": true}]})); + // Its name is the design's unless given. + run(&mut s, "drawing.close", json!({})); + run(&mut s, "drawing.create", json!({})); + assert_eq!(open_one(&s).name, s.doc.name); +} + +/// A drawing's ids come from the session's id source: two sessions seeded alike make a drawing +/// with the same ids (where a crash replay starts), another seed other ids. A file change keeps +/// the source, so the same holds for a drawing made after `file.new`. +#[test] +fn drawing_ids_come_from_the_sessions_seed() { + let ids = |seed: u64, new_file: bool| { + let mut s = design(); + s.seed_ids(seed); + if new_file { + run(&mut s, "file.new", json!({})); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Plate"})); + } + run(&mut s, "drawing.create", json!({})); + let d = open_one(&s); + (d.id, d.sheets[0].id, d.sources[0].id) + }; + assert_eq!(ids(7, false), ids(7, false)); + assert_ne!(ids(7, false), ids(8, false)); + assert_eq!(ids(7, true), ids(7, true), "the source kept across the file change"); + assert_ne!(ids(7, true), ids(8, true)); +} + +/// What making a drawing refuses, the design unchanged: an empty design, units, a language and a +/// name the record can't take, and a design that holds the most drawings already. +#[test] +fn a_drawing_is_made_only_of_a_design_with_something_in_it() { + assert!(refused(&mut Session::default(), "drawing.create", json!({})).contains("nothing to draw")); + let mut s = design(); + let before = s.doc.clone(); + for (p, says) in [ + (json!({"units": "parsec"}), "length unit"), + (json!({"units": 3}), "follow_model"), + (json!({"language": "e"}), "BCP 47"), + (json!({"name": " "}), "name"), + (json!({"name": 7}), "must be text"), + ] { + let e = refused(&mut s, "drawing.create", p.clone()); + assert!(e.contains(says), "{p}: {e}"); + assert!(Arc::ptr_eq(&s.doc, &before) && s.open_drawing.is_none() && s.undo.len() == 1, "{p}: nothing changed"); + } + run(&mut s, "drawing.create", json!({})); + run(&mut s, "drawing.close", json!({})); + let one = s.doc.drawings[0].clone(); + s.doc_mut().drawings = (1..=drawing::MAX_DRAWINGS as u64).map(|id| Arc::new(Drawing { id, ..(*one).clone() })).collect(); + let full = s.doc.clone(); + assert!(refused(&mut s, "drawing.create", json!({})).contains("at most 1000 drawings")); + assert!(Arc::ptr_eq(&s.doc, &full)); +} + +/// While a drawing is open the model's commands wait, and the drawing's run only while one is: +/// running a command, running it inside another and listing it all say so. +#[test] +fn model_and_drawing_commands_each_run_on_their_own_part() { + let mut s = design(); + for id in ["drawing.inspect", "drawing.set", "drawing.properties", "drawing.properties.set", "drawing.properties.remove"] { + assert!(refused(&mut s, id, json!({"name": "X", "key": "author", "value": "X"})).contains("open a drawing first"), "{id}"); + } + run(&mut s, "drawing.create", json!({})); + let doc = s.doc.clone(); + let boxed = json!({"length": 5, "width": 5, "height": 5}); + let e = refused(&mut s, "solid.box", boxed.clone()); + assert!(e.contains("a drawing is open: close it to change the model (drawing.close)"), "{e}"); + assert!(find_command("solid.box").unwrap().run_nested(&mut s, &boxed).is_err(), "nor inside another command"); + assert!(Arc::ptr_eq(&s.doc, &doc)); + let enabled = |s: &mut Session, id: &str| { + let listed = run(s, "engine.commands", json!({})); + listed.as_array().unwrap().iter().find(|c| c["id"] == id).map(|c| c["enabled"] == true).unwrap() + }; + assert!(!enabled(&mut s, "solid.box") && enabled(&mut s, "drawing.set")); + for id in ["edit.undo", "file.save", "file.new", "doc.open", "select.clear", "edit.checkpoint", "drawing.list", "drawing.close"] { + assert!(find_command(id).unwrap().allowed(&s).is_ok(), "{id} runs with a drawing open"); + } + run(&mut s, "drawing.close", json!({})); + assert!(enabled(&mut s, "solid.box") && !enabled(&mut s, "drawing.set")); + run(&mut s, "solid.box", boxed); + // A new design or another opened has no drawing open. + run(&mut s, "drawing.create", json!({})); + run(&mut s, "file.new", json!({})); + assert!(s.open_drawing.is_none() && s.doc.drawings.is_empty()); +} + +/// Each change of a drawing is one undo step of that drawing: undo and redo bring back the same +/// record, and a change to the same values is no step. No model is evaluated, and the design +/// changes, so whatever follows it sees each change. +#[test] +fn drawing_edits_are_undo_steps_of_the_drawing_that_evaluate_nothing() { + let mut s = design(); + run(&mut s, "drawing.create", json!({})); + let (first, evaluations, features, steps) = (open_one(&s), s.evaluations, s.doc.features.clone(), s.undo.len()); + let (doc, revision) = (s.doc.clone(), s.revision); + run(&mut s, "drawing.set", json!({"name": "Renamed", "language": "de", "units": "in"})); + let renamed = open_one(&s); + assert_eq!((renamed.name.as_str(), renamed.language.as_str()), ("Renamed", "de")); + assert_eq!(renamed.units, Units::Fixed { unit: "in".into() }); + assert!(!Arc::ptr_eq(&s.doc, &doc) && s.revision > revision, "the design changed"); + assert_eq!((s.undo.len(), s.undo.last().map(|u| u.part)), (steps + 1, Some(Some(first.id))), "a step of the drawing"); + run(&mut s, "drawing.set", json!({"name": "Renamed"})); + assert_eq!(s.undo.len(), steps + 1, "the same value again is no step"); + for _ in 0..100 { + assert_eq!(run(&mut s, "edit.undo", json!({}))["undone"], "Drawing Settings"); + assert!(Arc::ptr_eq(&open_one(&s), &first)); + run(&mut s, "edit.redo", json!({})); + assert!(Arc::ptr_eq(&open_one(&s), &renamed)); + } + assert_eq!((s.evaluations, &s.doc.features), (evaluations, &features), "no model evaluated or changed"); +} + +/// A drawing's projection is first or third angle, third when nothing chooses: shown by +/// `drawing.inspect`, changed by `drawing.set` as one undo step, saved with the design, and +/// anything else refused. +#[test] +fn a_drawings_projection_is_first_or_third_angle() { + let folder = Folder::new("drawing-projection"); + let mut s = design(); + let made = run(&mut s, "drawing.create", json!({})); + assert_eq!(made["projection"], "third"); + let steps = s.undo.len(); + assert_eq!(run(&mut s, "drawing.set", json!({"projection": "first"}))["projection"], "first"); + assert_eq!(s.undo.len(), steps + 1); + run(&mut s, "file.save", json!({"path": folder.path("plate.solidcraft")})); + let mut opened = Session::default(); + run(&mut opened, "doc.open", json!({"path": folder.path("plate.solidcraft")})); + assert_eq!(opened.doc.drawings[0].projection, Projection::First); + run(&mut s, "edit.undo", json!({})); + assert_eq!(run(&mut s, "drawing.inspect", json!({}))["projection"], "third"); + for bad in [json!("second"), json!("First"), json!(1), json!(null)] { + assert!(refused(&mut s, "drawing.set", json!({"projection": bad})).contains("first or third"), "{bad}"); + } +} + +/// Undo and redo go through the open part's steps only. With a drawing open, its own steps; the +/// model's stay where they are. With none open, the model's steps, which put the design back as +/// it was but keep each drawing it had as it is now. +#[test] +fn undo_and_redo_go_through_one_part_at_a_time() { + let mut s = design(); + run(&mut s, "drawing.create", json!({"name": "A"})); + let id = open_one(&s).id; + run(&mut s, "drawing.set", json!({"name": "B"})); + run(&mut s, "drawing.close", json!({})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5})); + let two = s.doc.features.len(); + run(&mut s, "drawing.open", the(id)); + run(&mut s, "drawing.set", json!({"name": "C"})); + // In the drawing: C, B, A; the model's box stays. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!((open_one(&s).name.as_str(), s.doc.features.len()), ("A", two)); + assert!(refused(&mut s, "edit.undo", json!({})).contains("nothing to undo in this drawing (close it to undo in the model)")); + // In the model: the box goes and the drawing stays as it is now (A, where the step had B); + // then the drawing goes. + run(&mut s, "drawing.close", json!({})); + let evaluations = s.evaluations; + run(&mut s, "edit.undo", json!({})); + assert_eq!((s.doc.features.len(), names(&s)), (two - 1, vec!["A"])); + assert!(s.evaluations > evaluations, "the model's step evaluates the model"); + run(&mut s, "edit.undo", json!({})); + assert!(s.doc.drawings.is_empty()); + // Redo: the drawing as it was when it went, then the box, the drawing kept. + run(&mut s, "edit.redo", json!({})); + assert_eq!((names(&s), s.open_drawing), (vec!["A"], None)); + run(&mut s, "edit.redo", json!({})); + assert_eq!((s.doc.features.len(), names(&s)), (two, vec!["A"])); + assert_eq!(refused(&mut s, "edit.redo", json!({})), "nothing to redo"); + // The drawing's own redo steps were kept all along. + run(&mut s, "drawing.open", the(id)); + run(&mut s, "edit.redo", json!({})); + run(&mut s, "edit.redo", json!({})); + assert_eq!(open_one(&s).name, "C"); + assert!(refused(&mut s, "edit.redo", json!({})).contains("nothing to redo in this drawing")); +} + +/// A new step ends what could be redone in its own part only: the others' redo steps still hold. +#[test] +fn a_new_step_ends_what_could_be_redone_in_its_part_only() { + let mut s = design(); + run(&mut s, "drawing.create", json!({"name": "A"})); + let id = open_one(&s).id; + run(&mut s, "drawing.set", json!({"name": "B"})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "drawing.close", json!({})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5})); + run(&mut s, "drawing.open", the(id)); + run(&mut s, "edit.redo", json!({})); + assert_eq!(open_one(&s).name, "B", "a model step leaves the drawing's redo"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "drawing.set", json!({"name": "Z"})); + assert!(refused(&mut s, "edit.redo", json!({})).contains("nothing to redo in this drawing"), "a drawing step ends its own"); + run(&mut s, "drawing.close", json!({})); + let features = s.doc.features.len(); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "drawing.open", the(id)); + run(&mut s, "drawing.set", json!({"name": "Q"})); + run(&mut s, "drawing.close", json!({})); + run(&mut s, "edit.redo", json!({})); + assert_eq!((s.doc.features.len(), names(&s)), (features, vec!["Q"]), "a drawing step leaves the model's redo"); +} + +/// A design lists its drawings by name, then id, whatever order they were made, renamed or +/// undone in. +#[test] +fn a_designs_drawings_are_listed_by_name_then_id() { + let mut s = design(); + for name in ["Zeta", "Alpha", "Mid", "Alpha"] { + run(&mut s, "drawing.create", json!({"name": name})); + } + assert_eq!(names(&s), ["Alpha", "Alpha", "Mid", "Zeta"]); + assert!(s.doc.drawings[0].id < s.doc.drawings[1].id); + let first = s.doc.drawings[0].id; + run(&mut s, "drawing.close", json!({})); + run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5})); + run(&mut s, "drawing.open", the(first)); + run(&mut s, "drawing.set", json!({"name": "Zz"})); + assert_eq!(names(&s), ["Alpha", "Mid", "Zeta", "Zz"]); + let listed = run(&mut s, "drawing.list", json!({})); + let open: Vec = listed["drawings"].as_array().unwrap().iter().map(|d| d["open"] == true).collect(); + assert_eq!(open, [false, false, false, true]); + // The model's step, made before the rename, keeps the drawing renamed and in its place. + run(&mut s, "drawing.close", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), ["Alpha", "Mid", "Zeta", "Zz"]); + run(&mut s, "drawing.open", the(first)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(names(&s), ["Alpha", "Alpha", "Mid", "Zeta"]); +} + +/// Deleting a drawing is a step of the model: it closes it when it was open, and undo brings it +/// back as it was, closed. What isn't a drawing of the design is refused. +#[test] +fn deleting_a_drawing_is_a_step_of_the_model() { + let mut s = design(); + run(&mut s, "drawing.create", json!({"name": "A"})); + let a = open_one(&s); + run(&mut s, "drawing.create", json!({"name": "B"})); + let b = open_one(&s); + let doc = s.doc.clone(); + for (p, says) in [(json!({}), "must be a drawing's id"), (json!({"drawing": 7}), "must be a drawing's id"), (the(1), "has no drawing")] { + let e = refused(&mut s, "drawing.delete", p.clone()); + assert!(e.contains(says), "{p}: {e}"); + assert!(Arc::ptr_eq(&s.doc, &doc) && s.open_drawing == Some(b.id)); + } + assert_eq!(run(&mut s, "drawing.delete", the(b.id)), json!({"deleted": ids::encode(b.id)})); + assert_eq!((names(&s), s.open_drawing), (vec!["A"], None)); + run(&mut s, "drawing.delete", the(a.id)); + assert!(s.doc.drawings.is_empty()); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(Arc::ptr_eq(&s.doc.drawings[0], &a) && Arc::ptr_eq(&s.doc.drawings[1], &b), "back as they were"); + assert_eq!(s.open_drawing, None); + assert!(refused(&mut s, "drawing.open", the(1)).contains("has no drawing")); +} + +/// A refused change leaves the drawing as it was, with no step, and a refused opening leaves the +/// drawing open as it was. +#[test] +fn a_refused_change_leaves_the_drawing_as_it_was() { + let mut s = design(); + run(&mut s, "drawing.create", json!({})); + let (before, steps) = (s.doc.clone(), s.undo.len()); + for p in [json!({"language": "e"}), json!({"name": ""}), json!({"units": "kg"}), json!({"name": "x".repeat(300)})] { + refused(&mut s, "drawing.set", p.clone()); + assert!(Arc::ptr_eq(&s.doc, &before) && s.undo.len() == steps, "{p}"); + } + let open = s.open_drawing; + refused(&mut s, "drawing.open", json!({"drawing": "AAAAAAAAAAAAA"})); + assert_eq!(s.open_drawing, open); +} + +/// A checkpoint brings back the design's drawings, the one open and the undo history. Going back +/// over a change of the model and of a drawing evaluates the model: it is no drawing-only change. +#[test] +fn a_checkpoint_brings_back_the_drawings_and_the_one_open() { + let mut s = design(); + run(&mut s, "drawing.create", json!({"name": "A"})); + let a = open_one(&s); + let (checkpoint, steps, features) = (run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].clone(), s.undo.len(), s.doc.features.clone()); + run(&mut s, "drawing.set", json!({"name": "B"})); + run(&mut s, "drawing.close", json!({})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + run(&mut s, "drawing.delete", the(a.id)); + run(&mut s, "drawing.create", json!({"name": "C"})); + let evaluations = s.evaluations; + run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": checkpoint})); + assert!(s.doc.drawings.len() == 1 && Arc::ptr_eq(&s.doc.drawings[0], &a)); + assert_eq!((s.open_drawing, s.undo.len(), &s.doc.features), (Some(a.id), steps, &features)); + assert!(s.evaluations > evaluations, "the model changed too, so it is evaluated"); +} + +/// A design's drawings are saved in its file and come back with it, as a container and as plain +/// JSON, with a drawing open when it is saved; a design opened has none open. +#[test] +fn a_designs_drawings_are_saved_with_it_and_come_back() { + let folder = Folder::new("drawing-saved"); + let mut s = design(); + run(&mut s, "drawing.create", json!({"name": "A", "language": "en-GB"})); + run(&mut s, "drawing.properties.set", json!({"values": {"author": "Jane Doe", "com.acme.shop": {"shop_id": 88}}})); + run(&mut s, "drawing.create", json!({"name": "B", "units": "mm"})); + let drawings = s.doc.drawings.clone(); + for file in ["plate.solidcraft", "plate.json"] { + run(&mut s, "file.save", json!({"path": folder.path(file)})); + assert!(!s.is_dirty(), "{file}"); + let mut opened = Session::default(); + run(&mut opened, "doc.open", json!({"path": folder.path(file)})); + assert_eq!(opened.doc.drawings, drawings, "{file}"); + assert!(opened.open_drawing.is_none(), "{file}"); + } +} + +/// A drawing's properties follow the design properties' rules: set, read and removed, each change +/// one undo step, other tools' keys kept, and what the design's would refuse refused. +#[test] +fn a_drawings_properties_follow_the_design_properties_rules() { + let mut s = design(); + run(&mut s, "drawing.create", json!({})); + let steps = s.undo.len(); + let set = run(&mut s, "drawing.properties.set", json!({"values": {"author": "Jane Doe", "com.acme.shop": {"shop_id": 88}}})); + assert_eq!(set["changed"], json!(["author", "com.acme.shop"])); + assert_eq!(s.undo.len(), steps + 1); + let read = run(&mut s, "drawing.properties", json!({})); + assert_eq!((read["properties"]["author"].clone(), read["metadata"]["com.acme.shop"]["shop_id"].clone()), (json!("Jane Doe"), json!(88))); + assert_eq!(read["properties"]["revision"], Value::Null); + run(&mut s, "drawing.properties.set", json!({"key": "author", "value": "Jane Doe"})); + assert_eq!(s.undo.len(), steps + 1, "the same value again is no change"); + let removed = run(&mut s, "drawing.properties.remove", json!({"keys": ["author", "missing"]})); + assert_eq!(removed["removed"], json!(["author"])); + assert_eq!((open_one(&s).properties.text("author"), s.undo.len()), (None, steps + 2)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(open_one(&s).properties.text("author"), Some("Jane Doe")); + assert!(s.doc.metadata.text("author").is_none(), "the design's own properties untouched"); + let before = open_one(&s); + for (id, p, says) in [ + ("drawing.properties.set", json!({"key": "bom_type", "value": "purchased"}), "component.metadata.set"), + ("drawing.properties.set", json!({"key": "author"}), "`value` is required"), + ("drawing.properties.set", json!({"values": {"author": 7}}), "author"), + ("drawing.properties.remove", json!({"keys": [1]}), "list of keys"), + ] { + let e = refused(&mut s, id, p.clone()); + assert!(e.contains(says), "{p}: {e}"); + assert!(Arc::ptr_eq(&open_one(&s), &before)); + } +} + +/// Hostile values for each key of every command that runs with a drawing open, from the registry, +/// and as the whole params, each on a copy of one session with a drawing open (the shared pass +/// runs with none, where the part gate refuses them): an error or a result, never a panic, and the +/// design's drawings and the one open still keeping their rules. As in the shared pass, what +/// writes files is left to its own tests; the recovery commands never read a drawing. +#[test] +fn hostile_drawing_params_never_panic() { + let mut s = design(); + run(&mut s, "drawing.create", json!({})); + run(&mut s, "drawing.create", json!({"name": "Second"})); + assert_eq!(s.scratch().open_drawing, s.open_drawing, "each copy has the drawing open"); + let keys = ["name", "language", "units", "drawing", "key", "value", "values", "keys", "checkpoint", "id"]; + let skipped = |id: &str| matches!(id, "doc.open" | "file.save" | "file.save_as") || id.starts_with("doc.recover"); + let mut internal = Vec::new(); + for spec in command_specs().iter().filter(|spec| spec.part != Part::Model && !skipped(spec.id)) { + for value in crate::tests::hostile_values() { + for p in keys.iter().map(|key| json!({ *key: value.clone() })).chain([value.clone()]) { + let mut copy = s.scratch(); + if let Err(crate::EngineError::Internal(_, msg)) = copy.execute(spec.id, &p) { + internal.push(format!("{} {p}: {msg}", spec.id)); + } + drawing::check_in_design(©.doc.drawings).unwrap(); + copy.doc.drawings.iter().for_each(|d| d.validate().unwrap()); + assert!(copy.open_drawing.is_none_or(|id| copy.doc.drawing(id).is_some()), "{} {p}", spec.id); + } + } + } + assert!(internal.is_empty(), "commands panicked with a drawing open:\n{}", internal.join("\n")); +} + +/// Making, opening, closing, changing and deleting drawings, model edits, undo, redo and +/// checkpoints in any order: never a panic, and the design's drawings and the one open always +/// keep their rules. +#[test] +fn drawing_steps_in_any_order_keep_the_rules() { + let mut state = 3890_u64; + let mut next = move |n: u64| { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (state >> 33) % n + }; + for _ in 0..12 { + let mut s = design(); + let mut checkpoints = Vec::new(); + for _ in 0..50 { + let pick = next(8) as usize; + let named = s.doc.drawings.get(pick % s.doc.drawings.len().max(1)).map_or(json!({"drawing": "AAAAAAAAAAAAA"}), |d| the(d.id)); + let (id, p) = match next(11) { + 0 => ("drawing.create", json!({"name": format!("D{}", next(4))})), + 1 => ("drawing.open", named), + 2 => ("drawing.close", json!({})), + 3 => ("drawing.set", json!({"name": format!("D{}", next(4))})), + 4 => ("drawing.delete", named), + 5 | 6 => ("edit.undo", json!({})), + 7 => ("edit.redo", json!({})), + 8 => ("solid.box", json!({"length": 1 + next(9), "width": 3, "height": 3})), + 9 => ("drawing.properties.set", json!({"key": "author", "value": format!("A{}", next(3))})), + _ => match checkpoints.pop() { + Some(checkpoint) if next(2) == 0 => ("edit.restore_checkpoint", json!({"checkpoint": checkpoint})), + _ => ("edit.checkpoint", json!({})), + }, + }; + let r = s.execute(id, &p); + if id == "edit.checkpoint" + && let Ok(v) = &r + { + checkpoints.push(v["checkpoint"].clone()); + } + assert!(!matches!(r, Err(crate::EngineError::Internal(..))), "{id} {p}: {r:?}"); + drawing::check_in_design(&s.doc.drawings).unwrap(); + assert!(s.doc.drawings.windows(2).all(|w| (&w[0].name, w[0].id) < (&w[1].name, w[1].id)), "{id}: in their order"); + assert!(s.open_drawing.is_none_or(|id| s.doc.drawing(id).is_some()), "{id}: the drawing open is the design's"); + } + } +} diff --git a/crates/engine/src/cmd/drawing_view.rs b/crates/engine/src/cmd/drawing_view.rs new file mode 100644 index 00000000000..b18561e1971 --- /dev/null +++ b/crates/engine/src/cmd/drawing_view.rs @@ -0,0 +1,513 @@ +//! `drawing.view.snapshot` (W07, #5866): one orthographic view of the design, worked out and +//! returned without saving anything. It reads the evaluated model and changes nothing. +//! +//! `drawing.view.inspect` and `drawing.view.edit` (W17c, #4816) read and change a saved view of a +//! drawing: each setting with where its value comes from ([`solidcraft_doc::drawing::Drawing::resolve_view`]) +//! and where the view sits on its sheet ([`crate::drawing_view::on_sheet`]), and a change as one +//! undo step that evaluates no model. +//! +//! `drawing.view.move_to_sheet` and `drawing.view.copy_to_sheet` (#4816) put a saved view on a +//! sheet: the views lined up with it go with it, and keep their places beside it. A copy is +//! independent of the views it was copied from (Cameron, 2026-10-26). Each lists the views it puts +//! outside the sheet's drawing space and moves none back in (#3875 S5). +//! +//! The view's settings are `doc::drawing_view::ViewSettings`; its basis, scale and map onto +//! paper are `geom::drawing_view`'s. Without a scale it takes the largest ISO 5455 scale at +//! which the view, centred where it goes, lies inside the sheet's drawing border. + +use std::sync::Arc; + +use serde::Serialize; +use serde_json::Value; +use solidcraft_doc::drawing::Drawing; +use solidcraft_doc::drawing::view::{ResolvedView, SetBy, Setting, View, ViewKind, ViewPlace}; +use solidcraft_doc::drawing_view::{Looking, ViewDirection, ViewOverrides}; +use solidcraft_doc::ids; +use solidcraft_geom::Plane; +use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Sheet}; +use solidcraft_geom::drawing_view::{NamedView, PRESETS, Scale}; +use solidcraft_geom::paper::MAX_COORDINATE_MM; +use solidcraft_geom::{Aabb2, Vec2}; +use solidcraft_render::VisualStyle; + +use super::CommandSpec; +use crate::drawing_view::{Extents, OnSheet, Unmeasured}; +use crate::params::bad; +use crate::schema::drawing_view::{ + BoxResult, ChoicesResult, CopyParams, DPI_RANGE, EditParams, EditResult, ExtentsResult, FromResult, InspectParams, InspectResult, MoveParams, + OutsideResult, PlaceParam, ScaleResult, SettingResult, SettingsResult, SnapshotParams, SnapshotResult, SourceResult, ToSheetResult, ViewResult, + ViewSet, +}; +use crate::schema::{TypedContract, output_schema_for}; +use crate::{Result, Session}; + +const CMD: &str = "drawing.view.snapshot"; +const CONTRACT: TypedContract = TypedContract::new(); +const INSPECT: &str = "drawing.view.inspect"; +const INSPECT_CONTRACT: TypedContract = TypedContract::new(); +const EDIT: &str = "drawing.view.edit"; +const EDIT_CONTRACT: TypedContract = TypedContract::new(); +const MOVE: &str = "drawing.view.move_to_sheet"; +const MOVE_CONTRACT: TypedContract = TypedContract::new(); +const COPY: &str = "drawing.view.copy_to_sheet"; +const COPY_CONTRACT: TypedContract = TypedContract::new(); + +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Drawing View Snapshot", crate::checked!("drawing.view.snapshot", CONTRACT, snapshot)) + .icon("export") + .noundo() + .contract(&CONTRACT) + .output(output_schema_for::) + .params("view?: front (default), back, top, bottom, left, right, iso (= iso_front_right), iso_front_left, iso_back_right, iso_back_left, or {direction, up, origin?}; scale?: \"paper:model\" such as \"1:2\" (default: the largest ISO 5455 scale that fits the sheet's drawing area); position_mm?: [x, y] for the view's centre on the sheet (default the sheet's centre); sheet?: {size: {standard: a3} or {custom: {sides_mm: [w, h]}}, orientation?: landscape|portrait, dpi?: 25..2400} (default A3 landscape, 300 dpi); display_style?, reference_style?: visible (default) or visible_hidden (the shaded styles aren't supported yet); reference_hides_model?: false; reference_margin_mm?: 0..100000 model mm on every side; tangent_edges?: hide (default) or show. Every body the design places, whatever the browser shows. Returns {view, scale: {text, factor, fitted}, position_mm, sheet, extents (model mm on the view's plane), boundary_mm (on the sheet), source}. Read-only: saves nothing."), + CommandSpec::new(INSPECT, "Inspect Drawing View", crate::checked!("drawing.view.inspect", INSPECT_CONTRACT, inspect)) + .icon("inspect") + .in_drawing() + .noundo() + .doc_only() + .contract(&INSPECT_CONTRACT) + .output(output_schema_for::) + .params("view: a saved view's id → {view, sheet, kind: base|projected, source, parent?, side?, direction, place: {at: [x, y]} or {aligned: n}, settings: {scale, display_style, reference_style, reference_hides_model, tangent_edges: {value, from: this|parent|default, parent?, set}}, reference_margin_mm, boundary_mm: {min, max} on the sheet (a 20 x 20 mm placeholder round the view's centre when there's nothing to measure), extents: {min, max, error_mm, status: approximate|placeholder, provenance} in model mm on the view's plane, linked? (a projected view's display settings: true, false or \"partly\"), choices: {display_style, scale}}. Read-only; no model is evaluated."), + CommandSpec::new(EDIT, "Edit Drawing View", crate::checked!("drawing.view.edit", EDIT_CONTRACT, edit)) + .icon("edit") + .in_drawing() + .doc_only() + .contract(&EDIT_CONTRACT) + .output(output_schema_for::) + .params("view: a saved view's id; set: {scale?, display_style?, reference_style?, reference_hides_model?, tangent_edges?: each a value, or null to follow the parent (a base view keeps a scale); reference_margin_mm?; view?: a base view's direction; place?: {at: [x, y]} or {aligned: n}; linked?: a projected view's display settings all following its parent (true) or all its own, as they are now (false)} → {view, changed: [fields], followers: [the views projected from it whose settings changed with it]}. One undo step; no model is evaluated."), + CommandSpec::new(MOVE, "Move View to Sheet", crate::checked!("drawing.view.move_to_sheet", MOVE_CONTRACT, move_to_sheet)) + .icon("move") + .in_drawing() + .doc_only() + .contract(&MOVE_CONTRACT) + .output(output_schema_for::) + .params("view: a saved view's id; sheet: id or name; position_mm?: [x, y] for its centre (default: where it is, or the sheet's centre for a view lined up with its parent); break_alignment?: true to move a view lined up with its parent, which is then placed apart → {view, sheet, views: [it, then the views lined up with it, which go with it], outside?: [those whose boundary leaves the sheet's drawing space, none moved back in]}. One undo step, none for the sheet it is on."), + CommandSpec::new(COPY, "Copy View to Sheet", crate::checked!("drawing.view.copy_to_sheet", COPY_CONTRACT, copy_to_sheet)) + .icon("copy") + .in_drawing() + .doc_only() + .contract(©_CONTRACT) + .output(output_schema_for::) + .params("view: a saved view's id; sheet: id or name; position_mm?: [x, y] for the copy's centre (default the sheet's centre); with_linked?: the views lined up with it copied too, lined up with the copy (true), or not (false); needed when it has any → {view: the copy, sheet, views: [the copies, its first], outside?: [those whose boundary leaves the sheet's drawing space]}. A copy follows none of the views it was copied from: a projected view copied alone becomes a base view, looking the way it did, with the settings it had. One undo step."), +]; + +fn snapshot(s: &mut Session, p: &Value) -> Result { + let request: SnapshotParams = crate::schema::read(CMD, p)?; + let settings = request.settings(); + let basis = settings.validate().map_err(|e| bad(CMD, e.to_string()))?; + if settings.display_style.is_shaded() || settings.reference_style.is_shaded() { + return Err(bad(CMD, "not supported yet: shaded views need the drawing renderer (#5624)")); + } + if !(request.sheet.dpi.is_finite() && DPI_RANGE.contains(&request.sheet.dpi)) { + return Err(bad(CMD, format!("sheet.dpi is a number from {} to {}", DPI_RANGE.start(), DPI_RANGE.end()))); + } + let sheet = Sheet { size: request.sheet.size, orientation: request.sheet.orientation }; + let paper = sheet.size_mm().map_err(|e| bad(CMD, e.to_string()))?; + let border = DrawingBorderProfile::iso().layout(&sheet).map_err(|e| bad(CMD, e.to_string()))?.drawing_border; + + let extents = crate::drawing_view::measure(s, &basis).map_err(|why| bad(CMD, why.to_string()))?; + let shown = extents.model.inflated(settings.reference_margin_mm); + let position = request.position_mm.map_or(paper * 0.5, |p| p.0); + let (scale, fitted) = match settings.scale { + Some(scale) => (scale, false), + None => (fit(shown.size(), position, border)?, true), + }; + let boundary = crate::drawing_view::boundary(basis, scale, &shown, position, CMD)?; + let on_paper = [boundary.min, boundary.max].iter().all(|c| c.is_finite() && c.x.abs() <= MAX_COORDINATE_MM && c.y.abs() <= MAX_COORDINATE_MM); + if !on_paper { + return Err(bad(CMD, format!("at scale {scale} the view reaches past ±{MAX_COORDINATE_MM} mm on paper: choose a smaller scale"))); + } + + let named = match settings.view { + ViewDirection::Named(view) => Some(snake_name(view)), + ViewDirection::Looking(_) => None, + }; + let reply = SnapshotResult { + view: ViewResult { + named, + // The line of sight, -(x × y), written so no component reads -0. + direction: basis.y.cross(basis.x).into(), + x: basis.x.into(), + y: basis.y.into(), + origin: basis.origin.into(), + }, + scale: ScaleResult { text: scale.to_string(), factor: scale.factor(), fitted }, + position_mm: position.into(), + sheet: request.sheet, + display_style: snake_name(settings.display_style), + reference_style: snake_name(settings.reference_style), + extents: extents_result(&extents, None), + boundary_mm: BoxResult { min: boundary.min.into(), max: boundary.max.into() }, + source: SourceResult { bodies: extents.bodies, timeline_at_end: s.doc.marker.is_none() }, + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| crate::EngineError::Other(e.to_string())) +} + +fn inspect(s: &mut Session, p: &Value) -> Result { + let request: InspectParams = crate::schema::read(INSPECT, p)?; + let d = s.drawing(INSPECT)?; + let view = find(d, request.view.0, INSPECT)?; + let resolved = d.resolve_view(view.id).map_err(|e| bad(INSPECT, e.to_string()))?; + let placed = crate::drawing_view::on_sheet(s, d, view.id, INSPECT)?; + let (parent, side) = match view.kind { + ViewKind::Base { .. } => (None, None), + ViewKind::Projected { parent, side } => (Some(ids::encode(parent)), Some(snake_name(side))), + }; + let own = view.settings; + let reply = InspectResult { + view: ids::encode(view.id), + sheet: ids::encode(view.sheet), + kind: if parent.is_some() { "projected" } else { "base" }, + source: ids::encode(resolved.source), + parent, + side, + direction: direction(&resolved.basis), + place: match view.place { + ViewPlace::At(at) => PlaceParam::At(at), + ViewPlace::Aligned(along) => PlaceParam::Aligned(along), + }, + settings: SettingsResult { + scale: setting(resolved.scale, own.scale, |s| s.to_string()), + display_style: setting(resolved.display_style, own.display_style, snake_name), + reference_style: setting(resolved.reference_style, own.reference_style, snake_name), + reference_hides_model: setting(resolved.reference_hides_model, own.reference_hides_model, |b| b), + tangent_edges: setting(resolved.tangent_edges, own.tangent_edges, snake_name), + }, + reference_margin_mm: view.reference_margin_mm, + boundary_mm: BoxResult { min: placed.boundary.min.into(), max: placed.boundary.max.into() }, + extents: extents_result(&placed.extents, placed.unmeasured), + linked: matches!(view.kind, ViewKind::Projected { .. }).then(|| match display_set(&own) { + 0 => Value::Bool(true), + DISPLAY_GROUP => Value::Bool(false), + _ => Value::String("partly".into()), + }), + choices: ChoicesResult { + display_style: VisualStyle::ALL.iter().map(|s| snake_name(*s)).collect(), + scale: PRESETS.iter().map(ToString::to_string).collect(), + }, + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| crate::EngineError::Other(e.to_string())) +} + +fn edit(s: &mut Session, p: &Value) -> Result { + let request: EditParams = crate::schema::read(EDIT, p)?; + let id = request.view.0; + let descendants = descendants(s.drawing(EDIT)?, id, |_| true); + let resolve = |d: &Drawing, ids: &[u64]| ids.iter().map(|id| d.resolve_view(*id).ok()).collect::>>(); + let before = resolve(s.drawing(EDIT)?, &descendants); + let changed = s.edit_drawing(EDIT, |d| change(d, id, &request.set))?; + let after = resolve(s.drawing(EDIT)?, &descendants); + let followers = descendants.iter().zip(before.iter().zip(&after)).filter(|(_, (b, a))| b != a).map(|(id, _)| ids::encode(*id)).collect(); + let reply = EditResult { view: ids::encode(id), changed, followers, param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| crate::EngineError::Other(e.to_string())) +} + +/// The display settings a linked view takes from its parent: every inheritable one but the scale, +/// which keeps its own switch. +const DISPLAY_GROUP: usize = 4; + +/// How many of the display settings `own` sets itself. +fn display_set(own: &ViewOverrides) -> usize { + [own.display_style.is_some(), own.reference_style.is_some(), own.reference_hides_model.is_some(), own.tangent_edges.is_some()] + .into_iter() + .filter(|set| *set) + .count() +} + +/// View `id` of `d`, for `cmd`. +fn find<'a>(d: &'a Drawing, id: u64, cmd: &str) -> Result<&'a View> { + d.views.iter().find(|v| v.id == id).map(|v| &**v).ok_or_else(|| bad(cmd, format!("the drawing has no view {}", ids::encode(id)))) +} + +/// The views projected from view `id`, directly or through others, in the drawing's order: each +/// one `follows` takes, whose parent is `id` or one of them. +fn descendants(d: &Drawing, id: u64, follows: impl Fn(&View) -> bool) -> Vec { + let mut found = vec![id]; + // Each pass adds the views whose parent is found; a chain is at most MAX_VIEW_DEPTH views. + for _ in 0..solidcraft_doc::drawing::view::MAX_VIEW_DEPTH { + let more: Vec = d + .views + .iter() + .filter(|v| !found.contains(&v.id) && matches!(v.kind, ViewKind::Projected { parent, .. } if found.contains(&parent)) && follows(v)) + .map(|v| v.id) + .collect(); + if more.is_empty() { + break; + } + found.extend(more); + } + found.retain(|v| *v != id); + d.views.iter().map(|v| v.id).filter(|v| found.contains(v)).collect() +} + +/// `set` made on view `id` of `d`: the fields it changes, by name. +fn change(d: &mut Drawing, id: u64, set: &ViewSet) -> Result> { + let resolved = d.resolve_view(id).map_err(|e| bad(EDIT, e.to_string()))?; + let at = d.views.iter().position(|v| v.id == id).ok_or_else(|| bad(EDIT, format!("the drawing has no view {}", ids::encode(id))))?; + let Some(view) = d.views.get_mut(at).map(std::sync::Arc::make_mut) else { return Ok(Vec::new()) }; + let before = view.clone(); + let base = matches!(view.kind, ViewKind::Base { .. }); + let own = &mut view.settings; + if let Some(linked) = set.linked { + if base { + return Err(bad(EDIT, "a base view has no parent to follow: `linked` is a projected view's")); + } + // Following: the display settings cleared. Its own: each at the value it has now. + own.display_style = (!linked).then_some(resolved.display_style.value); + own.reference_style = (!linked).then_some(resolved.reference_style.value); + own.reference_hides_model = (!linked).then_some(resolved.reference_hides_model.value); + own.tangent_edges = (!linked).then_some(resolved.tangent_edges.value); + } + if let Some(scale) = set.scale { + if base && scale.is_none() { + return Err(bad(EDIT, "a base view has no parent to follow: it keeps a scale")); + } + own.scale = scale.map(|s| s.0); + } + if let Some(style) = set.display_style { + own.display_style = style.map(|s| s.0); + } + if let Some(style) = set.reference_style { + own.reference_style = style.map(|s| s.0); + } + if let Some(hides) = set.reference_hides_model { + own.reference_hides_model = hides; + } + if let Some(edges) = set.tangent_edges { + own.tangent_edges = edges.map(|e| e.0); + } + if let Some(margin) = set.reference_margin_mm { + view.reference_margin_mm = margin; + } + if let Some(direction) = set.view { + let ViewKind::Base { view: looking, .. } = &mut view.kind else { + return Err(bad(EDIT, "a projected view looks from its side of its parent: only a base view's direction changes")); + }; + *looking = direction.0; + } + if let Some(place) = set.place { + view.place = match place { + PlaceParam::At(at) => ViewPlace::At(at), + PlaceParam::Aligned(along) => ViewPlace::Aligned(along), + }; + } + Ok(changed_fields(&before, view)) +} + +/// The names of the fields that differ between `a` and `b`, two states of one view. +fn changed_fields(a: &View, b: &View) -> Vec { + let (x, y) = (&a.settings, &b.settings); + let fields = [ + ("scale", x.scale != y.scale), + ("display_style", x.display_style != y.display_style), + ("reference_style", x.reference_style != y.reference_style), + ("reference_hides_model", x.reference_hides_model != y.reference_hides_model), + ("tangent_edges", x.tangent_edges != y.tangent_edges), + ("reference_margin_mm", a.reference_margin_mm != b.reference_margin_mm), + ("view", a.kind != b.kind), + ("place", a.place != b.place), + ]; + fields.into_iter().filter(|(_, changed)| *changed).map(|(name, _)| name.to_string()).collect() +} + +/// Extents as the replies give them: measured on the display mesh, or a placeholder's and why. +/// The views [`crate::drawing_view::outside`] lists, as the commands answer them. +pub(super) fn outside_results(outside: Vec<(u64, OnSheet)>) -> Vec { + let result = |(id, placed): (u64, OnSheet)| OutsideResult { + view: ids::encode(id), + boundary_mm: BoxResult { min: placed.boundary.min.into(), max: placed.boundary.max.into() }, + unmeasured: placed.unmeasured.map(Unmeasured::name), + }; + outside.into_iter().map(result).collect() +} + +fn extents_result(extents: &Extents, unmeasured: Option) -> ExtentsResult { + ExtentsResult { + min: extents.model.min.into(), + max: extents.model.max.into(), + error_mm: extents.error_mm, + status: if unmeasured.is_some() { "placeholder" } else { "approximate" }, + provenance: unmeasured.map_or("display_mesh", Unmeasured::name), + } +} + +/// A resolved setting as inspect shows it: its value, where it comes from and what the view sets. +fn setting(resolved: Setting, own: Option, show: impl Fn(T) -> U) -> SettingResult { + let (from, parent) = match resolved.set_by { + SetBy::This => (FromResult::This, None), + SetBy::Parent(id) => (FromResult::Parent, Some(ids::encode(id))), + SetBy::Default => (FromResult::Default, None), + }; + SettingResult { value: show(resolved.value), from, parent, set: own.map(&show) } +} + +/// The views lined up with view `id`, directly or through others: the views that go where it goes. +fn lined_up(d: &Drawing, id: u64) -> Vec { + descendants(d, id, |v| matches!(v.place, ViewPlace::Aligned(_))) +} + +/// `view`'s place moved by `by`: a point moves, and a place lined up with a parent moves along +/// its free axis, so the views lined up with a moved view stay where they were beside it. +fn shifted(view: &View, by: Vec2) -> ViewPlace { + match (view.place, view.kind) { + (ViewPlace::At([x, y]), _) => ViewPlace::At([x + by.x, y + by.y]), + (ViewPlace::Aligned(along), ViewKind::Projected { side, .. }) => ViewPlace::Aligned(along + side.along(by)), + (ViewPlace::Aligned(along), ViewKind::Base { .. }) => ViewPlace::Aligned(along + by.y), + } +} + +/// The sheet `named` names in `d` (its id or its one name), and its centre. +fn sheet_named(d: &Drawing, named: &str, cmd: &str) -> Result<(u64, Vec2)> { + let at = d.sheet_index(named).map_err(|e| bad(cmd, e.to_string()))?; + let sheet = d.sheets.get(at).ok_or_else(|| bad(cmd, format!("no sheet `{named}`")))?; + Ok((sheet.id, sheet.sheet.size_mm().map_err(|e| bad(cmd, e.to_string()))? * 0.5)) +} + +fn move_to_sheet(s: &mut Session, p: &Value) -> Result { + let request: MoveParams = crate::schema::read(MOVE, p)?; + let id = request.view.0; + let (sheet, views) = s.edit_drawing(MOVE, |d| { + let (sheet, middle) = sheet_named(d, &request.sheet, MOVE)?; + let view = find(d, id, MOVE)?; + if view.sheet == sheet { + return Ok((sheet, Vec::new())); + } + let lined = matches!(view.place, ViewPlace::Aligned(_)); + if lined && !request.break_alignment { + return Err(bad(MOVE, "it is lined up with its parent, which stays on its sheet: give `break_alignment: true` to place it apart")); + } + let from = d.view_centre(id).map_err(|e| bad(MOVE, e.to_string()))?; + let to = match request.position_mm { + Some(p) => p.0, + None if lined => middle, + None => from, + }; + let moved: Vec = std::iter::once(id).chain(lined_up(d, id)).collect(); + for view in d.views.iter_mut().filter(|v| moved.contains(&v.id)) { + let place = if view.id == id { ViewPlace::At([to.x, to.y]) } else { shifted(view, to - from) }; + let view = Arc::make_mut(view); + view.sheet = sheet; + view.place = place; + } + Ok((sheet, moved)) + })?; + let outside = crate::drawing_view::outside(s, s.drawing(MOVE)?, &views, MOVE)?; + to_sheet_answer(id, sheet, &views, outside) +} + +fn copy_to_sheet(s: &mut Session, p: &Value) -> Result { + let request: CopyParams = crate::schema::read(COPY, p)?; + let id = request.view.0; + let record = s.drawing(COPY)?.clone(); + find(&record, id, COPY)?; + let linked = lined_up(&record, id); + let with_linked = match request.with_linked { + Some(with) => with, + None if linked.is_empty() => false, + None => { + let names = linked.iter().map(|v| ids::encode(*v)).collect::>().join(", "); + return Err(bad(COPY, format!("views {names} are lined up with it: give `with_linked` (true to copy them too, false for it alone)"))); + } + }; + let originals: Vec = std::iter::once(id).chain(linked.into_iter().filter(|_| with_linked)).collect(); + let copies = originals + .iter() + .map(|_| record.allocate_id(&mut s.ids)) + .collect::>>() + .map_err(|e| bad(COPY, e.to_string()))?; + let copy_of = |old: u64| originals.iter().position(|o| *o == old).and_then(|i| copies.get(i)).copied(); + let sheet = s.edit_drawing(COPY, |d| { + let (sheet, middle) = sheet_named(d, &request.sheet, COPY)?; + let from = d.view_centre(id).map_err(|e| bad(COPY, e.to_string()))?; + let to = request.position_mm.map_or(middle, |p| p.0); + let resolved = d.resolve_view(id).map_err(|e| bad(COPY, e.to_string()))?; + let mut made = Vec::with_capacity(copies.len()); + for (old, new) in originals.iter().zip(&copies) { + let original = find(d, *old, COPY)?; + let mut view = View { id: *new, sheet, ..original.clone() }; + view.place = shifted(original, to - from); + match original.kind { + // The copy follows none of the views it came from: a projected view copied alone is + // a base view, looking the way it did, with the settings it had as its own. + ViewKind::Projected { .. } if *old == id => { + view.kind = ViewKind::Base { source: resolved.source, view: looking(&resolved.basis) }; + view.settings = ViewOverrides { + scale: Some(resolved.scale.value), + display_style: Some(resolved.display_style.value), + reference_style: Some(resolved.reference_style.value), + reference_hides_model: Some(resolved.reference_hides_model.value), + tangent_edges: Some(resolved.tangent_edges.value), + }; + view.place = ViewPlace::At([to.x, to.y]); + } + ViewKind::Projected { parent, side } => view.kind = ViewKind::Projected { parent: copy_of(parent).unwrap_or(parent), side }, + ViewKind::Base { .. } => {} + } + made.push(Arc::new(view)); + } + d.views.extend(made); + Ok(sheet) + })?; + let first = copies.first().copied().unwrap_or_default(); + let outside = crate::drawing_view::outside(s, s.drawing(COPY)?, &copies, COPY)?; + to_sheet_answer(first, sheet, &copies, outside) +} + +fn to_sheet_answer(view: u64, sheet: u64, views: &[u64], outside: Vec<(u64, OnSheet)>) -> Result { + let reply = ToSheetResult { + view: ids::encode(view), + sheet: ids::encode(sheet), + views: views.iter().map(|v| ids::encode(*v)).collect(), + outside: outside_results(outside), + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| crate::EngineError::Other(e.to_string())) +} + +/// The named view that is exactly `basis`, if one is. +fn named(basis: &Plane) -> Option { + NamedView::ALL.iter().copied().find(|v| v.basis() == *basis) +} + +/// `basis` as a base view saves it: by name when it is exactly a named view's, so nothing rounds; +/// else its line of sight and up, which give the same basis back to within rounding. +fn looking(basis: &Plane) -> ViewDirection { + named(basis).map_or_else( + || ViewDirection::Looking(Looking { direction: basis.y.cross(basis.x).into(), up: basis.y.into(), origin: basis.origin.into() }), + ViewDirection::Named, + ) +} + +/// A basis as the replies give it: its name when it is exactly a named view's. +fn direction(basis: &Plane) -> ViewResult { + ViewResult { + named: named(basis).map(snake_name), + // The line of sight, -(x × y), written so no component reads -0. + direction: basis.y.cross(basis.x).into(), + x: basis.x.into(), + y: basis.y.into(), + origin: basis.origin.into(), + } +} + +/// The largest preset scale at which a view `size` (model mm), centred at `position`, lies inside +/// the drawing border: the room is twice the distance from the position to the nearer side, +/// each way. +fn fit(size: Vec2, position: Vec2, border: Aabb2) -> Result { + let room = + Vec2::new(2.0 * (position.x - border.min.x).min(border.max.x - position.x), 2.0 * (position.y - border.min.y).min(border.max.y - position.y)); + Scale::fit(size, room).ok_or_else(|| { + let name = |s: Option<&Scale>| s.map(|s| s.to_string()).unwrap_or_default(); + let presets = format!("from {} to {}", name(PRESETS.first()), name(PRESETS.last())); + bad(CMD, format!("the view fits the sheet's drawing area at no preset scale {presets} here: give a scale, a position or a larger sheet")) + }) +} + +/// A unit enum's name as it reads and writes (`iso_front_right`, `visible_hidden`). +fn snake_name(value: impl Serialize) -> String { + serde_json::to_value(value).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default() +} + +#[cfg(test)] +#[path = "drawing_view_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/drawing_view_tests.rs b/crates/engine/src/cmd/drawing_view_tests.rs new file mode 100644 index 00000000000..b6708a1d05c --- /dev/null +++ b/crates/engine/src/cmd/drawing_view_tests.rs @@ -0,0 +1,620 @@ +use std::sync::Arc; + +use serde_json::json; +use solidcraft_doc::MAX_PLACEMENT_DEPTH; +use solidcraft_geom::cell::Projection; +use solidcraft_geom::drawing_view::ProjectedSide; + +use super::*; +use crate::schema::tests::conforms; + +const EPS: f64 = 1e-9; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap() +} + +/// A block 100 x 50 x 20 mm along X, Y and Z, from the origin. +fn block() -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 100, "width": 50, "height": 20, "body_name": "Block"})); + s +} + +fn snap(s: &mut Session, p: Value) -> Value { + run(s, CMD, p) +} + +fn refused(s: &mut Session, p: Value) -> String { + s.execute(CMD, &p).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("accepted: {p}")) +} + +fn point(v: &Value) -> Vec2 { + Vec2::new(v[0].as_f64().unwrap(), v[1].as_f64().unwrap()) +} + +/// The boundary's size and centre on the sheet. +fn boundary(v: &Value) -> (Vec2, Vec2) { + let (min, max) = (point(&v["boundary_mm"]["min"]), point(&v["boundary_mm"]["max"])); + (max - min, (min + max) * 0.5) +} + +/// `v`'s boundary is the box from `min` to `max` on the sheet. +fn assert_box(v: &Value, min: [f64; 2], max: [f64; 2]) { + let (lo, hi) = (point(&v["boundary_mm"]["min"]), point(&v["boundary_mm"]["max"])); + assert!((lo - Vec2::from(min)).len() < EPS && (hi - Vec2::from(max)).len() < EPS, "{v}"); +} + +/// A drawing of the block: its front view at 1:2 drawing hidden lines too, the right view lined up +/// with it, and the right view's top view placed apart. The session and the three views' ids. +fn three_views() -> (Session, [u64; 3]) { + three_views_of(block()) +} + +/// [`three_views`] of the design `s`. +fn three_views_of(mut s: Session) -> (Session, [u64; 3]) { + run(&mut s, "drawing.create", json!({})); + let mut d = (**s.drawing("test").unwrap()).clone(); + let mut id_source = solidcraft_doc::ids::IdSource::seeded(4816); + let (sheet, source) = (d.sheets[0].id, d.sources[0].id); + let mut add = |d: &mut Drawing, kind: ViewKind, place: ViewPlace, settings: ViewOverrides| { + let id = d.allocate_id(&mut id_source).unwrap(); + d.views.push(Arc::new(View { id, sheet, kind, place, settings, reference_margin_mm: 0.0 })); + id + }; + let front_settings = + ViewOverrides { scale: Some("1:2".parse().unwrap()), display_style: Some(VisualStyle::VisibleHidden), ..ViewOverrides::default() }; + let front = ViewKind::Base { source, view: ViewDirection::Named(NamedView::Front) }; + let front = add(&mut d, front, ViewPlace::At([150.0, 150.0]), front_settings); + let right = add(&mut d, ViewKind::Projected { parent: front, side: ProjectedSide::Right }, ViewPlace::Aligned(300.0), ViewOverrides::default()); + let top = add(&mut d, ViewKind::Projected { parent: right, side: ProjectedSide::Above }, ViewPlace::At([300.0, 250.0]), ViewOverrides::default()); + d.validate().unwrap(); + s.doc_mut().put_drawing(Arc::new(d)); + (s, [front, right, top]) +} + +fn inspect_view(s: &mut Session, view: u64) -> Value { + let reply = run(s, INSPECT, json!({"view": ids::encode(view)})); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}"); + reply +} + +fn edit_view(s: &mut Session, view: u64, set: Value) -> Value { + let reply = run(s, EDIT, json!({"view": ids::encode(view), "set": set})); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}"); + reply +} + +fn set_projection(s: &mut Session, projection: Projection) { + let mut d = (**s.drawing("test").unwrap()).clone(); + d.projection = projection; + s.doc_mut().put_drawing(Arc::new(d)); +} + +/// Component `L{level}`, placed inside `L{level - 1}` (the design itself at level 0). +fn nest(s: &mut Session, level: u64) { + let (component, parent) = (1000 + level, if level == 0 { 0 } else { 1000 + level - 1 }); + let doc = s.doc_mut(); + doc.components.push(solidcraft_doc::Component { id: component, name: format!("L{level}"), parent, ..Default::default() }); + let name = format!("L{level}"); + // From JSON, so a field another change adds to occurrences takes its default here. + let occurrence = json!({"id": 5000 + level, "component": component, "parent": parent, "name": name}); + doc.occurrences.push(serde_json::from_value(occurrence).unwrap()); +} + +fn edit_refused(s: &mut Session, view: u64, set: Value) -> String { + s.execute(EDIT, &json!({"view": ids::encode(view), "set": set})).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("accepted: {set}")) +} + +/// Each setting says its value, where it comes from (the view, a parent by id, or the default) and +/// what the view sets itself; a projected view says whether it follows its parent's display; the +/// direction is named only when it is exactly a named view's. +#[test] +fn inspect_says_where_each_setting_comes_from() { + let (mut s, [front, right, top]) = three_views(); + let front_id = ids::encode(front); + let base = inspect_view(&mut s, front); + assert_eq!( + (base["kind"].clone(), base["direction"]["named"].clone(), base["place"].clone()), + (json!("base"), json!("front"), json!({"at": [150.0, 150.0]})) + ); + assert_eq!(base["settings"]["scale"], json!({"value": "1:2", "from": "this", "set": "1:2"})); + assert_eq!(base["settings"]["display_style"], json!({"value": "visible_hidden", "from": "this", "set": "visible_hidden"})); + assert_eq!(base["settings"]["reference_style"], json!({"value": "visible", "from": "default", "set": null})); + assert!(base.get("linked").is_none() && base.get("parent").is_none(), "a base view has no parent"); + let projected = inspect_view(&mut s, right); + assert_eq!( + (projected["kind"].clone(), projected["parent"].clone(), projected["side"].clone()), + (json!("projected"), json!(front_id), json!("right")) + ); + assert_eq!( + (projected["direction"]["named"].clone(), projected["place"].clone(), projected["linked"].clone()), + (json!("right"), json!({"aligned": 300.0}), json!(true)) + ); + assert_eq!(projected["settings"]["scale"], json!({"value": "1:2", "from": "parent", "parent": front_id, "set": null})); + assert_eq!(projected["source"], base["source"]); + let chained = inspect_view(&mut s, top); + assert_eq!(chained["settings"]["display_style"], json!({"value": "visible_hidden", "from": "parent", "parent": front_id, "set": null})); + assert!(chained["direction"].get("named").is_none(), "the right view's top view is no named view: {chained}"); + assert_eq!(chained["choices"]["display_style"].as_array().unwrap().len(), 5); + assert_eq!(chained["choices"]["scale"][0], "50:1"); + assert!(s.execute(INSPECT, &json!({"view": ids::encode(99)})).unwrap_err().to_string().contains("no view")); +} + +/// An edit is one undo step that evaluates no model: it names what it changed and the views +/// projected from it whose settings changed with it; `null` follows the parent again; linking and +/// unlinking set or clear the display settings together; what isn't a view's to change is refused, +/// and an edit that changes nothing is no step. +#[test] +fn an_edit_is_one_undo_step_and_names_its_followers() { + let (mut s, [front, right, top]) = three_views(); + let evaluations = s.evaluations; + let steps = s.undo.len(); + let edited = edit_view(&mut s, right, json!({"display_style": "visible"})); + assert_eq!((edited["changed"].clone(), edited["followers"].clone()), (json!(["display_style"]), json!([ids::encode(top)]))); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!(inspect_view(&mut s, right)["linked"], "partly"); + assert_eq!(inspect_view(&mut s, top)["settings"]["display_style"]["parent"], json!(ids::encode(right))); + run(&mut s, "edit.undo", json!({})); + assert_eq!(inspect_view(&mut s, right)["settings"]["display_style"]["from"], "parent"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(edit_view(&mut s, right, json!({"display_style": null}))["changed"], json!(["display_style"])); + assert_eq!(inspect_view(&mut s, right)["settings"]["display_style"]["from"], "parent", "null follows the parent again"); + // Unlinked, the display settings are its own at the values they had; linked, they follow again. + edit_view(&mut s, right, json!({"linked": false})); + let unlinked = inspect_view(&mut s, right); + assert_eq!((unlinked["linked"].clone(), unlinked["settings"]["display_style"]["set"].clone()), (json!(false), json!("visible_hidden"))); + edit_view(&mut s, right, json!({"linked": true})); + assert_eq!(inspect_view(&mut s, right)["linked"], true); + // A base view keeps a scale and has nothing to link to; a projected view's direction is its side's. + assert!(edit_refused(&mut s, front, json!({"scale": null})).contains("keeps a scale")); + assert!(edit_refused(&mut s, front, json!({"linked": true})).contains("no parent")); + assert!(edit_refused(&mut s, right, json!({"view": "top"})).contains("only a base view's direction")); + assert!(edit_refused(&mut s, front, json!({"place": {"aligned": 10.0}})).contains("a base view is placed at a point")); + assert!(edit_refused(&mut s, front, json!({"dpi": 300.0})).contains("dpi"), "a resolution is the sheet's"); + assert!(edit_refused(&mut s, front, json!({"scale": "1:0"})).contains("scale")); + assert!(edit_refused(&mut s, 99, json!({})).contains("no view")); + // The front view turned to the top, and the right view placed apart. + let turned = edit_view(&mut s, front, json!({"view": "top", "scale": "1:5"})); + assert_eq!(turned["changed"], json!(["scale", "view"])); + assert_eq!(turned["followers"], json!([ids::encode(right), ids::encode(top)])); + assert_eq!(edit_view(&mut s, right, json!({"place": {"at": [320.0, 150.0]}}))["changed"], json!(["place"])); + assert_eq!(edit_view(&mut s, top, json!({"reference_margin_mm": 5.0}))["changed"], json!(["reference_margin_mm"])); + assert_eq!(inspect_view(&mut s, top)["reference_margin_mm"], 5.0); + assert!(edit_refused(&mut s, top, json!({"reference_margin_mm": -1.0})).contains("reference margin")); + // Nothing changed, no step. + let steps = s.undo.len(); + assert_eq!(edit_view(&mut s, front, json!({"scale": "1:5"}))["changed"], json!([])); + assert_eq!(s.undo.len(), steps, "no change, no step"); + assert_eq!(s.evaluations, evaluations, "no model is evaluated"); +} + +/// A second sheet in the drawing, A3 landscape as the first: its id. +fn second_sheet(s: &mut Session) -> u64 { + let added = run(s, "drawing.sheet.add", json!({})); + ids::decode(added["sheet"].as_str().unwrap()).unwrap() +} + +/// View `id` as the drawing holds it. +fn saved(s: &Session, id: u64) -> View { + s.drawing("test").unwrap().views.iter().find(|v| v.id == id).map(|v| (**v).clone()).unwrap() +} + +fn to_sheet(s: &mut Session, cmd: &str, p: Value) -> Value { + let reply = run(s, cmd, p); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}"); + reply +} + +fn listed(reply: &Value) -> Vec { + reply["views"].as_array().unwrap().iter().map(|v| ids::decode(v.as_str().unwrap()).unwrap()).collect() +} + +/// A move is one undo step: the view and the views lined up with it go to the sheet and keep their +/// places beside it, and a view placed apart stays. Without a position it keeps its own; to its +/// own sheet it changes nothing. +#[test] +fn a_moved_view_takes_the_views_lined_up_with_it() { + let (mut s, [front, right, top]) = three_views(); + let (first, second) = (saved(&s, front).sheet, second_sheet(&mut s)); + let steps = s.undo.len(); + let moved = to_sheet(&mut s, MOVE, json!({"view": ids::encode(front), "sheet": ids::encode(second), "position_mm": [100.0, 120.0]})); + assert_eq!((listed(&moved), moved["sheet"].clone()), (vec![front, right], json!(ids::encode(second)))); + assert_eq!(s.undo.len(), steps + 1); + assert_eq!((saved(&s, front).sheet, saved(&s, front).place), (second, ViewPlace::At([100.0, 120.0]))); + assert_eq!((saved(&s, right).sheet, saved(&s, right).place), (second, ViewPlace::Aligned(250.0)), "50 mm left, as its parent went"); + assert_eq!(saved(&s, top).sheet, first, "a view placed apart stays"); + run(&mut s, "edit.undo", json!({})); + assert_eq!((saved(&s, front).sheet, saved(&s, right).sheet, saved(&s, right).place), (first, first, ViewPlace::Aligned(300.0))); + to_sheet(&mut s, MOVE, json!({"view": ids::encode(front), "sheet": "Sheet 2"})); + assert_eq!((saved(&s, front).place, saved(&s, right).place), (ViewPlace::At([150.0, 150.0]), ViewPlace::Aligned(300.0)), "by name, where it was"); + let steps = s.undo.len(); + assert_eq!(to_sheet(&mut s, MOVE, json!({"view": ids::encode(front), "sheet": ids::encode(second)}))["views"], json!([])); + assert_eq!(s.undo.len(), steps, "its own sheet: no step"); +} + +/// A view lined up with its parent moves only with `break_alignment`, and is then placed apart: at +/// the position, else the sheet's centre; the views lined up with it keep their places beside it. +/// What would break the record (an unknown view or sheet, a place off the paper) is refused, and +/// changes nothing. +#[test] +fn a_lined_up_view_moves_only_when_its_line_up_is_broken() { + let (mut s, [front, right, top]) = three_views(); + let second = second_sheet(&mut s); + let to = |view: u64, more: Value| { + let mut p = json!({"view": ids::encode(view), "sheet": ids::encode(second)}); + p.as_object_mut().unwrap().extend(more.as_object().unwrap().clone()); + p + }; + let refused = |s: &mut Session, p: Value| s.execute(MOVE, &p).err().map(|e| e.to_string()).unwrap_or_else(|| panic!("accepted: {p}")); + assert!(refused(&mut s, to(right, json!({}))).contains("break_alignment")); + // The top view lined up above the right view, whose centre is (300, 150). + edit_view(&mut s, top, json!({"place": {"aligned": 250.0}})); + let moved = to_sheet(&mut s, MOVE, to(right, json!({"break_alignment": true, "position_mm": [200.0, 100.0]}))); + assert_eq!(listed(&moved), [right, top]); + assert_eq!( + (saved(&s, right).place, saved(&s, top).place, saved(&s, top).sheet), + (ViewPlace::At([200.0, 100.0]), ViewPlace::Aligned(200.0), second) + ); + assert_eq!(saved(&s, front).sheet, s.drawing("test").unwrap().sheets[0].id, "its parent stays"); + run(&mut s, "edit.undo", json!({})); + to_sheet(&mut s, MOVE, to(right, json!({"break_alignment": true}))); + assert_eq!((saved(&s, right).place, saved(&s, top).place), (ViewPlace::At([210.0, 148.5]), ViewPlace::Aligned(248.5)), "the A3 sheet's centre"); + run(&mut s, "edit.undo", json!({})); + let before = s.drawing("test").unwrap().clone(); + assert!(refused(&mut s, to(99, json!({}))).contains("no view")); + assert!(refused(&mut s, json!({"view": ids::encode(front), "sheet": "Sheet 9"})).contains("no sheet")); + assert!(refused(&mut s, to(front, json!({"position_mm": [1e8, 0.0]}))).contains("5000")); + assert!(refused(&mut s, to(front, json!({"position_mm": [4990.0, 150.0]}))).contains("5000"), "the right view would land off the paper"); + assert!(refused(&mut s, to(front, json!({"break_alignment": "yes"}))).contains("break_alignment")); + assert_eq!(*s.drawing("test").unwrap(), before); +} + +/// A copy is one undo step of new views, independent of the ones it came from: with its linked +/// views, they are copied lined up with the copy; without, it goes alone. Without a choice, a view +/// with views lined up with it is refused, naming them. +#[test] +fn a_copy_takes_its_linked_views_only_when_asked() { + let (mut s, [front, right, top]) = three_views(); + let second = second_sheet(&mut s); + let message = s.execute(COPY, &json!({"view": ids::encode(front), "sheet": ids::encode(second)})).unwrap_err().to_string(); + assert!(message.contains("with_linked") && message.contains(&ids::encode(right)), "{message}"); + let steps = s.undo.len(); + let p = json!({"view": ids::encode(front), "sheet": ids::encode(second), "position_mm": [100.0, 100.0], "with_linked": true}); + let copied = to_sheet(&mut s, COPY, p); + let [copy, side] = listed(&copied)[..] else { panic!("{copied}") }; + assert_eq!(s.undo.len(), steps + 1); + assert!(![front, right, top].contains(©) && ![front, right, top].contains(&side), "new ids"); + assert_eq!(copied["view"], json!(ids::encode(copy))); + let (original, made) = (saved(&s, front), saved(&s, copy)); + assert_eq!((made.sheet, made.kind, made.settings, made.place), (second, original.kind, original.settings, ViewPlace::At([100.0, 100.0]))); + assert_eq!(saved(&s, side).kind, ViewKind::Projected { parent: copy, side: ProjectedSide::Right }, "lined up with the copy, not the original"); + assert_eq!((saved(&s, side).place, saved(&s, side).sheet), (ViewPlace::Aligned(250.0), second)); + assert_eq!((saved(&s, front).place, saved(&s, right).place), (ViewPlace::At([150.0, 150.0]), ViewPlace::Aligned(300.0)), "the originals stay"); + // An edit of the original changes nothing of the copies. + edit_view(&mut s, front, json!({"scale": "1:5"})); + assert_eq!(inspect_view(&mut s, side)["settings"]["scale"]["value"], "1:2"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.drawing("test").unwrap().views.len(), 3, "the undo takes both copies away"); + let alone = to_sheet(&mut s, COPY, json!({"view": ids::encode(front), "sheet": ids::encode(second), "with_linked": false})); + assert_eq!(listed(&alone).len(), 1); + assert_eq!(saved(&s, listed(&alone)[0]).place, ViewPlace::At([210.0, 148.5]), "the sheet's centre"); + // Beside the original, on its own sheet. + let first = saved(&s, front).sheet; + let beside = to_sheet(&mut s, COPY, json!({"view": ids::encode(top), "sheet": ids::encode(first), "position_mm": [60.0, 60.0]})); + assert_eq!(saved(&s, listed(&beside)[0]).sheet, first); +} + +/// A copy's ids come from the session's id source, as every drawing object's do: sessions seeded +/// alike copy a view and the view lined up with it to the same new ids (where a crash replay +/// starts), another seed to others. +#[test] +fn a_copys_ids_come_from_the_sessions_seed() { + let copied = |seed: u64| { + let (mut s, [front, ..]) = three_views(); + s.seed_ids(seed); + let second = second_sheet(&mut s); + let p = json!({"view": ids::encode(front), "sheet": ids::encode(second), "with_linked": true}); + listed(&to_sheet(&mut s, COPY, p)) + }; + assert_eq!(copied(7), copied(7)); + assert_ne!(copied(7), copied(8)); +} + +/// A projected view copied alone is a base view of its own: looking the way it did (by name when it +/// is exactly a named view, else by its line of sight and up), with the settings it resolved to as +/// its own, whatever its old parents do after. +#[test] +fn a_side_view_copied_alone_is_a_base_view_looking_the_way_it_did() { + let (mut s, [front, right, top]) = three_views(); + let source = s.drawing("test").unwrap().sources[0].id; + let copy = |s: &mut Session, view: u64| listed(&to_sheet(s, COPY, json!({"view": ids::encode(view), "sheet": "Sheet 1"})))[0]; + let of_right = copy(&mut s, right); + let made = saved(&s, of_right); + assert_eq!(made.kind, ViewKind::Base { source, view: ViewDirection::Named(NamedView::Right) }); + let own = ViewOverrides { + scale: Some("1:2".parse().unwrap()), + display_style: Some(VisualStyle::VisibleHidden), + reference_style: Some(VisualStyle::Visible), + reference_hides_model: Some(false), + tangent_edges: Some(Default::default()), + }; + assert_eq!(made.settings, own); + let of_top = copy(&mut s, top); + let d = s.drawing("test").unwrap().clone(); + let ViewKind::Base { view: ViewDirection::Looking(_), .. } = saved(&s, of_top).kind else { panic!("the right view's top view is no named view") }; + let (was, is) = (d.resolve_view(top).unwrap().basis, d.resolve_view(of_top).unwrap().basis); + for (a, b) in [(was.x, is.x), (was.y, is.y), (was.origin, is.origin)] { + assert!((a - b).len() < 1e-12, "{a:?} {b:?}"); + } + edit_view(&mut s, front, json!({"display_style": "visible", "scale": "1:10"})); + assert_eq!(saved(&s, of_right).settings, own, "the copy follows nothing"); +} + +/// The block's boundary in each view at 1:2, worked by hand: front 50 x 10, top 50 x 25, right +/// 25 x 10, and from an isometric corner (100 + 50)/sqrt(2)/2 by (100 + 50 + 2 x 20)/sqrt(6)/2. +/// The centre lands on the position, and the extents are the model's own millimetres. +#[test] +fn a_blocks_boundary_in_each_view_is_its_size_at_the_scale() { + let mut s = block(); + let views = [ + (json!("front"), (50.0, 10.0)), + (json!("top"), (50.0, 25.0)), + (json!("right"), (25.0, 10.0)), + (json!("iso"), (150.0 / 2f64.sqrt() / 2.0, 190.0 / 6f64.sqrt() / 2.0)), + (json!({"direction": [0, 1, 0], "up": [0, 0, 1]}), (50.0, 10.0)), + ]; + for (view, (w, h)) in views { + let v = snap(&mut s, json!({"view": view, "scale": "1:2", "position_mm": [100, 120]})); + let (size, centre) = boundary(&v); + assert!((size - Vec2::new(w, h)).len() < EPS, "{view}: {size:?}"); + assert!((centre - Vec2::new(100.0, 120.0)).len() < EPS, "{view}: {centre:?}"); + assert_eq!((v["scale"]["text"].as_str(), v["scale"]["fitted"].as_bool()), (Some("1:2"), Some(false))); + } + let front = snap(&mut s, json!({"scale": "1:2"})); + assert_eq!(front["view"]["named"], "front"); + assert_eq!((front["view"]["direction"].clone(), front["view"]["x"].clone()), (json!([0.0, 1.0, 0.0]), json!([1.0, 0.0, 0.0]))); + assert!((point(&front["extents"]["min"]) - Vec2::ZERO).len() < EPS && (point(&front["extents"]["max"]) - Vec2::new(100.0, 20.0)).len() < EPS); + assert_eq!((front["extents"]["status"].as_str(), front["source"]["bodies"].as_u64()), (Some("approximate"), Some(1))); + assert_eq!(front["source"]["timeline_at_end"], true); + let iso = snap(&mut s, json!({"view": "iso", "scale": "1:2"})); + assert_eq!(iso["view"]["named"], "iso_front_right"); +} + +/// With no scale the view takes the largest preset scale that fits the sheet's drawing border, +/// centred on the sheet: the 100 x 20 front view on A3 landscape at 2:1 (5:1 would be 500 mm +/// wide), boundary 110..310 x 128.5..168.5. A scale given is used as it is, even when it overhangs. +#[test] +fn without_a_scale_the_view_fits_and_centres_on_its_sheet() { + let mut s = block(); + let v = snap(&mut s, json!({})); + assert_eq!((v["scale"]["text"].as_str(), v["scale"]["fitted"].as_bool()), (Some("2:1"), Some(true))); + assert!((point(&v["boundary_mm"]["min"]) - Vec2::new(110.0, 128.5)).len() < EPS, "{v}"); + assert!((point(&v["boundary_mm"]["max"]) - Vec2::new(310.0, 168.5)).len() < EPS, "{v}"); + let a4 = snap(&mut s, json!({"sheet": {"size": {"standard": "a4"}, "orientation": "portrait"}})); + assert_eq!(a4["scale"]["text"], "1:1", "A4 portrait has 95 mm to the border each side: 190 mm of room, so 2:1 (200 mm) doesn't fit"); + let near_the_left = snap(&mut s, json!({"position_mm": [80, 148.5]})); + assert_eq!(near_the_left["scale"]["text"], "1:1", "70 mm to the left border: 140 mm of room"); + let overhanging = snap(&mut s, json!({"scale": "5:1"})); + assert!((boundary(&overhanging).0 - Vec2::new(500.0, 100.0)).len() < EPS); + let off_the_border = refused(&mut s, json!({"position_mm": [5, 148.5]})); + assert!(off_the_border.contains("no preset scale from 50:1 to 1:10000"), "{off_the_border}"); + assert_eq!(a4["sheet"], json!({"size": {"standard": "a4"}, "orientation": "portrait", "dpi": 300.0}), "the sheet, its defaults filled in"); +} + +/// Scale and position only scale and move the boundary; the margin grows each side by the +/// margin times the scale; the browser's eye counts for nothing; nothing in the design changes. +#[test] +fn scale_position_and_margin_set_the_boundary_and_the_design_is_untouched() { + let mut s = block(); + let (undo, doc) = (s.undo.len(), s.doc.clone()); + let dirty = s.is_dirty(); + let one = boundary(&snap(&mut s, json!({"scale": "1:1", "position_mm": [0, 0]}))); + let half = boundary(&snap(&mut s, json!({"scale": "1:2", "position_mm": [0, 0]}))); + assert!((one.0 - half.0 * 2.0).len() < EPS && one.1.len() < EPS && half.1.len() < EPS); + let margin = boundary(&snap(&mut s, json!({"scale": "1:2", "position_mm": [0, 0], "reference_margin_mm": 5}))); + assert!((margin.0 - (half.0 + Vec2::new(5.0, 5.0))).len() < EPS, "2.5 mm a side at 1:2: {margin:?}"); + let first = snap(&mut s, json!({"view": "top"})); + assert_eq!(snap(&mut s, json!({"view": "top"})), first, "the same call gives the same answer"); + assert_eq!((s.undo.len(), s.is_dirty()), (undo, dirty)); + assert!(std::sync::Arc::ptr_eq(&doc, &s.doc), "nothing in the design changes"); + run(&mut s, "browser.visibility", json!({"items": ["Block"], "visible": false})); + assert_eq!(snap(&mut s, json!({"view": "top"}))["boundary_mm"], first["boundary_mm"], "a hidden body is still drawn"); +} + +/// What the snapshot refuses, each with nothing changed: bad settings, the shaded styles until +/// the drawing renderer, the sheet's resolution out of range, an empty design, a position off +/// the sheet's limit, and a view that would reach past the paper's coordinates. +#[test] +fn hostile_snapshots_are_refused() { + let mut s = block(); + let doc = s.doc.clone(); + let cases = [ + (json!({"scale": "0:1"}), "scale"), + (json!({"scale": "-1:2"}), "scale"), + (json!({"scale": "1e400:1"}), "scale"), + (json!({"scale": "1:2:3"}), "scale"), + (json!({"scale": 2}), "scale"), + (json!({"scale": null}), "scale"), + (json!({"view": "Front"}), "view is"), + (json!({"view": {"direction": [0, 0, 0], "up": [0, 0, 1]}}), "direction"), + (json!({"view": {"direction": [1e308, 1e308, 0], "up": [0, 0, 1]}}), "direction"), + (json!({"view": {"direction": [0, 0, 1], "up": [0, 0, 2]}}), "along the view direction"), + (json!({"display_style": "shaded"}), "not supported yet"), + (json!({"reference_style": "shaded_visible"}), "not supported yet"), + (json!({"display_style": "Shaded"}), "unknown variant"), + (json!({"sheet": {"dpi": 24.9}}), "dpi"), + (json!({"sheet": {"dpi": 2400.1}}), "dpi"), + (json!({"sheet": {"size": {"custom": {"sides_mm": [0, 10]}}}}), "sheet"), + (json!({"reference_margin_mm": -1}), "reference_margin_mm"), + (json!({"position_mm": [1e308, 0]}), "point"), + (json!({"position_mm": [5000.1, 0], "scale": "1:1"}), "position"), + (json!({"scael": "1:2"}), "scael"), + ]; + for (p, says) in cases { + let e = refused(&mut s, p.clone()); + assert!(e.contains(says), "{p}: {e}"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.doc), "{p}"); + } + let mut big = Session::default(); + run(&mut big, "solid.box", json!({"length": 300, "width": 10, "height": 10})); + let e = refused(&mut big, json!({"scale": "1000:1"})); + assert!(e.contains("past ±100000 mm"), "{e}"); + let e = refused(&mut Session::default(), json!({})); + assert!(e.contains("no bodies"), "{e}"); +} + +/// A view shows every body the design places, so a design whose assembly walk stops at its depth +/// limit before some occurrences is refused, and one that ends at the limit is drawn: a chain of +/// components one inside the next, one level at a time across the limit. +#[test] +fn a_view_of_an_assembly_past_the_walks_limit_is_refused() { + let mut s = block(); + // The deepest occurrence's path is MAX_PLACEMENT_DEPTH + 1 long: walked, its children not. + for level in 0..=MAX_PLACEMENT_DEPTH as u64 { + nest(&mut s, level); + } + assert!(s.doc.placements_complete()); + snap(&mut s, json!({"scale": "1:1"})); + nest(&mut s, MAX_PLACEMENT_DEPTH as u64 + 1); + assert!(!s.doc.placements_complete()); + let e = refused(&mut s, json!({"scale": "1:1"})); + assert!(e.contains("deeper than 64 levels or has more than 100000 placements"), "{e}"); +} + +/// A saved view's boundary, worked by hand for the block at 1:2 (front 50 x 10, right 25 x 10, the +/// right view's top 25 x 50): the front view round its point (150, 150), the right view at its 300 +/// across and the front view's 150 up, the top view round its own point; the same boxes in first +/// angle, as each of the block's sides is the size of the one opposite. The extents are the +/// model's own millimetres, and inspect evaluates no model. +#[test] +fn a_saved_views_boundary_is_its_extents_at_its_scale_round_its_centre() { + let (mut s, [front, right, top]) = three_views(); + let evaluations = s.evaluations; + for projection in [Projection::Third, Projection::First] { + set_projection(&mut s, projection); + assert_box(&inspect_view(&mut s, front), [125.0, 145.0], [175.0, 155.0]); + assert_box(&inspect_view(&mut s, right), [287.5, 145.0], [312.5, 155.0]); + assert_box(&inspect_view(&mut s, top), [287.5, 225.0], [312.5, 275.0]); + } + let base = inspect_view(&mut s, front); + let extents = &base["extents"]; + assert!((point(&extents["min"]) - Vec2::ZERO).len() < EPS && (point(&extents["max"]) - Vec2::new(100.0, 20.0)).len() < EPS, "{base}"); + assert_eq!((extents["status"].as_str(), extents["provenance"].as_str()), (Some("approximate"), Some("display_mesh"))); + assert_eq!(s.evaluations, evaluations, "no model is evaluated"); +} + +/// The right view follows the front view up and down when it moves, and keeps its own place +/// across; at its own scale (1:1, 50 x 20) it is still lined up through its centre, and the top +/// view projected from it takes that scale too. The top view's 5 mm reference margin grows it by +/// 2.5 mm a side at 1:2, its extents unchanged. The largest margin at the largest scale still +/// gives a finite box. +#[test] +fn a_lined_up_view_follows_its_parent_and_a_margin_grows_the_boundary() { + let (mut s, [front, right, top]) = three_views(); + edit_view(&mut s, front, json!({"place": {"at": [160.0, 140.0]}})); + assert_box(&inspect_view(&mut s, front), [135.0, 135.0], [185.0, 145.0]); + assert_box(&inspect_view(&mut s, right), [287.5, 135.0], [312.5, 145.0]); + edit_view(&mut s, top, json!({"reference_margin_mm": 5.0})); + let margin = inspect_view(&mut s, top); + assert_box(&margin, [285.0, 222.5], [315.0, 277.5]); + let size = point(&margin["extents"]["max"]) - point(&margin["extents"]["min"]); + assert!((size - Vec2::new(50.0, 100.0)).len() < EPS, "{margin}"); + edit_view(&mut s, right, json!({"scale": "1:1"})); + assert_box(&inspect_view(&mut s, right), [275.0, 130.0], [325.0, 150.0]); + assert_box(&inspect_view(&mut s, top), [270.0, 195.0], [330.0, 305.0]); + edit_view(&mut s, top, json!({"reference_margin_mm": 100000.0, "scale": "50:1"})); + let (huge, centre) = boundary(&inspect_view(&mut s, top)); + assert!(huge.x.is_finite() && huge.x > 1e7 && (centre - Vec2::new(300.0, 250.0)).len() < 1e-6, "{huge:?} {centre:?}"); +} + +/// With nothing to measure a view gets a 20 x 20 mm placeholder round its centre, and says why: +/// its design places more than a view walks, or has no bodies. +#[test] +fn a_view_with_nothing_to_measure_gets_a_placeholder() { + let placeholder = |s: &mut Session, view: u64, why: &str| { + let v = inspect_view(s, view); + assert_eq!((v["extents"]["status"].as_str(), v["extents"]["provenance"].as_str()), (Some("placeholder"), Some(why)), "{v}"); + v + }; + let (mut s, [front, right, _]) = three_views(); + for level in 0..=MAX_PLACEMENT_DEPTH as u64 + 1 { + nest(&mut s, level); + } + assert_box(&placeholder(&mut s, front, "past_walk_limit"), [140.0, 140.0], [160.0, 160.0]); + assert_box(&placeholder(&mut s, right, "past_walk_limit"), [290.0, 140.0], [310.0, 160.0]); + // One sketch: something to draw (an empty design isn't), and no bodies. + let mut sketch_only = Session::default(); + run(&mut sketch_only, "sketch.create", json!({"plane": "XY"})); + run(&mut sketch_only, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 5]})); + run(&mut sketch_only, "sketch.finish", json!({})); + let (mut sketch_only, [front, ..]) = three_views_of(sketch_only); + assert_box(&placeholder(&mut sketch_only, front, "no_bodies"), [140.0, 140.0], [160.0, 160.0]); +} + +/// What a reply lists as outside its sheet's drawing space, and those views' ids. +fn outside(reply: &Value) -> (Vec, Vec) { + let listed = reply.get("outside").map_or(Vec::new(), |o| o.as_array().unwrap().clone()); + let views = listed.iter().map(|v| ids::decode(v["view"].as_str().unwrap()).unwrap()).collect(); + (listed, views) +} + +fn sheet_set(s: &mut Session, sheet: u64, mut p: Value) -> Value { + p["sheet"] = json!(ids::encode(sheet)); + let reply = run(s, "drawing.sheet.set", p); + let schema = output_schema_for::(); + assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}"); + reply +} + +/// A change of paper moves no view and lists those it leaves outside the drawing space (S5, #3875). +/// On A3 the three views fit; on A4, either way up, the right and top views leave it (the right +/// view reaches x 312.5, past A4's 287), and stay where they were. A border through the right +/// view's edge leaves it inside, and so does one short of it by less than a rounding; a tenth of a +/// millimetre less paper puts it outside. A change of name +/// checks nothing, undo brings the paper back, a view moved or copied to a smaller sheet is listed +/// when it leaves the drawing space there, and a view with nothing to measure is listed by its +/// placeholder, saying why. +#[test] +fn a_change_of_paper_lists_the_views_it_leaves_outside_and_moves_none() { + let (mut s, [front, right, top]) = three_views(); + let sheet = saved(&s, front).sheet; + let places = |s: &Session| [front, right, top].map(|v| saved(s, v).place); + let before = places(&s); + let (listed, views) = outside(&sheet_set(&mut s, sheet, json!({"size": {"standard": "a4"}}))); + assert_eq!(views, [right, top]); + assert_box(&listed[0], [287.5, 145.0], [312.5, 155.0]); + assert_box(&listed[1], [287.5, 225.0], [312.5, 275.0]); + assert_eq!(places(&s), before, "nothing moves"); + assert_eq!(outside(&sheet_set(&mut s, sheet, json!({"orientation": "portrait"}))).1, [right, top]); + let up_to = sheet_set(&mut s, sheet, json!({"size": {"custom": {"sides_mm": [322.5, 297.0]}}, "orientation": "landscape"})); + assert!(up_to.get("outside").is_none(), "a view on the border is inside: {up_to}"); + assert_eq!(outside(&sheet_set(&mut s, sheet, json!({"size": {"custom": {"sides_mm": [322.4, 297.0]}}}))).1, [right, top]); + assert!(sheet_set(&mut s, sheet, json!({"name": "Views"})).get("outside").is_none(), "only a change of paper checks"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + let paper = s.drawing("test").unwrap().sheets[0].sheet; + assert_eq!(paper.size, solidcraft_geom::drawing_sheet::SheetSize::Custom { sides_mm: [322.5, 297.0] }); + let rounding = sheet_set(&mut s, sheet, json!({"size": {"custom": {"sides_mm": [322.5 - solidcraft_geom::EPS / 2.0, 297.0]}}})); + assert!(rounding.get("outside").is_none(), "within a rounding of the border is inside: {rounding}"); + run(&mut s, "edit.undo", json!({})); + let added = run(&mut s, "drawing.sheet.add", json!({"size": {"standard": "a4"}, "orientation": "portrait"})); + let a4 = ids::decode(added["sheet"].as_str().unwrap()).unwrap(); + let moved = to_sheet(&mut s, MOVE, json!({"view": ids::encode(top), "sheet": ids::encode(a4), "position_mm": [150.0, 280.0]})); + let (listed, views) = outside(&moved); + assert_eq!(views, [top]); + assert_box(&listed[0], [137.5, 255.0], [162.5, 305.0]); + let copied = to_sheet(&mut s, COPY, json!({"view": ids::encode(top), "sheet": ids::encode(a4), "position_mm": [100.0, 100.0]})); + assert!(copied.get("outside").is_none(), "{copied}"); + // Nothing to measure: the design places more than a view walks. + for level in 0..=MAX_PLACEMENT_DEPTH as u64 + 1 { + nest(&mut s, level); + } + let (listed, views) = outside(&sheet_set(&mut s, sheet, json!({"size": {"standard": "a4"}}))); + assert_eq!((views, listed[0]["unmeasured"].as_str()), (vec![right], Some("past_walk_limit"))); + assert_box(&listed[0], [290.0, 140.0], [310.0, 160.0]); +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e9b3d7ec5ed..d5f01b11791 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1,22 +1,24 @@ //! Undo/redo, the timeline, deletion and selection. use std::collections::BTreeMap; +use std::sync::Arc; use serde_json::{Value, json}; -use solidcraft_doc::{Feature, FeatureKind}; +use solidcraft_doc::drawing::{self, Drawing}; +use solidcraft_doc::{Document, Feature, FeatureKind}; use super::CommandSpec; use crate::params::{bad, bool_, num, str_, string_list}; use crate::{EngineError, Result, Sel, Session, Snapshot}; pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("edit.undo", "Undo", undo).icon("undo").key("Ctrl+Z").noundo().doc_only(), - CommandSpec::new("edit.redo", "Redo", redo).icon("redo").key("Ctrl+Y").noundo().doc_only(), - CommandSpec::new("edit.checkpoint", "Checkpoint", checkpoint).icon("checkpoint") + CommandSpec::new("edit.undo", "Undo", undo).any_part().icon("undo").key("Ctrl+Z").noundo().doc_only(), + CommandSpec::new("edit.redo", "Redo", redo).any_part().icon("redo").key("Ctrl+Y").noundo().doc_only(), + CommandSpec::new("edit.checkpoint", "Checkpoint", checkpoint).any_part().icon("checkpoint") .noundo() .doc_only() .params("→ {checkpoint: id}: remember the design, active sketch and undo history (restore with edit.restore_checkpoint)"), - CommandSpec::new("edit.restore_checkpoint", "Restore Checkpoint", restore_checkpoint).icon("restore") + CommandSpec::new("edit.restore_checkpoint", "Restore Checkpoint", restore_checkpoint).any_part().icon("restore") .noundo() .doc_only() .params("checkpoint: id; forget?: bool (true = drop it without going back). Goes back to it, undo history included"), @@ -68,14 +70,14 @@ pub static COMMANDS: &[CommandSpec] = &[ "feature: id|name → type, definition (the fields timeline.edit's set changes, with their current values), \ inputs: [{label, param, expression, unit}] (named inputs parameters.change can also set), error, warning", ), - CommandSpec::new("select.set", "Select", select_set).icon("select") + CommandSpec::new("select.set", "Select", select_set).any_part().icon("select") .noundo() .params("items: [{type: body|edge|face|feature|sketch_curve|sketch_point|profile, …}], add?: bool"), - CommandSpec::new("select.clear", "Clear Selection", select_clear).icon("select").noundo(), + CommandSpec::new("select.clear", "Clear Selection", select_clear).any_part().icon("select").noundo(), ]; fn undo(s: &mut Session, _p: &Value) -> Result { - let Some(prev) = s.undo.pop() else { return Err(EngineError::Other("nothing to undo".into())) }; + let prev = latest(&mut s.undo, s.open_drawing).ok_or_else(|| nothing(s, "undo"))?; let now = go_to(s, prev); let label = now.label.clone(); s.redo.push(now); @@ -83,28 +85,78 @@ fn undo(s: &mut Session, _p: &Value) -> Result { } fn redo(s: &mut Session, _p: &Value) -> Result { - let Some(next) = s.redo.pop() else { return Err(EngineError::Other("nothing to redo".into())) }; + let next = latest(&mut s.redo, s.open_drawing).ok_or_else(|| nothing(s, "redo"))?; let now = go_to(s, next); let label = now.label.clone(); s.undo.push(now); Ok(json!({"redone": label})) } -/// Put the session at `snap`; returns where it was, under the same label. +/// Takes the latest of `steps` on `part` (the open drawing, else the model): undo and redo go +/// through one part's steps, and leave the others' where they are. +fn latest(steps: &mut Vec, part: Option) -> Option { + let at = steps.iter().rposition(|step| step.part == part)?; + Some(steps.remove(at)) +} + +fn nothing(s: &Session, what: &str) -> EngineError { + match s.open_drawing { + Some(_) => EngineError::Other(format!("nothing to {what} in this drawing (close it to {what} in the model)")), + None => EngineError::Other(format!("nothing to {what}")), + } +} + +/// Put the session at `snap`; returns where it was, under the same label. A drawing's step puts +/// back only that drawing. The model's step puts back the design as it was, but keeps each +/// drawing the design had as it is now: each part's steps are undone in that part only. Neither +/// opens or closes a drawing: a drawing's steps are taken while it is open, and the model's while +/// none is. fn go_to(s: &mut Session, snap: Snapshot) -> Snapshot { - let was = Snapshot { label: snap.label, doc: s.doc.clone(), active_sketch: s.active_sketch, pending_moves: s.pending_moves.clone() }; - let same = std::sync::Arc::ptr_eq(&s.doc, &snap.doc); + let was = Snapshot { part: snap.part, ..Snapshot::of(s, &snap.label) }; + let snap = match snap.part { + Some(id) => Snapshot { doc: drawing_from(&s.doc, &snap.doc, id), ..was.clone() }, + None => Snapshot { doc: drawings_from(snap.doc, &s.doc), ..snap }, + }; + let same = Arc::ptr_eq(&s.doc, &snap.doc); + let moved = s.active_sketch != snap.active_sketch || s.pending_moves != snap.pending_moves; s.doc = snap.doc; s.active_sketch = snap.active_sketch; s.pending_moves = snap.pending_moves; s.selection.clear(); - // A new document is evaluated by `execute`. - if same { + // A new document is evaluated by `execute`, and a drawing's change evaluates nothing. + if same && moved { s.refresh(); } was } +/// `doc` with its drawing `id` as `step` has it. +fn drawing_from(doc: &Arc, step: &Document, id: u64) -> Arc { + let mut doc = doc.clone(); + if let Some(then) = step.drawing(id) + && !doc.drawing(id).is_some_and(|now| Arc::ptr_eq(then, now)) + { + Arc::make_mut(&mut doc).put_drawing(then.clone()); + } + doc +} + +/// The model's step `step` with each of its drawings as `now` has it. +fn drawings_from(mut step: Arc, now: &Document) -> Arc { + let current = |d: &Arc| now.drawing(d.id).filter(|n| !Arc::ptr_eq(d, n)); + if step.drawings.iter().any(|d| current(d).is_some()) { + let mut drawings = step.drawings.clone(); + for d in &mut drawings { + if let Some(n) = current(d) { + *d = n.clone(); + } + } + drawing::sort(&mut drawings); + Arc::make_mut(&mut step).drawings = drawings; + } + step +} + fn checkpoint(s: &mut Session, _p: &Value) -> Result { Ok(json!({"checkpoint": s.checkpoint()})) } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index c39e5a09732..ba9a7816b46 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -15,8 +15,8 @@ use crate::params::{bad, bool_, num, str_, string_list}; use crate::{EngineError, Result, Session}; pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("file.new", "New Design", new_doc).icon("new").key("Ctrl+N").noundo().params("name?"), - CommandSpec::new("doc.open", "Open", open) + CommandSpec::new("file.new", "New Design", new_doc).any_part().icon("new").key("Ctrl+N").noundo().params("name?"), + CommandSpec::new("doc.open", "Open", open).any_part() .icon("open") .key("Ctrl+O") .noundo() @@ -29,22 +29,22 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "INSERT") .icon("import") .params("path: .3mf, .stl, .obj, .glb or .gltf file (its meshes join the design as mesh bodies in a new component named after the file → component, component_name, occurrence; a glTF file's node tree becomes nested components held as one rigid group until component.unlock, a mesh placed again another occurrence, its materials the bodies' appearances, and its metres millimetres); name?; up?: z|y for a glTF file (default y: glTF has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence; z: the file's axes are kept)"), - CommandSpec::new("file.save", "Save", save) + CommandSpec::new("file.save", "Save", save).any_part() .icon("save") .key("Ctrl+S") .noundo() .params("path? (default: current file); format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false)"), - CommandSpec::new("file.save_as", "Save As", save_as) + CommandSpec::new("file.save_as", "Save As", save_as).any_part() .icon("save") .noundo() .params("path; format?: container|json (default: json for .json, otherwise container); compression?: fast|compact (default: fast); cache?: bool (the evaluated model, so the design opens without rebuilding; default: true); preview?: bool (saved display meshes, default: false)"), - CommandSpec::new("doc.recovery_list", "Recoverable Designs", recovery_list).icon("restore") + CommandSpec::new("doc.recovery_list", "Recoverable Designs", recovery_list).any_part().icon("restore") .noundo() .params("dir? (default: the recovery folder) → designs autosaved by apps that crashed or closed with unsaved changes"), - CommandSpec::new("doc.recover", "Recover Design", recover).icon("restore") + CommandSpec::new("doc.recover", "Recover Design", recover).any_part().icon("restore") .noundo() .params("id (from doc.recovery_list); dir?; discard?: bool (delete the entry once open) — opens it with its file path, unsaved"), - CommandSpec::new("doc.recovery_discard", "Discard Recovered Design", recovery_discard).icon("delete").noundo().params("id, or all: true; dir?"), + CommandSpec::new("doc.recovery_discard", "Discard Recovered Design", recovery_discard).any_part().icon("delete").noundo().params("id, or all: true; dir?"), CommandSpec::new("file.export", "Export", export) .icon("export") .noundo() diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index 76394f11349..aecc7cce53c 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -43,8 +43,8 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .doc_only() .params("→ the built-in materials, then the design's own (user: true, with their look)"), - CommandSpec::new("engine.commands", "List Commands", commands).icon("list").noundo(), - CommandSpec::new("engine.describe", "Describe Command", crate::checked!("engine.describe", DESCRIBE_CONTRACT, describe)) + CommandSpec::new("engine.commands", "List Commands", commands).any_part().icon("list").noundo(), + CommandSpec::new("engine.describe", "Describe Command", crate::checked!("engine.describe", DESCRIBE_CONTRACT, describe)).any_part() .icon("list") .noundo() .doc_only() diff --git a/crates/engine/src/cmd/metadata.rs b/crates/engine/src/cmd/metadata.rs index 9f8cdf16750..00648d38299 100644 --- a/crates/engine/src/cmd/metadata.rs +++ b/crates/engine/src/cmd/metadata.rs @@ -2,9 +2,11 @@ //! `document.metadata.set` and `document.metadata.remove` change it, each in one undo step. The //! keys SolidCraft reads, and the checks a change gets, are `solidcraft_doc::metadata`'s; keys //! other tools wrote are kept as they are. The UI's Design Properties dialog, scripts and MCP -//! agents all go through these commands. +//! agents all go through these commands. A drawing's properties are read and changed by the +//! same rules ([`reading`], [`setting`], [`removing`]), through `drawing.properties`. use serde_json::{Map, Value, json}; +use solidcraft_doc::Metadata; use solidcraft_doc::metadata::{BOM_TYPE, MAX_KEYS, WELL_KNOWN}; use super::CommandSpec; @@ -27,14 +29,16 @@ pub static COMMANDS: &[CommandSpec] = &[ .params("key, or keys: [keys] (any key, also one another tool wrote) → metadata, removed: [keys that were there]"), ]; -fn read(s: &mut Session, _: &Value) -> Result { - let m = &s.doc.metadata; +/// What reading `m` answers: the object as saved, and SolidCraft's properties, each its text or +/// null. +pub(super) fn reading(m: &Metadata) -> Value { let properties: Map = WELL_KNOWN.iter().map(|k| (k.to_string(), m.text(k).map_or(Value::Null, |t| json!(t)))).collect(); - Ok(json!({"metadata": m, "properties": properties})) + json!({"metadata": m, "properties": properties}) } -fn set(s: &mut Session, p: &Value) -> Result { - let cmd = "document.metadata.set"; +/// `m` with a call's `key` and `value`, or its `values`, set (all or nothing), and the keys that +/// changed. +pub(super) fn setting(cmd: &str, m: &Metadata, p: &Value) -> Result<(Metadata, Vec)> { let entries: Vec<(&str, &Value)> = match (p.get("values"), p.get("key")) { (Some(Value::Object(values)), None) if values.len() <= MAX_KEYS => values.iter().map(|(k, v)| (k.as_str(), v)).collect(), (Some(Value::Object(_)), None) => return Err(bad(cmd, format!("`values` can hold at most {MAX_KEYS} keys"))), @@ -45,7 +49,7 @@ fn set(s: &mut Session, p: &Value) -> Result { } _ => return Err(bad(cmd, "give `key` and `value`, or `values`: {key: value, …}")), }; - let mut next = s.doc.metadata.clone(); + let mut next = m.clone(); let mut changed = Vec::new(); for (key, value) in entries { if key == BOM_TYPE { @@ -55,15 +59,11 @@ fn set(s: &mut Session, p: &Value) -> Result { changed.push(key.to_string()); } } - // Only a real change touches the design (an undo step, unsaved changes). - if next != s.doc.metadata { - s.doc_mut().metadata = next; - } - Ok(json!({"metadata": s.doc.metadata, "changed": changed})) + Ok((next, changed)) } -fn remove(s: &mut Session, p: &Value) -> Result { - let cmd = "document.metadata.remove"; +/// `m` with a call's `key`, or its `keys`, removed, and the keys that were there. +pub(super) fn removing(cmd: &str, m: &Metadata, p: &Value) -> Result<(Metadata, Vec)> { let keys: Vec<&str> = match (p.get("keys"), p.get("key")) { (Some(Value::Array(keys)), None) if keys.len() <= MAX_KEYS => { keys.iter().map(Value::as_str).collect::>().ok_or_else(|| bad(cmd, "`keys` must be a list of keys"))? @@ -71,17 +71,36 @@ fn remove(s: &mut Session, p: &Value) -> Result { (None, Some(_)) => vec![str_(p, "key").ok_or_else(|| bad(cmd, "`key` must be text"))?], _ => return Err(bad(cmd, format!("give `key`, or `keys`: a list of at most {MAX_KEYS} keys"))), }; - let mut removed: Vec<&str> = Vec::new(); + let mut removed: Vec = Vec::new(); for k in keys { - if s.doc.metadata.get(k).is_some() && !removed.contains(&k) { - removed.push(k); + if m.get(k).is_some() && !removed.iter().any(|r| r == k) { + removed.push(k.to_string()); } } + let mut next = m.clone(); + for k in &removed { + next.remove(k); + } + Ok((next, removed)) +} + +fn read(s: &mut Session, _: &Value) -> Result { + Ok(reading(&s.doc.metadata)) +} + +fn set(s: &mut Session, p: &Value) -> Result { + let (next, changed) = setting("document.metadata.set", &s.doc.metadata, p)?; + // Only a real change touches the design (an undo step, unsaved changes). + if next != s.doc.metadata { + s.doc_mut().metadata = next; + } + Ok(json!({"metadata": s.doc.metadata, "changed": changed})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let (next, removed) = removing("document.metadata.remove", &s.doc.metadata, p)?; if !removed.is_empty() { - let m = &mut s.doc_mut().metadata; - for k in &removed { - m.remove(k); - } + s.doc_mut().metadata = next; } Ok(json!({"metadata": s.doc.metadata, "removed": removed})) } diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index b26c54e8658..a3a5f2ab56a 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -31,6 +31,9 @@ mod component_clone_assembly; mod construct; mod delete; mod diagnostics; +mod drawing; +mod drawing_sheet; +mod drawing_view; mod edit; mod face; mod features; @@ -102,6 +105,16 @@ pub type LiveRun = fn(&mut Session, &Value) -> Result<(Value, Option std::result::Result<(), String>; pub type SchemaFn = fn() -> schemars::Schema; +/// The part of the design a command works on (#3890): the model (most commands), the open +/// drawing, or either (files, undo, selection, diagnostics, choosing a drawing). +/// [`CommandSpec::allowed`] checks it before the command's own `enabled`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Part { + Model, + Drawing, + Any, +} + pub struct CommandSpec { pub id: &'static str, pub label: &'static str, @@ -130,6 +143,8 @@ pub struct CommandSpec { pub contract: Option<&'static dyn crate::schema::Contract>, /// The JSON Schema of a successful result; `None` until described. pub output: Option, + /// The part of the design it works on: the model unless it says otherwise. + pub part: Part, } impl CommandSpec { @@ -150,6 +165,7 @@ impl CommandSpec { planned: None, contract: None, output: None, + part: Part::Model, } } /// Not built yet; `issue` tracks building it. @@ -202,14 +218,33 @@ impl CommandSpec { self.undoable = false; self } - /// Run inside another command: when it is enabled, its `run` (the caller's command owns the + /// Works with a drawing open or with none. + pub const fn any_part(mut self) -> Self { + self.part = Part::Any; + self + } + /// Works on the open drawing. + pub const fn in_drawing(mut self) -> Self { + self.part = Part::Drawing; + self + } + /// Whether the command can run in `s` now: on the part open, and enabled. The one check + /// running a command, running it inside another and listing it make. + pub fn allowed(&self, s: &Session) -> std::result::Result<(), String> { + match (self.part, s.open_drawing.is_some()) { + (Part::Model, true) => Err("a drawing is open: close it to change the model (drawing.close)".into()), + (Part::Drawing, false) => Err("open a drawing first (drawing.open, or drawing.create)".into()), + _ => (self.enabled)(s), + } + } + /// Run inside another command: when it is allowed, its `run` (the caller's command owns the /// undo step and the evaluation). pub(crate) fn run_nested(&self, s: &mut Session, p: &Value) -> Result { - (self.enabled)(s).map_err(|why| crate::EngineError::Disabled(self.id.to_string(), why))?; + self.allowed(s).map_err(|why| crate::EngineError::Disabled(self.id.to_string(), why))?; (self.run)(s, p) } pub fn info(&self, s: &Session) -> CommandInfo { - let e = (self.enabled)(s); + let e = self.allowed(s); CommandInfo { id: self.id, label: self.label, @@ -303,6 +338,9 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(section::COMMANDS.iter()); v.extend(view_navigation::COMMANDS.iter()); v.extend(view_dxf::COMMANDS.iter()); + v.extend(drawing::COMMANDS.iter()); + v.extend(drawing_sheet::COMMANDS.iter()); + v.extend(drawing_view::COMMANDS.iter()); v.extend(diagnostics::COMMANDS.iter()); v.extend(render::COMMANDS.iter()); v diff --git a/crates/engine/src/crash.rs b/crates/engine/src/crash.rs index c7cfee7bb8b..67019a3af3e 100644 --- a/crates/engine/src/crash.rs +++ b/crates/engine/src/crash.rs @@ -503,20 +503,20 @@ pub(crate) fn command_begin(s: &Session, id: &str, params: &Value) { } else { json!("unknown") }; - j.rebase(&base, ptr); + j.rebase(&base, ptr, Some(s.ids.seed())); } j.run(id, params); } /// A top-level command ended: the journal records how, and panics caught inside it are reported -/// with `before` (the design it started from) and the command, which together reproduce them. +/// with `before` (the design it started from) and the command (its id, its parameters and the +/// session's id seed when it started), which together reproduce them. pub(crate) fn command_done( journaled: bool, changed: bool, before: &Document, after: &std::sync::Arc, - id: &str, - params: &Value, + (id, params, ids): (&str, &Value, u64), outcome: std::result::Result<(), String>, ) { let Some(state) = STATE.get() else { return }; @@ -531,7 +531,7 @@ pub(crate) fn command_done( for p in pending { let kind = if p.recovered { "kernel_panic_recovered" } else { "command_panic" }; let design = solidcraft_io::write_design(before); - let replay = json!({ "commands": [{ "command": id, "params": params }] }); + let replay = json!({ "commands": [{ "command": id, "params": params }], "ids": ids }); let recent = if journaled { read_live_journal(state).recent } else { Vec::new() }; let extra = Extra { command: Some(json!({ "command": id, "params": params })), @@ -562,7 +562,7 @@ pub(crate) fn rebased(s: &Session, file: Option<&Path>, autosave: bool) { (None, _) if s.doc.features.is_empty() => json!("new"), _ => json!("unknown"), }; - j.rebase(&base, std::sync::Arc::as_ptr(&s.doc) as usize); + j.rebase(&base, std::sync::Arc::as_ptr(&s.doc) as usize, Some(s.ids.seed())); } // --------------------------------------------------------------------------------------------- @@ -602,7 +602,7 @@ impl Journal { phase_step: None, environment: None, }; - j.rebase(&json!("new"), 0); + j.rebase(&json!("new"), 0, None); j } @@ -618,7 +618,9 @@ impl Journal { self.write(&v.to_string()); } - fn rebase(&mut self, base: &Value, doc: usize) { + /// A new base: `base`, the design the commands after it start from, and `ids`, the session's + /// id seed there. + fn rebase(&mut self, base: &Value, doc: usize, ids: Option) { if let Some(f) = &self.file && f.set_len(0).is_err() { @@ -630,7 +632,11 @@ impl Journal { self.last_doc = doc; let h = self.header.clone(); self.write(&h); - self.record(&json!({ "base": base })); + let mut line = json!({ "base": base }); + if let Some(ids) = ids { + line["ids"] = json!(ids); + } + self.record(&line); for line in [self.phase.clone(), self.environment.clone()].into_iter().flatten() { self.write(&line); } @@ -681,6 +687,8 @@ impl Journal { struct JournalRead { header: Value, base: Value, + /// The session's id seed at the base, when it was kept. + ids: Option, /// Commands since the base that changed something or did nothing wrong, in order. replay: Vec, /// The command that was running, if one was. @@ -723,6 +731,7 @@ fn read_journal_file(mut file: File) -> JournalRead { } if let Some(b) = v.get("base") { r.base = b.clone(); + r.ids = v.get("ids").and_then(Value::as_u64); r.replay.clear(); r.recent.clear(); running = None; @@ -928,7 +937,10 @@ fn from_journal(j: JournalRead) -> Extra { Extra { command: j.in_flight, design, - replay: replay.then(|| json!({ "commands": commands })), + replay: replay.then(|| match j.ids { + Some(ids) => json!({ "commands": commands, "ids": ids }), + None => json!({ "commands": commands }), + }), recent: j.recent, base: j.base, notes, diff --git a/crates/engine/src/crash_tests.rs b/crates/engine/src/crash_tests.rs index b7a9b5f005a..0b3d56a1bd9 100644 --- a/crates/engine/src/crash_tests.rs +++ b/crates/engine/src/crash_tests.rs @@ -40,6 +40,8 @@ fn child() { } set_environment("Renderer: test"); let mut s = Session { crash_journal: true, ..Default::default() }; + // Where the session's ids stand at the journal's base, its first command. + println!("BASE_IDS {}", s.ids.seed()); s.execute("solid.box", &json!({"length": 10, "width": 20, "height": 30})).unwrap(); // Commands that only read are not kept. for _ in 0..50 { @@ -55,6 +57,7 @@ fn child() { let _ = s.execute("diagnostics.crash_test", &json!({"mode":"abort"})); } "command" => { + println!("IDS {}", s.ids.seed()); for _ in 0..3 { let r = s.execute("diagnostics.crash_test", &json!({"mode": "panic"})); assert!(matches!(r, Err(crate::EngineError::Internal(..))), "{r:?}"); @@ -93,6 +96,11 @@ fn run_child(dir: &Path, mode: &str) -> (String, bool) { (String::from_utf8_lossy(&out.stdout).into_owned(), out.status.success()) } +/// The id seed a child printed after `label`. +fn printed_seed(out: &str, label: &str) -> u64 { + out.lines().find_map(|l| l.strip_prefix(label)).and_then(|x| x.trim().parse().ok()).unwrap() +} + fn only_report(dir: &Path) -> (Summary, Value) { let all = list(dir); assert_eq!(all.len(), 1, "{all:?}"); @@ -104,7 +112,7 @@ fn only_report(dir: &Path) -> (Summary, Value) { #[test] fn a_command_panic_is_reported_once_with_the_design_and_the_command() { let d = fresh_dir("command"); - let (_, ok) = run_child(&d, "command"); + let (out, ok) = run_child(&d, "command"); assert!(ok, "the panics were caught"); let (s, v) = only_report(&d); assert_eq!(s.kind, "command_panic"); @@ -126,6 +134,7 @@ fn a_command_panic_is_reported_once_with_the_design_and_the_command() { assert_eq!(design.features.len(), 1); let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap(); assert_eq!(replay["commands"], json!([{"command": "diagnostics.crash_test", "params": {"mode": "panic"}}])); + assert_eq!(replay["ids"], json!(printed_seed(&out, "IDS ")), "the session's id seed when the command started"); assert!(fs::read_dir(d.join("sessions")).unwrap().next().is_none(), "a clean exit leaves no journal"); let _ = fs::remove_dir_all(&d); } @@ -160,7 +169,7 @@ fn a_panic_outside_commands_is_reported() { #[test] fn an_abort_is_reported_at_the_next_start_with_a_replay() { let d = fresh_dir("abort"); - let (_, ok) = run_child(&d, "abort"); + let (started, ok) = run_child(&d, "abort"); assert!(!ok, "the child aborted"); assert!(list(&d).is_empty(), "no hook sees an abort"); // The next start finds the journal nobody holds and tells about it. @@ -176,6 +185,7 @@ fn an_abort_is_reported_at_the_next_start_with_a_replay() { let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap(); let ids: Vec<&str> = replay["commands"].as_array().unwrap().iter().map(|c| c["command"].as_str().unwrap()).collect(); assert_eq!(ids, ["solid.box", "diagnostics.crash_test"], "read-only commands are not journaled"); + assert_eq!(replay["ids"], json!(printed_seed(&started, "BASE_IDS ")), "the id seed kept at the journal's base"); assert!(v.get("design_path").is_none()); // Told once: the start after that has nothing new. let (out, _) = run_child(&d, "none"); @@ -256,7 +266,7 @@ fn startup_steps_survive_a_rebase_and_running_ends_startup() { let mut j = Journal::open(&d, &build(), now()); j.phase = Some(json!({"phase": "first frame", "ms": 5}).to_string()); j.environment = Some(json!({"environment": "Renderer: X"}).to_string()); - j.rebase(&json!("new"), 1); + j.rebase(&json!("new"), 1, None); // Read through the journal's own handle, as `read_live_journal` does: Windows refuses a // second handle on a live journal's locked range (#1448). let r = read_journal_file(j.file.as_ref().unwrap().try_clone().unwrap()); diff --git a/crates/engine/src/drawing_view.rs b/crates/engine/src/drawing_view.rs new file mode 100644 index 00000000000..84e07dcb4f8 --- /dev/null +++ b/crates/engine/src/drawing_view.rs @@ -0,0 +1,132 @@ +//! Drawing views of the session's model (W07, #5866): what a view shows and how far it reaches, +//! and where a saved view sits on its sheet (#4816). The snapshot command and saved views use it; +//! their pictures (W17b) will too. +//! +//! A view shows every body the design places, where its occurrences place it. The browser's eye +//! counts for nothing: hiding a part in the model never changes a drawing. + +use std::fmt; + +use solidcraft_doc::drawing::Drawing; +use solidcraft_doc::{MAX_PLACEMENT_DEPTH, MAX_PLACEMENTS, ids}; +use solidcraft_geom::drawing_view::{Scale, ViewFrame}; +use solidcraft_geom::{Aabb2, EPS, Plane, Vec2}; + +use crate::params::bad; +use crate::{Result, Session}; + +/// The paper millimetres each way of a view's boundary when there's nothing to measure, round its +/// centre, so it can still be picked, moved and deleted. +pub const PLACEHOLDER_MM: f64 = 20.0; + +/// How far a view reaches on its own plane, in model millimetres. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Extents { + /// The bodies' box in the plane's own coordinates ([`Plane::to_local`]). + pub model: Aabb2, + /// How far a curved face may lie outside its display mesh: the largest display tolerance. + pub error_mm: f64, + pub bodies: usize, +} + +/// Why a view has nothing to measure. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Unmeasured { + /// The assembly places more than a view walks, so a view of it would leave parts out. + PastWalkLimit, + NoBodies, +} + +impl Unmeasured { + /// Its name in replies. + pub fn name(self) -> &'static str { + match self { + Unmeasured::PastWalkLimit => "past_walk_limit", + Unmeasured::NoBodies => "no_bodies", + } + } +} + +impl fmt::Display for Unmeasured { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Unmeasured::PastWalkLimit => write!( + f, + "the assembly is deeper than {MAX_PLACEMENT_DEPTH} levels or has more than {MAX_PLACEMENTS} placements: a view of it would leave parts out" + ), + Unmeasured::NoBodies => f.write_str("the view's source has no bodies"), + } + } +} + +/// A saved view on its sheet. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OnSheet { + /// Its box on the sheet, in paper millimetres. + pub boundary: Aabb2, + /// Its design's extents on its plane; with nothing to measure, the placeholder's box there, + /// [`PLACEHOLDER_MM`] each way on paper round the plane's origin. + pub extents: Extents, + /// Why there's nothing to measure, when there isn't. + pub unmeasured: Option, +} + +/// The extents of every body the design places, seen on `basis`, or why there's nothing to +/// measure: the assembly places more than a view walks, or it has no bodies. +pub fn measure(s: &Session, basis: &Plane) -> std::result::Result { + if !s.doc.placements_complete() { + return Err(Unmeasured::PastWalkLimit); + } + let st = s.world_state(); + let extents = st.bodies.iter().fold(Extents { model: Aabb2::EMPTY, error_mm: 0.0, bodies: 0 }, |e, body| Extents { + model: e.model.union(&body.mesh_bounds_in(basis)), + error_mm: e.error_mm.max(body.display_tol()), + bodies: e.bodies + 1, + }); + if extents.model.is_empty() { Err(Unmeasured::NoBodies) } else { Ok(extents) } +} + +/// The boundary on the sheet of a view through `basis` at `scale`, with the middle of `shown` +/// (model mm on its plane) at `centre`: the one rule the snapshot and saved views are placed by. +pub fn boundary(basis: Plane, scale: Scale, shown: &Aabb2, centre: Vec2, cmd: &str) -> Result { + let frame = ViewFrame::new(basis, scale, shown.center(), centre).map_err(|e| bad(cmd, e.to_string()))?; + frame.boundary(shown).map_err(|e| bad(cmd, e.to_string())) +} + +/// Saved view `id` of `drawing`, one of `s`'s design's drawings, on its sheet: the design's extents +/// on its plane (a view's source is the design the drawing is in), grown by its reference margin, +/// at its scale, with their middle on its centre ([`Drawing::view_centre`]); with nothing to +/// measure, a placeholder [`PLACEHOLDER_MM`] each way round its centre. It reads the model as it +/// is evaluated: no model is evaluated. +pub fn on_sheet(s: &Session, drawing: &Drawing, id: u64, cmd: &str) -> Result { + let view = drawing.resolve_view(id).map_err(|e| bad(cmd, e.to_string()))?; + let centre = drawing.view_centre(id).map_err(|e| bad(cmd, e.to_string()))?; + let scale = view.scale.value; + let (extents, shown, unmeasured) = match measure(s, &view.basis) { + Ok(extents) => (extents, extents.model.inflated(view.reference_margin_mm), None), + Err(why) => { + let half = PLACEHOLDER_MM / 2.0 / scale.factor(); + let model = Aabb2 { min: Vec2::new(-half, -half), max: Vec2::new(half, half) }; + (Extents { model, error_mm: 0.0, bodies: 0 }, model, Some(why)) + } + }; + Ok(OnSheet { boundary: boundary(view.basis, scale, &shown, centre, cmd)?, extents, unmeasured }) +} + +/// Each of `views` of `drawing` (one of `s`'s design's) whose boundary leaves its sheet's drawing +/// space ([`solidcraft_doc::drawing::Sheet::drawing_space`]), sides included, with where it sits: +/// what a change of paper or a move to another sheet leaves outside. Nothing is moved. +pub fn outside(s: &Session, drawing: &Drawing, views: &[u64], cmd: &str) -> Result> { + let mut out = Vec::new(); + for &id in views { + let view = drawing.views.iter().find(|v| v.id == id).ok_or_else(|| bad(cmd, format!("no view {}", ids::encode(id))))?; + let sheet = drawing.sheets.iter().find(|s| s.id == view.sheet).ok_or_else(|| bad(cmd, format!("no sheet {}", ids::encode(view.sheet))))?; + // A view drawn up to the border, its sides on it, is inside: the margin takes rounding. + let space = sheet.drawing_space().map_err(|e| bad(cmd, e.to_string()))?.inflated(EPS); + let placed = on_sheet(s, drawing, id, cmd)?; + if !(space.contains(placed.boundary.min) && space.contains(placed.boundary.max)) { + out.push((id, placed)); + } + } + Ok(out) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 942e6b385f0..2fe0394503b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,7 @@ pub mod capture; pub mod cmd; pub mod control_auth; pub mod crash; +pub mod drawing_view; pub mod frames; pub mod fuzz; pub mod licences; @@ -164,6 +165,17 @@ pub struct Snapshot { pub doc: Arc, pub active_sketch: Option, pub pending_moves: std::collections::BTreeMap, + /// The part of the design the step changed: a drawing (by id), or the model and the list of + /// drawings (`None`). Undo and redo go through one part's steps (`edit.undo`). + pub part: Option, +} + +impl Snapshot { + /// The session as it is now, as a step of the model, under `label`: the one place a step is + /// taken. + pub fn of(s: &Session, label: &str) -> Snapshot { + Snapshot { label: label.to_string(), doc: s.doc.clone(), active_sketch: s.active_sketch, pending_moves: s.pending_moves.clone(), part: None } + } } /// A copy of a session that evaluates commands ahead of it ([`Session::ahead`]). @@ -243,8 +255,15 @@ pub struct Session { pub redo: Vec, /// Sketch feature being edited (sketch mode). pub active_sketch: Option, + /// The drawing open (by id): drawing commands change it, and the model's wait until it is + /// closed ([`cmd::Part`]). + pub open_drawing: Option, pub selection: Vec, pub path: Option, + /// Where the drawing commands' object ids come from: one source for the session, kept across + /// a file change, so a session seeded alike and run alike gives the same ids + /// ([`Session::seed_ids`]). A failed command draws none. + pub(crate) ids: solidcraft_doc::ids::IdSource, /// One-shot display-only notification during doc.open, before authoritative evaluation. /// Interactive loaders may show it provisionally; it never becomes model state. pub open_preview: Option>, @@ -321,12 +340,13 @@ pub struct LiveEdit { pub report: solidcraft_sketch::SolveReport, } -/// The design, active sketch, pending positions and undo history at an `edit.checkpoint`. +/// The design, active sketch, open drawing, pending positions and undo history at an `edit.checkpoint`. #[derive(Clone, Debug)] pub(crate) struct Checkpoint { pub id: u64, pub doc: Arc, pub active_sketch: Option, + pub open_drawing: Option, pub pending_moves: std::collections::BTreeMap, pub undo: Vec, pub redo: Vec, @@ -415,8 +435,10 @@ impl Session { undo: Vec::new(), redo: Vec::new(), active_sketch: None, + open_drawing: None, selection: Vec::new(), path: None, + ids: solidcraft_doc::ids::IdSource::from_entropy(), open_preview: None, log: Vec::new(), revision: 1, @@ -462,6 +484,7 @@ impl Session { let render_jobs = self.render_jobs.scratch(); let checkpoints = std::mem::take(&mut self.checkpoints); let next_checkpoint = self.next_checkpoint; + let ids = self.ids.clone(); *self = fresh; self.auto_project = auto_project; self.param_check = param_check; @@ -469,6 +492,13 @@ impl Session { self.render_jobs = render_jobs; self.checkpoints = checkpoints; self.next_checkpoint = next_checkpoint; + self.ids = ids; + } + + /// Object ids from `seed` from here on, as a replay of a session whose ids stood there + /// (`replay.json`'s `ids`) gives. + pub fn seed_ids(&mut self, seed: u64) { + self.ids = solidcraft_doc::ids::IdSource::seeded(seed); } /// The design has changes not in its file: in the document, or in what is hidden. @@ -557,6 +587,28 @@ impl Session { Arc::make_mut(&mut self.doc) } + /// The drawing open, for `cmd`. + pub fn drawing(&self, cmd: &str) -> Result<&Arc> { + self.open_drawing.and_then(|id| self.doc.drawing(id)).ok_or_else(|| params::bad(cmd, "open a drawing first (drawing.open)")) + } + + /// Change the drawing open, for `cmd`: kept when it still keeps the record's rules, and only + /// when it changed (one undo step of the drawing, through `execute`; the design's other + /// drawings shared). + pub fn edit_drawing(&mut self, cmd: &str, change: impl FnOnce(&mut solidcraft_doc::drawing::Drawing) -> Result) -> Result { + let open = self.drawing(cmd)?; + let mut d = (**open).clone(); + let out = change(&mut d)?; + if d.id != open.id { + return Err(params::bad(cmd, "a drawing keeps its id")); + } + d.validate().map_err(|e| params::bad(cmd, e.to_string()))?; + if d != **open { + self.doc_mut().put_drawing(Arc::new(d)); + } + Ok(out) + } + /// Prepared placements only: optional save caches must not compute a cold world. pub(crate) fn cached_world_state(&self) -> Option> { let state = self.model.state(); @@ -708,12 +760,14 @@ impl Session { Some((old, new)) } - /// Only persistent render intent, or only part properties, changed. Never evaluate or clear - /// a stale model here. + /// Only persistent render intent, part properties or drawings changed. Never evaluate or + /// clear a stale model here. fn render_only_change(&self, before: &Snapshot) -> bool { self.active_sketch == before.active_sketch && self.pending_moves == before.pending_moves - && (self.doc.differs_only_in_render(&before.doc) || self.doc.differs_only_in_part_properties(&before.doc)) + && (self.doc.differs_only_in_render(&before.doc) + || self.doc.differs_only_in_part_properties(&before.doc) + || self.doc.differs_only_in_drawings(&before.doc)) } fn refresh_render(&mut self, previous: &Arc) { @@ -789,13 +843,10 @@ impl Session { if live.is_none() && spec.reads_model && self.model.is_stale() { self.refresh(); } - (spec.enabled)(self).map_err(|why| EngineError::Disabled(spec.id.to_string(), why))?; - let before = Snapshot { - label: spec.label.to_string(), - doc: self.doc.clone(), - active_sketch: self.active_sketch, - pending_moves: self.pending_moves.clone(), - }; + spec.allowed(self).map_err(|why| EngineError::Disabled(spec.id.to_string(), why))?; + let open_drawing = self.open_drawing; + let before = Snapshot { part: open_drawing.filter(|_| spec.part == cmd::Part::Drawing), ..Snapshot::of(self, spec.label) }; + let ids = self.ids.clone(); let null = Value::Object(Default::default()); let params = if params.is_null() { &null } else { params }; let given = params; @@ -834,8 +885,9 @@ impl Session { let changed = !Arc::ptr_eq(&self.doc, &before.doc) || self.active_sketch != before.active_sketch || self.pending_moves != before.pending_moves + || self.open_drawing != open_drawing || spec.id.starts_with("select."); - crash::command_done(self.crash_journal, changed, &before.doc, after, spec.id, given, failed.map_or(Ok(()), Err)); + crash::command_done(self.crash_journal, changed, &before.doc, after, (spec.id, given, ids.seed()), failed.map_or(Ok(()), Err)); } let changed = !Arc::ptr_eq(&self.doc, &before.doc); match r { @@ -845,11 +897,14 @@ impl Session { let render_only = self.render_only_change(&before); let previous_doc = before.doc.clone(); if spec.undoable { + // A new step ends what could be redone in its part; the other parts' redo + // steps still hold, as undo puts back only the part a step changed. + let part = before.part; self.undo.push(before); if self.undo.len() > MAX_UNDO { self.undo.remove(0); } - self.redo.clear(); + self.redo.retain(|step| step.part != part); } match live_edit { Some(edit) => self.refresh_live(edit), @@ -860,6 +915,9 @@ impl Session { Ok(v) } Err(e) => { + // A failed command draws no ids, so a replay of what succeeded draws the same. + self.ids = ids; + self.open_drawing = open_drawing; if changed || self.pending_moves != before.pending_moves { self.doc = before.doc; self.active_sketch = before.active_sketch; @@ -892,7 +950,8 @@ impl Session { v } - /// Remember the design, active sketch, pending positions and undo history; returns the checkpoint's id. + /// Remember the design, active sketch, open drawing, pending positions and undo history; + /// returns the checkpoint's id. pub fn checkpoint(&mut self) -> u64 { let id = self.next_checkpoint; self.next_checkpoint += 1; @@ -900,6 +959,7 @@ impl Session { id, doc: self.doc.clone(), active_sketch: self.active_sketch, + open_drawing: self.open_drawing, undo: self.undo.clone(), pending_moves: self.pending_moves.clone(), redo: self.redo.clone(), @@ -915,10 +975,10 @@ impl Session { pub fn restore_checkpoint(&mut self, id: u64) -> Result<()> { let i = self.checkpoints.iter().position(|c| c.id == id).ok_or_else(|| EngineError::Other(format!("no checkpoint {id}")))?; let Some(c) = self.checkpoints.drain(i..).next() else { return Err(EngineError::Other(format!("no checkpoint {id}"))) }; - let before = - Snapshot { label: String::new(), doc: self.doc.clone(), active_sketch: self.active_sketch, pending_moves: self.pending_moves.clone() }; + let before = Snapshot::of(self, ""); self.doc = c.doc; self.active_sketch = c.active_sketch; + self.open_drawing = c.open_drawing; self.pending_moves = c.pending_moves; self.undo = c.undo; self.redo = c.redo; @@ -947,8 +1007,10 @@ impl Session { undo: Vec::new(), redo: Vec::new(), active_sketch: self.active_sketch, + open_drawing: self.open_drawing, selection: self.selection.clone(), path: None, + ids: self.ids.clone(), open_preview: None, saved: self.saved.clone(), log: Vec::new(), diff --git a/crates/engine/src/schema/check.rs b/crates/engine/src/schema/check.rs index 251bb780681..864a6f74692 100644 --- a/crates/engine/src/schema/check.rs +++ b/crates/engine/src/schema/check.rs @@ -223,6 +223,12 @@ fn nearest(key: &str, allowed: &BTreeSet) -> Option { .map(|(_, a)| a.clone()) } +/// The command `cmd`'s parameters `p` as its contract type `P`, refused in the words the contract +/// check uses, so the handler and the check say the same thing about the same mistake. +pub(crate) fn read(cmd: &str, p: &Value) -> Result

{ + serde_path_to_error::deserialize(p).map_err(|e| bad(cmd, parse_issue(&e).message)) +} + /// A deserialization failure as an issue, in the engine's style. pub(crate) fn parse_issue(e: &serde_path_to_error::Error) -> Issue { let path = error_path(e); diff --git a/crates/engine/src/schema/drawing_sheet.rs b/crates/engine/src/schema/drawing_sheet.rs new file mode 100644 index 00000000000..03d794eb23d --- /dev/null +++ b/crates/engine/src/schema/drawing_sheet.rs @@ -0,0 +1,194 @@ +//! Contracts and result types for the commands in `cmd/drawing_sheet.rs` (#3875). + +use schemars::JsonSchema; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::{Map, Value}; + +use super::check::whole; + +/// A sheet named by its id or, when only one has it, its name. +pub(super) fn sheet_ref<'de, D: Deserializer<'de>>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => Ok(s), + _ => Err(serde::de::Error::custom("must be a sheet's id or name")), + } +} + +/// [`sheet_ref`], for a key that may be absent (`null` is refused). +fn some_sheet_ref<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + sheet_ref(d).map(Some) +} + +fn text<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::String(s) => Ok(Some(s)), + _ => Err(serde::de::Error::custom("must be text")), + } +} + +/// A paper size, as `SheetSize` reads it. +fn size<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let v = Value::deserialize(d)?; + match serde_json::from_value::(v.clone()) { + Ok(_) => Ok(Some(v)), + Err(_) => Err(serde::de::Error::custom(whole("`size` is {\"standard\": \"a3\"} or {\"custom\": {\"sides_mm\": [w, h]}}"))), + } +} + +fn orientation<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)? { + Value::String(s) if matches!(s.as_str(), "landscape" | "portrait") => Ok(Some(s)), + _ => Err(serde::de::Error::custom(whole("`orientation` is landscape or portrait"))), + } +} + +/// A finite number below 1e9 in size, as `params::num` reads it. +fn number<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)?.as_f64().and_then(crate::params::finite) { + Some(x) => Ok(Some(x)), + None => Err(serde::de::Error::custom("must be a number")), + } +} + +/// What a sheet documents: `{source, component?}`, or `null` for nothing. +fn documents<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let v = Value::deserialize(d)?; + if v.is_null() { + return Ok(Some(v)); + } + if v.get("source").and_then(Value::as_str).and_then(solidcraft_doc::ids::decode).is_none() { + return Err(serde::de::Error::custom(whole("`documents.source` must be a source's id"))); + } + if v.get("component").is_some_and(|c| c.as_u64().is_none()) { + return Err(serde::de::Error::custom(whole("`documents.component` must be a component id"))); + } + Ok(Some(v)) +} + +/// What a sheet leaves out: an object of `count` and `print`, each true or false. +fn excluded<'de, D: Deserializer<'de>>(d: D) -> Result>, D::Error> { + let shape = || serde::de::Error::custom(whole("`excluded` is {count?: true|false, print?: true|false}")); + let Value::Object(o) = Value::deserialize(d)? else { return Err(shape()) }; + if !o.keys().all(|k| matches!(k.as_str(), "count" | "print")) { + return Err(shape()); + } + for key in ["count", "print"] { + if o.get(key).is_some_and(|v| !v.is_boolean()) { + return Err(serde::de::Error::custom(whole(format!("`excluded.{key}` is true or false")))); + } + } + Ok(Some(o)) +} + +/// Every sheet's id once, in a new order. +fn every_sheet<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let every = || serde::de::Error::custom(whole("`sheets` must list every sheet's id once")); + let Value::Array(ids) = Value::deserialize(d)? else { return Err(every()) }; + ids.into_iter() + .map(|id| id.as_str().filter(|s| solidcraft_doc::ids::decode(s).is_some()).map(str::to_string)) + .collect::>() + .ok_or_else(every) +} + +/// Add a sheet after another: it takes that sheet's paper, border and resolution, unless told +/// otherwise, and a name of its own; it documents nothing and leaves nothing out unless told. +/// One undo step. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SheetAddParams { + /// The sheet it follows, by id or name. Default: the last. + #[serde(default, deserialize_with = "some_sheet_ref", skip_serializing_if = "Option::is_none")] + #[schemars(with = "String")] + pub after: Option, + #[serde(flatten, deserialize_with = "super::flattened")] + pub settings: SheetSettings, +} + +/// Change a sheet's settings, the rest kept: one undo step, none when nothing changes. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SheetSetParams { + /// The sheet, by id or name. + #[serde(deserialize_with = "sheet_ref")] + pub sheet: String, + #[serde(flatten, deserialize_with = "super::flattened")] + pub settings: SheetSettings, +} + +/// A sheet's settings, each optional. +#[derive(Debug, Deserialize, JsonSchema)] +pub struct SheetSettings { + /// Its name: 1 to 256 bytes, not only spaces. Names may repeat (a sheet is then named by id). + #[serde(default, deserialize_with = "text", skip_serializing_if = "Option::is_none")] + #[schemars(with = "String")] + pub name: Option, + /// Its paper: `{"standard": "a3"}` (ISO A0 to A4, B and C sizes, US letter and the like) or + /// `{"custom": {"sides_mm": [w, h]}}`, each side above 0 and at most 5000 mm. Its border + /// must lay out on it. + #[serde(default, deserialize_with = "size", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Value")] + pub size: Option, + /// `landscape` or `portrait`. + #[serde(default, deserialize_with = "orientation", skip_serializing_if = "Option::is_none")] + #[schemars(with = "String")] + pub orientation: Option, + /// The resolution its pictures are rendered at: 25 to 2400 dots per inch. + #[serde(default, deserialize_with = "number", skip_serializing_if = "Option::is_none")] + #[schemars(with = "f64")] + pub dpi: Option, + /// The component it documents, `{"source": id, "component": id}` (component 0, the + /// default, is the design itself), or `null` for none. + #[serde(default, deserialize_with = "documents", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Value")] + pub documents: Option, + /// What it leaves out, `{"count"?: true|false, "print"?: true|false}`: from the bill of + /// materials' counts, from printing. A flag not given is kept. + #[serde(default, deserialize_with = "excluded", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Map")] + pub excluded: Option>, +} + +/// Put the sheets in a new order. One undo step, none when the order is the same. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SheetReorderParams { + /// Every sheet's id, once each, in the new order. + #[serde(deserialize_with = "every_sheet")] + pub sheets: Vec, +} + +/// Delete a sheet; a drawing keeps at least one. One undo step. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SheetDeleteParams { + /// The sheet, by id or name. + #[serde(deserialize_with = "sheet_ref")] + pub sheet: String, +} + +/// One of the drawing's sheets. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SheetName { + pub id: String, + pub name: String, +} + +/// What the sheet commands return: the drawing's sheets in order, the new sheet's id from +/// `drawing.sheet.add`, and the views a change of paper leaves outside from `drawing.sheet.set`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SheetsResult { + #[serde(skip_serializing_if = "Option::is_none")] + pub sheet: Option, + pub sheets: Vec, + /// After a change of paper, the sheet's views whose boundary leaves its drawing space. None is + /// moved: what goes where stays the drawing's author's choice. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub outside: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "drawing_sheet_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/drawing_sheet_tests.rs b/crates/engine/src/schema/drawing_sheet_tests.rs new file mode 100644 index 00000000000..cb968d7220a --- /dev/null +++ b/crates/engine/src/schema/drawing_sheet_tests.rs @@ -0,0 +1,71 @@ +use serde_json::{Value, json}; + +use super::*; +use crate::schema::tests::{assert_keys, conforms, drawing_session}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + let settings = ["documents", "dpi", "excluded", "name", "orientation", "size"]; + let with = |key: &'static str| -> Vec<&'static str> { + let mut keys: Vec<&str> = settings.iter().copied().chain([key]).collect(); + keys.sort_unstable(); + keys + }; + assert_keys(input_schema_for::(), &with("after")); + assert_keys(input_schema_for::(), &with("sheet")); + assert_keys(input_schema_for::(), &["sheets"]); + assert_keys(input_schema_for::(), &["sheet"]); +} + +/// A call that already fails gets the same error in strict as with the check off. +#[test] +fn strict_keeps_todays_errors() { + let cases = [ + ("drawing.sheet.add", json!({"after": 5})), + ("drawing.sheet.add", json!({"name": null})), + ("drawing.sheet.add", json!({"size": {"standard": "b7"}})), + ("drawing.sheet.add", json!({"orientation": "upright"})), + ("drawing.sheet.add", json!({"dpi": "high"})), + ("drawing.sheet.set", json!({"sheet": 5})), + ("drawing.sheet.set", json!({"sheet": "Sheet 1", "documents": {"source": 5}})), + ("drawing.sheet.set", json!({"sheet": "Sheet 1", "documents": {"source": "0000000000001", "component": -1}})), + ("drawing.sheet.set", json!({"sheet": "Sheet 1", "excluded": {"count": "yes"}})), + ("drawing.sheet.set", json!({"sheet": "Sheet 1", "excluded": {"cuont": true}})), + ("drawing.sheet.set", json!({"sheet": "Sheet 1", "excluded": []})), + ("drawing.sheet.reorder", json!({"sheets": "all"})), + ("drawing.sheet.reorder", json!({"sheets": [5]})), + ("drawing.sheet.delete", json!({"sheet": null})), + ]; + for (command, p) in cases { + let error = |level| drawing_session(level).0.execute(command, &p).err().map(|e| e.to_string()); + let off = error(ParamCheck::Off); + assert!(off.is_some(), "{command} {p} should fail today"); + assert_eq!(error(ParamCheck::Strict), off, "{command} {p}"); + } +} + +/// Each command's reply, in each form, matches its output schema, with no warnings in warn mode. +#[test] +fn replies_match_the_output_schema() { + let (mut s, source) = drawing_session(ParamCheck::Warn); + let schema = output_schema_for::(); + let schema = schema.as_value(); + let mut check = |command: &str, p: Value| { + let r = s.execute(command, &p).unwrap_or_else(|e| panic!("{command}: {e}")); + assert!(conforms(schema, schema, &r) && r.get("param_warnings").is_none(), "{command}: {r} doesn't match {schema}"); + r + }; + let full = json!({ + "name": "Details", "size": {"custom": {"sides_mm": [300, 200]}}, "orientation": "portrait", "dpi": 300, + "documents": {"source": source, "component": 0}, "excluded": {"count": true, "print": false}, + }); + let added = check("drawing.sheet.add", full); + let id = added["sheet"].clone(); + check("drawing.sheet.add", json!({"after": "Sheet 1"})); + check("drawing.sheet.set", json!({"sheet": id, "size": {"standard": "a2"}, "documents": null})); + let order: Vec = + check("drawing.sheet.set", json!({"sheet": "Sheet 1"}))["sheets"].as_array().unwrap().iter().rev().map(|sheet| sheet["id"].clone()).collect(); + check("drawing.sheet.reorder", json!({"sheets": order})); + check("drawing.sheet.delete", json!({"sheet": id})); +} diff --git a/crates/engine/src/schema/drawing_view.rs b/crates/engine/src/schema/drawing_view.rs new file mode 100644 index 00000000000..40bfc984f34 --- /dev/null +++ b/crates/engine/src/schema/drawing_view.rs @@ -0,0 +1,483 @@ +//! Contracts and result types for the commands in `cmd/drawing_view.rs`. +//! +//! The view's own settings are `solidcraft_doc::drawing_view::ViewSettings`, which a saved view +//! (W12) keeps too. The contract lists the same fields, each read by that type's own reader, and +//! `the_contract_lists_the_view_settings` keeps the two lists the same. A saved view's own +//! settings (`ViewOverrides`) are read and changed through `drawing.view.inspect` and +//! `drawing.view.edit`, each setting with where its value comes from. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use solidcraft_doc::drawing_view::{TangentEdges, ViewDirection, ViewSettings}; +use solidcraft_geom::drawing_sheet::{Orientation, PaperSize, SheetSize}; +use solidcraft_geom::drawing_view::{NamedView, Scale}; +use solidcraft_render::VisualStyle; + +use super::Point2; + +/// The lowest and highest picture resolution a sheet takes, in dots per inch. +pub const DPI_RANGE: std::ops::RangeInclusive = 25.0..=2400.0; + +/// What `drawing.view.snapshot` takes: the view's settings, the page it fits on, and where its +/// centre goes. +#[derive(Debug, Default, Deserialize, JsonSchema)] +#[serde(default, deny_unknown_fields)] +#[schemars(deny_unknown_fields)] +pub struct SnapshotParams { + pub view: ViewParam, + #[serde(deserialize_with = "super::present")] + #[schemars(with = "ScaleParam")] + pub scale: Option, + pub display_style: StyleParam, + pub reference_style: StyleParam, + /// Whether reference parts hide the model's lines behind them (false when not given). + pub reference_hides_model: bool, + /// Model millimetres added on every side of the view's extents, so reference parts around + /// the model show inside its boundary: 0 to 100000 (0 when not given). + pub reference_margin_mm: f64, + pub tangent_edges: TangentEdgesParam, + pub sheet: SheetParam, + /// Where the view's centre goes on the sheet, in paper millimetres from its lower-left + /// corner (the sheet's centre when not given). + #[serde(deserialize_with = "super::present")] + #[schemars(with = "Point2")] + pub position_mm: Option, +} + +impl SnapshotParams { + pub fn settings(&self) -> ViewSettings { + ViewSettings { + view: self.view.0, + scale: self.scale.map(|s| s.0), + display_style: self.display_style.0, + reference_style: self.reference_style.0, + reference_hides_model: self.reference_hides_model, + reference_margin_mm: self.reference_margin_mm, + tangent_edges: self.tangent_edges.0, + } + } +} + +// Each parameter type below reads as the type it wraps, so the contract accepts exactly what the +// view's settings do; it is there for its schema. + +/// Which way the view looks. +#[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize)] +#[serde(transparent)] +pub struct ViewParam(pub ViewDirection); + +impl JsonSchema for ViewParam { + fn schema_name() -> Cow<'static, str> { + "DrawingView".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let names: Vec = NamedView::ALL.iter().filter_map(|v| serde_json::to_value(v).ok()).chain([json!("iso")]).collect(); + let vector = json!({"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}); + json_schema!({ + "description": "Which way the view looks: a named view (front when not given; iso is iso_front_right), or {direction, up, origin?}: the line of sight, the way up the paper (not along the direction) and the point the view's plane passes through (the world origin when not given).", + "anyOf": [ + {"type": "string", "enum": names}, + {"type": "object", "properties": {"direction": vector, "up": vector, "origin": vector}, "required": ["direction", "up"], "additionalProperties": false} + ] + }) + } +} + +/// A drawing scale, paper:model. +#[derive(Clone, Copy, Debug, PartialEq, Deserialize)] +#[serde(transparent)] +pub struct ScaleParam(pub Scale); + +impl JsonSchema for ScaleParam { + fn schema_name() -> Cow<'static, str> { + "DrawingScale".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "The scale as paper:model text, such as \"1:2\" or \"5:1\", from 1:100000 to 1000:1. When not given, the largest ISO 5455 scale at which the view fits the sheet's drawing area.", + "type": "string", + "pattern": "^[0-9]+(\\.[0-9]+)?:[0-9]+(\\.[0-9]+)?$" + }) + } +} + +/// How the model draws. +#[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize)] +#[serde(transparent)] +pub struct StyleParam(pub VisualStyle); + +impl JsonSchema for StyleParam { + fn schema_name() -> Cow<'static, str> { + "VisualStyle".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let names: Vec = VisualStyle::ALL.iter().filter_map(|s| serde_json::to_value(s).ok()).collect(); + json_schema!({ + "description": "How the model draws: visible (the default), visible_hidden, shaded, shaded_visible or shaded_visible_hidden.", + "type": "string", + "enum": names + }) + } +} + +/// Tangent edges hidden or shown. +#[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize)] +#[serde(transparent)] +pub struct TangentEdgesParam(pub TangentEdges); + +impl JsonSchema for TangentEdgesParam { + fn schema_name() -> Cow<'static, str> { + "TangentEdges".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"description": "Edges where faces meet smoothly: hide (the default) or show.", "type": "string", "enum": ["hide", "show"]}) + } +} + +/// The page the view fits on: its size, the way it lies and its picture resolution. +#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)] +#[serde(default, deny_unknown_fields)] +pub struct SheetParam { + pub size: SheetSize, + pub orientation: Orientation, + pub dpi: f64, +} + +impl Default for SheetParam { + fn default() -> Self { + SheetParam { size: SheetSize::Standard(PaperSize::A3), orientation: Orientation::Landscape, dpi: 300.0 } + } +} + +impl JsonSchema for SheetParam { + fn schema_name() -> Cow<'static, str> { + "SnapshotSheet".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + let papers: Vec = PaperSize::ALL.iter().filter_map(|p| serde_json::to_value(p).ok()).collect(); + let sides = json!({"type": "array", "items": {"type": "number", "exclusiveMinimum": 0}, "minItems": 2, "maxItems": 2}); + let standard = json!({"type": "object", "properties": {"standard": {"type": "string", "enum": papers}}, "required": ["standard"], "additionalProperties": false}); + let custom = json!({ + "type": "object", + "properties": {"custom": {"type": "object", "properties": {"sides_mm": sides}, "required": ["sides_mm"], "additionalProperties": false}}, + "required": ["custom"], + "additionalProperties": false + }); + json_schema!({ + "description": "The page the view fits and centres on (A3 landscape at 300 dpi when not given).", + "type": "object", + "properties": { + "size": {"anyOf": [standard, custom]}, + "orientation": {"type": "string", "enum": ["landscape", "portrait"]}, + "dpi": {"type": "number", "minimum": *DPI_RANGE.start(), "maximum": *DPI_RANGE.end()} + }, + "additionalProperties": false + }) + } +} + +/// A saved view, by its id as `drawing.inspect` lists it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ViewIdParam(pub u64); + +impl<'de> Deserialize<'de> for ViewIdParam { + fn deserialize>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => solidcraft_doc::ids::decode(&s).map(ViewIdParam).ok_or_else(|| serde::de::Error::custom("must be a view's id")), + _ => Err(serde::de::Error::custom("must be a view's id")), + } + } +} + +impl JsonSchema for ViewIdParam { + fn schema_name() -> Cow<'static, str> { + "DrawingViewId".into() + } + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"description": "A view's id: 13 characters of lowercase Crockford base32.", "type": "string", "pattern": "^[0-9a-hjkmnp-tv-z]{13}$"}) + } +} + +/// Where a saved view's centre sits on its sheet, in paper millimetres. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case", deny_unknown_fields)] +pub enum PlaceParam { + /// At this point of the sheet, from its lower-left corner. + At([f64; 2]), + /// Lined up with its parent, this far along the free axis (a projected view only). + Aligned(f64), +} + +/// What `drawing.view.inspect` takes. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(deny_unknown_fields)] +pub struct InspectParams { + pub view: ViewIdParam, +} + +/// What `drawing.view.edit` takes: the view, and what to change. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(deny_unknown_fields)] +pub struct EditParams { + pub view: ViewIdParam, + pub set: ViewSet, +} + +/// The settings `drawing.view.edit` changes, each only when given. For the five that can follow +/// the view's parent, `null` means follow it (a base view's scale can't: it has no parent). +#[derive(Debug, Default, Deserialize, JsonSchema)] +#[serde(default, deny_unknown_fields)] +#[schemars(deny_unknown_fields)] +pub struct ViewSet { + #[serde(deserialize_with = "super::present")] + pub scale: Option>, + #[serde(deserialize_with = "super::present")] + pub display_style: Option>, + #[serde(deserialize_with = "super::present")] + pub reference_style: Option>, + #[serde(deserialize_with = "super::present")] + pub reference_hides_model: Option>, + #[serde(deserialize_with = "super::present")] + pub tangent_edges: Option>, + /// Model millimetres added on every side of the view's extents: 0 to 100000. + #[serde(deserialize_with = "super::present")] + #[schemars(with = "f64")] + pub reference_margin_mm: Option, + /// A base view's direction. + #[serde(deserialize_with = "super::present")] + #[schemars(with = "ViewParam")] + pub view: Option, + #[serde(deserialize_with = "super::present")] + #[schemars(with = "PlaceParam")] + pub place: Option, + /// A projected view's display settings (styles, reference parts, tangent edges) all following + /// its parent (true), or all its own, at the values they have now (false). + #[serde(deserialize_with = "super::present")] + #[schemars(with = "bool")] + pub linked: Option, +} + +/// Where a setting's value comes from. +#[derive(Clone, Copy, Debug, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum FromResult { + This, + Parent, + Default, +} + +/// One of a saved view's settings: its value, where it comes from (the parent's id when it is a +/// parent), and what the view sets itself (null when it follows). +#[derive(Debug, Serialize, JsonSchema)] +pub struct SettingResult { + pub value: T, + pub from: FromResult, + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + pub set: Option, +} + +/// A saved view's settings. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SettingsResult { + pub scale: SettingResult, + pub display_style: SettingResult, + pub reference_style: SettingResult, + pub reference_hides_model: SettingResult, + pub tangent_edges: SettingResult, +} + +/// The values a window offers for a view's settings. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ChoicesResult { + pub display_style: Vec, + /// ISO 5455's preset scales, largest first. + pub scale: Vec, +} + +/// What `drawing.view.inspect` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct InspectResult { + pub view: String, + pub sheet: String, + /// `base` or `projected`. + pub kind: &'static str, + /// The design it draws: its own source, or its base view's. + pub source: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + /// The side of its parent a projected view sits on. + #[serde(skip_serializing_if = "Option::is_none")] + pub side: Option, + /// Which way it looks, as resolved through its parents. + pub direction: ViewResult, + pub place: PlaceParam, + pub settings: SettingsResult, + pub reference_margin_mm: f64, + /// Where it sits on its sheet: its extents grown by its reference margin, at its scale, round + /// its centre; a placeholder 20 mm each way when there's nothing to measure. + pub boundary_mm: BoxResult, + /// Its design's extents on its plane. + pub extents: ExtentsResult, + /// A projected view's display settings: `true` when all follow its parent, `false` when none + /// does, `"partly"` otherwise. None for a base view. + #[serde(skip_serializing_if = "Option::is_none")] + #[schemars(with = "Value")] + pub linked: Option, + pub choices: ChoicesResult, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `drawing.view.edit` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct EditResult { + pub view: String, + /// The fields the edit changed. + pub changed: Vec, + /// The other views whose resolved settings changed with it: the views projected from it. + pub followers: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `drawing.view.move_to_sheet` takes. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(deny_unknown_fields)] +pub struct MoveParams { + pub view: ViewIdParam, + /// The sheet, by id or name. + #[serde(deserialize_with = "super::drawing_sheet::sheet_ref")] + pub sheet: String, + /// Where its centre goes, in paper millimetres from the sheet's lower-left corner. + #[serde(default, deserialize_with = "super::present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Point2")] + pub position_mm: Option, + /// A view lined up with its parent moves only when this is true, and is then placed apart. + #[serde(default)] + pub break_alignment: bool, +} + +/// What `drawing.view.copy_to_sheet` takes. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(deny_unknown_fields)] +pub struct CopyParams { + pub view: ViewIdParam, + /// The sheet, by id or name. + #[serde(deserialize_with = "super::drawing_sheet::sheet_ref")] + pub sheet: String, + /// Where the copy's centre goes, in paper millimetres from the sheet's lower-left corner. + #[serde(default, deserialize_with = "super::present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "Point2")] + pub position_mm: Option, + /// Whether the views lined up with it are copied too, lined up with the copy. Needed when it + /// has any. + #[serde(default, deserialize_with = "super::present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "bool")] + pub with_linked: Option, +} + +/// What `drawing.view.move_to_sheet` and `drawing.view.copy_to_sheet` return. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ToSheetResult { + /// The view moved, or its copy. + pub view: String, + pub sheet: String, + /// Every view moved or made: the view's first, then the views lined up with it. + pub views: Vec, + /// Those of them whose boundary leaves the sheet's drawing space; none is moved back in. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub outside: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// A view whose boundary leaves its sheet's drawing space, and where it sits. +#[derive(Debug, Serialize, JsonSchema)] +pub struct OutsideResult { + pub view: String, + pub boundary_mm: BoxResult, + /// With nothing to measure, why its boundary is the placeholder's, as `extents.provenance` + /// names it in `drawing.view.inspect`. + #[serde(skip_serializing_if = "Option::is_none")] + pub unmeasured: Option<&'static str>, +} + +/// A view's extents on its own plane, in model millimetres. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ExtentsResult { + pub min: [f64; 2], + pub max: [f64; 2], + /// How far the display mesh may lie inside a curved face: the largest display tolerance. + pub error_mm: f64, + /// `approximate`: measured on the display mesh; `placeholder`: nothing to measure, so the box is + /// the placeholder's. + pub status: &'static str, + /// `display_mesh`; with a placeholder, why: `past_walk_limit` or `no_bodies`. + pub provenance: &'static str, +} + +/// A box on the sheet, in paper millimetres. +#[derive(Debug, Serialize, JsonSchema)] +pub struct BoxResult { + pub min: [f64; 2], + pub max: [f64; 2], +} + +/// The scale the view was drawn at. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ScaleResult { + pub text: String, + pub factor: f64, + /// Whether the scale was worked out to fit the sheet rather than given. + pub fitted: bool, +} + +/// The view's basis as resolved: its name when it has one, the line of sight and the paper axes. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ViewResult { + #[serde(skip_serializing_if = "Option::is_none")] + pub named: Option, + pub direction: [f64; 3], + pub x: [f64; 3], + pub y: [f64; 3], + pub origin: [f64; 3], +} + +/// What the view was drawn from. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SourceResult { + pub bodies: usize, + /// Whether the timeline marker is at the end; otherwise the view shows the rolled-back model. + pub timeline_at_end: bool, +} + +/// What `drawing.view.snapshot` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SnapshotResult { + pub view: ViewResult, + pub scale: ScaleResult, + pub position_mm: [f64; 2], + /// The sheet the view is placed on, its defaults filled in. + pub sheet: SheetParam, + pub display_style: String, + pub reference_style: String, + pub extents: ExtentsResult, + /// The view's box on the sheet: `position_mm` at its centre, the extents at the scale. + pub boundary_mm: BoxResult, + pub source: SourceResult, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "drawing_view_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/drawing_view_tests.rs b/crates/engine/src/schema/drawing_view_tests.rs new file mode 100644 index 00000000000..81a4978b664 --- /dev/null +++ b/crates/engine/src/schema/drawing_view_tests.rs @@ -0,0 +1,72 @@ +use serde_json::json; +use solidcraft_doc::drawing_view::ViewSettings; + +use super::{CopyParams, EditParams, InspectParams, MoveParams, SnapshotParams, ViewSet}; +use crate::schema::input_schema_for; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors}; + +#[test] +fn schemas_and_the_key_check_agree() { + let keys = [ + "display_style", + "position_mm", + "reference_hides_model", + "reference_margin_mm", + "reference_style", + "scale", + "sheet", + "tangent_edges", + "view", + ]; + assert_keys(input_schema_for::(), &keys); + assert_keys(input_schema_for::(), &["view"]); + assert_keys(input_schema_for::(), &["set", "view"]); + assert_keys(input_schema_for::(), &["break_alignment", "position_mm", "sheet", "view"]); + assert_keys(input_schema_for::(), &["position_mm", "sheet", "view", "with_linked"]); +} + +/// `drawing.view.edit` changes what a saved view sets itself, field for field, and its direction, +/// place and link, so the edit and the record keep one list of a view's settings. +#[test] +fn the_edit_contract_lists_a_saved_views_settings() { + let all = solidcraft_doc::drawing_view::ViewOverrides { + scale: "1:2".parse().ok(), + display_style: Some(Default::default()), + reference_style: Some(Default::default()), + reference_hides_model: Some(false), + tangent_edges: Some(Default::default()), + }; + let own = serde_json::to_value(all).unwrap_or_default(); + let mut theirs: Vec = own.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(); + theirs.extend(["linked", "place", "reference_margin_mm", "view"].map(String::from)); + theirs.sort(); + let schema = input_schema_for::(); + let mut ours: Vec = schema.as_value()["properties"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(); + ours.sort(); + assert_eq!(ours, theirs); +} + +/// The contract takes the view's settings field for field, plus the sheet and the position, so +/// the snapshot and a saved view (W12) keep one parameter set. +#[test] +fn the_contract_lists_the_view_settings() { + // With a scale: none is left out when written. + let settings = serde_json::to_value(ViewSettings { scale: "1:2".parse().ok(), ..ViewSettings::default() }).unwrap_or_default(); + let mut theirs: Vec = settings.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(); + theirs.extend(["position_mm".to_string(), "sheet".to_string()]); + theirs.sort(); + let schema = input_schema_for::(); + let mut ours: Vec = schema.as_value()["properties"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(); + ours.sort(); + assert_eq!(ours, theirs); +} + +#[test] +fn strict_keeps_todays_errors() { + assert_strict_keeps_todays_errors(&[ + ("drawing.view.snapshot", json!({"scale": "0:1"})), + ("drawing.view.snapshot", json!({"view": "Front"})), + ("drawing.view.snapshot", json!({"display_style": "shaded"})), + ("drawing.view.snapshot", json!({"sheet": {"dpi": 1e9}})), + ]); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 266d5fa87c2..ee21f0054c5 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -43,12 +43,15 @@ mod record; mod types; #[cfg(test)] -mod tests; +pub(crate) mod tests; // The contracts, by command file. +pub mod drawing_sheet; +pub mod drawing_view; pub mod features; pub mod inspect; +pub(crate) use check::read; pub use check::{Contract, Issue, ParamCheck, TypedContract, input_schema_for, output_schema_for, run_checked}; pub use types::*; diff --git a/crates/engine/src/schema/tests.rs b/crates/engine/src/schema/tests.rs index aa5ef6aea88..3aa847b2d05 100644 --- a/crates/engine/src/schema/tests.rs +++ b/crates/engine/src/schema/tests.rs @@ -185,6 +185,19 @@ fn present_null_is_refused_but_absent_is_fine() { } } +/// A box design's drawing, open, checking parameters at `level`, and its source's id: where the +/// drawing commands' schemas are tested. +pub(super) fn drawing_session(level: ParamCheck) -> (Session, Value) { + let mut s = Session::default(); + let design = json!({"length": 40, "width": 30, "height": 10, "body_name": "Plate"}); + for (id, p) in [("solid.box", design), ("drawing.create", json!({}))] { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + } + s.param_check = level; + let id = s.execute("drawing.inspect", &json!({})).unwrap_or_else(|e| panic!("{e}"))["sources"][0]["id"].clone(); + (s, id) +} + pub(super) fn sketch_rectangle(s: &mut Session) { for (id, p) in [ ("sketch.create", json!({"plane": "XY"})), @@ -264,7 +277,7 @@ fn the_level_survives_a_new_design() { /// `items`, `minItems`, `maxItems`, `uniqueItems`, `enum`, `minLength`, `maxLength`, `minimum`, /// `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `anyOf`, `not` and `$ref`. (`integer` /// here is what serde reads as one, so `1.0` is not.) -pub(super) fn conforms(root: &Value, node: &Value, v: &Value) -> bool { +pub(crate) fn conforms(root: &Value, node: &Value, v: &Value) -> bool { if let Some(name) = node.get("$ref").and_then(Value::as_str).and_then(|r| r.strip_prefix("#/$defs/")) { return root.get("$defs").and_then(|d| d.get(name)).is_some_and(|t| conforms(root, t, v)); } diff --git a/crates/engine/src/schema/types.rs b/crates/engine/src/schema/types.rs index 6cc26ba6d29..1608dd9676a 100644 --- a/crates/engine/src/schema/types.rs +++ b/crates/engine/src/schema/types.rs @@ -778,6 +778,12 @@ pub struct FeatureCommon { /// issue's path (serde's flatten otherwise loses the key). serde reads a flattened field after /// all the parent's own, so its problems come after theirs, including a missing key. pub fn feature_common<'de, D: Deserializer<'de>>(d: D) -> Result { + flattened(d) +} + +/// Deserializes any flattened part of a contract as [`feature_common`] does `FeatureCommon`: +/// its problems name their keys as the parent's own would. +pub fn flattened<'de, D: Deserializer<'de>, T: serde::de::DeserializeOwned>(d: D) -> Result { let v = Value::deserialize(d)?; serde_path_to_error::deserialize(&v).map_err(|e| D::Error::custom(super::check::located(&e))) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f2d8cf46a3f..87d757422d3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4,6 +4,26 @@ use serde_json::{Value, json}; use crate::*; +/// A folder of the test's own, removed when dropped. +pub(crate) struct Folder(pub std::path::PathBuf); + +impl Folder { + pub(crate) fn new(name: &str) -> Folder { + let dir = solidcraft_io::vfs::temp_dir().join(format!("solidcraft-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + Folder(dir) + } + pub(crate) fn path(&self, file: &str) -> String { + self.0.join(file).to_str().unwrap().to_string() + } +} + +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + mod mesh_convert; fn run(s: &mut Session, id: &str, p: Value) -> Value { @@ -822,6 +842,14 @@ fn hostile_params_never_panic() { "keep_with", "stitch", "extend", + "view", + "display_style", + "reference_style", + "reference_hides_model", + "reference_margin_mm", + "tangent_edges", + "sheet", + "position_mm", ]; // Commands are independent; worker threads take them one at a time (their costs vary a lot). let ids: Vec<&str> = command_specs() @@ -892,12 +920,12 @@ fn only_own_ids_name_commands() { } /// An unknown command's error names the ids it was probably meant to be: a typo's, or the -/// command that ends in the same word. +/// commands that end in the same word, the nearest first. #[test] fn unknown_commands_suggest_the_closest_ids() { let mut s = Session::default(); let mut msg = |id: &str| s.execute(id, &serde_json::json!({})).unwrap_err().to_string(); - assert_eq!(msg("file.open"), "unknown command `file.open` (did you mean `doc.open`?)"); + assert!(msg("file.open").starts_with("unknown command `file.open` (did you mean `doc.open`"), "{}", msg("file.open")); assert!(msg("solid.extrud").starts_with("unknown command `solid.extrud` (did you mean `solid.extrude`"), "{}", msg("solid.extrud")); assert!(msg("Extrude").contains("`solid.extrude`"), "{}", msg("Extrude")); assert_eq!(msg("FusionFilletEdgesCommand"), "unknown command `FusionFilletEdgesCommand`"); diff --git a/crates/geom/src/cell.rs b/crates/geom/src/cell.rs index 04b8a144887..a686cd441a7 100644 --- a/crates/geom/src/cell.rs +++ b/crates/geom/src/cell.rs @@ -111,11 +111,13 @@ pub enum HAlign { } /// The projection a drawing's views use, first or third angle (ISO 5456-2): the value of -/// `drawing.projection`, which the views and the title block's symbol both read. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +/// `drawing.projection`, which the views and the title block's symbol both read. Third angle when +/// nothing chooses (a template or a preference may). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Projection { First, + #[default] Third, } diff --git a/crates/geom/src/drawing_measure.rs b/crates/geom/src/drawing_measure.rs new file mode 100644 index 00000000000..ca48ac71653 --- /dev/null +++ b/crates/geom/src/drawing_measure.rs @@ -0,0 +1,132 @@ +//! Measurement on drawing views (W19a, #4896): what a dimension on a view reads, in model +//! millimetres or radians, from model points and edges and the view's basis. One rule for every +//! dimension: the dimension record (W19b) keeps what to measure, and W09 formats the number. +//! +//! A value is **projected** (as the view shows it) or **true** (as the model has it); +//! `foreshortened` says a measured line isn't parallel to the view's plane, so the two differ. The +//! view's scale and place on the sheet never change a measurement. + +use crate::drawing_view::{Invalid, PARALLEL, require}; +use crate::section::{MAX_NUMBER, validate_plane}; +use crate::{EPS, Plane, Vec2, Vec3}; + +type Result = std::result::Result; + +/// Which way a linear dimension measures on its view. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum LinearDirection { + /// Along the view's horizontal (paper x). + Horizontal, + /// Along the view's vertical (paper y). + Vertical, + /// Along the segment as the view shows it. + Aligned, + /// Along a direction on the view, in its plane's coordinates (any length but zero): a rotated + /// dimension, or one along a picked edge. + Along(Vec2), +} + +/// What a dimension reads: the length or angle as the view shows it, or as the model has it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reading { + Projected, + True, +} + +/// The line an angle is measured from. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum AngleFrom { + /// The view's horizontal, pointing right (paper +x). + Horizontal, + /// The view's vertical, pointing up (paper +y). + Vertical, + /// A model direction, such as the part's axis, as the view shows it. + ModelAxis(Vec3), + /// Another edge, from its first point to its second. + Edge(Vec3, Vec3), +} + +/// What a dimension reads, and whether a measured line is out of the view's plane. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Measured { + /// Model millimetres, or radians for an angle. + pub value: f64, + /// A measured line isn't parallel to the view's plane, so its projected value differs from + /// the model's. + pub foreshortened: bool, +} + +/// The distance from `a` to `b` (model points) that a linear dimension measuring `direction` on +/// the view through `basis` reads. A true reading is the segment's own length, so it goes with +/// [`LinearDirection::Aligned`] only: a true horizontal has no one meaning in a tilted view. +pub fn linear(basis: &Plane, a: Vec3, b: Vec3, direction: LinearDirection, reading: Reading) -> Result { + let d = segment(basis, a, b)?; + let shown = Vec2::new(d.dot(basis.x), d.dot(basis.y)); + let value = match (direction, reading) { + (LinearDirection::Aligned, Reading::True) => d.len(), + (_, Reading::True) => return Err(Invalid("a true length is along the segment: measure it aligned")), + (LinearDirection::Horizontal, Reading::Projected) => shown.x.abs(), + (LinearDirection::Vertical, Reading::Projected) => shown.y.abs(), + (LinearDirection::Aligned, Reading::Projected) => shown.len(), + (LinearDirection::Along(along), Reading::Projected) => { + let along = along.normalized().ok_or(Invalid("the direction to measure along is zero or not finite"))?; + shown.dot(along).abs() + } + }; + require(value > EPS, "the dimension would read 0: the points line up across the direction it measures")?; + Ok(Measured { value, foreshortened: out_of_plane(basis, d) }) +} + +/// The angle from the line `from` to `edge` (model points, from its first to its second) on the +/// view through `basis`, from 0 to π: each line goes the way its caller gives it (from the vertex +/// outwards), so the other side of the angle reads π minus it. A true reading is the angle +/// between the model lines, so it isn't given from the view's horizontal or vertical. +pub fn angle(basis: &Plane, edge: (Vec3, Vec3), from: AngleFrom, reading: Reading) -> Result { + let d = segment(basis, edge.0, edge.1)?; + let (reference, model_line) = match from { + AngleFrom::Horizontal => (basis.x, false), + AngleFrom::Vertical => (basis.y, false), + AngleFrom::ModelAxis(axis) => (axis.normalized().ok_or(Invalid("the model axis is zero or not finite"))?, true), + AngleFrom::Edge(a, b) => (segment(basis, a, b)?, true), + }; + let value = match reading { + Reading::True if model_line => between(d, reference)?, + Reading::True => return Err(Invalid("a true angle is between two model lines, not from the view's horizontal or vertical")), + Reading::Projected => between(on_view(basis, d)?, on_view(basis, reference)?)?, + }; + Ok(Measured { value, foreshortened: out_of_plane(basis, d) || (model_line && out_of_plane(basis, reference)) }) +} + +/// `b - a`, both finite model points within 1e12 mm of the origin, the segment not of zero length, +/// on a valid basis. +fn segment(basis: &Plane, a: Vec3, b: Vec3) -> Result { + validate_plane(basis).map_err(|_| Invalid("a view's basis is finite and orthonormal"))?; + let point = |p: Vec3| p.is_finite() && [p.x, p.y, p.z].iter().all(|v| v.abs() <= MAX_NUMBER); + require(point(a) && point(b), "a model point is finite and within 1e12 mm of the origin")?; + let d = b - a; + require(d.len() > EPS, "a segment or edge has no length")?; + Ok(d) +} + +/// `d` as the view shows it, in its plane's coordinates: refused when the view sees it end-on. +fn on_view(basis: &Plane, d: Vec3) -> Result { + let shown = Vec3::new(d.dot(basis.x), d.dot(basis.y), 0.0); + require(shown.len() > PARALLEL * d.len(), "a line is seen end-on in this view: it has no direction there")?; + Ok(shown) +} + +/// The angle between `u` and `v`, from 0 to π: refused when they are parallel either way. +fn between(u: Vec3, v: Vec3) -> Result { + let sine = u.cross(v).len(); + require(sine > PARALLEL * u.len() * v.len(), "the lines are parallel: there is no angle between them")?; + Ok(sine.atan2(u.dot(v))) +} + +/// Whether `d` leaves the view's plane: the sine of its angle to the plane is over [`PARALLEL`]. +fn out_of_plane(basis: &Plane, d: Vec3) -> bool { + d.dot(basis.normal()).abs() > PARALLEL * d.len() +} + +#[cfg(test)] +#[path = "drawing_measure_tests.rs"] +mod tests; diff --git a/crates/geom/src/drawing_measure_tests.rs b/crates/geom/src/drawing_measure_tests.rs new file mode 100644 index 00000000000..ac32c21d1b9 --- /dev/null +++ b/crates/geom/src/drawing_measure_tests.rs @@ -0,0 +1,209 @@ +use super::*; +use crate::drawing_view::{NamedView, basis_looking}; + +use AngleFrom::{Edge, ModelAxis}; +use LinearDirection::{Aligned, Along, Horizontal, Vertical}; +use Reading::{Projected, True}; + +/// Paper x along X, y along Z. +fn front() -> Plane { + NamedView::Front.basis() +} + +/// From the (1, -1, 1) corner. +fn iso() -> Plane { + NamedView::IsoFrontRight.basis() +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() <= 1e-12 * b.abs().max(1.0) +} + +fn reads(m: Result) -> (f64, bool) { + let m = m.unwrap(); + (m.value, m.foreshortened) +} + +fn degrees(m: Result) -> f64 { + m.unwrap().value.to_degrees() +} + +fn refused(result: Result, says: &str) { + match result { + Err(Invalid(message)) => assert!(message.contains(says), "{message:?} doesn't say {says:?}"), + other => panic!("expected a refusal saying {says:?}, got {other:?}"), + } +} + +/// From (0, 0, 0) to (30, 0, 40) in the front view: 30 across, 40 up, 50 aligned, 70/√2 along +/// (1, 1), 30 along (-2, 0); none foreshortened, and the true length is 50 too. +#[test] +fn a_segment_in_the_views_plane_reads_its_lengths() { + let (a, b) = (Vec3::ZERO, Vec3::new(30.0, 0.0, 40.0)); + let cases = [ + (Horizontal, 30.0), + (Vertical, 40.0), + (Aligned, 50.0), + (Along(Vec2::new(1.0, 1.0)), 70.0 / 2f64.sqrt()), + (Along(Vec2::new(-2.0, 0.0)), 30.0), + ]; + for (direction, value) in cases { + let (v, foreshortened) = reads(linear(&front(), a, b, direction, Projected)); + assert!(close(v, value) && !foreshortened, "{direction:?}: {v}"); + } + assert_eq!(reads(linear(&front(), a, b, Aligned, True)), (50.0, false)); +} + +/// The same segment 20 mm deeper at one end, to (30, 20, 40): still 30, 40 and 50 as the view +/// shows it, now foreshortened; its true length √2900. Scale and place don't enter: a view moved +/// along its normal reads the same. +#[test] +fn a_segment_out_of_the_views_plane_is_foreshortened() { + let (a, b) = (Vec3::ZERO, Vec3::new(30.0, 20.0, 40.0)); + for (direction, value) in [(Horizontal, 30.0), (Vertical, 40.0), (Aligned, 50.0)] { + let (v, foreshortened) = reads(linear(&front(), a, b, direction, Projected)); + assert!(close(v, value) && foreshortened, "{direction:?}: {v}"); + } + let (v, foreshortened) = reads(linear(&front(), a, b, Aligned, True)); + assert!(close(v, 2900f64.sqrt()) && foreshortened); + let moved = Plane { origin: Vec3::new(5.0, -300.0, 7.0), ..front() }; + let (v, foreshortened) = reads(linear(&moved, a, b, Aligned, Projected)); + assert!(close(v, 50.0) && foreshortened, "{v}"); +} + +/// A 50 mm cube edge along X in the front-right isometric view: 50·√(2/3) as drawn, 50 true, +/// foreshortened either way. +#[test] +fn a_cube_edge_in_an_isometric_view() { + let edge = (Vec3::ZERO, Vec3::new(50.0, 0.0, 0.0)); + let (drawn, foreshortened) = reads(linear(&iso(), edge.0, edge.1, Aligned, Projected)); + assert!(close(drawn, 50.0 * (2.0f64 / 3.0).sqrt()) && foreshortened, "{drawn}"); + let (true_length, foreshortened) = reads(linear(&iso(), edge.0, edge.1, Aligned, True)); + assert!(close(true_length, 50.0) && foreshortened); +} + +/// A 30° bevel in the front view, from its low end: 30° to the horizontal, 60° to the vertical, +/// 30° to the X axis and 60° to a vertical edge, none foreshortened; from its high end it reads +/// the other side, 150° to the horizontal. The true angle to X is 30° too; to an axis leaning out +/// of the view, (1, 1, 0), it is 30° as drawn and foreshortened. The Y axis is seen end-on in +/// this view, so an angle to it is refused. +#[test] +fn a_bevel_reads_its_angles_to_the_view_and_the_model() { + let rise = 30f64.to_radians(); + let bevel = (Vec3::ZERO, Vec3::new(rise.cos(), 0.0, rise.sin()) * 10.0); + let upright = Edge(Vec3::ZERO, Vec3::new(0.0, 0.0, 10.0)); + for (from, value) in [(AngleFrom::Horizontal, 30.0), (AngleFrom::Vertical, 60.0), (ModelAxis(Vec3::X), 30.0), (upright, 60.0)] { + let m = angle(&front(), bevel, from, Projected).unwrap(); + assert!(close(m.value.to_degrees(), value) && !m.foreshortened, "{from:?}: {}", m.value.to_degrees()); + } + assert!(close(degrees(angle(&front(), (bevel.1, bevel.0), AngleFrom::Horizontal, Projected)), 150.0)); + assert!(close(degrees(angle(&front(), bevel, ModelAxis(Vec3::X), True)), 30.0)); + let leaning = angle(&front(), bevel, ModelAxis(Vec3::new(1.0, 1.0, 0.0)), Projected).unwrap(); + assert!(close(leaning.value.to_degrees(), 30.0) && leaning.foreshortened, "an axis leaning out of the view: {leaning:?}"); + refused(angle(&front(), bevel, ModelAxis(Vec3::Y), Projected), "end-on"); +} + +/// The X and Z axes in the front-right isometric view (both toward the viewer) are 120° apart as +/// drawn and 90° in the model, foreshortened; X and Y, one away from the viewer, are 60° as drawn. +#[test] +fn model_axes_in_an_isometric_view() { + let x = (Vec3::ZERO, Vec3::X * 50.0); + let drawn = angle(&iso(), x, ModelAxis(Vec3::Z), Projected).unwrap(); + assert!(close(drawn.value.to_degrees(), 120.0) && drawn.foreshortened, "{drawn:?}"); + assert!(close(degrees(angle(&iso(), x, ModelAxis(Vec3::Z), True)), 90.0)); + assert!(close(degrees(angle(&iso(), x, Edge(Vec3::ZERO, Vec3::Y), Projected)), 60.0)); +} + +/// What can't be measured, each refused with its reason. +#[test] +fn what_cant_be_measured_is_refused() { + let (a, b) = (Vec3::ZERO, Vec3::new(30.0, 0.0, 40.0)); + for p in [Vec3::new(f64::NAN, 0.0, 0.0), Vec3::new(0.0, f64::INFINITY, 0.0), Vec3::new(0.0, 0.0, 1.000_000_1e12)] { + refused(linear(&front(), a, p, Aligned, Projected), "model point"); + refused(angle(&front(), (p, b), AngleFrom::Horizontal, Projected), "model point"); + } + linear(&front(), Vec3::new(-1e12, 0.0, 0.0), Vec3::new(1e12, 0.0, 0.0), Horizontal, Projected).unwrap(); + refused(linear(&front(), a, a, Aligned, True), "no length"); + refused(linear(&front(), a, a + Vec3::X * 1e-10, Horizontal, Projected), "no length"); + let skewed = Plane { x: Vec3::new(2.0, 0.0, 0.0), ..front() }; + refused(linear(&skewed, a, b, Horizontal, Projected), "basis"); + refused(angle(&skewed, (a, b), AngleFrom::Horizontal, Projected), "basis"); + for along in [Vec2::ZERO, Vec2::new(f64::NAN, 1.0), Vec2::new(f64::INFINITY, 0.0)] { + refused(linear(&front(), a, b, Along(along), Projected), "direction to measure along"); + } + refused(linear(&front(), a, Vec3::new(0.0, 0.0, 40.0), Horizontal, Projected), "would read 0"); + refused(linear(&front(), a, Vec3::new(0.0, 25.0, 0.0), Aligned, Projected), "would read 0"); + for direction in [Horizontal, Vertical, Along(Vec2::X)] { + refused(linear(&front(), a, b, direction, True), "true length"); + } + let edge = (a, b); + refused(angle(&front(), edge, Edge(a, b * 2.0), Projected), "parallel"); + refused(angle(&front(), edge, Edge(b, a), Projected), "parallel"); + refused(angle(&front(), edge, Edge(b, a), True), "parallel"); + refused(angle(&front(), (a, Vec3::new(0.0, 25.0, 0.0)), AngleFrom::Horizontal, Projected), "end-on"); + refused(angle(&front(), edge, AngleFrom::Horizontal, True), "true angle"); + refused(angle(&front(), edge, AngleFrom::Vertical, True), "true angle"); + for axis in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0), Vec3::new(1e308, 1e308, 0.0)] { + refused(angle(&front(), edge, ModelAxis(axis), Projected), "model axis"); + } + refused(angle(&front(), edge, Edge(a, a), Projected), "no length"); +} + +fn random(state: &mut u64) -> u64 { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + *state +} + +/// Points, edges, bases and directions, three cases in four tidy (the named views and views +/// looking any way, points within a metre) and the rest hostile (non-finite, huge, repeated, +/// along the view's normal), 20,000 seeded cases: nothing panics; across² + up² = aligned²; a +/// projected aligned length is never more than the true one; every angle is from 0 to π, and a +/// true angle and its projection agree in a view square to both lines. +#[test] +fn measurements_seeded_never_panic_and_keep_their_rules() { + let mut seed = 0x4896_19a0_d1e5_7c3b; + let hostile = [0.0, -0.0, 1e-10, 1e12, 1.1e12, f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300, -5.0]; + let (mut lengths, mut angles) = (0, 0); + for case in 0..20_000 { + let tidy = !random(&mut seed).is_multiple_of(4); + let number = |seed: &mut u64| { + if tidy { + (random(seed) % 2_001) as f64 / 2.0 - 500.0 + } else { + hostile.get((random(seed) % hostile.len() as u64) as usize).copied().unwrap_or(0.0) + } + }; + let point = |seed: &mut u64| Vec3::new(number(seed), number(seed), number(seed)); + let basis = match random(&mut seed) % 3 { + 0 => NamedView::ALL.get((random(&mut seed) % 10) as usize).map(|v| v.basis()).unwrap_or_else(front), + 1 => basis_looking(point(&mut seed), Vec3::Z, Vec3::ZERO).unwrap_or_else(|_| iso()), + _ => Plane { origin: point(&mut seed), x: point(&mut seed), y: point(&mut seed) }, + }; + let (a, b, c, d) = (point(&mut seed), point(&mut seed), point(&mut seed), point(&mut seed)); + let along = Vec2::new(number(&mut seed), number(&mut seed)); + let read = |direction| linear(&basis, a, b, direction, Projected).map(|m| m.value); + if let (Ok(h), Ok(v), Ok(aligned)) = (read(Horizontal), read(Vertical), read(Aligned)) { + lengths += 1; + assert!((h * h + v * v - aligned * aligned).abs() <= 1e-9 * aligned * aligned, "case {case}"); + let true_length = linear(&basis, a, b, Aligned, True).map(|m| m.value); + assert!(true_length.is_ok_and(|t| aligned <= t * (1.0 + 1e-12)), "case {case}"); + } + let _ = linear(&basis, a, b, Along(along), Projected); + for from in [AngleFrom::Horizontal, AngleFrom::Vertical, ModelAxis(c - d), Edge(c, d)] { + for reading in [Projected, True] { + if let Ok(m) = angle(&basis, (a, b), from, reading) { + angles += 1; + assert!(m.value > 0.0 && m.value < std::f64::consts::PI, "case {case}: {m:?}"); + } + } + } + if let (Ok(drawn), Ok(model)) = (angle(&basis, (a, b), Edge(c, d), Projected), angle(&basis, (a, b), Edge(c, d), True)) + && !drawn.foreshortened + { + assert!((drawn.value - model.value).abs() <= 1e-6, "case {case}: {drawn:?} {model:?}"); + } + } + assert!(lengths > 5_000 && angles > 20_000, "lengths {lengths}, angles {angles}"); +} diff --git a/crates/geom/src/drawing_view.rs b/crates/geom/src/drawing_view.rs index 4459c10db32..ce06a67ffc6 100644 --- a/crates/geom/src/drawing_view.rs +++ b/crates/geom/src/drawing_view.rs @@ -6,6 +6,9 @@ //! `x × y` toward the viewer. [`NamedView`] gives the principal views and the four upper //! isometric corners exactly, never from a camera, which tilts a top view by its pitch clamp; //! [`basis_looking`] gives any other view from its direction and up. +//! - A **projected view** sits on one side of its parent ([`ProjectedSide`]) and looks from that +//! side in third angle, from the side away from it in first ([`projected_basis`]); its frame +//! lines up with the parent's ([`ViewFrame::aligned`]). //! - A **[`Scale`]** is a ratio of two numbers from 0.000001 to 1000000, written `"1:2"` (paper : //! model), from 1:100000 to 1000:1. [`Scale::fit`] picks the largest of ISO 5455's preset //! scales at which a view fits a space. @@ -18,6 +21,7 @@ use std::str::FromStr; use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use crate::cell::Projection; use crate::paper::MAX_SIDE_MM; use crate::section::{CurveAccuracy, MAX_NUMBER, validate_plane}; use crate::{Aabb2, Plane, Seg2, Similarity2, Vec2, Vec3}; @@ -37,12 +41,12 @@ pub struct Invalid(pub &'static str); type Result = std::result::Result; -fn require(condition: bool, message: &'static str) -> Result<()> { +pub(crate) fn require(condition: bool, message: &'static str) -> Result<()> { if condition { Ok(()) } else { Err(Invalid(message)) } } /// Two directions closer to parallel than this (the sine of their angle) give no view. -const PARALLEL: f64 = 1e-9; +pub(crate) const PARALLEL: f64 = 1e-9; /// A view with a name: the six principal views and the isometric views from the four upper /// corners. Each looks at the model from where its name says; `iso` reads as the front-right one. @@ -119,6 +123,68 @@ pub fn basis_looking(direction: Vec3, up: Vec3, origin: Vec3) -> Result { Ok(basis) } +/// The side of its parent a projected view sits on. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ProjectedSide { + Left, + Right, + Above, + Below, +} + +impl ProjectedSide { + pub const ALL: [ProjectedSide; 4] = [ProjectedSide::Left, ProjectedSide::Right, ProjectedSide::Above, ProjectedSide::Below]; + + /// `point`'s coordinate on this side's free axis, the one a view lined up with its parent keeps + /// its own place along: x for a view to the left or right of its parent, y for one above or below. + pub fn along(self, point: Vec2) -> f64 { + match self { + ProjectedSide::Left | ProjectedSide::Right => point.x, + ProjectedSide::Above | ProjectedSide::Below => point.y, + } + } + + /// `point` with its coordinate on this side's free axis ([`ProjectedSide::along`]) set to `along`. + pub fn on_free_axis(self, point: Vec2, along: f64) -> Vec2 { + match self { + ProjectedSide::Left | ProjectedSide::Right => Vec2::new(along, point.y), + ProjectedSide::Above | ProjectedSide::Below => Vec2::new(point.x, along), + } + } +} + +/// The basis of the view projected from `parent` onto `side` of it, in `projection` (ISO 5456-2): +/// in third angle a view shows the side of the model it sits on (one to the right looks from the +/// right), and in first angle the side away from it. It is the parent's basis turned a quarter +/// turn about one of its paper axes, through the parent's origin, with no rounding beyond the +/// parent's normal (a principal view's projections are exact), and it lines up with the parent: a +/// view to the left or right keeps the parent's paper y, one above or below its paper x. +pub fn projected_basis(parent: &Plane, side: ProjectedSide, projection: Projection) -> Result { + validate_plane(parent).map_err(|_| Invalid("a view's basis is finite and orthonormal"))?; + // 1 when the view looks from the side it sits on, -1 when from the side away from it. + let from = match projection { + Projection::Third => 1.0, + Projection::First => -1.0, + }; + // The normal, toward the parent's viewer, becomes the paper axis the turn doesn't keep. + let normal = parent.x.cross(parent.y); + let (x, y) = match side { + ProjectedSide::Right => (normal * -from, parent.y), + ProjectedSide::Left => (normal * from, parent.y), + ProjectedSide::Above => (parent.x, normal * -from), + ProjectedSide::Below => (parent.x, normal * from), + }; + Ok(Plane { origin: parent.origin, x: positive_zeros(x), y: positive_zeros(y) }) +} + +/// `v` with any -0 made 0 (turning by a sign makes a zero component -0), so a view's axes write +/// out as `[0.0, 1.0, 0.0]`, never `[-0.0, 1.0, -0.0]`. +fn positive_zeros(v: Vec3) -> Vec3 { + let positive = |c: f64| if c == 0.0 { 0.0 } else { c }; + Vec3::new(positive(v.x), positive(v.y), positive(v.z)) +} + /// Paper x and y for an isometric view from the upper corner `(cx, cy, 1)`: x is horizontal, the /// view direction × Z, and y = x × direction, so the normal points back at the corner. fn iso(cx: f64, cy: f64) -> (Vec3, Vec3) { @@ -224,6 +290,12 @@ impl<'de> Deserialize<'de> for Scale { } } +/// Whether `v` can place a view on paper: finite and at most [`MAX_SIDE_MM`] from the sheet's +/// origin either way. +pub fn is_paper_coordinate(v: f64) -> bool { + v.is_finite() && v.abs() <= MAX_SIDE_MM +} + /// A view placed on paper: its basis, its scale, and where it sits. #[derive(Clone, Copy, Debug, PartialEq)] pub struct ViewFrame { @@ -238,13 +310,25 @@ impl ViewFrame { pub fn new(basis: Plane, scale: Scale, centre: Vec2, position_mm: Vec2) -> Result { validate_plane(&basis).map_err(|_| Invalid("a view's basis is finite and orthonormal"))?; require(centre.is_finite() && centre.x.abs() <= MAX_NUMBER && centre.y.abs() <= MAX_NUMBER, "a view's centre is finite")?; - let on_paper = position_mm.is_finite() && position_mm.x.abs() <= MAX_SIDE_MM && position_mm.y.abs() <= MAX_SIDE_MM; + let on_paper = is_paper_coordinate(position_mm.x) && is_paper_coordinate(position_mm.y); require(on_paper, "a view's position is finite and at most 5000 mm from the sheet's origin")?; let factor = scale.factor(); let map = Similarity2::new(factor, 0.0, position_mm - centre * factor).ok_or(Invalid("a view's position is finite"))?; Ok(ViewFrame { basis, scale, map }) } + /// The view projected from this one onto `side` of it in `projection`, at this view's scale and + /// lined up with it: the point `centre` of its plane lands at `position_mm` along the free axis + /// (paper x for a view to the left or right, y above or below), and on this view's line along + /// the other, so each point of the model sits as high in both views (or as far across). + pub fn aligned(&self, side: ProjectedSide, projection: Projection, centre: Vec2, position_mm: Vec2) -> Result { + let basis = projected_basis(&self.basis, side, projection)?; + // The kept axis's coordinate of `centre` is the same in this view's plane, and this view's + // map turns nothing, so across the free axis `centre` lands where this view puts it. + let position = side.on_free_axis(self.map.apply(centre), side.along(position_mm)); + ViewFrame::new(basis, self.scale, centre, position) + } + pub fn basis(&self) -> Plane { self.basis } diff --git a/crates/geom/src/drawing_view_tests.rs b/crates/geom/src/drawing_view_tests.rs index 75228a89b70..be7f1c7f228 100644 --- a/crates/geom/src/drawing_view_tests.rs +++ b/crates/geom/src/drawing_view_tests.rs @@ -248,6 +248,118 @@ fn the_fitted_scale_is_the_largest_preset_that_fits() { } } +/// Whether any component of `v` is -0. +fn negative_zero(v: Vec3) -> bool { + [v.x, v.y, v.z].iter().any(|c| *c == 0.0 && c.is_sign_negative()) +} + +/// Projected from the front view, each side is exactly a named view: in third angle the side the +/// view sits on (right of the front, the right view), in first angle the side away from it, as +/// ISO 5456-2 places them. Their axes are exact, with no -0, and the names read as written. +#[test] +fn projected_views_of_the_front_are_the_named_views_in_either_angle() { + use ProjectedSide::{Above, Below, Left, Right}; + let front = NamedView::Front.basis(); + let sides = [ + (Right, NamedView::Right, NamedView::Left), + (Left, NamedView::Left, NamedView::Right), + (Above, NamedView::Top, NamedView::Bottom), + (Below, NamedView::Bottom, NamedView::Top), + ]; + for (side, third, first) in sides { + for (projection, named) in [(Projection::Third, third), (Projection::First, first)] { + let view = projected_basis(&front, side, projection).unwrap(); + assert_eq!(view, named.basis(), "{side:?} in {projection:?}"); + assert!(!negative_zero(view.x) && !negative_zero(view.y), "{side:?} in {projection:?}: {view:?}"); + } + } + let names: Vec<_> = ProjectedSide::ALL.iter().map(|s| serde_json::to_value(s).unwrap()).collect(); + assert_eq!(names, [serde_json::json!("left"), serde_json::json!("right"), serde_json::json!("above"), serde_json::json!("below")]); + assert!(serde_json::from_value::(serde_json::json!("top")).is_err()); +} + +/// From any view: the projected view looks from its side's paper axis (or the opposite one in +/// first angle), keeps the parent's other axis and origin, and is a basis; four quarter turns the +/// same way bring the parent back, and so does a turn and its opposite. +#[test] +fn a_projected_view_is_its_parent_turned_a_quarter_turn() { + use ProjectedSide::{Above, Below, Left, Right}; + let leaning = basis_looking(Vec3::new(0.3, 1.0, -0.2), Vec3::new(0.1, 0.2, 1.0), Vec3::new(5.0, -7.0, 2.0)).unwrap(); + for parent in NamedView::ALL.map(NamedView::basis).into_iter().chain([leaning]) { + for projection in [Projection::Third, Projection::First] { + let from = if projection == Projection::Third { 1.0 } else { -1.0 }; + for side in ProjectedSide::ALL { + let view = projected_basis(&parent, side, projection).unwrap(); + validate_plane(&view).unwrap(); + assert_eq!(view.origin, parent.origin); + let (toward_viewer, kept, kept_by) = match side { + Right => (parent.x * from, view.y, parent.y), + Left => (parent.x * -from, view.y, parent.y), + Above => (parent.y * from, view.x, parent.x), + Below => (parent.y * -from, view.x, parent.x), + }; + assert!(close(view.normal(), toward_viewer) && kept == kept_by, "{parent:?} {side:?} {projection:?}: {view:?}"); + } + let turned = |mut b: Plane, side, n: usize| { + for _ in 0..n { + b = projected_basis(&b, side, projection).unwrap(); + } + b + }; + for side in ProjectedSide::ALL { + let back = turned(parent, side, 4); + assert!(close(back.x, parent.x) && close(back.y, parent.y), "{parent:?}: four turns {side:?}"); + } + for (side, opposite) in [(Right, Left), (Above, Below)] { + let back = turned(turned(parent, side, 1), opposite, 1); + assert!(close(back.x, parent.x) && close(back.y, parent.y), "{parent:?}: {side:?} then {opposite:?}"); + } + } + // The principal views' projections stay exact, with no -0. + if parent.x.x.fract() == 0.0 && parent.x.y.fract() == 0.0 && parent.x.z.fract() == 0.0 { + for (side, projection) in ProjectedSide::ALL.into_iter().flat_map(|s| [(s, Projection::Third), (s, Projection::First)]) { + let view = projected_basis(&parent, side, projection).unwrap(); + assert!(!negative_zero(view.x) && !negative_zero(view.y), "{parent:?} {side:?} {projection:?}"); + } + } + } + let skewed = Plane { x: Vec3::new(1.0, 0.1, 0.0), ..NamedView::Front.basis() }; + let not_finite = Plane { origin: Vec3::new(f64::NAN, 0.0, 0.0), ..NamedView::Front.basis() }; + for parent in [skewed, not_finite] { + assert_eq!(projected_basis(&parent, Right, Projection::Third), Err(Invalid("a view's basis is finite and orthonormal"))); + } +} + +/// An aligned projected view takes its parent's scale and lines up with it: every corner of a box +/// sits as high in the front view and the views to its left and right, and as far across in the +/// views above and below it; the projected view's centre lands at the position asked for along the +/// free axis. A position past the paper's limit is refused. +#[test] +fn an_aligned_view_lines_up_with_its_parent() { + let corners: Vec = + (0..8).map(|i| Vec3::new(f64::from(i & 1) * 100.0, f64::from((i >> 1) & 1) * 50.0, f64::from((i >> 2) & 1) * 20.0)).collect(); + let front = ViewFrame::new(NamedView::Front.basis(), "1:2".parse().unwrap(), Vec2::new(50.0, 10.0), Vec2::new(150.0, 150.0)).unwrap(); + for projection in [Projection::Third, Projection::First] { + for side in ProjectedSide::ALL { + let centre = Vec2::new(25.0, -10.0); + let view = front.aligned(side, projection, centre, Vec2::new(300.0, 60.0)).unwrap(); + assert_eq!(view.scale(), front.scale()); + let across = matches!(side, ProjectedSide::Above | ProjectedSide::Below); + for p in &corners { + let (a, b) = (front.to_paper(*p), view.to_paper(*p)); + let lined_up = if across { (a.x - b.x).abs() } else { (a.y - b.y).abs() }; + assert!(lined_up < EPS, "{side:?} {projection:?}: {p:?} at {a:?} and {b:?}"); + } + let at = view.paper_map().apply(centre); + let free = if across { (at.y - 60.0).abs() } else { (at.x - 300.0).abs() }; + assert!(free < EPS, "{side:?} {projection:?}: centre at {at:?}"); + } + } + let right = front.aligned(ProjectedSide::Right, Projection::Third, Vec2::ZERO, Vec2::new(5000.001, 0.0)); + assert!(right.is_err(), "past the paper's limit"); + assert!(front.aligned(ProjectedSide::Above, Projection::Third, Vec2::new(f64::NAN, 0.0), Vec2::ZERO).is_err(), "a centre not finite"); +} + /// What a frame refuses: a basis that isn't orthonormal or finite, a centre that isn't finite, and /// a position past the paper's limit. #[test] @@ -271,3 +383,15 @@ fn a_frame_refuses_hostile_input() { } assert!(ViewFrame::new(front, one, Vec2::ZERO, Vec2::new(5000.0, -5000.0)).is_ok()); } + +/// A side's free axis is x for a view to the left or right of its parent, y above or below it. +#[test] +fn a_sides_free_axis_is_x_beside_its_parent_and_y_above_or_below() { + let p = Vec2::new(3.0, 4.0); + for side in [ProjectedSide::Left, ProjectedSide::Right] { + assert_eq!((side.along(p), side.on_free_axis(p, 9.0)), (3.0, Vec2::new(9.0, 4.0)), "{side:?}"); + } + for side in [ProjectedSide::Above, ProjectedSide::Below] { + assert_eq!((side.along(p), side.on_free_axis(p, 9.0)), (4.0, Vec2::new(3.0, 9.0)), "{side:?}"); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 0c60fbe722c..e1a2d37548e 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -18,6 +18,7 @@ mod bvh; pub mod cell; mod chain; pub mod compare; +pub mod drawing_measure; pub mod drawing_sheet; pub mod drawing_view; pub mod env; diff --git a/crates/io/src/design.rs b/crates/io/src/design.rs index 7bfdee5b682..a4b2512433f 100644 --- a/crates/io/src/design.rs +++ b/crates/io/src/design.rs @@ -8,7 +8,6 @@ use std::sync::Arc; mod drawing; mod native_cache; mod thumbnail; -pub use drawing::{FileKind, file_kind, read_drawing, read_drawing_file, write_drawing_container}; pub use native_cache::read_design_geometry; pub use thumbnail::{THUMBNAIL_SIZE, read_design_thumbnail, read_design_thumbnail_file}; @@ -74,12 +73,6 @@ struct PackageWriter { } impl PackageWriter { - fn new() -> PackageWriter { - PackageWriter { zip: zip::ZipWriter::new(Cursor::new(Vec::new())), names: BTreeSet::new(), expanded: 0, resolved: 0 } - } - fn finish(self) -> Result> { - Ok(self.zip.finish().map_err(invalid)?.into_inner()) - } fn part(&mut self, name: &str, bytes: &[u8], compressed: bool) -> Result<()> { if bytes.len() > if name.ends_with(".step") { MAX_STEP_PART } else { MAX_PART } { return Err(invalid("part too large")); @@ -228,7 +221,7 @@ fn write_container( thumbnail: Option<&[u8]>, budget: usize, ) -> Result> { - let mut writer = PackageWriter::new(); + let mut writer = PackageWriter { zip: zip::ZipWriter::new(Cursor::new(Vec::new())), names: BTreeSet::new(), expanded: 0, resolved: 0 }; let mut features = Vec::with_capacity(doc.features.len()); for feature in &doc.features { let replacements = match &feature.kind { @@ -273,10 +266,16 @@ fn write_container( value.as_object_mut().ok_or_else(|| invalid("canvas metadata"))?.insert("image_blob".into(), blob); canvases.push(value); } - let metadata = replace(doc, fields([("features", Value::Array(features)), ("canvases", Value::Array(canvases))])).map_err(invalid)?; + let replacements = fields([("features", Value::Array(features)), ("canvases", Value::Array(canvases)), ("drawings", Value::Null)]); + let mut metadata = replace(doc, replacements).map_err(invalid)?; + // The drawings have entries of their own: `document.json` is the same with them or without. + if let Some(o) = metadata.as_object_mut() { + o.remove("drawings"); + } let metadata = serde_json::to_vec(&metadata).map_err(invalid)?; writer.part("document.json", &metadata, true)?; writer.part("container.json", &serde_json::to_vec(&json!({"format": VERSION})).map_err(invalid)?, false)?; + drawing::write(&mut writer, doc)?; // The model cache is optional: one that does not fit the container is left out, never a // failed save. let cache = geometry.and_then(|g| native_cache::encode_model(g, &metadata).ok()).filter(|(manifest, data)| { @@ -302,7 +301,7 @@ fn write_container( if let Some(png) = thumbnail { thumbnail::write(&mut writer, png, &metadata)?; } - let bytes = writer.finish()?; + let bytes = writer.zip.finish().map_err(invalid)?.into_inner(); if bytes.len() > MAX_DESIGN_BYTES { return Err(invalid(format!("the design would be {} MB, over the {} MB a design file may hold", bytes.len() >> 20, MAX_DESIGN_BYTES >> 20))); } @@ -436,8 +435,9 @@ impl PackageReader { } self.document.as_ref().filter(|d| d.len() <= limit).cloned().ok_or_else(|| invalid("metadata budget")) } - fn has_part(&self, name: &str) -> bool { - self.zip.index_for_name(name).is_some() + /// Every entry's name (each was checked when the container was opened). + fn names(&self) -> Result> { + self.zip.file_names().map(|name| name.map(|n| n.into_owned()).map_err(invalid)).collect() } fn part(&mut self, name: &str) -> Result> { self.limited_part(name, if name.ends_with(".step") { MAX_STEP_PART } else { MAX_PART }) @@ -623,33 +623,6 @@ pub(super) fn read(bytes: &[u8]) -> Result { /// keeps one seekable file handle instead of buffering the complete archive. JSON continues /// through the normal migrations. pub fn read_design_file(path: &str, notify: Option) -> Result<(Document, Option)> { - let mut source = open_regular_file(path)?; - if is_container_source(&mut source)? { - let mut reader = DesignContainerReader::new(source)?; - // A design with its model opens without a picture first: the model is the session. - let model = reader.geometry(); - if let Some(notify) = notify - && model.is_none() - && let Ok(preview) = read_preview(&mut reader.reader) - { - notify(preview); - } - Ok((reader.read_document()?, model)) - } else { - let mut bytes = Vec::new(); - source.take(MAX_DESIGN_BYTES as u64 + 1).read_to_end(&mut bytes).map_err(invalid)?; - Ok((crate::read_design(&bytes)?, None)) - } -} - -#[cfg(not(target_arch = "wasm32"))] -type FileSource = std::fs::File; -#[cfg(target_arch = "wasm32")] -type FileSource = Cursor>; - -/// A file to read: inside the folders this process may use, a regular file, and at most -/// [`MAX_DESIGN_BYTES`], read from its start. -fn open_regular_file(path: &str) -> Result { #[cfg(not(target_arch = "wasm32"))] let mut source = { crate::vfs::check(path).map_err(invalid)?; @@ -673,24 +646,33 @@ fn open_regular_file(path: &str) -> Result { return Err(invalid("file too large")); } source.seek(SeekFrom::Start(0)).map_err(invalid)?; - Ok(source) -} - -/// Whether a source starts as a container does, leaving it at its start. -fn is_container_source(source: &mut FileSource) -> Result { let mut prefix = [0u8; 4]; - let size = source.seek(SeekFrom::End(0)).map_err(invalid)?; - source.seek(SeekFrom::Start(0)).map_err(invalid)?; if size >= 4 { source.read_exact(&mut prefix).map_err(invalid)?; } source.seek(SeekFrom::Start(0)).map_err(invalid)?; - Ok(is_design_container(&prefix)) + if is_design_container(&prefix) { + let mut reader = DesignContainerReader::new(source)?; + // A design with its model opens without a picture first: the model is the session. + let model = reader.geometry(); + if let Some(notify) = notify + && model.is_none() + && let Ok(preview) = read_preview(&mut reader.reader) + { + notify(preview); + } + Ok((reader.read_document()?, model)) + } else { + let mut bytes = Vec::new(); + source.take(MAX_DESIGN_BYTES as u64 + 1).read_to_end(&mut bytes).map_err(invalid)?; + Ok((crate::read_design(&bytes)?, None)) + } } fn read_document(reader: &mut PackageReader) -> Result { - if drawing::container_kind(reader)? == FileKind::Drawing { - return Err(IoError::Invalid("this file is a SolidCraft drawing, not a design: open it as a drawing".into())); + let version: Value = serde_json::from_slice(&reader.part("container.json")?).map_err(invalid)?; + if !matches!(version.get("format").and_then(Value::as_str), Some(VERSION | LEGACY_VERSION)) { + return Err(invalid("unsupported container version")); } let bytes = reader.document(MAX_DESIGN_BYTES)?; let metadata: Value = serde_json::from_slice(&bytes).map_err(invalid)?; @@ -698,6 +680,9 @@ fn read_document(reader: &mut PackageReader) -> Result(reader: &mut PackageReader) -> Result.json` (Deflate, as `document.json`), its id as [`ids::encode`] writes it and its +//! text [`Drawing::to_json`]'s. `document.json` holds nothing of them, so its bytes, and the model +//! cache keyed to them, don't change when only a drawing does. An entry under `drawings/` that +//! isn't a drawing's, or whose record has another id, is damage: the design is refused. -use std::io::{Cursor, Read, Seek}; +use std::io::{Read, Seek}; +use std::sync::Arc; -use serde::Deserialize; -use serde_json::{Value, json}; -use solidcraft_doc::drawing::{Drawing, MAX_DRAWING_BYTES}; -use solidcraft_doc::format::DRAWING; +use solidcraft_doc::drawing::{self, Drawing, MAX_DRAWING_BYTES}; +use solidcraft_doc::{Document, ids}; -use super::{PackageReader, PackageWriter, VERSION, invalid, is_design_container}; -use crate::{IoError, MAX_DESIGN_BYTES, Result}; +use super::{PackageReader, PackageWriter, invalid}; +use crate::Result; -/// The part a drawing container keeps its drawing in. -const DRAWING_PART: &str = "drawing.json"; -/// What a drawing's `container.json` says it holds. -const DRAWING_CONTENT: &str = "drawing"; +/// The folder of a container's drawing entries. +const FOLDER: &str = "drawings/"; -/// What a SolidCraft file holds. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum FileKind { - Design, - Drawing, -} - -/// Which kind of file `bytes` are, from the container's `container.json` or the JSON's `format`. -/// JSON that isn't a drawing's counts as a design, which the design reader then checks. -pub fn file_kind(bytes: &[u8]) -> Result { - if is_design_container(bytes) { - return container_kind(&mut PackageReader::new(Cursor::new(bytes))?); - } - #[derive(Deserialize)] - struct Format { - format: Option, - } - let format = serde_json::from_slice::(bytes).ok().and_then(|f| f.format); - Ok(if format.is_some_and(|f| DRAWING.version_of(&f).is_some()) { FileKind::Drawing } else { FileKind::Design }) -} - -/// What a container holds, by its `container.json`: no `content` is a design. -pub(super) fn container_kind(reader: &mut PackageReader) -> Result { - let container: Value = serde_json::from_slice(&reader.limited_part("container.json", 4096)?).map_err(invalid)?; - if !matches!(container.get("format").and_then(Value::as_str), Some(super::VERSION | super::LEGACY_VERSION)) { - return Err(invalid("unsupported container version")); - } - match container.get("content") { - None => Ok(FileKind::Design), - Some(Value::String(content)) if content == DRAWING_CONTENT => Ok(FileKind::Drawing), - Some(other) => Err(invalid(format!("this build doesn't know container content {other}"))), +/// Write each of the design's drawings to its entry. +pub(super) fn write(writer: &mut PackageWriter, doc: &Document) -> Result<()> { + drawing::check_in_design(&doc.drawings)?; + for d in &doc.drawings { + writer.part(&format!("{FOLDER}{}.json", ids::encode(d.id)), d.to_json()?.as_bytes(), true)?; } + Ok(()) } -/// The drawing as a container: the same bytes for the same drawing. -pub fn write_drawing_container(drawing: &Drawing) -> Result> { - let text = drawing.to_json()?; - let mut writer = PackageWriter::new(); - writer.part(DRAWING_PART, text.as_bytes(), true)?; - let container = json!({"format": VERSION, "content": DRAWING_CONTENT}); - writer.part("container.json", &serde_json::to_vec(&container).map_err(invalid)?, false)?; - writer.finish() -} - -/// Read a drawing file's bytes: a container or plain JSON. -pub fn read_drawing(bytes: &[u8]) -> Result { - if bytes.len() > MAX_DESIGN_BYTES { - return Err(IoError::Invalid("drawing file too large".into())); - } - if is_design_container(bytes) { - return read_container(Cursor::new(bytes)); - } - if file_kind(bytes)? == FileKind::Design { - return Err(IoError::Invalid("this file is a SolidCraft design, not a drawing: open it as a design".into())); - } - let text = std::str::from_utf8(bytes).map_err(|_| IoError::Invalid("drawing file is not UTF-8 JSON".into()))?; - Ok(Drawing::from_json(text)?) -} - -/// Read a drawing from disk (or the browser's files), a container through one seekable handle. -pub fn read_drawing_file(path: &str) -> Result { - let mut source = super::open_regular_file(path)?; - if super::is_container_source(&mut source)? { - return read_container(source); - } - let mut bytes = Vec::new(); - source.take(MAX_DRAWING_BYTES as u64 + 1).read_to_end(&mut bytes).map_err(invalid)?; - read_drawing(&bytes) -} - -fn read_container(source: R) -> Result { - let mut reader = PackageReader::new(source)?; - if container_kind(&mut reader)? == FileKind::Design { - return Err(IoError::Invalid("this file is a SolidCraft design, not a drawing: open it as a design".into())); - } - if reader.has_part("document.json") { - return Err(invalid("a drawing container also holds a design's document.json")); - } - let bytes = reader.limited_part(DRAWING_PART, MAX_DRAWING_BYTES)?; - let text = std::str::from_utf8(&bytes).map_err(invalid)?; - Ok(Drawing::from_json(text)?) +/// Read the container's drawings, in their order. +pub(super) fn read(reader: &mut PackageReader) -> Result>> { + let names: Vec = reader.names()?.into_iter().filter(|n| n.starts_with(FOLDER)).collect(); + drawing::check_count(names.len()).map_err(invalid)?; + let mut drawings = Vec::with_capacity(names.len()); + for name in names { + let id = name.strip_prefix(FOLDER).and_then(|n| n.strip_suffix(".json")).and_then(ids::decode); + let id = id.ok_or_else(|| invalid(format!("`{name}` is not a drawing's entry")))?; + let bytes = reader.limited_part(&name, MAX_DRAWING_BYTES)?; + let d = Drawing::from_json(std::str::from_utf8(&bytes).map_err(invalid)?).map_err(|e| invalid(format!("`{name}`: {e}")))?; + if d.id != id { + return Err(invalid(format!("`{name}` holds the drawing {}", ids::encode(d.id)))); + } + drawings.push(d); + } + drawing::in_design(drawings).map_err(invalid) } #[cfg(test)] diff --git a/crates/io/src/design/drawing_tests.rs b/crates/io/src/design/drawing_tests.rs index 9562bb65f9b..a5d4a643f3f 100644 --- a/crates/io/src/design/drawing_tests.rs +++ b/crates/io/src/design/drawing_tests.rs @@ -1,24 +1,28 @@ -use std::collections::BTreeMap; -use std::io::Write; +use std::collections::{BTreeMap, BTreeSet}; +use std::io::{Cursor, Write}; -use solidcraft_doc::Document; -use solidcraft_doc::drawing::Source; +use serde_json::{Value, json}; +use solidcraft_doc::drawing::{MAX_DRAWINGS, Source}; +use solidcraft_doc::format::DRAWING; use solidcraft_doc::ids::IdSource; use solidcraft_geom::drawing_sheet::{self, DrawingBorderProfile, Orientation, PaperSize}; use super::*; -use crate::{is_drawing_path, read_design, write_design, write_design_container}; +use crate::{read_design, write_design, write_design_container}; -/// A drawing of two designs on one A3 sheet. -fn drawing() -> Drawing { +/// A design with two drawings of it, each on one A3 sheet, in their order. +fn plate() -> Document { let mut ids = IdSource::seeded(3890); - let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape); - let mut d = Drawing::new("Plate assembly", "en-GB", "Assembly", a3, Some(DrawingBorderProfile::iso()), &mut ids).unwrap(); - for path in ["plate.solidcraft", "../parts/bolt.solidcraft"] { + let mut doc = Document::new("Plate"); + for name in ["Assembly", "Details"] { + let a3 = drawing_sheet::Sheet::standard(PaperSize::A3, Orientation::Landscape); + let taken: BTreeSet = doc.drawings.iter().map(|d| d.id).collect(); + let mut d = Drawing::new(name, "en-GB", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &taken, &mut ids).unwrap(); let id = d.allocate_id(&mut ids).unwrap(); - d.sources.push(Source { id, path: path.into() }); + d.sources.push(Source { id }); + doc.drawings.push(Arc::new(d)); } - d + doc } /// A container's parts by name. @@ -34,122 +38,105 @@ fn parts(bytes: &[u8]) -> BTreeMap> { .collect() } -/// A container written part by part, as a hostile or older tool might. -fn container(parts: &[(&str, &[u8])]) -> Vec { - let mut writer = PackageWriter::new(); +/// A container of these parts, as a hostile or older tool might write it. +fn container(parts: &BTreeMap>) -> Vec { + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); for (name, bytes) in parts { - writer.part(name, bytes, true).unwrap(); + zip.start_file(name.as_str(), zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(bytes).unwrap(); } - writer.finish().unwrap() + zip.finish().unwrap().into_inner() } -fn error(result: Result) -> String { - result.err().map(|e| e.to_string()).unwrap_or_else(|| panic!("accepted")) +/// The entry of the drawing with this id. +fn entry(id: u64) -> String { + format!("drawings/{}.json", ids::encode(id)) } -/// A drawing round-trips through both forms, each giving the same bytes every save; the -/// container holds `container.json` and `drawing.json`, and no `document.json`. +/// A design's drawings round-trip through both forms byte for byte. The container keeps each in its +/// own entry, holding the drawing's own text, and its `document.json` and `container.json` are the +/// same bytes with drawings or without: a drawing edit never makes the model cache, keyed to +/// `document.json`, stale. #[test] -fn a_drawing_round_trips_through_both_forms_byte_for_byte() { - let d = drawing(); - let bytes = write_drawing_container(&d).unwrap(); - assert_eq!(read_drawing(&bytes).unwrap(), d); - assert_eq!(write_drawing_container(&read_drawing(&bytes).unwrap()).unwrap(), bytes, "save, open, save: the same bytes"); +fn a_designs_drawings_round_trip_through_both_forms_byte_for_byte() { + let doc = plate(); + let bytes = write_design_container(&doc).unwrap(); + let read = read_design(&bytes).unwrap(); + assert_eq!(read.drawings, doc.drawings); + assert_eq!(write_design_container(&read).unwrap(), bytes, "save, open, save: the same bytes"); let inside = parts(&bytes); - assert_eq!(inside.keys().map(String::as_str).collect::>(), ["container.json", "drawing.json"]); - assert_eq!(inside["container.json"], br#"{"content":"drawing","format":"solidcraft-container/1"}"#); - let json = d.to_json().unwrap(); - assert_eq!(inside["drawing.json"], json.as_bytes(), "the container holds the plain form's text"); - let again = read_drawing(json.as_bytes()).unwrap(); - assert_eq!((again.to_json().unwrap(), &again), (json, &d)); -} - -/// Each file is the kind it says: a design container's `container.json` has no `content`, a -/// drawing's says `drawing`, and plain JSON is a drawing when its format is one. -#[test] -fn file_kind_tells_designs_and_drawings_apart() { - let doc = Document::new("Plate"); - let design = write_design_container(&doc).unwrap(); - assert_eq!(parts(&design)["container.json"], br#"{"format":"solidcraft-container/1"}"#, "a design's container is as it was"); - let d = drawing(); - let cases = [ - (design, FileKind::Design), - (write_design(&doc), FileKind::Design), - (write_drawing_container(&d).unwrap(), FileKind::Drawing), - (d.to_json().unwrap().into_bytes(), FileKind::Drawing), - (b"{\"format\": \"solidcraft-drawing/1\"}".to_vec(), FileKind::Drawing), - (b"{\"format\": \"solidcraft/1\"}".to_vec(), FileKind::Design), - (b"not json".to_vec(), FileKind::Design), - ]; - for (bytes, kind) in cases { - assert_eq!(file_kind(&bytes).unwrap(), kind, "{}", String::from_utf8_lossy(&bytes[..bytes.len().min(40)])); + let entries: Vec<_> = inside.keys().filter(|n| n.starts_with("drawings/")).cloned().collect(); + assert_eq!(entries, doc.drawings.iter().map(|d| entry(d.id)).collect::>().into_iter().collect::>()); + for d in &doc.drawings { + assert_eq!(inside[&entry(d.id)], d.to_json().unwrap().as_bytes()); } -} - -/// Neither reader takes the other's file, and each says what the file is. -#[test] -fn a_design_is_never_read_as_a_drawing_nor_a_drawing_as_a_design() { - let d = drawing(); - for bytes in [write_drawing_container(&d).unwrap(), d.to_json().unwrap().into_bytes()] { - assert!(error(read_design(&bytes)).contains("is a SolidCraft drawing, not a design")); - } - let doc = Document::new("Plate"); - for bytes in [write_design_container(&doc).unwrap(), write_design(&doc)] { - assert!(error(read_drawing(&bytes)).contains("is a SolidCraft design, not a drawing")); + let without = parts(&write_design_container(&Document { drawings: Vec::new(), ..doc.clone() }).unwrap()); + for part in ["document.json", "container.json"] { + assert_eq!(inside[part], without[part], "{part} is the same with drawings or without"); } + let json = write_design(&doc); + let read = read_design(&json).unwrap(); + assert_eq!(read.drawings, doc.drawings); + assert_eq!(write_design(&read), json, "the plain form too"); } -/// What a drawing container refuses: content this build doesn't know, a design's document beside -/// the drawing, a missing drawing, an unknown container version, and a damaged drawing. +/// What a container refuses in its drawings, each time the whole design: an entry under +/// `drawings/` that isn't a drawing's, one whose record has another id, a damaged drawing, one a +/// newer build saved, drawings inline in `document.json` beside the entries, and more entries than +/// a design may hold, counted before any is read. #[test] -fn a_drawing_container_refuses_what_it_cant_take() { - let text = drawing().to_json().unwrap(); - let drawing_json = |content: &str| format!(r#"{{"content":{content},"format":"solidcraft-container/1"}}"#); - let cases: [(Vec, &str); 6] = [ - (container(&[("container.json", drawing_json("\"sketch\"").as_bytes()), ("drawing.json", text.as_bytes())]), "container content \"sketch\""), - (container(&[("container.json", drawing_json("7").as_bytes()), ("drawing.json", text.as_bytes())]), "container content 7"), - ( - container(&[ - ("container.json", drawing_json("\"drawing\"").as_bytes()), - ("drawing.json", text.as_bytes()), - ("document.json", &b"{}"[..]), - ]), - "also holds a design's document.json", - ), - (container(&[("container.json", drawing_json("\"drawing\"").as_bytes())]), "required part `drawing.json`"), - ( - container(&[("container.json", &br#"{"content":"drawing","format":"solidcraft-container/9"}"#[..]), ("drawing.json", text.as_bytes())]), - "version", - ), - ( - container(&[("container.json", drawing_json("\"drawing\"").as_bytes()), ("drawing.json", text.replace("en-GB", "e").as_bytes())]), - "damaged drawing", - ), - ]; - for (bytes, says) in cases { - let e = error(read_drawing(&bytes)); - assert!(e.contains(says), "{says}: {e}"); +fn a_container_refuses_drawing_entries_it_cant_take() { + let doc = plate(); + let good = parts(&write_design_container(&doc).unwrap()); + let [first, second] = [0, 1].map(|i| doc.drawings[i].id); + let text = |i: usize| String::from_utf8(good[&entry(doc.drawings[i].id)].clone()).unwrap(); + let refusal = |edit: &dyn Fn(&mut BTreeMap>)| { + let mut parts = good.clone(); + edit(&mut parts); + read_design(&container(&parts)).map_or_else(|e| e.to_string(), |d| format!("read {}", d.drawings.len())) + }; + assert_eq!(refusal(&|_| {}), "read 2"); + for name in ["drawings/0000000000000.json", "drawings/ABCDEFGHJKMNP.json", "drawings/x/0000000000001.json", "drawings/0000000000001.svg"] { + let why = refusal(&|p| { + p.insert(name.into(), b"{}".to_vec()); + }); + assert_eq!(why, format!("design container: `{name}` is not a drawing's entry")); } - assert!(error(read_design(&container(&[("container.json", drawing_json("\"sketch\"").as_bytes())]))).contains("container content")); + let moved = refusal(&|p| { + let bytes = p.remove(&entry(first)).unwrap(); + p.insert(entry(7), bytes); + }); + assert_eq!(moved, format!("design container: `{}` holds the drawing {}", entry(7), ids::encode(first))); + let damaged = refusal(&|p| { + p.insert(entry(second), text(1).replace("en-GB", "e").into_bytes()); + }); + assert!(damaged.starts_with(&format!("design container: `{}`: damaged drawing: the language", entry(second))), "{damaged}"); + let newer = DRAWING.format_string(DRAWING.current() + 1); + let why = refusal(&|p| { + p.insert(entry(second), text(1).replace(&DRAWING.format_string(DRAWING.current()), &newer).into_bytes()); + }); + assert!(why.contains("this drawing was saved by a newer SolidCraft"), "{why}"); + let inline = refusal(&|p| { + let mut metadata: Value = serde_json::from_slice(&p["document.json"]).unwrap(); + metadata["drawings"] = json!([serde_json::from_str::(&text(0)).unwrap()]); + p.insert("document.json".into(), serde_json::to_vec(&metadata).unwrap()); + }); + assert_eq!(inline, "design container: ambiguous drawings in document.json and in their own entries"); + let over = refusal(&|p| { + for id in 1..=MAX_DRAWINGS as u64 { + p.insert(entry(id), Vec::new()); + } + }); + assert_eq!(over, format!("design container: a design holds at most {MAX_DRAWINGS} drawings")); } -/// Drawing files: the extension, and reading one from disk in either form. -#[cfg(not(target_arch = "wasm32"))] +/// A design whose drawings break the rules isn't saved: two with one id would share one entry, and +/// one of them would be lost. #[test] -fn drawing_files_open_from_disk_in_either_form() { - // The browsers' file pickers take only ASCII letters, digits, `+` and `.`, up to 16 long. - assert!(crate::DRAWING_EXT.len() < 16 && crate::DRAWING_EXT.bytes().all(|b| b.is_ascii_alphanumeric()), "{}", crate::DRAWING_EXT); - for (path, drawing) in [("a.scdwg", true), ("A.SCDWG", true), ("a.solidcraft", false), ("scdwg", false), ("a.dwg", false)] { - assert_eq!(is_drawing_path(path), drawing, "{path}"); - } - let d = drawing(); - let dir = std::env::temp_dir().join(format!("solidcraft-drawing-files-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - for (name, bytes) in [("container.scdwg", write_drawing_container(&d).unwrap()), ("plain.scdwg", d.to_json().unwrap().into_bytes())] { - let path = dir.join(name); - std::fs::File::create(&path).unwrap().write_all(&bytes).unwrap(); - assert_eq!(read_drawing_file(path.to_str().unwrap()).unwrap(), d, "{name}"); - } - assert!(error(read_drawing_file(dir.to_str().unwrap())).contains("not a regular file")); - std::fs::remove_dir_all(&dir).unwrap(); +fn a_design_with_two_drawings_of_one_id_is_not_saved() { + let mut doc = plate(); + let first = doc.drawings[0].clone(); + doc.drawings[1] = Arc::new(Drawing { name: "Details".into(), ..(*first).clone() }); + let why = write_design_container(&doc).unwrap_err().to_string(); + assert_eq!(why, format!("two drawings have the id {}", ids::encode(first.id))); } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index bd0adaf02d0..a1538fd6fb4 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -12,10 +12,9 @@ mod design_metadata; mod dxf; mod dxf_out; pub use design::{ - DesignCompression, DesignContainerReader, DesignPreview, FileKind, THUMBNAIL_SIZE, file_kind, is_design_container, read_design_file, - read_design_geometry, read_design_preview, read_design_thumbnail, read_design_thumbnail_file, read_drawing, read_drawing_file, - write_design_container, write_design_container_with_cache, write_design_container_with_compression, write_design_container_with_preview, - write_design_container_with_thumbnail, write_drawing_container, + DesignCompression, DesignContainerReader, DesignPreview, THUMBNAIL_SIZE, is_design_container, read_design_file, read_design_geometry, + read_design_preview, read_design_thumbnail, read_design_thumbnail_file, write_design_container, write_design_container_with_cache, + write_design_container_with_compression, write_design_container_with_preview, write_design_container_with_thumbnail, }; mod legacy_dir; #[cfg(test)] @@ -61,14 +60,6 @@ pub fn is_design_path(path: &str) -> bool { .and_then(|e| e.to_str()) .is_some_and(|e| DESIGN_EXTS.iter().chain(["json"].iter()).any(|x| e.eq_ignore_ascii_case(x))) } -/// Drawing file extension: a drawing is a file of its own beside the designs it draws. Short and -/// plain, as the browsers' file pickers take only ASCII letters, digits, `+` and `.`, up to 16 long. -pub const DRAWING_EXT: &str = "scdwg"; - -/// Is this a drawing file name (`.scdwg`, any case)? -pub fn is_drawing_path(path: &str) -> bool { - std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case(DRAWING_EXT)) -} /// Largest design file we read. pub const MAX_DESIGN_BYTES: usize = 256 << 20; @@ -586,11 +577,7 @@ pub fn read_design(bytes: &[u8]) -> Result { return design::read(bytes); } let s = std::str::from_utf8(bytes).map_err(|_| IoError::Invalid("design file is not UTF-8 JSON".into()))?; - // Only a file that isn't a design pays for asking whether it is a drawing. - Document::from_json(s).map_err(|e| match file_kind(bytes) { - Ok(FileKind::Drawing) => IoError::Invalid("this file is a SolidCraft drawing, not a design: open it as a drawing".into()), - _ => e.into(), - }) + Ok(Document::from_json(s)?) } /// Design file bytes. diff --git a/crates/io/src/mutate.rs b/crates/io/src/mutate.rs index 942446d7b35..48efecff52a 100644 --- a/crates/io/src/mutate.rs +++ b/crates/io/src/mutate.rs @@ -525,29 +525,30 @@ outer survives("design JSON", &mutations(&json, true, 0xde6), usize::MAX, |b| crate::read_design(b).ok().map(|d| d.features.len())); } - /// A drawing, as a container and as plain JSON: every mutation gives an error or a drawing, - /// never a panic, and `file_kind` always answers. + /// A design with two drawings, as a container and as plain JSON: every mutation gives an error + /// or a design, never a panic, and never more drawings than a design may hold. #[test] - fn drawings_survive_mutation() { + fn designs_with_drawings_survive_mutation() { + use solidcraft_doc::drawing::{Drawing, MAX_DRAWINGS, Source}; use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet}; let mut ids = solidcraft_doc::ids::IdSource::seeded(0xd4a); - let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); - let mut drawing = solidcraft_doc::drawing::Drawing::new("Fuzz", "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &mut ids).unwrap(); - let id = drawing.allocate_id(&mut ids).unwrap(); - drawing.sources.push(solidcraft_doc::drawing::Source { id, path: "plate.solidcraft".into() }); - let container = crate::write_drawing_container(&drawing).unwrap(); - assert!(crate::read_drawing(&container).is_ok()); - survives("drawing container", &mutations(&container, false, 0xd4b), usize::MAX, |b| { - let _ = crate::file_kind(b); - let _ = crate::read_design(b); - crate::read_drawing(b).ok().map(|d| d.sheets.len()) - }); - let json = drawing.to_json().unwrap().into_bytes(); - assert!(crate::read_drawing(&json).is_ok()); - survives("drawing JSON", &mutations(&json, true, 0xd4c), usize::MAX, |b| { - let _ = crate::file_kind(b); - crate::read_drawing(b).ok().map(|d| d.sheets.len()) + let mut doc = solidcraft_doc::Document::new("Fuzz"); + for name in ["Assembly", "Details"] { + let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); + let taken = doc.drawings.iter().map(|d| d.id).collect(); + let mut drawing = Drawing::new(name, "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &taken, &mut ids).unwrap(); + let id = drawing.allocate_id(&mut ids).unwrap(); + drawing.sources.push(Source { id }); + doc.drawings.push(drawing.into()); + } + let container = crate::write_design_container(&doc).unwrap(); + assert_eq!(crate::read_design(&container).unwrap().drawings, doc.drawings); + survives("design container with drawings", &mutations(&container, false, 0xd4b), MAX_DRAWINGS, |b| { + crate::read_design(b).ok().map(|d| d.drawings.len()) }); + let json = crate::write_design(&doc); + assert_eq!(crate::read_design(&json).unwrap().drawings, doc.drawings); + survives("design JSON with drawings", &mutations(&json, true, 0xd4c), MAX_DRAWINGS, |b| crate::read_design(b).ok().map(|d| d.drawings.len())); } /// A paper scene's JSON, mutated, read, prepared and written as SVG: an error or a document, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4f9e70be790..fbf44448445 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -20,6 +20,7 @@ pub mod texture_input; pub mod texture_interpolation; pub mod texture_lod; pub mod texture_sampling; +mod visual_style; pub use analysis::{AnalysisColors, AnalysisMode, SceneAnalysis}; pub use backend::{ @@ -33,3 +34,4 @@ pub use gif::gif; pub use product::{FaceAppearance, ProductMesh, ProductScene}; pub use raster::{Canvas, render, render_png, render_transparent}; pub use scene::{MIN_ALPHA, Rgb, SECTION_CAP, SEE_THROUGH, Scene, SceneLine, SceneMesh, png}; +pub use visual_style::VisualStyle; diff --git a/crates/render/src/visual_style.rs b/crates/render/src/visual_style.rs new file mode 100644 index 00000000000..eced8480ebb --- /dev/null +++ b/crates/render/src/visual_style.rs @@ -0,0 +1,59 @@ +//! How a view draws the model: its lines, its shading, or both. One list for drawing views +//! (W07, W17b) and the viewport's styles (#5219, #5307) to map to. + +use serde::{Deserialize, Serialize}; + +/// A view's visual style. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum VisualStyle { + /// The visible lines only. + #[default] + Visible, + /// The visible lines and the hidden ones. + VisibleHidden, + /// The shaded model with no lines. + Shaded, + /// The shaded model under its visible lines. + ShadedVisible, + /// The shaded model under its visible and hidden lines. + ShadedVisibleHidden, +} + +impl VisualStyle { + pub const ALL: [VisualStyle; 5] = + [VisualStyle::Visible, VisualStyle::VisibleHidden, VisualStyle::Shaded, VisualStyle::ShadedVisible, VisualStyle::ShadedVisibleHidden]; + + /// Whether the model is drawn as a picture. + pub fn is_shaded(self) -> bool { + matches!(self, VisualStyle::Shaded | VisualStyle::ShadedVisible | VisualStyle::ShadedVisibleHidden) + } + + /// Whether hidden lines are drawn. + pub fn draws_hidden(self) -> bool { + matches!(self, VisualStyle::VisibleHidden | VisualStyle::ShadedVisibleHidden) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The five styles, by their snake-case names, and what each draws. + #[test] + fn each_style_reads_by_its_name_and_says_what_it_draws() { + let names = ["visible", "visible_hidden", "shaded", "shaded_visible", "shaded_visible_hidden"]; + for (style, name) in VisualStyle::ALL.into_iter().zip(names) { + assert_eq!(serde_json::to_value(style).unwrap(), serde_json::json!(name)); + assert_eq!(serde_json::from_value::(serde_json::json!(name)).unwrap(), style); + } + let shaded: Vec = VisualStyle::ALL.iter().map(|s| s.is_shaded()).collect(); + let hidden: Vec = VisualStyle::ALL.iter().map(|s| s.draws_hidden()).collect(); + assert_eq!(shaded, [false, false, true, true, true]); + assert_eq!(hidden, [false, true, false, false, true]); + assert_eq!(VisualStyle::default(), VisualStyle::Visible); + for not_a_style in ["Shaded", "hidden", "", "visible-hidden"] { + assert!(serde_json::from_value::(serde_json::json!(not_a_style)).is_err(), "{not_a_style}"); + } + } +} diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index e73f401faea..dc434a299e4 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -1270,7 +1270,8 @@ fn end_turn(app: &mut SolveApp) { } /// Merge the undo steps made since `start_doc` (at depth `start_undo`) into one, labelled `label`; -/// how many steps it took in (0: none were made, or the history no longer reaches that far). +/// how many steps it took in (0: none were made, the history no longer reaches that far, or they +/// changed several parts of the design, whose steps are each undone in their own part). fn merge_undo( undo: &mut Vec, start_doc: &Arc, @@ -1282,6 +1283,10 @@ fn merge_undo( let Some(first) = (0..undo.len().min(start_undo + 1)).rev().find(|&i| undo.get(i).is_some_and(|s| Arc::ptr_eq(&s.doc, start_doc))) else { return 0; }; + let part = undo.get(first).map(|s| s.part); + if undo.iter().skip(first).any(|s| Some(s.part) != part) { + return 0; + } let steps = undo.len() - first; undo.truncate(first + 1); if let Some(s) = undo.get_mut(first) { diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 04c215735b5..d2db1ffcc50 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -175,6 +175,7 @@ fn merging_finds_the_turns_start_when_the_history_was_trimmed() { doc: d.clone(), active_sketch: None, pending_moves: Default::default(), + part: None, }; let docs: Vec<_> = (0..6).map(doc).collect(); // The turn began at depth 3 with docs[3]; the history then lost its oldest step. @@ -186,6 +187,11 @@ fn merging_finds_the_turns_start_when_the_history_was_trimmed() { let mut undo: Vec<_> = docs[1..6].iter().map(snap).collect(); assert_eq!(merge_undo(&mut undo, &doc(9), 3, "Agent"), 0); assert_eq!(undo.len(), 5); + // A drawing's step among the model's: each part keeps its own steps. + let mut undo: Vec<_> = docs[1..6].iter().map(snap).collect(); + undo[3].part = Some(7); + assert_eq!(merge_undo(&mut undo, &docs[3], 3, "Agent"), 0); + assert_eq!(undo.len(), 5); } /// People who don't want AI never see it: with "Show AI features" off there is no button, the diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 058815d7fa7..456334c331c 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -33,8 +33,8 @@ //! - `ui.confirm {accept?}`: the Delete confirmation (without `accept`: what it lists) //! - `ui.shortcut {command, key?, replace?}`: a command's key, or bind one ("" clears) //! - `ui.help {item?: about|shortcuts|report}`: the Help menu; returns the version and diagnostics -//! - `ui.prefs {...}`: the preferences (default_units, nav, zoom_reverse, orbit_around, msaa, -//! length_decimals, angle_decimals); returns them all +//! - `ui.prefs {...}`: the preferences (default_units, default_projection, nav, zoom_reverse, +//! orbit_around, msaa, length_decimals, angle_decimals); returns them all //! - `ui.capture {action?: capture|revert|cancel}`: the Capture Position question //! - `ui.agent_cursor {show?, speed?: 1–5 (times) | "instant", follow_camera?}`: the agent cursor //! (#35); while it is shown, `engine.execute` first glides to the command's button and picks diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ca2ea57207c..1ad14b70000 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -823,6 +823,10 @@ impl SolveApp { // `file.new` starts from millimetres. Units of new designs still apply (#1205). prefs::apply_new_design(self); } + if id == "drawing.create" { + // A new drawing is third angle. Projection of new drawings still applies. + prefs::apply_new_drawing(self); + } if matches!(id, "file.new" | "doc.open" | "doc.recover") { render_workspace::reset_document(self); dim_view::cancel(); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index c68d20460a9..8658f2eb390 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize}; use serde_json::json; pub use solidcraft_engine::doc::display_units::{format_length, length_number, length_precision, unit_scale}; use solidcraft_engine::geom::Vec3; +use solidcraft_engine::geom::cell::Projection; /// The key the apps keep the preferences under in eframe's storage. pub const STORAGE_KEY: &str = "solidcraft.prefs"; @@ -425,6 +426,9 @@ macro_rules! preference_settings { preference_settings! { /// Units of new designs. default_units: String = "mm".into(), PAGE_DESIGN; + /// First or third angle for new drawings (third when not set, or set to one this version + /// doesn't know). + default_projection: Projection = Projection::Third, PAGE_DESIGN; /// Mouse mapping: `fusion`, `solidworks` or `inventor`. nav: String = "fusion".into(), PAGE_NAVIGATION; /// Opt in to rotation through both poles with roll, without the Shift axis-snap spring. @@ -938,6 +942,16 @@ pub fn apply_new_design(app: &mut SolveApp) { apply_new_design_units(app, &app.preferences.default_units.clone()); } +/// A new drawing takes the preferred projection, as a new design takes the preferred units: not +/// an undo step. Caller: `drawing.create` run from the app. +pub fn apply_new_drawing(app: &mut SolveApp) { + let projection = app.preferences.default_projection; + let differs = app.session.drawing("drawing.create").is_ok_and(|d| d.projection != projection); + if differs && app.session.execute("drawing.set", &json!({ "projection": projection })).is_ok() { + app.session.undo.pop(); + } +} + /// Explicit units for a new-design tile; the user's default preference stays unchanged. pub(crate) fn apply_new_design_units(app: &mut SolveApp, units: &str) { if app.session.doc.features.is_empty() && app.session.doc.units != units { @@ -1569,6 +1583,7 @@ mod tests { use super::*; let fields = [ ("default_units", json!("ft"), PAGE_DESIGN), + ("default_projection", json!("first"), PAGE_DESIGN), ("length_decimals", json!(5), PAGE_DESIGN), ("angle_decimals", json!(4), PAGE_DESIGN), ("theme", json!("light"), PAGE_INTERFACE), @@ -2168,6 +2183,28 @@ mod tests { assert_eq!(format_length(25.4, "in", 3), "1.000 in"); } + /// Projection of new drawings: third angle unless chosen, refused when it is neither when set, + /// read as third when saved so; a new drawing takes it without an undo step of its own. + #[test] + fn new_drawings_take_the_preferred_projection() { + use solidcraft_engine::geom::cell::Projection; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + assert_eq!(app.preferences.default_projection, Projection::Third); + assert!(set(&mut app, &json!({"default_projection": "second"})).is_err()); + let saved = json!({"default_projection": "fourth", "default_units": "in"}); + assert_eq!((lenient(&saved).default_projection, lenient(&saved).default_units.as_str()), (Projection::Third, "in")); + let drawn = |projection: &str| { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + set(&mut app, &json!({"default_projection": projection})).unwrap(); + app.run("solid.box", json!({"length": 40, "width": 30, "height": 10})).unwrap(); + app.run("drawing.create", json!({})).unwrap(); + (app.session.drawing("test").ok().map(|d| d.projection), app.session.undo.len()) + }; + let (first, third) = (drawn("first"), drawn("third")); + assert_eq!((first.0, third.0), (Some(Projection::First), Some(Projection::Third))); + assert_eq!(first.1, third.1, "the projection is no undo step of its own"); + } + /// The dialog: changes apply at once, Cancel puts back what was there when it opened, Apply /// keeps them, Restore Defaults resets one page, and the shortcuts menus open its page. #[test] diff --git a/crates/ui-egui/src/prefs/design.rs b/crates/ui-egui/src/prefs/design.rs index 72477178cee..764712f7623 100644 --- a/crates/ui-egui/src/prefs/design.rs +++ b/crates/ui-egui/src/prefs/design.rs @@ -30,6 +30,19 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { }); }); }); + ui_kit::settings_section(ui, "drawings", app.tr("prefs.drawings"), |ui| { + ui_kit::settings_form(ui, t.space_24 * 7.0 + t.space_2, |ui| { + ui_kit::row(ui, app.tr("ui.projection_of_new_drawings"), |ui| { + let projections = [Projection::First, Projection::Third]; + let labels = [app.tr("ui.first_angle"), app.tr("ui.third_angle")]; + let mut selected = projections.iter().position(|p| *p == app.preferences.default_projection).unwrap_or(1); + ui_kit::segmented(ui, &mut selected, &labels, ui_kit::Segments { intrinsic: true, ..Default::default() }); + if let Some(projection) = projections.get(selected) { + app.preferences.default_projection = *projection; + } + }); + }); + }); ui_kit::settings_section(ui, "orientation", app.tr("prefs.orientation"), |ui| { ui.horizontal_wrapped(|ui| { for (id, label, y_up) in [("z", "Z up", false), ("y", "Y up", true)] { diff --git a/docs/mcp.md b/docs/mcp.md index 5741e169542..6ffd967bb4d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -200,8 +200,8 @@ Errors: an unknown tool or arguments that don't match the tool's schema are JSON result with `isError: true` and the engine's message, which the model can read and correct. `batch` rollback goes back to an engine checkpoint (`edit.checkpoint`) taken before the first -step: the design, the active sketch and the undo history are restored exactly as they were, -however long the history is. Batches that call `file.new` or `doc.open` get the design back, +step: the design (its drawings too), the active sketch, the drawing open and the undo history +are restored exactly as they were, however long the history is. Batches that call `file.new` or `doc.open` get the design back, not its file path. (An older app without checkpoints falls back to undoing as many steps as the batch added to the undo history.)