diff --git a/assets/locales/pending/drawing-update.json b/assets/locales/pending/drawing-update.json new file mode 100644 index 000000000..368446b39 --- /dev/null +++ b/assets/locales/pending/drawing-update.json @@ -0,0 +1,26 @@ +{ + "en": { + "cmd.drawing_update": "Update Drawing" + }, + "ar": { + "cmd.drawing_update": "تحديث اللوحة" + }, + "de": { + "cmd.drawing_update": "Zeichnung aktualisieren" + }, + "he": { + "cmd.drawing_update": "עדכון שרטוט" + }, + "ja": { + "cmd.drawing_update": "図面を更新" + }, + "ko": { + "cmd.drawing_update": "도면 업데이트" + }, + "vi": { + "cmd.drawing_update": "Cập nhật bản vẽ" + }, + "zh": { + "cmd.drawing_update": "更新图纸" + } +} diff --git a/crates/doc/src/drawing.rs b/crates/doc/src/drawing.rs index c00e430b4..748bac387 100644 --- a/crates/doc/src/drawing.rs +++ b/crates/doc/src/drawing.rs @@ -100,6 +100,17 @@ pub const MIN_DPI: f64 = 25.0; /// The highest resolution a sheet may ask for. pub const MAX_DPI: f64 = 2400.0; +/// When a drawing's views follow what they draw. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Updates { + /// As it changes. + #[default] + Automatic, + /// When asked (`drawing.update`): until then each view shows its last lines, out of date. + Deferred, +} + /// A drawing: its sheets and the designs they draw. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -126,6 +137,9 @@ pub struct Drawing { /// First or third angle: what every projected view shows, and the title block's symbol. #[serde(default)] pub projection: Projection, + /// When its views follow a changed model. Saved only when deferred. + #[serde(default, skip_serializing_if = "follows_at_once")] + pub updates: Updates, /// The language of the drawing's content, a BCP 47 tag (`en-GB`). pub language: String, /// The font family its text is set in, by name; empty: the built-in font. @@ -328,6 +342,7 @@ impl Drawing { properties: Arc::default(), units: Units::default(), projection: Projection::default(), + updates: Updates::default(), language: language.into(), font: String::new(), sheets: vec![Arc::new(first)], @@ -584,6 +599,11 @@ fn no_properties(properties: &Arc) -> bool { properties.is_empty() } +/// Whether the drawing's views follow the model as it changes, so its file leaves `updates` out. +fn follows_at_once(updates: &Updates) -> bool { + *updates == Updates::Automatic +} + /// Adds `more` to `records`, each where its id puts it: the order every list of records after the /// sheets keeps (the module's rule), whatever order they come in. fn add_by_id(records: &mut Vec>, more: impl IntoIterator>, id: impl Fn(&T) -> u64) { diff --git a/crates/doc/src/drawing/format/pending/deferred-updates.rs b/crates/doc/src/drawing/format/pending/deferred-updates.rs new file mode 100644 index 000000000..6a7fdf801 --- /dev/null +++ b/crates/doc/src/drawing/format/pending/deferred-updates.rs @@ -0,0 +1,3 @@ +//! A drawing can say when its views follow a changed model (`updates`: `deferred`, only on +//! `drawing.update`), saved only when set. An older drawing follows the model as it changes. The last +//! release refuses a drawing with this format's number. diff --git a/crates/engine/src/cmd/drawing.rs b/crates/engine/src/cmd/drawing.rs index e02486bba..9098e14ae 100644 --- a/crates/engine/src/cmd/drawing.rs +++ b/crates/engine/src/cmd/drawing.rs @@ -15,7 +15,7 @@ use solidcraft_doc::drawing::balloon::balloons_by_row; use solidcraft_doc::drawing::fields::{Component, Values}; use solidcraft_doc::drawing::table::Kind; use solidcraft_doc::drawing::view::{MAX_VIEW_DEPTH, View, ViewKind}; -use solidcraft_doc::drawing::{self, Drawing, Source, Units, template}; +use solidcraft_doc::drawing::{self, Drawing, Source, Units, Updates, template}; use solidcraft_doc::drawing_view::ViewDirection; use solidcraft_doc::{Document, ids}; use solidcraft_geom::cell::{Content, Projection}; @@ -93,13 +93,13 @@ pub static COMMANDS: &[CommandSpec] = &[ "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, font, font_note: why its text is set in the built-in font instead (the font isn't on this computer, or can't be set on paper), or null, properties, sources: [{id}], sheets: [{id, name, size_mm, orientation, title_block (its definition, or null), title_block_cells: [{name, text, value?}] (each text cell as the sheet shows it: its fields' values, \"-\" for one with none, or the text typed over it with the value it hides as `value`), title_block_overrides, dpi, documents, excluded, views: [{id, kind: base|projected, parent?, side?, label, dimensions: [ids], balloons: [ids]}], base views by id, each followed by those projected from it}], revisions: {rows: [{row, revision, description, designer, checker, date, hidden}], the oldest first (the newest is the drawing's revision), next: the revision a new row gets}}. Read-only.", + "→ {id, name, units, projection, updates: automatic or deferred, language, font, font_note: why its text is set in the built-in font instead (the font isn't on this computer, or can't be set on paper), or null, properties, sources: [{id}], sheets: [{id, name, size_mm, orientation, title_block (its definition, or null), title_block_cells: [{name, text, value?}] (each text cell as the sheet shows it: its fields' values, \"-\" for one with none, or the text typed over it with the value it hides as `value`), title_block_overrides, dpi, documents, excluded, views: [{id, kind: base|projected, parent?, side?, label, dimensions: [ids], balloons: [ids]}], base views by id, each followed by those projected from it}], revisions: {rows: [{row, revision, description, designer, checker, date, hidden}], the oldest first (the newest is the drawing's revision), next: the revision a new row gets}}. 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, font?: the font family its text is set in, by name, never a file (\"\": the built-in font). revision_numbering?: {start: 0 or 1}, the number new revisions count from: rows already there stay as typed. One undo step."), + .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, updates?: automatic, or deferred: its views follow a changed model only on drawing.update, font?: the font family its text is set in, by name, never a file (\"\": the built-in font). revision_numbering?: {start: 0 or 1}, the number new revisions count from: rows already there stay as typed. 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).", ), @@ -131,6 +131,14 @@ fn projection(cmd: &str, p: &Value) -> Result> { } } +/// `updates` as given: when the views follow a changed model. +fn updates(cmd: &str, p: &Value) -> Result> { + match p.get("updates") { + None => Ok(None), + Some(v) => serde_json::from_value(v.clone()).map(Some).map_err(|_| bad(cmd, "`updates` is automatic or deferred")), + } +} + /// `font` as given: a font family's name, never a file (drawings name fonts by family, so they /// travel). fn font<'a>(cmd: &str, p: &'a Value) -> Result> { @@ -409,6 +417,7 @@ fn inspect(s: &mut Session, _p: &Value) -> Result { "name": d.name, "units": d.units, "projection": d.projection, + "updates": d.updates, "language": d.language, "font": d.font, "font_note": solidcraft_sketch::paper_font_note(&solidcraft_sketch::font_dirs(), &d.font), @@ -493,6 +502,9 @@ fn set(s: &mut Session, p: &Value) -> Result { if let Some(projection) = projection(cmd, p)? { d.projection = projection; } + if let Some(updates) = updates(cmd, p)? { + d.updates = updates; + } if let Some(font) = font(cmd, p)? { d.font = font.to_string(); } diff --git a/crates/engine/src/cmd/drawing_export.rs b/crates/engine/src/cmd/drawing_export.rs index 03ae56d8d..099c911ba 100644 --- a/crates/engine/src/cmd/drawing_export.rs +++ b/crates/engine/src/cmd/drawing_export.rs @@ -90,7 +90,7 @@ fn export(s: &mut Session, p: &Value) -> Result { } solidcraft_io::vfs::check(path).map_err(|e| EngineError::Other(e.to_string()))?; } - let built = crate::drawing_scene::build(s, &d, sheet)?; + let built = crate::drawing_scene::as_shown(s, &d, sheet)?; let failed: Vec = built .views .iter() @@ -138,6 +138,7 @@ fn export(s: &mut Session, p: &Value) -> Result { report: ExportReport { widths_snapped: grid.widths_snapped, pieces_merged: grid.pieces_merged, pixels }, views: built.views.into_iter().map(Into::into).collect(), dimensions: super::drawing_scene::dimension_results(built.dimensions), + out_of_date: built.out_of_date.iter().map(|id| ids::encode(*id)).collect(), param_warnings: Vec::new(), }; serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) diff --git a/crates/engine/src/cmd/drawing_scene.rs b/crates/engine/src/cmd/drawing_scene.rs index 09674a1db..b5347d84e 100644 --- a/crates/engine/src/cmd/drawing_scene.rs +++ b/crates/engine/src/cmd/drawing_scene.rs @@ -7,7 +7,8 @@ //! page's picking uses ([`crate::drawing_scene::hit`]). //! //! `drawing.status` (#4894 WE2) says where the drawing open stands: each view as the provider last -//! drew it, and each dimension as the model has it now, in one read. +//! drew it, and each dimension as the model has it now, in one read. `drawing.update` (#4892) lets a +//! deferred drawing draw from the model as it is now. use serde_json::Value; use solidcraft_doc::ids; @@ -15,8 +16,9 @@ use solidcraft_doc::ids; use super::CommandSpec; use crate::drawing_scene::{CMD, DimensionState}; use crate::schema::drawing_scene::{ - DimensionStatusResult, DrawingStatusParams, DrawingStatusResult, HitResult, LineHitResult, SheetHitParams, SheetHitResult, SheetLineParams, - SheetLineResult, SheetPaperScene, SheetSceneDimension, SheetSceneParams, SheetSceneResult, ViewStatusResult, + DimensionStatusResult, DrawingStatusParams, DrawingStatusResult, DrawingUpdateParams, DrawingUpdateResult, HitResult, LineHitResult, + SheetHitParams, SheetHitResult, SheetLineParams, SheetLineResult, SheetPaperScene, SheetSceneDimension, SheetSceneParams, SheetSceneResult, + ViewStatusResult, }; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; @@ -28,6 +30,8 @@ const LINE: &str = "drawing.scene.line"; const LINE_CONTRACT: TypedContract = TypedContract::new(); const STATUS: &str = "drawing.status"; const STATUS_CONTRACT: TypedContract = TypedContract::new(); +const UPDATE: &str = "drawing.update"; +const UPDATE_CONTRACT: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(STATUS, "Drawing Status", crate::checked!("drawing.status", status)) .icon("inspect") @@ -36,7 +40,15 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(STATUS, "Drawing Status .doc_only() .contract(&STATUS_CONTRACT) .output(output_schema_for::) - .params("→ {views: [{view, sheet, status: current|out_of_date|placeholder|failed, reason?}], dimensions: [{dimension, status: ok|overridden|ambiguous|suppressed|lost|unmeasurable, why?}], waiting: how many views are out of date}. current: drawn, from the model and with the settings the view has now. Balloons aren't listed: drawing.balloon.inspect reads each one. Read-only: nothing is drawn, and each body a dimension names is read once for the call."), + .params("→ {views: [{view, sheet, status: current|out_of_date|placeholder|failed, reason?}], dimensions: [{dimension, status: ok|overridden|ambiguous|suppressed|lost|unmeasurable, why?}], waiting: how many views are out of date, held?: true when a deferred drawing's wait for drawing.update}. current: drawn, from the model and with the settings the view has now. Balloons aren't listed: drawing.balloon.inspect reads each one. Read-only: nothing is drawn, and each body a dimension names is read once for the call."), + CommandSpec::new(UPDATE, "Update Drawing", crate::checked!("drawing.update", update)) + .icon("update") + .in_drawing() + .noundo() + .doc_only() + .contract(&UPDATE_CONTRACT) + .output(output_schema_for::) + .params("→ {waiting}: a deferred drawing's views may draw from the model as it is now, until that moves on; waiting: how many are out of date until they are drawn. Nothing is drawn here: the sheet page draws them, as drawing.scene or an export of their sheet does. A drawing that isn't deferred follows the model already."), CommandSpec::new(HIT, "What Is Under a Point", crate::checked!("drawing.scene.hit", hit)) .icon("inspect") .in_drawing() @@ -60,7 +72,7 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(STATUS, "Drawing Status .doc_only() .contract(&CONTRACT) .output(output_schema_for::) - .params("sheet: id or name → {sheet, scene: {size_mm, groups: [{object, kind: drawing_border|sheet_image|view|dimension|title_block, items: [{kind: stroke, path, closed, width_mm} or {kind: fill, region} or {kind: picture, source, rect: {min, max}, opacity}]}]} in paint order: the sheet's drawing border (object: the sheet), then each image on it by id (object and source: the placement), then each view on it by id (object: the view; its hidden lines dashed, under its visible ones), then the dimensions of those views by view and id (object: the dimension; lines and arrowheads, in paper millimetres at any scale, with no text yet), then its title block's lines (object: the sheet), views: [{view, status: drawn|placeholder|failed, reason?, stats?}], objects: [{object, kind, bounds_mm: {min, max}, boundary_mm?}], where the border, each view and each dimension sit on paper, dimensions: [{dimension, view, status: ok|overridden|ambiguous|suppressed|lost|unmeasurable, drawn, why?}]}. A view with nothing to measure, or one that can't be drawn yet, is left out and says why, and so is a dimension that isn't found again or whose view isn't drawn. Read-only; no model is evaluated.")]; + .params("sheet: id or name → {sheet, scene: {size_mm, groups: [{object, kind: drawing_border|sheet_image|view|dimension|title_block, items: [{kind: stroke, path, closed, width_mm} or {kind: fill, region} or {kind: picture, source, rect: {min, max}, opacity}]}]} in paint order: the sheet's drawing border (object: the sheet), then each image on it by id (object and source: the placement), then each view on it by id (object: the view; its hidden lines dashed, under its visible ones), then the dimensions of those views by view and id (object: the dimension; lines and arrowheads, in paper millimetres at any scale, with no text yet), then its title block's lines (object: the sheet), views: [{view, status: drawn|placeholder|failed, reason?, stats?}], objects: [{object, kind, bounds_mm: {min, max}, boundary_mm?}], where the border, each view and each dimension sit on paper, dimensions: [{dimension, view, status: ok|overridden|ambiguous|suppressed|lost|unmeasurable, drawn, why?}]}. A view with nothing to measure, or one that can't be drawn yet, is left out and says why, and so is a dimension that isn't found again or whose view isn't drawn. Read-only; no model is evaluated. A deferred drawing draws only what drawing.update allows; out_of_date lists the views and dimensions it shows as they last were.")]; fn status(s: &mut Session, p: &Value) -> Result { let _: DrawingStatusParams = crate::schema::read(STATUS, p)?; @@ -80,10 +92,19 @@ fn status(s: &mut Session, p: &Value) -> Result { }) .collect(); let waiting = views.iter().filter(|v| v.status == "out_of_date").count(); - let reply = DrawingStatusResult { views, dimensions, waiting, param_warnings: Vec::new() }; + let held = waiting > 0 && crate::drawing_scene::held(s, &d); + let reply = DrawingStatusResult { views, dimensions, waiting, held, param_warnings: Vec::new() }; serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) } +fn update(s: &mut Session, p: &Value) -> Result { + let _: DrawingUpdateParams = crate::schema::read(UPDATE, p)?; + let d = s.drawing(UPDATE)?.clone(); + crate::drawing_scene::update(s); + let waiting = crate::drawing_scene::standing(s, &d).iter().filter(|v| v.status == "out_of_date").count(); + serde_json::to_value(DrawingUpdateResult { waiting, param_warnings: Vec::new() }).map_err(|e| EngineError::Other(e.to_string())) +} + fn hit(s: &mut Session, p: &Value) -> Result { let request: SheetHitParams = crate::schema::read(HIT, p)?; if !request.band_mm.is_finite() || request.band_mm < 0.0 { @@ -91,7 +112,7 @@ fn hit(s: &mut Session, p: &Value) -> Result { } let d = s.drawing(HIT)?.clone(); let sheet = crate::drawing_scene::sheet_id(&d, &request.sheet, HIT)?; - let built = crate::drawing_scene::build(s, &d, sheet)?; + let built = crate::drawing_scene::as_shown(s, &d, sheet)?; let found = crate::drawing_scene::hit(&built.objects, request.point_mm.0, request.band_mm); let hit = found.map(|h| HitResult { object: ids::encode(h.object), kind: h.kind, on_edge: h.on_edge }); serde_json::to_value(SheetHitResult { hit, param_warnings: Vec::new() }).map_err(|e| EngineError::Other(e.to_string())) @@ -134,11 +155,19 @@ fn scene(s: &mut Session, p: &Value) -> Result { let request: SheetSceneParams = crate::schema::read(CMD, p)?; let d = s.drawing(CMD)?.clone(); let sheet = crate::drawing_scene::sheet_id(&d, &request.sheet, CMD)?; - let built = crate::drawing_scene::build(s, &d, sheet)?; + let built = crate::drawing_scene::as_shown(s, &d, sheet)?; + let out_of_date = built.out_of_date.iter().map(|id| ids::encode(*id)).collect(); let views = built.views.into_iter().map(Into::into).collect(); let objects = built.objects.into_iter().map(Into::into).collect(); let dimensions = dimension_results(built.dimensions); - let reply = - SheetSceneResult { sheet: ids::encode(sheet), scene: SheetPaperScene(built.scene), views, objects, dimensions, param_warnings: Vec::new() }; + let reply = SheetSceneResult { + sheet: ids::encode(sheet), + scene: SheetPaperScene(built.scene), + views, + objects, + dimensions, + out_of_date, + param_warnings: Vec::new(), + }; serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) } diff --git a/crates/engine/src/cmd/drawing_tests.rs b/crates/engine/src/cmd/drawing_tests.rs index 8e0796333..9258dd484 100644 --- a/crates/engine/src/cmd/drawing_tests.rs +++ b/crates/engine/src/cmd/drawing_tests.rs @@ -344,6 +344,30 @@ fn a_drawings_projection_is_first_or_third_angle() { } } +/// A drawing's views follow the model automatically, or only on `drawing.update` when deferred: +/// shown by `drawing.inspect`, changed by `drawing.set` as one undo step, saved with the design only +/// when deferred, and anything else refused. +#[test] +fn a_drawings_updates_are_automatic_or_deferred() { + let folder = Folder::new("drawing-updates"); + let mut s = design(); + assert_eq!(run(&mut s, "drawing.create", json!({}))["updates"], "automatic"); + let saved = serde_json::to_value(&*open_one(&s)).unwrap(); + assert!(saved.get("updates").is_none(), "automatic isn't saved: {saved}"); + let steps = s.undo.len(); + assert_eq!(run(&mut s, "drawing.set", json!({"updates": "deferred"}))["updates"], "deferred"); + 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].updates, drawing::Updates::Deferred); + run(&mut s, "edit.undo", json!({})); + assert_eq!(run(&mut s, "drawing.inspect", json!({}))["updates"], "automatic"); + for bad in [json!("sometimes"), json!("Deferred"), json!(true), json!(null)] { + assert!(refused(&mut s, "drawing.set", json!({"updates": bad})).contains("automatic or deferred"), "{bad}"); + } +} + /// A drawing's font is a family named by `drawing.create` or `drawing.set` (one undo step), saved /// with the design; the built-in font when none is named. A family this computer lacks is named in /// `font_note`, and a font file or anything but text is refused. diff --git a/crates/engine/src/cmd/drawing_ui.rs b/crates/engine/src/cmd/drawing_ui.rs index de7195648..931b82c6c 100644 --- a/crates/engine/src/cmd/drawing_ui.rs +++ b/crates/engine/src/cmd/drawing_ui.rs @@ -27,7 +27,7 @@ pub const PENDING_ICONS: &[(&str, &str)] = &[ ("drawing.parts_list", "drawing_parts_list"), ("drawing.balloon", "drawing_balloon"), ("drawing.revision_table", "drawing_revision_table"), - ("drawing.update", "drawing_update"), + ("drawing.update.planned", "drawing_update"), ("drawing.check", "drawing_check"), ("drawing.revision", "drawing_revision"), ("drawing.print", "drawing_print"), @@ -57,7 +57,7 @@ pub static COMMANDS: &[CommandSpec] = &[ planned!("drawing.parts_list", "Parts List", "3874").at("DRAWING PARTS", "ASSEMBLY").icon("placeholder"), planned!("drawing.balloon", "Balloon", "3874").at("DRAWING PARTS", "ASSEMBLY").icon("placeholder"), planned!("drawing.revision_table", "Revision Table", "4894").at("DRAWING PARTS", "TABLES").icon("placeholder"), - planned!("drawing.update", "Update Drawing", "4892").at("DRAWING REVIEW", "CHANGES").icon("placeholder"), + planned!("drawing.update.planned", "Update Drawing", "4892").at("DRAWING REVIEW", "CHANGES").icon("placeholder"), planned!("drawing.check", "Check Drawing", "4894").at("DRAWING REVIEW", "CHANGES").icon("placeholder"), planned!("drawing.revision", "Add Drawing Revision", "4894").at("DRAWING REVIEW", "REVISION").icon("placeholder"), planned!("drawing.export.planned", "Export Drawing", "4890").at("DRAWING REVIEW", "OUTPUT").icon("export"), diff --git a/crates/engine/src/drawing_scene.rs b/crates/engine/src/drawing_scene.rs index 270d5785c..b7997073b 100644 --- a/crates/engine/src/drawing_scene.rs +++ b/crates/engine/src/drawing_scene.rs @@ -24,6 +24,10 @@ //! drawing closes, all but its views' lines (`drawing_scene_kept.rs`), which the drawing opened //! again starts from. //! +//! A deferred drawing ([`Updates::Deferred`]) draws nothing once the model has moved on from its last +//! `drawing.update`, which isn't saved: its last lines show, listed in `stale`, and every command that reads +//! a sheet ([`as_shown`]) reads those and says so. +//! //! [`hit`] says which of a scene's objects is under a point of the sheet, the one rule for picking //! there: the sheet page's hover and `drawing.scene.hit`. //! @@ -39,7 +43,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use solidcore_record::{Loop2, Region2, Seg2, Vec2}; use solidcraft_doc::drawing::dimension::{self, Dimension}; use solidcraft_doc::drawing::view::{ResolvedView, View}; -use solidcraft_doc::drawing::{Drawing, Sheet}; +use solidcraft_doc::drawing::{Drawing, Sheet, Updates}; use solidcraft_doc::drawing_view::TangentEdges; use solidcraft_doc::{DocError, ModelState, ids}; use solidcraft_geom::cell::Projection; @@ -145,6 +149,8 @@ pub struct SheetScene { pub objects: Vec, /// Each dimension of a view on the sheet, by view and id. pub dimensions: Vec, + /// The views and dimensions a deferred drawing shows as they last were ([`as_shown`]). + pub out_of_date: Vec, } /// One sheet as the provider last drew it ([`extract`]). @@ -235,16 +241,16 @@ pub struct LineHit { /// drawn first, as the page draws them ([`step`]), so the line is one the page shows. A view that /// can't be drawn, or isn't in the scene, has no lines. No model is evaluated. pub fn line_at(s: &mut Session, sheet: u64, point_mm: Vec2, band_mm: f64) -> Result> { + let d = s.drawing(CMD)?.clone(); extract(s, sheet)?; - while step(s) {} + settle(s, &d); let answer = extract(s, sheet)?; let views: Vec = answer.objects.iter().filter(|o| o.kind == ObjectKind::View).copied().collect(); let Some(view) = hit(&views, point_mm, band_mm).map(|h| h.object) else { return Ok(None) }; if !answer.views.iter().any(|v| v.view == view && v.status == Status::Drawn) { return Ok(None); } - let d = s.drawing(CMD)?; - let centre = views_on(d, sheet)?.into_iter().find(|(id, ..)| *id == view).map(|(.., centre)| centre); + let centre = views_on(&d, sheet)?.into_iter().find(|(id, ..)| *id == view).map(|(.., centre)| centre); let drawn = s.drawing_scenes.views.get(&view).map(|e| &e.drawn); let (Some(centre), Some(Drawn { group: Some(group), owners: Some(owners), .. })) = (centre, drawn) else { return Ok(None) }; // The group is centred on the view, as it was drawn. @@ -280,7 +286,42 @@ pub fn build(s: &Session, drawing: &Drawing, sheet: u64) -> Result { let dimensions = draw_dimensions(s, drawing, &wanted, |view| frames.get(&view).copied()); assembly.add_dimensions(dimensions.iter()); let (scene, views, objects, dimensions) = assembly.finish()?; - Ok(SheetScene { scene, views, objects, dimensions }) + Ok(SheetScene { scene, views, objects, dimensions, out_of_date: Vec::new() }) +} + +/// Sheet `sheet` of `d`, the drawing open, as a command reads it: drawn at once ([`build`]), or for a +/// deferred drawing, what its last [`update`] allows, with what that leaves behind listed. +pub fn as_shown(s: &mut Session, d: &Drawing, sheet: u64) -> Result { + if d.updates == Updates::Automatic { + return build(s, d, sheet); + } + extract(s, sheet)?; + settle(s, d); + let shown = extract(s, sheet)?; + let out_of_date = shown.stale.into_iter().chain(shown.stale_dimensions).collect(); + let (scene, objects) = (Arc::unwrap_or_clone(shown.scene), shown.objects.to_vec()); + Ok(SheetScene { scene, views: shown.views, objects, dimensions: shown.dimensions, out_of_date }) +} + +/// Draws what is waiting on the sheet last extracted, as the sheet page would: each view once, then +/// each view's dimensions once, so a script reads what the page shows. +pub(crate) fn settle(s: &mut Session, d: &Drawing) { + for _ in 0..=d.views.len().saturating_mul(2) { + if !step(s) { + break; + } + } +} + +/// Lets the drawing open draw from the model as it is now, until that moves on: then a deferred +/// drawing holds again. [`step`] does the drawing, on whichever sheet is shown. +pub(crate) fn update(s: &mut Session) { + s.drawing_scenes.updated = s.world_state().ok(); +} + +/// `d`, the drawing open, is deferred and the model has moved on from its last [`update`]. +pub(crate) fn held(s: &Session, d: &Drawing) -> bool { + s.world_state().is_ok_and(|state| s.drawing_scenes.holds(d, &state)) } /// A view's lines for a sheet scene, centred on the view, or why it has none. @@ -608,6 +649,8 @@ pub struct Cache { /// The shown set of the world state views were last drawn from, worked out once for it. shown: Option<(Arc, std::result::Result)>, last: Option, + /// The world state a deferred drawing may draw from: its last [`update`]. + updated: Option>, /// Numbers each view drawn and each read of dimensions, so a scene is assembled again only when /// one of its views or dimensions was. serial: u64, @@ -700,6 +743,11 @@ impl Cache { } } + /// `d` is deferred, and `state` isn't the one its last [`update`] took. + fn holds(&self, d: &Drawing, state: &Arc) -> bool { + d.updates == Updates::Deferred && !self.updated.as_ref().is_some_and(|updated| Arc::ptr_eq(updated, state)) + } + /// Whether view `id`, drawing as `view` now, was last drawn so, from `state`. fn fresh(&self, id: u64, state: &Arc, view: &ResolvedView) -> bool { self.views.get(&id).is_some_and(|e| Arc::ptr_eq(&e.state, state) && e.view == *view) @@ -840,8 +888,11 @@ pub fn step(s: &mut Session) -> bool { let (Ok(d), Some(sheet)) = (s.drawing(CMD).cloned(), s.drawing_scenes.sheet) else { return false }; let Ok(on) = views_on(&d, sheet) else { return false }; let Ok(state) = s.world_state() else { return false }; - let units = s.doc.drawing_units(&d).to_string(); keep_what_shows_the_same(s, &on, &state); + if s.drawing_scenes.holds(&d, &state) { + return false; + } + let units = s.doc.drawing_units(&d).to_string(); let waiting: Vec<(u64, ResolvedView)> = on.iter().filter(|(id, view, _)| !s.drawing_scenes.fresh(*id, &state, view)).map(|(id, view, _)| (*id, view.clone())).collect(); let Some((id, view)) = waiting.first().cloned() else { return step_dimensions(s, &d, &on, &state, units) }; diff --git a/crates/engine/src/drawing_scene_tests.rs b/crates/engine/src/drawing_scene_tests.rs index 4448bca3f..88a2833e1 100644 --- a/crates/engine/src/drawing_scene_tests.rs +++ b/crates/engine/src/drawing_scene_tests.rs @@ -548,6 +548,63 @@ fn a_part_made_reference_draws_again() { assert_eq!(extract(&mut s, sheet).unwrap().stale.len(), 2); } +/// A deferred drawing draws nothing until `drawing.update`: then from the model as it is now, until +/// that changes. Reopened, it waits again. While it waits, every command that reads its sheet reads +/// what the page shows and lists what is out of date, and `drawing.status` says it is held. +#[test] +fn a_deferred_drawing_keeps_its_lines_until_it_is_updated() { + let (mut s, sheet, [front, top]) = front_and_top(); + let drawing = json!({"drawing": ids::encode(s.open_drawing.unwrap())}); + run(&mut s, "drawing.set", json!({"updates": "deferred"})); + let checkpoint = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].clone(); + extract(&mut s, sheet).unwrap(); + assert!(!step(&mut s), "nothing is drawn before an update"); + assert_eq!(run(&mut s, "drawing.update", json!({}))["waiting"], 2); + let before = settled(&mut s, sheet); + assert!(before.stale.is_empty()); + + run(&mut s, "drawing.close", json!({})); + let block = s.doc.features[0].id; + run(&mut s, "timeline.edit", json!({"feature": block.to_string(), "set": {"height": 40}})); + run(&mut s, "drawing.open", drawing); + run(&mut s, "drawing.view.edit", json!({"view": ids::encode(front), "set": {"scale": "1:4"}})); + let held = settled(&mut s, sheet); + assert_eq!((held.stale.len(), bytes(&held.scene)), (2, bytes(&before.scene)), "its last lines, out of date"); + let status = run(&mut s, "drawing.status", json!({})); + assert_eq!((&status["held"], &status["waiting"]), (&json!(true), &json!(2))); + let sheet_id = ids::encode(sheet); + let scene = run(&mut s, "drawing.scene", json!({"sheet": sheet_id})); + let mut listed: Vec = serde_json::from_value(scene["out_of_date"].clone()).unwrap(); + listed.sort(); + let mut both = vec![ids::encode(front), ids::encode(top)]; + both.sort(); + assert_eq!(listed, both); + assert_eq!(run(&mut s, "drawing.export", json!({"sheet": sheet_id}))["out_of_date"].as_array().map(Vec::len), Some(2)); + assert_eq!(s.drawing_scenes.projections, 0); + + run(&mut s, "drawing.update", json!({})); + let now = settled(&mut s, sheet); + assert_eq!((now.stale.len(), bytes(&now.scene)), (0, bytes(&built(&s, sheet).scene))); + assert!(run(&mut s, "drawing.status", json!({})).get("held").is_none()); + assert!(run(&mut s, "drawing.scene", json!({"sheet": sheet_id})).get("out_of_date").is_none()); + + // The next change waits again: back to 20 tall, its lines stay 40 tall. + run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": checkpoint})); + let waiting = settled(&mut s, sheet); + assert_eq!((waiting.stale.len(), bytes(&waiting.scene)), (2, bytes(&now.scene))); +} + +/// `drawing.update` on a drawing that follows the model changes nothing, and draws nothing itself. +#[test] +fn updating_an_automatic_drawing_changes_nothing() { + let (mut s, sheet, _) = front_and_top(); + let doc = s.doc.clone(); + assert_eq!(run(&mut s, "drawing.update", json!({}))["waiting"], 2); + assert_eq!(s.drawing_scenes.projections, 0); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert!(settled(&mut s, sheet).stale.is_empty()); +} + /// Opened again after a model change, with a view's scale changed too, a drawing shows its last /// lines, out of date, until each view is drawn; then it draws as the built scene does. #[test] diff --git a/crates/engine/src/schema/drawing_export.rs b/crates/engine/src/schema/drawing_export.rs index c98d02279..586fc7de0 100644 --- a/crates/engine/src/schema/drawing_export.rs +++ b/crates/engine/src/schema/drawing_export.rs @@ -140,6 +140,9 @@ pub struct ExportResult { /// Each dimension of a view on the sheet, as `drawing.scene` reports it: one that isn't drawn /// leaves the file written, and says why here. pub dimensions: Vec, + /// What a deferred drawing wrote as it last was, as `drawing.scene` reports it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub out_of_date: 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, diff --git a/crates/engine/src/schema/drawing_scene.rs b/crates/engine/src/schema/drawing_scene.rs index 216242045..90ef66cc3 100644 --- a/crates/engine/src/schema/drawing_scene.rs +++ b/crates/engine/src/schema/drawing_scene.rs @@ -175,6 +175,21 @@ pub struct SheetLineResult { #[schemars(deny_unknown_fields)] pub struct DrawingStatusParams {} +/// Lets the drawing open draw from the model as it is now. It takes nothing. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(deny_unknown_fields)] +pub struct DrawingUpdateParams {} + +/// What `drawing.update` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct DrawingUpdateResult { + /// How many views wait to be drawn: the sheet page draws them, as a command that reads their sheet does. + pub waiting: usize, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + /// One view: `current`, `out_of_date`, `placeholder` or `failed`, with why for the last two. #[derive(Debug, Serialize, JsonSchema)] pub struct ViewStatusResult { @@ -203,6 +218,9 @@ pub struct DrawingStatusResult { pub dimensions: Vec, /// How many views are out of date. pub waiting: usize, + /// A deferred drawing: they wait for `drawing.update`. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub held: bool, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub param_warnings: Vec, } @@ -218,6 +236,9 @@ pub struct SheetSceneResult { pub objects: Vec, /// Each dimension of a view on the sheet, by view and id. pub dimensions: Vec, + /// The views and dimensions a deferred drawing shows as they last were. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub out_of_date: 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, diff --git a/crates/ui-egui/src/drawing_workspace.rs b/crates/ui-egui/src/drawing_workspace.rs index 48ba1498c..76ae8d36c 100644 --- a/crates/ui-egui/src/drawing_workspace.rs +++ b/crates/ui-egui/src/drawing_workspace.rs @@ -561,7 +561,7 @@ mod tests { assert_eq!(h.app.cam, cam); } assert!(!can_open_options("drawing.export.planned")); - assert!(!can_open_options("drawing.update")); + assert!(!can_open_options("drawing.update.planned")); } fn app_width(h: &Harness) -> f32 { diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index 03221425e..e504909ef 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -154,7 +154,7 @@ pub const SECTIONS: &[Section] = &[ Section { tab: "DRAWING PARTS", panel: "ASSEMBLY", promoted: 2, ids: &["drawing.parts_list", "drawing.balloon"] }, Section { tab: "DRAWING PARTS", panel: "TABLES", promoted: 2, ids: &["drawing.table.edit", "drawing.revision_table"] }, Section { tab: "DRAWING PARTS", panel: "SOURCE", promoted: 2, ids: &["assembly.bom", "sheet.flat_pattern"] }, - Section { tab: "DRAWING REVIEW", panel: "CHANGES", promoted: 2, ids: &["drawing.update", "drawing.check"] }, + Section { tab: "DRAWING REVIEW", panel: "CHANGES", promoted: 2, ids: &["drawing.update.planned", "drawing.check"] }, Section { tab: "DRAWING REVIEW", panel: "REVISION", promoted: 2, ids: &["drawing.revision", "drawing.revision_table"] }, Section { tab: "DRAWING REVIEW", panel: "OUTPUT", promoted: 2, ids: &["drawing.export.planned", "drawing.print"] }, Section { @@ -480,7 +480,7 @@ pub const RIBBON_LABELS: &[(&str, &str)] = &[ ("drawing.revision", "Add Revision"), ("drawing.revision_table", "Revision Tbl."), ("drawing.table.edit", "Edit Table"), - ("drawing.update", "Update"), + ("drawing.update.planned", "Update"), ("drawing.view.projected.planned", "Projected"), ("drawing.view.section", "Section View"), ("document.units", "Units"), diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPT index 10c1a2606..319b6afcb 100644 --- a/tests/kernel-cases/EXEMPT +++ b/tests/kernel-cases/EXEMPT @@ -113,6 +113,7 @@ drawing.table.edit a drawing: its tests in crates/engine/src/cmd/ drawing.template.apply a drawing: its tests in crates/engine/src/cmd/drawing*_tests.rs drawing.template.list a drawing: its tests in crates/engine/src/cmd/drawing*_tests.rs drawing.template.save a drawing: its tests in crates/engine/src/cmd/drawing*_tests.rs +drawing.update a drawing: its tests in crates/engine/src/drawing_scene_tests.rs drawing.view.base a drawing: its tests in crates/engine/src/cmd/drawing*_tests.rs drawing.view.copy_to_sheet a drawing: its tests in crates/engine/src/cmd/drawing*_tests.rs drawing.view.edit a drawing: its tests in crates/engine/src/cmd/drawing*_tests.rs