From 1df1b04b84d52209ffa344a94c208b1de993a8c7 Mon Sep 17 00:00:00 2001 From: Travis Hughes Date: Mon, 23 Nov 2026 16:50:33 -0500 Subject: [PATCH 1/4] Records an undo step for a change of the current layer, colour, lineweight or linetype With nothing selected, the ribbon and the Properties palette set the current value of the drawing and added no undo step. UNDO then kept the new value and took back the step before it. The four functions now call push_undo_snapshot before the change. The lineweight message of the palette calls on_ribbon_lineweight_changed, as the other three palette messages call their functions. Co-Authored-By: Claude --- src/app/update/command/properties.rs | 4 ++++ src/app/update/dispatch.rs | 9 ++------- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/app/update/command/properties.rs b/src/app/update/command/properties.rs index 22759b1f7c..49a33bc0cb 100644 --- a/src/app/update/command/properties.rs +++ b/src/app/update/command/properties.rs @@ -10,6 +10,7 @@ impl OpenCADStudio { if self.has_property_selection(i) { return Task::none(); } + self.push_undo_snapshot(i, "CLAYER"); // No selection — change the creation default. Persist // into the tab's header (CLAYER) so it survives a tab // switch and rides the next save. #21. @@ -52,6 +53,7 @@ impl OpenCADStudio { if self.has_property_selection(i) { return Task::none(); } + self.push_undo_snapshot(i, "CECOLOR"); // Persist the new default into the tab's header so it // round-trips through tab switches and writes back on // save (CECOLOR). #21. @@ -80,6 +82,7 @@ impl OpenCADStudio { if self.has_property_selection(i) { return Task::none(); } + self.push_undo_snapshot(i, "CELWEIGHT"); // Persist into the tab's header (CELWEIGHT). #21. self.tabs[i].scene.document.header.current_line_weight = lw.value(); self.tabs[i].dirty = true; @@ -106,6 +109,7 @@ impl OpenCADStudio { if self.has_property_selection(i) { return Task::none(); } + self.push_undo_snapshot(i, "CELTYPE"); // Persist into the tab's header (CELTYPE). Resolve to a // handle when the name matches a line_types entry so the // handle-based lookup stays in sync. #21. diff --git a/src/app/update/dispatch.rs b/src/app/update/dispatch.rs index 5cf1a3d72d..657f722907 100644 --- a/src/app/update/dispatch.rs +++ b/src/app/update/dispatch.rs @@ -9129,14 +9129,9 @@ impl OpenCADStudio { let i = self.active_tab; let handles = self.property_target_handles(i); if handles.is_empty() { - if self.has_property_selection(i) { - return Task::none(); - } - self.tabs[i].scene.document.header.current_line_weight = lw.value(); - self.tabs[i].dirty = true; - self.ribbon.active_lineweight = lw; + let task = self.on_ribbon_lineweight_changed(lw); self.refresh_properties(); - return Task::none(); + return task; } self.apply_property_op(i, "CHPROP", &handles, |app, handle| { if let Some(entity) = app.tabs[i].scene.document.get_entity_mut(handle) { From 5969e5525a66a36e55af1b4fc7e450c9bba6771d Mon Sep 17 00:00:00 2001 From: Travis Hughes Date: Mon, 23 Nov 2026 16:50:33 -0500 Subject: [PATCH 2/4] Tests that UNDO takes back a change of a current value 8 cases in the undo sweep: the current layer, colour, lineweight and linetype, from the Properties palette and from the ribbon, with nothing selected. Co-Authored-By: Claude --- src/app/undo_sweep_tests.rs | 42 +++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/app/undo_sweep_tests.rs b/src/app/undo_sweep_tests.rs index 3a108721bf..f64a52f9f5 100644 --- a/src/app/undo_sweep_tests.rs +++ b/src/app/undo_sweep_tests.rs @@ -240,6 +240,39 @@ fn palette_cases(d: &Drawing) -> Vec { ] } +/// Changes of the current layer, colour, lineweight and linetype: nothing is +/// selected, and the Properties palette or the ribbon sends its message. +fn current_value_cases() -> Vec { + use document::types::{Color, LineWeight}; + let case = |name: &str, message: Message| Case { + name: format!("Nothing selected: {name}"), + steps: vec![ + Step::Op(serde_json::json!({"op": "select", "clear": true, "handles": []})), + Step::Send(Box::new(message)), + ], + }; + let (layer, linetype) = ("Walls".to_string(), "Continuous".to_string()); + vec![ + case("palette layer", Message::PropLayerChanged(layer.clone())), + case("palette color", Message::PropColorChanged(Color::Index(1))), + case( + "palette lineweight", + Message::PropLwChanged(LineWeight::W0_50), + ), + case( + "palette linetype", + Message::PropLinetypeChanged(linetype.clone()), + ), + case("ribbon layer", Message::RibbonLayerChanged(layer)), + case("ribbon color", Message::RibbonColorChanged(Color::Index(1))), + case( + "ribbon lineweight", + Message::RibbonLineweightChanged(LineWeight::W0_50), + ), + case("ribbon linetype", Message::RibbonLinetypeChanged(linetype)), + ] +} + /// Text made in an editor: the command stops with the editor open, the text /// goes in, and the editor's OK commits it. fn editor_cases() -> Vec { @@ -544,6 +577,15 @@ fn every_palette_change_is_undone_and_redone_exactly() { } /// The same for text that an editor makes. +#[test] +fn every_change_of_a_current_value_is_undone_and_redone_exactly() { + let failures: Vec = current_value_cases() + .iter() + .flat_map(|case| check_steps(&case.name, &case.steps)) + .collect(); + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + #[test] fn every_editor_commit_is_undone_and_redone_exactly() { let failures: Vec = editor_cases() From ce860bcf5bdd13170dc67302fe99c6c02ceeb0fd Mon Sep 17 00:00:00 2001 From: Travis Hughes Date: Mon, 23 Nov 2026 15:54:32 -0500 Subject: [PATCH 3/4] Adds a test guard that fails when a change of the drawing has no undo step In a test build, update, automation_op and control_request compare each drawing before and after the handler. A drawing that changed with no undo record fails the test, with the name of the message. The 60 names that do this on main are in undo_record_guard_known.txt, with reasons. A release build has no change. Co-Authored-By: Claude --- src/app/automation.rs | 15 + src/app/control/mod.rs | 11 + src/app/update/mod.rs | 6 + src/app/update/undo_record_guard.rs | 345 +++++++++++++++++++++ src/app/update/undo_record_guard_known.txt | 91 ++++++ 5 files changed, 468 insertions(+) create mode 100644 src/app/update/undo_record_guard.rs create mode 100644 src/app/update/undo_record_guard_known.txt diff --git a/src/app/automation.rs b/src/app/automation.rs index a3ac9bac81..a514efbf5a 100644 --- a/src/app/automation.rs +++ b/src/app/automation.rs @@ -944,6 +944,21 @@ impl OpenCADStudio { /// Handle one JSON request line and return the JSON response. #[cfg(any(test, not(target_arch = "wasm32")))] pub(crate) fn automation_op(&mut self, line: &str) -> Value { + // A test build checks that a change of the drawing has an undo step. + #[cfg(all(test, not(target_arch = "wasm32")))] + let undo_guard = super::update::undo_record_guard::begin_request( + self, + "automation", + &serde_json::from_str::(line).unwrap_or(Value::Null), + ); + let response = self.automation_op_unguarded(line); + #[cfg(all(test, not(target_arch = "wasm32")))] + super::update::undo_record_guard::end(self, undo_guard); + response + } + + #[cfg(any(test, not(target_arch = "wasm32")))] + fn automation_op_unguarded(&mut self, line: &str) -> Value { // The plugin pump exists only on native targets (the plugins are // native processes); on wasm this is a no-op. #[cfg(not(target_arch = "wasm32"))] diff --git a/src/app/control/mod.rs b/src/app/control/mod.rs index 2a2c6ac417..a41f0398e2 100644 --- a/src/app/control/mod.rs +++ b/src/app/control/mod.rs @@ -700,6 +700,17 @@ impl OpenCADStudio { } pub(super) fn control_request(&mut self, req: Value) -> (Value, Task) { + // A test build checks that a change of the drawing has an undo step. + #[cfg(all(test, not(target_arch = "wasm32")))] + let undo_guard = + crate::app::update::undo_record_guard::begin_request(self, "control", &req); + let response = self.control_request_unguarded(req); + #[cfg(all(test, not(target_arch = "wasm32")))] + crate::app::update::undo_record_guard::end(self, undo_guard); + response + } + + fn control_request_unguarded(&mut self, req: Value) -> (Value, Task) { // First control contact marks the session automated (#1349): a // DonationPrompt that is still queued (not yet shown) is dropped so // automation never waits behind it, and `queue_startup_prompts` diff --git a/src/app/update/mod.rs b/src/app/update/mod.rs index 6717ef0ec2..a0f043bdbd 100644 --- a/src/app/update/mod.rs +++ b/src/app/update/mod.rs @@ -189,6 +189,8 @@ mod qselect; mod style; pub(in crate::app) mod table_style_cells; pub(crate) mod style_import; +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(in crate::app) mod undo_record_guard; pub(in crate::app) mod util; mod viewport; pub(in crate::app) mod viewport_snap; @@ -1148,6 +1150,8 @@ impl OpenCADStudio { // answered move writes it. Answer the withheld position first, so the // order stays the order the pointer reported — the hazard // `on_snap_dwell_tick` documents is a replay that lands *after*. + #[cfg(all(test, not(target_arch = "wasm32")))] + let undo_guard = undo_record_guard::begin_message(self, &msg); let owed = self.flush_owed_pointer_move(&msg); let task = Task::batch([owed, self.update_inner(msg)]); let perf_dispatch_ms = crate::perf::elapsed_ms(perf_started); @@ -1181,6 +1185,8 @@ impl OpenCADStudio { // Close the document-level first-touch transaction started by // push_undo_snapshot at this message boundary. self.finish_all_pending_history(); + #[cfg(all(test, not(target_arch = "wasm32")))] + undo_record_guard::end(self, undo_guard); if self.tabs[self.active_tab].active_cmd.is_none() { self.tool_palettes.placing = None; } diff --git a/src/app/update/undo_record_guard.rs b/src/app/update/undo_record_guard.rs new file mode 100644 index 0000000000..3b8a95cca6 --- /dev/null +++ b/src/app/update/undo_record_guard.rs @@ -0,0 +1,345 @@ +//! A change of the drawing must be in an undo step. In a test build, the +//! places that run a handler (`update`, `automation_op`, `control_request`) +//! compare each drawing before and after it, and fail the test when a +//! drawing changed with no undo record. The names that can do that are in +//! `undo_record_guard_known.txt`, with reasons. `OCS_UNDO_GUARD_LIST=` +//! writes the names that the tests give now and fails no test. + +use std::cell::Cell; +use std::collections::HashSet; +use std::fmt::Write as _; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +use serde_json::Value; + +use crate::app::{Message, OpenCADStudio}; + +thread_local! { + /// How many guarded handlers run inside each other on this thread. + static DEPTH: Cell = const { Cell::new(0) }; + /// The depth of a handler that changed a drawing with no undo record + /// and whose name is in the list. The handlers around it (a smaller + /// depth) see the same change and do not report it again. + static KNOWN_AT: Cell> = const { Cell::new(None) }; +} + +/// The names that can change a drawing with no undo record. +fn known() -> &'static HashSet<&'static str> { + static KNOWN: OnceLock> = OnceLock::new(); + KNOWN.get_or_init(|| parse_known(include_str!("undo_record_guard_known.txt"))) +} + +pub(super) fn parse_known(text: &'static str) -> HashSet<&'static str> { + text.lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .collect() +} + +fn list_file() -> Option<&'static PathBuf> { + static FILE: OnceLock> = OnceLock::new(); + FILE.get_or_init(|| std::env::var_os("OCS_UNDO_GUARD_LIST").map(PathBuf::from)) + .as_ref() +} + +/// The name of a message: its variant, and the variant of its first field +/// when that is an enum or a struct (`Linetype(SetCurrent)`). +pub(super) fn message_name(debug: &str) -> String { + let ident = |text: &str| -> usize { + text.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .unwrap_or(text.len()) + }; + let first = ident(debug); + let mut name = debug[..first].to_string(); + if let Some(rest) = debug[first..].strip_prefix('(') { + if rest.starts_with(|c: char| c.is_ascii_uppercase()) { + let second = ident(rest); + let _ = write!(name, "({})", &rest[..second]); + } + } + name +} + +/// The messages that carry a line of the command line. +const COMMAND_LINES: [&str; 2] = ["ScriptLine", "CommandInput"]; + +/// The command that a command line message starts: the first word of its +/// text (`ScriptLine("tilemode 0")` gives `TILEMODE`). +pub(super) fn command_word(debug: &str) -> Option { + let (variant, rest) = debug.split_once("(\"")?; + if !COMMAND_LINES.contains(&variant) { + return None; + } + let word: String = rest + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_')) + .take(40) + .collect(); + (!word.is_empty()).then(|| word.to_ascii_uppercase()) +} + +/// The command that is active before the handler. +fn active_command(app: &OpenCADStudio) -> Option { + app.tabs + .get(app.active_tab) + .and_then(|tab| tab.active_cmd.as_ref()) + .map(|command| command.name().to_ascii_uppercase()) +} + +/// A message does different work in different commands, so the command is a +/// part of the name: the active one (`CommandEscape during BACTION`), or +/// with none active the one that a command line starts (`ScriptLine +/// TILEMODE`). +pub(super) fn full_name(name: String, active: Option, started: Option) -> String { + match (active, started) { + (Some(command), _) => format!("{name} during {command}"), + (None, Some(command)) => format!("{name} {command}"), + (None, None) => name, + } +} + +/// The name of a request: its kind and operation, and for `run` the command. +pub(super) fn request_name(kind: &str, request: &Value) -> String { + let op = request["op"].as_str().unwrap_or("?"); + match request["cmd"] + .as_str() + .and_then(|cmd| cmd.split_whitespace().next()) + { + Some(command) if op == "run" => format!("{kind}:run {}", command.to_ascii_uppercase()), + _ => format!("{kind}:{op}"), + } +} + +/// The start of a `Debug` text; a message can hold a whole drawing. +struct Start(String); + +impl std::fmt::Write for Start { + fn write_str(&mut self, text: &str) -> std::fmt::Result { + if self.0.len() >= 160 { + return Err(std::fmt::Error); + } + self.0.push_str(text); + Ok(()) + } +} + +struct TabBefore { + id: u64, + document: document::Document, + undo_len: usize, + redo_len: usize, + edit_revision: u64, + record_open: bool, +} + +/// What the guard keeps from before one handler. +pub(in crate::app) struct Frame { + name: String, + /// 0 for the handler that no other guarded handler runs. + depth: u32, + tabs: Vec, +} + +impl Drop for Frame { + fn drop(&mut self) { + DEPTH.with(|depth| depth.set(self.depth)); + if self.depth == 0 { + KNOWN_AT.with(|known| known.set(None)); + } + } +} + +/// A handler inside this one already answered for the change. +fn inner_answered(depth: u32) -> bool { + KNOWN_AT.with(Cell::get).is_some_and(|at| at > depth) +} + +fn record_open(tab: &crate::app::DocumentTab) -> bool { + tab.history.pending.is_some() || tab.scene.is_recording_undo() +} + +fn begin(app: &OpenCADStudio, name: String) -> Frame { + let depth = DEPTH.with(|depth| { + let now = depth.get(); + depth.set(now + 1); + now + }); + Frame { + name, + depth, + tabs: app + .tabs + .iter() + .map(|tab| TabBefore { + id: tab.id, + document: tab.scene.document.clone(), + undo_len: tab.history.undo_stack.len(), + redo_len: tab.history.redo_stack.len(), + edit_revision: tab.edit_revision, + record_open: record_open(tab), + }) + .collect(), + } +} + +/// Before the handler of a message. +pub(in crate::app) fn begin_message(app: &OpenCADStudio, message: &Message) -> Frame { + let mut start = Start(String::new()); + let _ = write!(start, "{message:?}"); + let name = full_name( + message_name(&start.0), + active_command(app), + command_word(&start.0), + ); + begin(app, name) +} + +/// Before the handler of an automation or control request. +pub(in crate::app) fn begin_request(app: &OpenCADStudio, kind: &str, request: &Value) -> Frame { + begin( + app, + full_name(request_name(kind, request), active_command(app), None), + ) +} + +/// What one handler did to one drawing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Evidence { + pub(super) changed: bool, + /// An undo record was open before the handler or is open after it: the + /// record has the change, or will have it. + pub(super) record_open: bool, + /// The handler added an undo step, or ran UNDO or REDO. + pub(super) history_moved: bool, +} + +impl Evidence { + pub(super) fn has_no_undo_record(self) -> bool { + self.changed && !self.record_open && !self.history_moved + } +} + +/// The parts of two drawings that differ, as a short text; `None` when the +/// drawings are equal. +fn difference(before: &mut document::Document, after: &mut document::Document) -> Option { + let mut added = 0usize; + let mut modified = 0usize; + let mut kept = 0usize; + for entity in after.entities() { + match before.get_entity(entity.common().handle) { + None => added += 1, + Some(old) => { + kept += 1; + // An entity that no handler touched is the same allocation. + if !std::ptr::eq(old, entity) && old != entity { + modified += 1; + } + } + } + } + let removed = before.entity_count() - kept; + // All that is not an entity: tables, objects, header, block records. + let old = before.snapshot_structure(); + let new = after.snapshot_structure(); + let mut parts: Vec<&str> = Vec::new(); + if old != new { + macro_rules! part { + ($($field:ident),*) => {$( + if old.$field != new.$field { + parts.push(stringify!($field)); + } + )*}; + } + part!( + header, + layers, + line_types, + text_styles, + block_records, + dim_styles, + app_ids, + views, + vports, + ucss, + objects + ); + if parts.is_empty() { + parts.push("other data"); + } + } + if added == 0 && modified == 0 && removed == 0 && parts.is_empty() { + return None; + } + let mut text = format!("{added} entities added, {modified} modified, {removed} removed"); + if !parts.is_empty() { + let _ = write!(text, "; changed: {}", parts.join(", ")); + } + Some(text) +} + +/// After the handler, and after the message boundary closed its undo +/// records. Fails the test when a drawing changed with no undo record. +pub(in crate::app) fn end(app: &mut OpenCADStudio, frame: Frame) { + if let Some(report) = check(app, frame, known(), list_file().map(PathBuf::as_path)) { + panic!("{report}"); + } +} + +/// The report for one handler, or `None`. `known` has the names that can +/// change a drawing with no undo record; with `list`, each such name goes to +/// that file and nothing is reported. +pub(super) fn check( + app: &mut OpenCADStudio, + mut frame: Frame, + known: &HashSet<&'static str>, + list: Option<&Path>, +) -> Option { + let name = std::mem::take(&mut frame.name); + for mut before in std::mem::take(&mut frame.tabs) { + let Some(tab) = app.tabs.iter_mut().find(|tab| tab.id == before.id) else { + continue; + }; + let Some(what) = difference(&mut before.document, &mut tab.scene.document) else { + continue; + }; + let evidence = Evidence { + changed: true, + record_open: before.record_open || record_open(tab), + history_moved: tab.history.undo_stack.len() != before.undo_len + || tab.history.redo_stack.len() != before.redo_len + || tab.edit_revision != before.edit_revision, + }; + if !evidence.has_no_undo_record() { + continue; + } + // This handler answers for the change to the handlers around it too. + let answered = || KNOWN_AT.with(|known| known.set(Some(frame.depth))); + if inner_answered(frame.depth) { + answered(); + continue; + } + if let Some(path) = list { + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + { + let _ = file.write_all(format!("{name}\n").as_bytes()); + } + answered(); + continue; + } + if known.contains(name.as_str()) { + answered(); + continue; + } + return Some(format!( + "`{name}` changed a drawing and made no undo step ({what}). Open one \ + (`push_undo_snapshot`) before the change, or add the name with its \ + reason to src/app/update/undo_record_guard_known.txt." + )); + } + None +} diff --git a/src/app/update/undo_record_guard_known.txt b/src/app/update/undo_record_guard_known.txt new file mode 100644 index 0000000000..30748f4ff6 --- /dev/null +++ b/src/app/update/undo_record_guard_known.txt @@ -0,0 +1,91 @@ +# The messages and requests that change a drawing and make no undo step +# (see undo_record_guard.rs). One name on each line; `#` starts a comment. +# Remove a name when its handler gets an undo step. A new name needs a reason. + +# By design: the drawing is made, opened or saved. These are not edits. +FileOpened +SaveFinished(SaveOutcome) +ScriptLine during EXIT +ScriptPump +TabNew +automation:new +automation:open +automation:save +control:new +control:save + +# By design: a live edit. The entity changes while the user draws or drags, +# and the end of the command or of the grip edit completes one undo step +# (`finish_live_entity_history`, `push_entity_group_history`). +CommandInput during PLINE +CommandOptionPick during PLINE +ContextMenuPick(Grip) +SetModifiers +ViewportLeftPressAt(Point) during PLINE + +# By design: a cancelled command takes back what it placed. +CommandEscape during BACTION + +# By design: view state. A viewport's stale saved view is corrected when +# the viewport becomes active. +EnterViewport(Handle) during ALIGNSPACE + +# No undo step when the guard was added, and known then: a layout becomes +# current (the first use of a layout also adds its viewport). +LayoutSwitch +automation:run TILEMODE +control:layout_activate + +# No undo step when the guard was added, and known then: a typed command or +# the linetype manager sets the current layer, colour or linetype. (The +# palette and the ribbon record an undo step for these.) +CommandInput LINETYPE +Linetype(SetCurrent) +ScriptLine -LINETYPE +ScriptLine during LINETYPE +automation:run CLAYER +automation:run COLOR +automation:run LINETYPE + +# Not examined when the guard was added. Each of these changed a drawing +# with no undo step in its own message; a later message can have completed +# one (a style manager records at Apply, a command at its end). + +# Style managers and their windows. +CloseModal +Linetype(Copy) +Linetype(Delete) +Linetype(New) +Linetype(SaveToLibrary) +Linetype(Select) +LinetypeLoaded(Some) +StyleRenameCommit(Linetype) +StyleRenameCommit(Text) +StyleRenameStart(Text) +TableStyleDialogOpen +TextStyleCard(NewOk) +TextStyleDialogCopy + +# The block editor opens. +BlockEditPickerApply +automation:run -BEDIT + +# Drawing variables, view state and plot settings. +AnnoObjectScaleToggle +DispSilhChanged +IsolinesChanged +LayerMenu +OptionsCloseDiscard +PlotDlg(Commit) +RibbonToolClick +SetRenderMode(FlatShaded) +SetRenderMode(GouraudShaded) +ShortcutPressed +SyncViewportAnnotationScale +TabSwitch +automation:run INSUNITS +automation:run MSLTSCALE +automation:run REVCLOUD +automation:run SETVAR +control:plot +control:xref_source_register From 9c5addf3633847a291794ac5605d98179236538a Mon Sep 17 00:00:00 2001 From: Travis Hughes Date: Mon, 23 Nov 2026 15:54:32 -0500 Subject: [PATCH 4/4] Tests the undo record guard The name rules, the decision rule, a change with and without an undo record, a name of the list, nested handlers and list mode. Co-Authored-By: Claude --- src/app/update/mod.rs | 2 + src/app/update/undo_record_guard.rs | 6 + src/app/update/undo_record_guard_tests.rs | 351 ++++++++++++++++++++++ 3 files changed, 359 insertions(+) create mode 100644 src/app/update/undo_record_guard_tests.rs diff --git a/src/app/update/mod.rs b/src/app/update/mod.rs index a0f043bdbd..257937733c 100644 --- a/src/app/update/mod.rs +++ b/src/app/update/mod.rs @@ -191,6 +191,8 @@ pub(in crate::app) mod table_style_cells; pub(crate) mod style_import; #[cfg(all(test, not(target_arch = "wasm32")))] pub(in crate::app) mod undo_record_guard; +#[cfg(all(test, not(target_arch = "wasm32")))] +mod undo_record_guard_tests; pub(in crate::app) mod util; mod viewport; pub(in crate::app) mod viewport_snap; diff --git a/src/app/update/undo_record_guard.rs b/src/app/update/undo_record_guard.rs index 3b8a95cca6..e03b25e139 100644 --- a/src/app/update/undo_record_guard.rs +++ b/src/app/update/undo_record_guard.rs @@ -142,6 +142,12 @@ pub(in crate::app) struct Frame { tabs: Vec, } +impl Frame { + pub(super) fn depth(&self) -> u32 { + self.depth + } +} + impl Drop for Frame { fn drop(&mut self) { DEPTH.with(|depth| depth.set(self.depth)); diff --git a/src/app/update/undo_record_guard_tests.rs b/src/app/update/undo_record_guard_tests.rs new file mode 100644 index 0000000000..29ad7e30cb --- /dev/null +++ b/src/app/update/undo_record_guard_tests.rs @@ -0,0 +1,351 @@ +//! The undo record guard: it is silent for a change that has an undo step +//! and for a name of the list, and it reports each other change. + +use std::collections::HashSet; + +use document::entities::Line; +use document::types::Vector3; +use document::EntityType; +use serde_json::json; + +use super::undo_record_guard::{ + begin_request, check, command_word, end, full_name, message_name, parse_known, request_name, + Evidence, +}; +use crate::app::{Message, OpenCADStudio}; + +fn app() -> OpenCADStudio { + let mut app = OpenCADStudio::new_for_test(); + let _ = app.automation_op(r#"{"op":"new"}"#); + app +} + +fn names(list: &[&'static str]) -> HashSet<&'static str> { + list.iter().copied().collect() +} + +/// A line from (1, 2, 0) to (7, 5, 0), added with no undo record. +fn add_line_with_no_record(app: &mut OpenCADStudio) { + let i = app.active_tab; + let line = Line::from_points(Vector3::new(1.0, 2.0, 0.0), Vector3::new(7.0, 5.0, 0.0)); + app.tabs[i].scene.add_entity(EntityType::Line(line)); +} + +fn undo_depth(app: &OpenCADStudio) -> usize { + app.tabs[app.active_tab].history.undo_stack.len() +} + +#[test] +fn a_message_name_is_its_variant_and_the_variant_of_its_first_field() { + assert_eq!(message_name("LayoutSwitch"), "LayoutSwitch"); + assert_eq!(message_name("Linetype(SetCurrent)"), "Linetype(SetCurrent)"); + assert_eq!( + message_name("PropColorChanged(Index(9))"), + "PropColorChanged(Index)" + ); + // A field that is a number or a text is not a part of the name. + assert_eq!( + message_name("PanePressAt(0, Point { x: 1.5 })"), + "PanePressAt" + ); + assert_eq!( + message_name("CommandOptionPick(\"C\")"), + "CommandOptionPick" + ); + assert_eq!(message_name("ScriptLine(\"tilemode 0\")"), "ScriptLine"); + assert_eq!( + message_name("SetModifiers { shift: false, ctrl: true }"), + "SetModifiers" + ); + // The text can stop in the middle of a field. + assert_eq!(message_name("FileOpened(Ok(Docu"), "FileOpened(Ok)"); + assert_eq!(message_name("FileOpened(Ok"), "FileOpened(Ok)"); +} + +#[test] +fn a_command_line_message_gives_the_command_that_it_starts() { + assert_eq!( + command_word("ScriptLine(\"tilemode 0\")").as_deref(), + Some("TILEMODE") + ); + assert_eq!( + command_word("CommandInput(\"-LAYER NEW Walls\")").as_deref(), + Some("-LAYER") + ); + // Only the two command line messages: the text of another one is data. + assert_eq!(command_word("LayoutSwitch(\"Layout1\")"), None); + assert_eq!(command_word("CommandOptionPick(\"C\")"), None); + // A text that does not start with a word, and a message with no text. + assert_eq!(command_word("CommandInput(\"\")"), None); + assert_eq!(command_word("ScriptLine(\" \")"), None); + assert_eq!(command_word("LayoutSwitch"), None); +} + +#[test] +fn the_command_is_a_part_of_the_name() { + let text = |value: &str| Some(value.to_string()); + assert_eq!( + full_name("LayoutSwitch".to_string(), None, None), + "LayoutSwitch" + ); + assert_eq!( + full_name("ScriptLine".to_string(), None, text("TILEMODE")), + "ScriptLine TILEMODE" + ); + assert_eq!( + full_name("CommandEscape".to_string(), text("BACTION"), None), + "CommandEscape during BACTION" + ); + // In a command, a command line is an answer, not a new command. + assert_eq!( + full_name("ScriptLine".to_string(), text("LINETYPE"), text("FENCE")), + "ScriptLine during LINETYPE" + ); +} + +#[test] +fn a_request_name_has_its_kind_its_operation_and_the_command_of_a_run() { + assert_eq!( + request_name("automation", &json!({"op": "save"})), + "automation:save" + ); + assert_eq!( + request_name("automation", &json!({"op": "run", "cmd": "tilemode 0"})), + "automation:run TILEMODE" + ); + assert_eq!( + request_name( + "control", + &json!({"protocol": 1, "op": "layout_activate", "name": "A"}) + ), + "control:layout_activate" + ); + // A `cmd` field names the command only for `run`. + assert_eq!( + request_name("control", &json!({"op": "input", "cmd": "MOVE"})), + "control:input" + ); + assert_eq!(request_name("control", &json!({})), "control:?"); + assert_eq!( + request_name("automation", &json!({"op": "run"})), + "automation:run" + ); +} + +#[test] +fn only_a_change_with_no_record_and_no_history_step_is_reported() { + let evidence = |changed, record_open, history_moved| Evidence { + changed, + record_open, + history_moved, + }; + assert!(evidence(true, false, false).has_no_undo_record()); + assert!(!evidence(false, false, false).has_no_undo_record()); + assert!(!evidence(true, true, false).has_no_undo_record()); + assert!(!evidence(true, false, true).has_no_undo_record()); + assert!(!evidence(true, true, true).has_no_undo_record()); +} + +#[test] +fn the_list_file_has_names_comments_and_empty_lines() { + let list = parse_known("# reason\nLayoutSwitch\n\n automation:run TILEMODE \n# end\n"); + assert_eq!(list, names(&["LayoutSwitch", "automation:run TILEMODE"])); +} + +#[test] +fn the_list_has_each_name_one_time() { + let text = include_str!("undo_record_guard_known.txt"); + let mut seen = HashSet::new(); + for line in text.lines().map(str::trim) { + if line.is_empty() || line.starts_with('#') { + continue; + } + assert!(seen.insert(line), "`{line}` is in the list two times"); + } + assert_eq!(seen, parse_known(text)); +} + +#[test] +fn a_command_that_makes_an_undo_step_passes() { + let mut app = app(); + // `update` holds the guard: a report would stop this test here. + let _ = app.update_root(Message::ScriptLine("CIRCLE 3,4 5".to_string())); + assert_eq!(undo_depth(&app), 1, "the circle is one undo step"); +} + +#[test] +fn a_change_inside_an_undo_record_is_not_reported() { + let mut app = app(); + let frame = begin_request(&app, "test", &json!({"op": "recorded"})); + let i = app.active_tab; + app.push_undo_snapshot(i, "TEST"); + add_line_with_no_record(&mut app); + app.finish_all_pending_history(); + assert_eq!(undo_depth(&app), 1); + assert_eq!(check(&mut app, frame, &names(&[]), None), None); +} + +#[test] +fn a_record_that_stays_open_is_not_reported() { + let mut app = app(); + let frame = begin_request(&app, "test", &json!({"op": "open_record"})); + let i = app.active_tab; + app.push_undo_snapshot(i, "TEST"); + add_line_with_no_record(&mut app); + // The message boundary did not close it yet: it will have the change. + assert_eq!(check(&mut app, frame, &names(&[]), None), None); + app.finish_all_pending_history(); +} + +#[test] +fn an_added_entity_with_no_undo_record_is_reported_with_its_name() { + let mut app = app(); + let frame = begin_request(&app, "test", &json!({"op": "add_line"})); + add_line_with_no_record(&mut app); + let report = check(&mut app, frame, &names(&[]), None).expect("a report"); + assert!( + report.contains("`test:add_line` changed a drawing"), + "{report}" + ); + assert!( + report.contains("1 entities added, 0 modified, 0 removed"), + "{report}" + ); + assert!(report.contains("undo_record_guard_known.txt"), "{report}"); + assert_eq!(undo_depth(&app), 0); +} + +#[test] +fn a_changed_header_with_no_undo_record_is_reported() { + let mut app = app(); + let frame = begin_request(&app, "test", &json!({"op": "header"})); + let i = app.active_tab; + app.tabs[i].scene.document.header.handle_seed += 3; + let report = check(&mut app, frame, &names(&[]), None).expect("a report"); + assert!( + report.contains("0 entities added, 0 modified, 0 removed; changed: header"), + "{report}" + ); +} + +#[test] +fn a_modified_and_a_removed_entity_with_no_undo_record_are_reported() { + let mut app = app(); + add_line_with_no_record(&mut app); + add_line_with_no_record(&mut app); + let i = app.active_tab; + let handles: Vec<_> = app.tabs[i] + .scene + .document + .entities() + .map(|entity| entity.common().handle) + .collect(); + let frame = begin_request(&app, "test", &json!({"op": "edit"})); + let first = app.tabs[i] + .scene + .document + .get_entity_mut(handles[0]) + .expect("the first line"); + first.common_mut().layer = "Walls".to_string(); + app.tabs[i].scene.erase_entities(&handles[1..]); + let report = check(&mut app, frame, &names(&[]), None).expect("a report"); + assert!( + report.contains("0 entities added, 1 modified, 1 removed"), + "{report}" + ); +} + +#[test] +#[should_panic(expected = "changed a drawing and made no undo step")] +fn the_guard_fails_the_test_for_a_change_with_no_undo_record() { + // In list mode the guard fails no test: keep this test as it is there. + if std::env::var_os("OCS_UNDO_GUARD_LIST").is_some() { + panic!("list mode: changed a drawing and made no undo step"); + } + let mut app = app(); + let frame = begin_request(&app, "test", &json!({"op": "not_in_the_list"})); + add_line_with_no_record(&mut app); + end(&mut app, frame); +} + +#[test] +fn a_handler_that_ended_leaves_no_depth_and_no_answer_behind() { + let mut app = app(); + let list = names(&["test:listed"]); + let outer = begin_request(&app, "test", &json!({"op": "outer"})); + let listed = begin_request(&app, "test", &json!({"op": "listed"})); + assert_eq!((outer.depth(), listed.depth()), (0, 1)); + add_line_with_no_record(&mut app); + assert_eq!(check(&mut app, listed, &list, None), None); + // The outer handler stops (a panic) before it looks at the change. + drop(outer); + let next = begin_request(&app, "test", &json!({"op": "next"})); + assert_eq!(next.depth(), 0); + add_line_with_no_record(&mut app); + assert!(check(&mut app, next, &list, None).is_some()); +} + +#[test] +fn a_handler_that_changes_nothing_is_not_reported() { + let mut app = app(); + let frame = begin_request(&app, "test", &json!({"op": "nothing"})); + assert_eq!(check(&mut app, frame, &names(&[]), None), None); +} + +#[test] +fn a_name_of_the_list_is_not_reported() { + let mut app = app(); + let frame = begin_request(&app, "test", &json!({"op": "add_line"})); + add_line_with_no_record(&mut app); + assert_eq!( + check(&mut app, frame, &names(&["test:add_line"]), None), + None + ); +} + +#[test] +fn the_handler_around_a_listed_handler_does_not_report_the_same_change() { + let mut app = app(); + let list = names(&["test:inner"]); + let outer = begin_request(&app, "test", &json!({"op": "outer"})); + let middle = begin_request(&app, "test", &json!({"op": "middle"})); + let inner = begin_request(&app, "test", &json!({"op": "inner"})); + add_line_with_no_record(&mut app); + assert_eq!(check(&mut app, inner, &list, None), None); + assert_eq!(check(&mut app, middle, &list, None), None); + assert_eq!(check(&mut app, outer, &list, None), None); + // The next handler starts with nothing answered. + let next = begin_request(&app, "test", &json!({"op": "next"})); + add_line_with_no_record(&mut app); + assert!(check(&mut app, next, &list, None).is_some()); +} + +#[test] +fn a_handler_after_a_listed_handler_still_reports_its_own_change() { + let mut app = app(); + let list = names(&["test:listed"]); + let outer = begin_request(&app, "test", &json!({"op": "outer"})); + let listed = begin_request(&app, "test", &json!({"op": "listed"})); + add_line_with_no_record(&mut app); + assert_eq!(check(&mut app, listed, &list, None), None); + // A second handler at the same depth is not covered by the first. + let second = begin_request(&app, "test", &json!({"op": "second"})); + add_line_with_no_record(&mut app); + let report = check(&mut app, second, &list, None).expect("a report"); + assert!(report.contains("`test:second`"), "{report}"); + drop(outer); +} + +#[test] +fn list_mode_writes_the_name_and_reports_nothing() { + let mut app = app(); + let dir = tempfile::tempdir().expect("a temporary folder"); + let file = dir.path().join("names.txt"); + for _ in 0..2 { + let frame = begin_request(&app, "test", &json!({"op": "add_line"})); + add_line_with_no_record(&mut app); + assert_eq!(check(&mut app, frame, &names(&[]), Some(&file)), None); + } + let written = std::fs::read_to_string(&file).expect("the list file"); + assert_eq!(written, "test:add_line\ntest:add_line\n"); +}