Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.8

0.11.8 / src / history.luc

## Bounded undo history of immutable geometry plus copied editor graph state.
## A snapshot keeps the component selection too: selections are immutable
## luce-geocore objects, so keeping one costs a reference.
from network import Network
from luce_geocore.geocore import Selection

pub class Snapshot:
    pub let graph: Network
    pub let selection: Selection?
    pub let mode: int
    ## The faces hidden in the viewport (Hide), as selections are kept.
    pub let hidden: Selection?

    pub func init(self, graph: Network, selection: Selection?, mode: int, hidden: Selection? = none) -> unit!:
        self.graph = graph.copy()
        self.selection = selection
        self.mode = mode
        self.hidden = hidden

pub class Change:
    pub let label: str
    pub let before: Snapshot
    pub let after: Snapshot

    pub func init(self, label: str, before: Snapshot, after: Snapshot):
        self.label = label
        self.before = before
        self.after = after

pub class History:
    pub var changes: list[Change]
    pub var cursor: int = 0
    ## Counts changes to `changes` (what the held results it keeps alive
    ## depend on: Workspace.keep_held).
    pub var version: int = 0

    pub func init(self):
        self.changes = []

    pub func push(self, label: str, before: Snapshot, after: Snapshot):
        while self.changes.length > self.cursor:
            _ = self.changes.pop()
        self.changes.append(Change(label, before, after))
        self.version += 1
        if self.changes.length > 64:
            _ = self.changes.remove_at(0)
        self.cursor = self.changes.length

    ## Forget the changes before `count` (the oldest ones: a memory bound).
    pub func drop_before(self, count: int):
        if count <= 0:
            return
        let kept = count if count < self.changes.length else self.changes.length
        self.changes = self.changes[kept..]
        self.version += 1
        self.cursor = self.cursor - kept if self.cursor > kept else 0

    ## Fold the last change into the one before it, keeping that one's label
    ## (a tool's drag after the tool: one undo step).
    pub func merge_last(self):
        if self.cursor < 2 or self.cursor != self.changes.length:
            return
        let last = self.changes.pop()
        let earlier = self.changes.pop()
        self.version += 1
        self.changes.append(Change(earlier.label, earlier.before, last.after))
        self.cursor = self.changes.length

    pub func can_undo(self) -> bool:
        return self.cursor > 0
    pub func can_redo(self) -> bool:
        return self.cursor < self.changes.length
    pub func undo_label(self) -> str:
        return "Undo " + self.changes[self.cursor - 1].label if self.can_undo() else "Undo"
    pub func redo_label(self) -> str:
        return "Redo " + self.changes[self.cursor].label if self.can_redo() else "Redo"