TableTower/ui/edit_history.gd
2026-11-10 19:45:56 -06:00

354 lines
12 KiB
GDScript

class_name EditHistory
extends RefCounted
## Undo and redo for one collection's Build edits: a stack of whole-board
## snapshots each way, plus `cache`, the snapshot of the last committed state
## (the "before" of the next edit). Main keeps one per collection.
##
## A snapshot holds each table and group as its own compact JSON string, with
## the collapsed flags kept apart (collapsing is view state, not an edit; see
## restore). A table that didn't change shares its string with the snapshot
## before it (Godot strings are copy-on-write), so a step costs roughly the
## size of the cards it changed, not the whole board.
##
## Step labels come from diffing the snapshots on either side of the step
## (label_for), unless the caller gives one.
## Most steps kept, and roughly the most memory they may use between them.
const MAX_STEPS := 200
const MAX_BYTES := 48 * 1024 * 1024
## Edits to the same thing this close together become one step.
const COALESCE_SECS := 0.8
var undo_stack: Array[Dictionary] = [] # {snap, label, key, time, focus, serial}
var redo_stack: Array[Dictionary] = [] # {snap, label, serial}
var cache: Dictionary = {}
## How long the last capture took (microseconds), and its size in characters.
var last_capture_usec := 0
var _serial := 0
func _init(board: TowerBoard = null) -> void:
if board:
cache = capture(board)
func can_undo() -> bool:
return not undo_stack.is_empty()
func can_redo() -> bool:
return not redo_stack.is_empty()
func undo_label() -> String:
return str(undo_stack.back()["label"]) if can_undo() else ""
func redo_label() -> String:
return str(redo_stack.back()["label"]) if can_redo() else ""
## The serial of the newest undo step (-1 when there is none).
func top_serial() -> int:
return int(undo_stack.back()["serial"]) if can_undo() else -1
func clear() -> void:
undo_stack.clear()
redo_stack.clear()
## Takes the board as the new baseline. If it differs from the cached state
## (the collection was replaced from outside), the history no longer applies
## and is cleared.
func resync(board: TowerBoard) -> void:
var snap := capture(board, cache)
if cache.is_empty() or not is_empty_diff(diff(cache, snap)):
clear()
cache = snap
## Records the board's current state. Returns {step, merged, label, diff}:
## `step` is false when nothing undoable changed (only collapsing, or group
## frames refitting around their cards), in which case the baseline just
## catches up. Without a `label`, an edit to the same single thing as the
## newest step merges into it when it comes within COALESCE_SECS or from the
## same text field (`focus`, an instance id, 0 for none).
func commit(board: TowerBoard, label: String = "", focus: int = 0, now: float = -1.0) -> Dictionary:
if now < 0.0:
now = Time.get_ticks_msec() / 1000.0
var t0 := Time.get_ticks_usec()
var snap := capture(board, cache)
last_capture_usec = Time.get_ticks_usec() - t0
var d := diff(cache, snap)
if is_empty_diff(d):
# The old baseline goes, but strings it shared with the stacks stay
# with the new one: count them there.
snap["bytes"] = mini(int(snap["bytes"]) + int(cache.get("bytes", 0)), full_bytes(snap))
cache = snap
return {"step": false, "merged": false, "label": "", "diff": d}
var key := coalesce_key(cache, snap, d) if label == "" else ""
if key != "" and can_undo() and redo_stack.is_empty():
var top: Dictionary = undo_stack.back()
if str(top["key"]) == key and (now - float(top["time"]) < COALESCE_SECS or (focus != 0 and focus == int(top["focus"]))):
var d2 := diff(top["snap"], snap)
cache = snap
if is_empty_diff(d2):
# Typed and then put back: nothing left to undo.
undo_stack.pop_back()
return {"step": true, "merged": true, "label": "", "diff": d}
top["label"] = label_for(top["snap"], snap, d2)
top["time"] = now
top["focus"] = focus
return {"step": true, "merged": true, "label": top["label"], "diff": d}
redo_stack.clear()
_serial += 1
var lbl := label if label != "" else label_for(cache, snap, d)
undo_stack.push_back({"snap": cache, "label": lbl, "key": key, "time": now, "focus": focus, "serial": _serial})
cache = snap
_trim()
return {"step": true, "merged": false, "label": lbl, "diff": d}
## Pops the newest step for undoing: returns {snap (to restore), label, from
## (the state being left)} and moves the current state onto the redo stack.
## The caller restores `snap` and then sets `cache` (restore's result).
func pop_undo() -> Dictionary:
var e: Dictionary = undo_stack.pop_back()
redo_stack.push_back({"snap": cache, "label": e["label"], "serial": e["serial"]})
return {"snap": e["snap"], "label": e["label"], "from": cache}
func pop_redo() -> Dictionary:
var e: Dictionary = redo_stack.pop_back()
undo_stack.push_back({"snap": cache, "label": e["label"], "key": "", "time": 0.0, "focus": 0, "serial": e["serial"]})
return {"snap": e["snap"], "label": e["label"], "from": cache}
## Rough memory held by the stacks (unshared characters plus per-card overhead).
func bytes() -> int:
var n := 0
for e in undo_stack:
n += int(e["snap"].get("bytes", 0))
for e in redo_stack:
n += int(e["snap"].get("bytes", 0))
return n
func _trim() -> void:
while undo_stack.size() > MAX_STEPS:
undo_stack.pop_front()
var total := bytes()
while undo_stack.size() > 1 and total > MAX_BYTES:
total -= int(undo_stack[0]["snap"].get("bytes", 0))
undo_stack.pop_front()
# ---------- Snapshots ----------
## The board as {ids, tables, gids, groups, collapsed, bytes}. Strings equal
## to the ones in `prev` are shared with it; `bytes` counts the rest.
static func capture(board: TowerBoard, prev: Dictionary = {}) -> Dictionary:
var old_t := _strings_by_id(prev, "ids", "tables")
var old_g := _strings_by_id(prev, "gids", "groups")
var ids := PackedStringArray()
var tables := PackedStringArray()
var gids := PackedStringArray()
var groups := PackedStringArray()
var collapsed := {}
var n := 0
for t in board.tables:
var d := t.to_dict()
d.erase("collapsed")
var s := JSON.stringify(d)
var o: Variant = old_t.get(t.id)
if o != null and o == s:
s = o
else:
n += s.length()
ids.append(t.id)
tables.append(s)
if t.collapsed:
collapsed["t:" + t.id] = true
for g in board.groups:
var d := g.to_dict()
d.erase("collapsed")
var s := JSON.stringify(d)
var o: Variant = old_g.get(g.id)
if o != null and o == s:
s = o
else:
n += s.length()
gids.append(g.id)
groups.append(s)
if g.collapsed:
collapsed["g:" + g.id] = true
n += (ids.size() + gids.size()) * 16
var book := JSON.stringify(board.book_list())
if prev.get("book", "") == book:
book = prev["book"]
else:
n += book.length()
return {"ids": ids, "tables": tables, "gids": gids, "groups": groups, "collapsed": collapsed, "book": book, "bytes": n}
## A snapshot's size if it shared nothing.
static func full_bytes(snap: Dictionary) -> int:
var n := 0
for k in ["tables", "groups"]:
for s in (snap[k] as PackedStringArray):
n += s.length()
return n + ((snap["ids"] as PackedStringArray).size() + (snap["gids"] as PackedStringArray).size()) * 16
static func _strings_by_id(snap: Dictionary, ids_key: String, strs_key: String) -> Dictionary:
var out := {}
if snap.is_empty():
return out
var ids: PackedStringArray = snap[ids_key]
var strs: PackedStringArray = snap[strs_key]
for i in ids.size():
out[ids[i]] = strs[i]
return out
## Replaces the board's tables and groups with the snapshot's. Collapsing
## isn't undone: tables and groups that exist now keep their collapsed state;
## ones brought back take the state they had. The collection's id and name
## stay. Returns the snapshot with its collapsed flags as applied.
static func restore(board: TowerBoard, snap: Dictionary) -> Dictionary:
var now := {}
for t in board.tables:
now["t:" + t.id] = t.collapsed
for g in board.groups:
now["g:" + g.id] = g.collapsed
var was: Dictionary = snap["collapsed"]
var collapsed := {}
var tables: Array = []
var ids: PackedStringArray = snap["ids"]
var strs: PackedStringArray = snap["tables"]
for i in ids.size():
var d: Dictionary = JSON.parse_string(strs[i])
var k := "t:" + ids[i]
if (bool(now[k]) if now.has(k) else was.has(k)):
d["collapsed"] = true
collapsed[k] = true
tables.append(d)
var groups: Array = []
var gids: PackedStringArray = snap["gids"]
var gstrs: PackedStringArray = snap["groups"]
for i in gids.size():
var d: Dictionary = JSON.parse_string(gstrs[i])
var k := "g:" + gids[i]
if (bool(now[k]) if now.has(k) else was.has(k)):
d["collapsed"] = true
collapsed[k] = true
groups.append(d)
board.load_dict({"format_version": TowerBoard.FORMAT_VERSION, "tables": tables, "groups": groups,
"book": JSON.parse_string(str(snap.get("book", "[]")))})
var out := snap.duplicate()
out["collapsed"] = collapsed
return out
## Restores a snapshot by touching only what differs from `from` (the board's
## current snapshot): tables and groups whose text changed are updated in
## place, new ones are made and missing ones dropped, so every other object
## (and the card showing it) stays. Collapsed flags as in restore. Returns
## {snap (as restore), tables (ids updated in place), added, removed, groups
## (ids updated in place), groups_changed (true when any group came, went or
## changed more than its frame)}, or {} without a `from`.
static func patch(board: TowerBoard, snap: Dictionary, from: Dictionary) -> Dictionary:
if from.is_empty():
return {}
if str(snap.get("book", "[]")) != str(from.get("book", "[]")):
board.load_book(JSON.parse_string(str(snap.get("book", "[]"))))
var old_t := _strings_by_id(from, "ids", "tables")
var old_g := _strings_by_id(from, "gids", "groups")
var was: Dictionary = snap["collapsed"]
var collapsed := {}
var by_id := {}
for t in board.tables:
by_id[t.id] = t
var ids: PackedStringArray = snap["ids"]
var strs: PackedStringArray = snap["tables"]
var tables: Array[RollTable] = []
var updated: Array = []
var added: Array = []
for i in ids.size():
var t: RollTable = by_id.get(ids[i])
if t == null:
t = RollTable.from_dict(JSON.parse_string(strs[i]))
t.collapsed = was.has("t:" + ids[i])
added.append(t.id)
elif old_t.get(t.id) != strs[i]:
var fresh := RollTable.from_dict(JSON.parse_string(strs[i]))
fresh.collapsed = t.collapsed
_copy_fields(fresh, t)
updated.append(t.id)
by_id.erase(ids[i])
if t.collapsed:
collapsed["t:" + t.id] = true
tables.append(t)
var removed: Array = by_id.keys()
var gby_id := {}
for g in board.groups:
gby_id[g.id] = g
var gids: PackedStringArray = snap["gids"]
var gstrs: PackedStringArray = snap["groups"]
var groups: Array[TableGroup] = []
var gupdated: Array = []
var regroup := false
for i in gids.size():
var g: TableGroup = gby_id.get(gids[i])
if g == null:
g = TableGroup.from_dict(JSON.parse_string(gstrs[i]))
g.collapsed = was.has("g:" + gids[i])
regroup = true
elif old_g.get(g.id) != gstrs[i]:
var fresh := TableGroup.from_dict(JSON.parse_string(gstrs[i]))
fresh.collapsed = g.collapsed
if fresh.name != g.name or fresh.details != g.details or fresh.members != g.members or fresh.parent != g.parent:
regroup = true
_copy_fields(fresh, g)
gupdated.append(g.id)
gby_id.erase(gids[i])
if g.collapsed:
collapsed["g:" + g.id] = true
groups.append(g)
if not gby_id.is_empty():
regroup = true
board.tables = tables
board.groups = groups
var out := snap.duplicate()
out["collapsed"] = collapsed
return {"snap": out, "tables": updated, "added": added, "removed": removed, "groups": gupdated, "groups_changed": regroup}
## Copies every script variable of `src` onto `dst` (same class).
static func _copy_fields(src: Object, dst: Object) -> void:
for p: Dictionary in src.get_property_list():
if int(p["usage"]) & PROPERTY_USAGE_SCRIPT_VARIABLE:
dst.set(p["name"], src.get(p["name"]))
# ---------- Diffs and labels (see EditLabels) ----------
static func diff(a: Dictionary, b: Dictionary) -> Dictionary:
return EditLabels.diff(a, b)
static func is_empty_diff(d: Dictionary) -> bool:
return EditLabels.is_empty_diff(d)
static func touched_tables(d: Dictionary) -> Array:
return EditLabels.touched_tables(d)
static func coalesce_key(a: Dictionary, b: Dictionary, d: Dictionary) -> String:
return EditLabels.coalesce_key(a, b, d)
static func label_for(a: Dictionary, b: Dictionary, d: Dictionary = {}) -> String:
return EditLabels.label_for(a, b, d)