diagram_core/src/edit.rs#
Source: lib/diagram_core/src/edit.rs
edit -- changing a document in transactions that can be undone and redone (DM-02)
let mut tx = doc.transaction("Verschieben"); every edit goes through tx
tx.set_length(sheet, addr, 25.0, Unit::Millimeters)?;
tx.set_formula(sheet, addr, "Width*0.5")?; ... add_shape, delete_row, add_page ...
let change = tx.commit(); Option<Change>: None when nothing changed
(dropping tx without commit takes all its edits back)
change.undo(&mut doc) / change.redo(&mut doc) -> bool
change.label() / merging(key) / merge(&next) / sheets()
With ui::history (lib/ui/history.rs) the app wraps a Change in an Edit of its own (the orphan
rule keeps the impl in the app; diagram_core does not depend on ui):
struct Step(Change);
impl Edit<Document> for Step {
fn apply(&mut self, d: &mut Document) { self.0.redo(d); }
fn revert(&mut self, d: &mut Document) { self.0.undo(d); }
fn label(&self) -> &str { self.0.label() }
fn merge(&mut self, next: &mut dyn Edit<Document>) -> bool {
next.value().and_then(|v| v.downcast_ref::<Step>()).is_some_and(|n| self.0.merge(&n.0))
}
fn value(&self) -> Option<&dyn core::any::Any> { Some(self) }
}
history.record(Box::new(Step(change))); the change is already applied
How undo works: inverse operations, not snapshots. Each edit is broken into primitive steps
on the smallest part it touches -- one cell, one row, one section, one shape's attributes,
one shape subtree, one page, master or style -- and each step, when it runs, hands back the
step that undoes it (a cell's old content, a removed subtree, an old position). Undo runs the
inverse steps backwards and collects their inverses for redo. So a step costs memory and time
in proportion to what it changes, whatever the size of the drawing: moving 1000 shapes keeps
2000 cells, not 1000 sheets or the document. Handles stay valid because slots are never
reused and deleted shapes come back into their slots. The steps address cells and rows by
position, which holds because undo and redo replay them in exact reverse order on the state
they left; an untracked change in between (the *_mut functions) breaks that, a step that no
longer fits is refused (undo returns false) and the steps run before it are taken back; when
even that fails the change is_broken and refuses from then on. IDs, like slots, are never
handed out twice (NoIds once a file used the largest one, 4294967294; NO_ID is none); a step that would give two pages,
masters or styles one ID is refused.
Structure keeps inheritance: a subshape of an instance stays in its instance, the master
shape of a master in use stays its first top-level shape (InUse), an instance never goes into
a master it depends on (Cycle). delete_shapes deletes a selection in one pass.
Formula and value stay a pair: set_formula keeps the old value and marks the cell stale for
the engine (JD6), set_constant writes a value whose formula is the value itself, set_result
is the engine's way to store a formula's result; GUARD(...) formulas refuse both unless
forced (force_formula, force_constant). Deleting an inherited row, section or subshape writes
a Del="1" mark; restore_row and restore_section remove it again.
enum EditErrorwhy an edit was refused (the transaction keeps its earlier edits)NoSheet-- the sheet does not existNoShape-- the shape does not existNoPage-- the page does not existNoMaster-- the master does not existNoStyle-- the style does not existNoSection-- the section does not exist for the sheetNoRow-- the row does not exist for the sheetDeleted-- the row or section is deleted here (Del="1"); restore it firstGuarded-- GUARD protects the formula; force_formula / force_constant override itExists-- it exists alreadyInUse-- something still refers to it (instances of a master, users of a style)Cycle-- the change would make a cycle (background pages, styles, groups)NotBackground-- the page is not a background pageInvalid-- the request does not fit the objectStale-- the document no longer matches (changed outside transactions)NoIds-- no free ID is left (a file used the largest ID, 4294967294)
struct Changea committed transaction: one undo step
impl Change
fn label(&self) -> &strthe label of the transaction ("Verschieben")fn steps(&self) -> usizethe number of primitive stepsfn is_undone(&self) -> boolwhether it is undone nowfn is_broken(&self) -> boolwhether it stopped working: a step no longer fitted and what ran before could not be taken back (only after untracked changes); undo and redo then refusefn merging(mut self, key: u32) -> Changechanges with the same non-zero key merge into one step (a drag)fn merge_key(&self) -> u32the merge key (0: none)fn merge(&mut self, next: &Change) -> booltake the following change into this one when both have the same non-zero key and both are applied -> whether it did (the next change is then part of this step)fn undo(&mut self, doc: &mut Document) -> booltake the change back -> false when it is undone already or no longer fits the document (then nothing changes)fn redo(&mut self, doc: &mut Document) -> booldo the change again -> false when it is applied or no longer fitsfn sheets(&self) -> Vec<SheetRef>the sheets it touches, for recalculation: whose cells, rows, sections or attributes it changes, shapes it adds or removes (of a removed group only the group), the page or master sheet of changed Connect entries, added or removed pages, masters and styles, the document sheet for the settingsstruct Transaction<'d>edits that become one undo step (Document::transaction)
impl Document
fn transaction(&mut self, label: &str) -> Transaction<'_>start a transaction; its edits become one undo step when committed
impl<'d> Transaction<'d>
fn doc(&self) -> &Documentthe document as it is now (with the edits so far)fn intern(&mut self, s: &str) -> Symthe handle of a text (cell names for addresses, values)fn single(&mut self, cell: &str) -> CellAddrthe address of a single cell by namefn named(&mut self, section: &str, row: &str, cell: &str) -> CellAddrthe address of a cell of a named row (User, Property, Hyperlink ...)fn commit(mut self) -> Option<Change>end the transaction -> the change to keep for undo (None: nothing changed)fn rollback(self)take every edit of the transaction backfn sheets(&self) -> Vec<SheetRef>the sheets the edits so far touch, as Change::sheets names them once committed (an app that follows a gesture with more work in the same step asks which pages it changed)fn set_formula(&mut self, sheet: SheetRef, addr: &CellAddr, formula: &str) -> Result<(), EditError>give the cell a formula of its own; its value stays until the engine computes the new one (the cell is stale until then)fn force_formula(&mut self, sheet: SheetRef, addr: &CellAddr, formula: &str) -> Result<(), EditError>set_formula also over a GUARD formulafn set_constant(&mut self, sheet: SheetRef, addr: &CellAddr, value: Value, unit: Option<Unit>) -> Result<(), EditError>set the cell to a constant: the value (internal units) is its formula, shown inunitfn force_constant(&mut self, sheet: SheetRef, addr: &CellAddr, value: Value, unit: Option<Unit>) -> Result<(), EditError>set_constant also over a GUARD formulafn set_length(&mut self, sheet: SheetRef, addr: &CellAddr, value: f64, unit: Unit) -> Result<(), EditError>set a length or angle given inunit(converted to internal units, shown inunit)fn set_string(&mut self, sheet: SheetRef, addr: &CellAddr, value: &str) -> Result<(), EditError>set a string constant (shown as STR)fn inherit_cell(&mut self, sheet: SheetRef, addr: &CellAddr) -> Result<(), EditError>remove the sheet's own cell: the cell inherits again ("Formel löschen")fn set_result(&mut self, sheet: SheetRef, addr: &CellAddr, value: Value, error: Option<CellError>) -> Result<(), EditError>(the engine) store the result of the cell's formula for this sheet; a cell that inherits its formula gets an F="Inh" cell of its ownfn set_result_unit(&mut self, sheet: SheetRef, addr: &CellAddr, value: Value, error: Option<CellError>, unit: Option<Unit>) -> Result<(), EditError>(JD19) set_result with the unit that marks the value's type in the file (the formula engine: a Value cell's string is U='STR', a colour U='COLOR', a point U='PNT')fn add_section(&mut self, sheet: SheetRef, name: &str) -> Result<SecKey, EditError>add a section of the sheet's own -> its key (Geometry: the next free index); Exists when the sheet has it alreadyfn delete_section(&mut self, sheet: SheetRef, sk: SecKey) -> Result<(), EditError>delete a section: an inherited one gets a Del="1" mark, an own one goesfn restore_section(&mut self, sheet: SheetRef, sk: SecKey) -> Result<(), EditError>remove the Del="1" mark of an inherited section: it is inherited againfn add_row(&mut self, sheet: SheetRef, sk: SecKey, key: Option<RowKey>, kind: Option<&str>) -> Result<RowKey, EditError>add a row of the sheet's own to a section (made when missing) -> its key;keyNone: the next index (Geometry from 1, other indexed sections from 0);kindthe row type (Geometry: "LineTo" ...)fn delete_row(&mut self, sheet: SheetRef, sk: SecKey, key: RowKey) -> Result<(), EditError>delete a row: an inherited one gets a Del="1" mark (its own cells go), an own one goesfn restore_row(&mut self, sheet: SheetRef, sk: SecKey, key: RowKey) -> Result<(), EditError>remove the Del="1" mark of an inherited row: it is inherited againfn set_user(&mut self, sheet: SheetRef, name: &str, value: Value, unit: Option<Unit>) -> Result<(), EditError>set a user-defined cell (User.<name>.Value) to a constant, adding the row when missingfn set_user_formula(&mut self, sheet: SheetRef, name: &str, formula: &str) -> Result<(), EditError>give a user-defined cell a formula, adding the row when missingfn set_shape_data(&mut self, sheet: SheetRef, name: &str, label: &str, value: Value) -> Result<(), EditError>set a shape data field (Prop.<name>): its label and value, adding the row when missingfn set_hyperlink(&mut self, sheet: SheetRef, name: &str, address: &str, sub_address: &str, description: &str) -> Result<(), EditError>add or change a hyperlink (Hyperlink.<name>): address, sub-address, descriptionfn add_layer(&mut self, page: PageRef, name: &str, name_univ: &str) -> Result<u32, EditError>add a layer to a page -> its index; visible, printed, snapping and gluing, not lockedfn set_layers(&mut self, shape: ShapeRef, layers: &[u32]) -> Result<(), EditError>put a shape on these layers (LayerMember; empty: on none)fn delete_layer(&mut self, page: PageRef, ix: u32) -> Result<(), EditError>delete a layer of a page; shapes on it leave it (their own LayerMember cells), the shapes themselves stay (LY-04 asks the user first and deletes them before). The layers after it move one down (IX - 1, as Visio keeps a page's layers numbered without gaps) and the shapes' own LayerMember cells followfn add_shape(&mut self, owner: Owner, parent: Option<ShapeRef>, kind: ShapeKind) -> Result<ShapeRef, EditError>add an empty shape on a page or in a master, on top of its siblings -> its handle; a parent that is not a group becomes onefn add_shape_with(&mut self, owner: Owner, parent: Option<ShapeRef>, data: ShapeData) -> Result<ShapeRef, EditError>add a shape with its attributes and cells (the ID is the tree's next one)fn add_instance(&mut self, owner: Owner, master: MasterRef, pin_x: f64, pin_y: f64) -> Result<ShapeRef, EditError>drop an instance of a master on a page (MS-02): a shape that inherits everything from the master shape and sets only its pin, with subshapes for the master's subshapes -> the instance; its Name is the caller's (LG-04: the name in the current language)fn delete_shape(&mut self, shape: ShapeRef) -> Result<(), EditError>delete a shape with its subshapes and the glue records of them; a subshape the master passes on gets a Del="1" mark insteadfn delete_shapes(&mut self, shapes: &[ShapeRef]) -> Result<(), EditError>delete several shapes in one go (a selection): the glue records are searched once, not once per shape; shapes inside another one of the list go with it. The master shape of a master in use cannot be deleted (InUse: its instances would inherit from another shape)fn undelete_shape(&mut self, shape: ShapeRef) -> Result<(), EditError>bring a deleted subshape of an instance back (remove its Del="1" mark)fn move_shape(&mut self, shape: ShapeRef, parent: Option<ShapeRef>, pos: Option<usize>) -> Result<(), EditError>move a shape in the z-order or into another group of the same tree: underparent(None: top level) atpos(None: on top); a parent that is not a group becomes one. Coordinates stay as they are (re-grouping with transforms is the canvas's work, JD7)fn bring_to_front(&mut self, shape: ShapeRef) -> Result<(), EditError>put a shape on top of its siblingsfn send_to_back(&mut self, shape: ShapeRef) -> Result<(), EditError>put a shape below its siblingsfn bring_forward(&mut self, shape: ShapeRef) -> Result<(), EditError>move a shape one step up among its siblingsfn send_backward(&mut self, shape: ShapeRef) -> Result<(), EditError>move a shape one step down among its siblingsfn set_shape_names(&mut self, shape: ShapeRef, name: Option<&str>, name_u: Option<&str>) -> Result<(), EditError>set a shape's Name and NameU (None: derived again)fn set_shape_styles(&mut self, shape: ShapeRef, styles: StyleRefs) -> Result<(), EditError>set the styles a shape inherits from (LineStyle, FillStyle, TextStyle)fn set_shape_header(&mut self, shape: ShapeRef, header: ShapeHeader) -> Result<(), EditError>set a shape's attributes as a whole (kind, names, references)fn set_text(&mut self, shape: ShapeRef, text: Option<Text>) -> Result<(), EditError>set a shape's own text (None: inherited from the master shape again)fn add_part(&mut self, name: &str, content_type: &str, rel_type: &str, data: Vec<u8>) -> Result<usize, EditError>add a part the model keeps as bytes (a picture's media part) at the end of Document::parts -> its index; a name some part has already (ASCII case ignored, a leading '/' too) is refused (Exists)fn remove_part(&mut self, index: usize) -> Result<(), EditError>remove the part atindexof Document::parts (shapes that name it show no picture)fn set_data(&mut self, data: crate::data::DataSets) -> Result<(), EditError>(JD18) replace the document's external data (data.rs builds the new value; one step keeps the old value for undo, the cached rows are shared, not copied)fn set_foreign(&mut self, shape: ShapeRef, foreign: Option<ForeignData>) -> Result<(), EditError>set the picture data of a Foreign shapefn add_connect(&mut self, owner: Owner, connect: Connect) -> Result<(), EditError>add a Connect entry on a page or in a masterfn remove_connect(&mut self, owner: Owner, index: usize) -> Result<(), EditError>remove the Connect entry atindexfn add_page(&mut self, name: &str, name_u: &str, background: bool, pos: Option<usize>) -> Result<PageRef, EditError>add a page (foreground or background) atposin document order (None: at the end) with the next free page ID -> its handlefn delete_page(&mut self, page: PageRef) -> Result<(), EditError>delete a page; pages that had it as background lose that background, TopPage moves to the first remaining foreground pagefn move_page(&mut self, page: PageRef, pos: usize) -> Result<(), EditError>move a page toposin document orderfn rename_page(&mut self, page: PageRef, name: &str, name_u: &str) -> Result<(), EditError>rename a page (Name and NameU)fn set_page_header(&mut self, page: PageRef, header: PageHeader) -> Result<(), EditError>set the page's attributes as a wholefn set_background(&mut self, page: PageRef, back: Option<PageRef>) -> Result<(), EditError>give a page a background page (None: none); the background must be a background page and the chain of backgrounds must not lead back to the pagefn set_page_theme(&mut self, page: PageRef, theme: Option<u32>) -> Result<(), EditError>set the theme of a page (an index into Document::themes, None: none)fn add_page_like(&mut self, like: PageRef, name: &str, name_u: &str, background: bool, pos: Option<usize>) -> Result<PageRef, EditError>add an empty page with the settings of pagelike(PG-03: Visio gives a new page the properties of the active page -- size, scale, units, print setup, layout and routing, background page, design): its page sheet without the Layer section (layers belong to a page's shapes), the styles of its PageSheet element, its theme; a foreground page keepslike's background page, a background page gets none. Atposin document order (None: the end) with the next free page ID -> its handlefn duplicate_page(&mut self, page: PageRef, name: &str, name_u: &str, pos: Option<usize>) -> Result<PageRef, EditError>a copy of a page with its shapes, glue records and settings (PG-03 Duplizieren) atposin document order (None: right after the original, as Visio's Page.Duplicate puts it) -> its handle. The shapes keep their IDs (IDs count per page), so formulas that name Sheet.N, the Connect entries and the Relationships of containers and lists stay inside the copy; UniqueIDs are dropped (each names one shape of the document), the copy gets the next free page ID, the names given (not marked as custom names) and a part of its own when it is written. Pages that use the original as their background keep itfn add_master(&mut self, name: &str, name_u: &str) -> Result<MasterRef, EditError>add an empty master with the next free master ID -> its handle (add shapes with add_shape(Owner::Master(..)))fn delete_master(&mut self, master: MasterRef) -> Result<(), EditError>delete a master that no shape uses (InUse otherwise)fn rename_master(&mut self, master: MasterRef, name: &str, name_u: &str) -> Result<(), EditError>rename a master (Name and NameU)fn set_master_header(&mut self, master: MasterRef, header: MasterHeader) -> Result<(), EditError>set the master's attributes as a wholefn add_style(&mut self, name: &str, name_u: &str, based_on: StyleRefs) -> Result<StyleRef, EditError>add a style with the next free style ID, based onbased_on-> its handlefn delete_style(&mut self, style: StyleRef) -> Result<(), EditError>delete a style nothing refers to (InUse otherwise)fn rename_style(&mut self, style: StyleRef, name: &str, name_u: &str) -> Result<(), EditError>rename a style (Name and NameU)fn set_based_on(&mut self, style: StyleRef, based_on: StyleRefs) -> Result<(), EditError>set the styles a style is based on (Cycle when a chain would lead back to it)fn update_settings(&mut self, f: impl FnOnce(&mut DocSettings)) -> Result<(), EditError>change the document settings (snap, glue, protection, default styles ...)fn set_themes(&mut self, themes: Vec<Theme>) -> Result<(), EditError>replace the document's theme parts (JD11: a design applied brings its part); pages keep their Page::theme indices, so a caller that removes a part fixes those first
impl Transaction<'_>
fn insert_row(&mut self, sheet: SheetRef, sk: SecKey, at: RowKey, kind: Option<&str>) -> Result<RowKey, EditError>insert a row of the sheet's own into an indexed section atat(an Index; past the last row: after it): the rows from there on move one down (IX + 1) and the references to them in the sheet's formulas follow; an inherited section is made the sheet's own first (see above) -> the key of the new row.kindis the row type (Geometry: "LineTo" ...)fn remove_row(&mut self, sheet: SheetRef, sk: SecKey, key: RowKey) -> Result<(), EditError>take a row out of an indexed section: the rows after it move one up (IX - 1), the references to them follow and references to the row itself become its values; an inherited section is made the sheet's own firstfn set_row_kind(&mut self, sheet: SheetRef, sk: SecKey, key: RowKey, kind: &str) -> Result<(), EditError>change the type (T) of a row the sheet has (Geometry: "MoveTo", "LineTo" ...); an inherited row gets an entry of the sheet's own that names the type