TableTower/ui/edit_history.gd
RobinFiredrake ea1e7a6492 Rename to Table Tarot in the UI: spreads, threads, deck mode, branch, repeat
User-facing text only; code names, JSON keys and the project's internal
name (and so the user:// folder) are unchanged. The Collection card kind
keeps its name until a new one is chosen. The window title says Table
Tarot; the top bar shows the theme's logo (the fortune teller, drawn from a
copy of the art without its background square); the app icon is the
mascot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 18:24:23 -06:00

596 lines
22 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
return {"ids": ids, "tables": tables, "gids": gids, "groups": groups, "collapsed": collapsed, "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})
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 {}
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:
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 ----------
## What changed from snapshot a to b, by id: tables added, removed, changed
## (anything but position) and moved (position only); groups likewise, where
## gmoved (frame only) is ignored for groups with members, whose frames
## follow their cards.
static func diff(a: Dictionary, b: Dictionary) -> Dictionary:
var out := {"added": [], "removed": [], "changed": [], "moved": [],
"gadded": [], "gremoved": [], "gchanged": [], "gmoved": [], "gmoved_empty": []}
_diff_lists(_strings_by_id(a, "ids", "tables"), _strings_by_id(b, "ids", "tables"),
["x", "y"], out, "added", "removed", "changed", "moved")
_diff_lists(_strings_by_id(a, "gids", "groups"), _strings_by_id(b, "gids", "groups"),
["x", "y", "w", "h"], out, "gadded", "gremoved", "gchanged", "gmoved")
var gb := _strings_by_id(b, "gids", "groups")
for gid: String in out["gmoved"]:
var d: Variant = JSON.parse_string(gb[gid])
if d is Dictionary and (d.get("members", []) as Array).is_empty():
out["gmoved_empty"].append(gid)
return out
static func _diff_lists(ma: Dictionary, mb: Dictionary, geometry: Array, out: Dictionary,
k_add: String, k_rem: String, k_chg: String, k_mov: String) -> void:
for id: String in mb:
if not ma.has(id):
out[k_add].append(id)
elif ma[id] != mb[id]:
var da: Dictionary = JSON.parse_string(ma[id])
var db: Dictionary = JSON.parse_string(mb[id])
for g: String in geometry:
da.erase(g)
db.erase(g)
out[k_chg if da != db else k_mov].append(id)
for id: String in ma:
if not mb.has(id):
out[k_rem].append(id)
static func is_empty_diff(d: Dictionary) -> bool:
for k in ["added", "removed", "changed", "moved", "gadded", "gremoved", "gchanged", "gmoved_empty"]:
if not (d[k] as Array).is_empty():
return false
return true
## Table ids whose cards changed in any way (added, changed or moved).
static func touched_tables(d: Dictionary) -> Array:
return (d["added"] as Array) + (d["changed"] as Array) + (d["moved"] as Array)
## A key for edits that may merge with the step before: one table's or one
## group's fields (text, weight, pipe options...), with nothing added or taken
## away. "" for anything else.
static func coalesce_key(a: Dictionary, b: Dictionary, d: Dictionary) -> String:
for k in ["added", "removed", "moved", "gadded", "gremoved", "gmoved_empty"]:
if not (d[k] as Array).is_empty():
return ""
var ch: Array = d["changed"]
var gch: Array = d["gchanged"]
if ch.size() == 1 and gch.is_empty():
var ta: Dictionary = _parsed(a, "ids", "tables", ch[0])
var tb: Dictionary = _parsed(b, "ids", "tables", ch[0])
var e := _entry_changes(ta, tb)
if e["added"].is_empty() and e["removed"].is_empty() and e["pipes_added"].is_empty() and e["pipes_removed"].is_empty():
return "t:" + str(ch[0])
elif gch.size() == 1 and ch.is_empty():
var ga: Dictionary = _parsed(a, "gids", "groups", gch[0])
var gb: Dictionary = _parsed(b, "gids", "groups", gch[0])
if ga.get("members") == gb.get("members"):
return "g:" + str(gch[0])
return ""
## Describes the step from a to b ("Edit Loot", "Delete table Weapons", "Add
## pipe Loot → Gems", "Move 3 cards", "Group Careers"...).
static func label_for(a: Dictionary, b: Dictionary, d: Dictionary = {}) -> String:
if d.is_empty():
d = diff(a, b)
var added: Array = d["added"]
var removed: Array = d["removed"]
var gadded: Array = d["gadded"]
var gremoved: Array = d["gremoved"]
if not gadded.is_empty() and not added.is_empty():
return "Add %s" % _count(added.size(), "card")
if gadded.size() == 1:
return "Group %s" % _name(b, "gids", "groups", gadded[0])
if gremoved.size() == 1:
var gname := _name(a, "gids", "groups", gremoved[0])
return ("Delete group %s" if not removed.is_empty() else "Ungroup %s") % gname
if not gadded.is_empty() or not gremoved.is_empty():
return "Change groups"
if added.size() == 1:
return "Add %s %s" % [_kind_word(_parsed(b, "ids", "tables", added[0])), _name(b, "ids", "tables", added[0])]
if not added.is_empty():
return "Add %s" % _count(added.size(), "card")
if removed.size() == 1:
return "Delete %s %s" % [_kind_word(_parsed(a, "ids", "tables", removed[0])), _name(a, "ids", "tables", removed[0])]
if not removed.is_empty():
return "Delete %s" % _count(removed.size(), "card")
var changed: Array = d["changed"]
var gchanged: Array = d["gchanged"]
# Group membership (a card dragged into or out of a group).
for gid: String in gchanged:
var ga := _parsed(a, "gids", "groups", gid)
var gb := _parsed(b, "gids", "groups", gid)
var ma: Array = ga.get("members", [])
var mb: Array = gb.get("members", [])
if ma != mb:
var ins := 0
var outs := 0
for m: Variant in mb:
if not ma.has(m):
ins += 1
for m: Variant in ma:
if not mb.has(m):
outs += 1
var gname := Formatter.strip_tags(str(gb.get("name", "")))
if ins > 0 and outs == 0:
return "Add %s to group %s" % [_count(ins, "card"), gname]
if outs > 0 and ins == 0:
return "Take %s out of group %s" % [_count(outs, "card"), gname]
return "Change group %s" % gname
if changed.size() == 1:
return _table_label(_parsed(a, "ids", "tables", changed[0]), _parsed(b, "ids", "tables", changed[0]), b)
if changed.size() > 1:
return "Edit %s" % _count(changed.size(), "card")
if gchanged.size() == 1:
var ga := _parsed(a, "gids", "groups", gchanged[0])
var gb := _parsed(b, "gids", "groups", gchanged[0])
var gname := Formatter.strip_tags(str(gb.get("name", "")))
if ga.get("name") != gb.get("name"):
return "Rename group %s" % gname
return "Edit group %s" % gname
if gchanged.size() > 1:
return "Edit %s" % _count(gchanged.size(), "group")
var moved: Array = d["moved"]
if not moved.is_empty():
# All the moved cards belong to one group whose frame moved too.
for gid: String in d["gmoved"]:
var gb := _parsed(b, "gids", "groups", gid)
var members: Array = gb.get("members", [])
var all := true
for tid: Variant in moved:
if not members.has(tid):
all = false
break
if all and moved.size() == members.size():
return "Move group %s" % Formatter.strip_tags(str(gb.get("name", "")))
if moved.size() == 1:
return "Move %s" % _name(b, "ids", "tables", moved[0])
return "Move %s" % _count(moved.size(), "card")
if not (d["gmoved_empty"] as Array).is_empty():
return "Move group %s" % _name(b, "gids", "groups", d["gmoved_empty"][0])
return "Edit"
## One table's change: results added or deleted, pipes laid, removed or
## changed, a rename, a reorder, or a plain edit.
static func _table_label(ta: Dictionary, tb: Dictionary, b: Dictionary) -> String:
var tname := Formatter.strip_tags(str(tb.get("name", "")))
var e := _entry_changes(ta, tb)
if not e["added"].is_empty():
return ("Add result to %s" % tname) if e["added"].size() == 1 else "Add %d results to %s" % [e["added"].size(), tname]
if not e["removed"].is_empty():
if e["removed"].size() == 1:
return "Delete result “%s” from %s" % [_short(Formatter.strip_tags(str(e["removed"][0].get("text", "")))), tname]
return "Delete %d results from %s" % [e["removed"].size(), tname]
if not e["pipes_added"].is_empty():
return "Add thread %s → %s" % [tname, _name(b, "ids", "tables", e["pipes_added"][0])]
if not e["pipes_removed"].is_empty():
return "Delete thread %s → %s" % [tname, _name(b, "ids", "tables", e["pipes_removed"][0])]
if not e["pipes_changed"].is_empty():
return "Edit thread %s → %s" % [tname, _name(b, "ids", "tables", e["pipes_changed"][0])]
if ta.get("name") != tb.get("name"):
var rest_a := ta.duplicate()
var rest_b := tb.duplicate()
rest_a.erase("name")
rest_b.erase("name")
if rest_a == rest_b:
return "Rename %s → %s" % [Formatter.strip_tags(str(ta.get("name", ""))), tname]
if e["reordered"]:
return "Reorder %s" % tname
return "Edit %s" % tname
## Entries added and removed (dicts), pipe targets added, removed and changed,
## and whether the order changed.
static func _entry_changes(ta: Dictionary, tb: Dictionary) -> Dictionary:
var ea := {}
var order_a: Array = []
for x: Variant in ta.get("entries", []):
if x is Dictionary:
ea[str(x.get("id", ""))] = x
order_a.append(str(x.get("id", "")))
var eb := {}
var order_b: Array = []
for x: Variant in tb.get("entries", []):
if x is Dictionary:
eb[str(x.get("id", ""))] = x
order_b.append(str(x.get("id", "")))
var out := {"added": [], "removed": [], "pipes_added": [], "pipes_removed": [], "pipes_changed": [], "reordered": false}
for id: String in eb:
if not ea.has(id):
out["added"].append(eb[id])
for id: String in ea:
if not eb.has(id):
out["removed"].append(ea[id])
continue
var pa := _pipes(ea[id])
var pb := _pipes(eb[id])
for to: String in pb:
if not pa.has(to):
out["pipes_added"].append(to)
elif typeof(pa[to]) != typeof(pb[to]) or pa[to] != pb[to]:
out["pipes_changed"].append(to)
for to: String in pa:
if not pb.has(to):
out["pipes_removed"].append(to)
if out["added"].is_empty() and out["removed"].is_empty() and order_a != order_b:
out["reordered"] = true
return out
## target table id -> the pipe as written (an id or a dict of options).
static func _pipes(entry: Dictionary) -> Dictionary:
var out := {}
for p: Variant in entry.get("pipes", []):
if p is Dictionary:
out[str(p.get("table", ""))] = p
else:
out[str(p)] = p
return out
static func _parsed(snap: Dictionary, ids_key: String, strs_key: String, id: String) -> Dictionary:
var ids: PackedStringArray = snap[ids_key]
var i := ids.find(id)
if i < 0:
return {}
var v: Variant = JSON.parse_string((snap[strs_key] as PackedStringArray)[i])
return v if v is Dictionary else {}
static func _name(snap: Dictionary, ids_key: String, strs_key: String, id: String) -> String:
var d := _parsed(snap, ids_key, strs_key, id)
var n := Formatter.strip_tags(str(d.get("name", ""))).strip_edges()
return n if n != "" else id
static func _kind_word(d: Dictionary) -> String:
match str(d.get("kind", RollTable.KIND_ROLL)):
RollTable.KIND_CHOICE:
return "choice"
RollTable.KIND_LOOP:
return "loop"
RollTable.KIND_ROUTER:
return "router"
RollTable.KIND_VARIABLE:
return "variable"
RollTable.KIND_SHEET:
return "sheet"
return "table"
static func _count(n: int, noun: String) -> String:
return "%d %s%s" % [n, noun, "" if n == 1 else "s"]
static func _short(s: String) -> String:
return s if s.length() <= 28 else s.substr(0, 27) + "…"