Size audit: split MainLayout out of Main, EditLabels out of EditHistory

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
RobinFiredrake 2026-11-10 19:45:37 -06:00
parent b1525687ad
commit 97258b0d2b
6 changed files with 648 additions and 571 deletions

View file

@ -332,278 +332,23 @@ static func _copy_fields(src: Object, dst: Object) -> void:
dst.set(p["name"], src.get(p["name"]))
# ---------- Diffs and labels ----------
# ---------- Diffs and labels (see EditLabels) ----------
## 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")
out["book"] = str(a.get("book", "[]")) != str(b.get("book", "[]"))
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)
return EditLabels.diff(a, b)
static func is_empty_diff(d: Dictionary) -> bool:
if d.get("book", false):
return false
for k in ["added", "removed", "changed", "moved", "gadded", "gremoved", "gchanged", "gmoved_empty"]:
if not (d[k] as Array).is_empty():
return false
return true
return EditLabels.is_empty_diff(d)
## 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)
return EditLabels.touched_tables(d)
## 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 ""
return EditLabels.coalesce_key(a, b, d)
## 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)
if d.get("book", false) and (d["changed"] as Array).is_empty() and (d["added"] as Array).is_empty():
return "Edit the Book"
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) + "…"
return EditLabels.label_for(a, b, d)

278
ui/edit_labels.gd Normal file
View file

@ -0,0 +1,278 @@
class_name EditLabels
extends RefCounted
## Diffs between undo snapshots and the step labels derived from them.
## EditHistory keeps one-line delegators for the public functions.
## 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(EditHistory._strings_by_id(a, "ids", "tables"), EditHistory._strings_by_id(b, "ids", "tables"),
["x", "y"], out, "added", "removed", "changed", "moved")
_diff_lists(EditHistory._strings_by_id(a, "gids", "groups"), EditHistory._strings_by_id(b, "gids", "groups"),
["x", "y", "w", "h"], out, "gadded", "gremoved", "gchanged", "gmoved")
out["book"] = str(a.get("book", "[]")) != str(b.get("book", "[]"))
var gb := EditHistory._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:
if d.get("book", false):
return false
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)
if d.get("book", false) and (d["changed"] as Array).is_empty() and (d["added"] as Array).is_empty():
return "Edit the Book"
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) + "…"

1
ui/edit_labels.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://c2h6ltf4rrp7r

View file

@ -81,9 +81,10 @@ var nav: MainNavigation
var undo_redo: MainHistory
var inspecting: MainInspectorLink
var cli: MainCli
var layout: MainLayout
func _init() -> void:
layout = MainLayout.new(self)
top_bar = MainTopBar.new(self)
editing = MainEditing.new(self)
grouping = MainGroups.new(self)
@ -99,7 +100,6 @@ func _init() -> void:
demo = DemoMode.new(self)
prompt_hook = rolling._ask_player
func _ready() -> void:
rng.randomize()
# The project keeps its old internal name so the user:// folder (saved
@ -109,7 +109,7 @@ func _ready() -> void:
if args.has("--sample") or MainCli._arg_value(args, "--screenshot") != "":
_saving_enabled = false
if _saving_enabled:
_open_library()
layout._open_library()
if ThemeStore.carry_board != null:
if not _saving_enabled:
data = ThemeStore.carry_board
@ -122,7 +122,7 @@ func _ready() -> void:
data.id = "fantasy-loot"
data.name = "Fantasy Loot"
_build_ui()
layout._build_ui()
add_child(TouchInput.new(self))
if MobileLayout.wanted():
mobile = MobileLayout.new(self)
@ -135,237 +135,21 @@ func _ready() -> void:
board.fit()
cli._run_cli(args)
func _exit_tree() -> void:
_save_now()
## Migrates the old board.json if needed, then opens the last collection (or the
## first one, or a new "Fantasy Loot" made from the sample tables).
func _open_library() -> void:
state = StateStore.new()
library = LibraryStore.new("user://", state)
library.migrate_legacy()
var last := str(state.get_setting("last_collection", ""))
if last != "":
data = library.load_collection(last)
if data == null:
for entry in library.list():
data = library.load_collection(str(entry["id"]))
if data:
break
if data == null:
data = library.create("Fantasy Loot")
data.tables = SampleBoard.create().tables
library.save(data)
state.set_setting("last_collection", data.id)
func _save_now() -> void:
if _saving_enabled and data and library:
library.save(data)
state.set_setting("last_collection", data.id)
state.save()
# ---------- UI ----------
func _build_ui() -> void:
set_anchors_and_offsets_preset(PRESET_FULL_RECT)
var root := VBoxContainer.new()
root.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
root.add_theme_constant_override("separation", 0)
add_child(root)
root.add_child(top_bar._build_top_bar())
var middle := HBoxContainer.new()
middle.add_theme_constant_override("separation", 0)
middle.size_flags_vertical = SIZE_EXPAND_FILL
root.add_child(middle)
list_view = ListView.new()
list_view.setup(self)
var lside := PanelSplitter.new(self, false, "list_width", ListView.WIDTH, ListView.MIN_WIDTH)
lside.before = true
lside.size_changed.connect(list_view.set_width)
list_view.splitter = lside
list_view.set_width(lside.size_px)
middle.add_child(list_view)
middle.add_child(lside)
var list_on := state != null and bool(state.get_setting(ListView.SETTING, false))
list_view.visible = list_on
lside.visible = list_on
board = BoardView.new()
board.setup(self)
board.size_flags_horizontal = SIZE_EXPAND_FILL
middle.add_child(board)
book = BookPanel.new()
book.setup(self)
var bside := PanelSplitter.new(self, false, "book_width", BookPanel.WIDTH, 260.0)
bside.size_changed.connect(book.set_width)
book.splitter = bside
book.set_width(bside.size_px)
middle.add_child(bside)
middle.add_child(book)
var book_on := state != null and bool(state.get_setting(BookPanel.SETTING, false))
book.visible = book_on
bside.visible = book_on
inspector = Inspector.new()
inspector.setup(self)
inspector.visible = false
# Drag handles size the inspector and the tray (kept in local settings).
var side := PanelSplitter.new(self, false, "inspector_width", Inspector.WIDTH, Inspector.MIN_WIDTH)
side.size_changed.connect(inspector.set_width)
inspector.splitter = side
inspector.set_width(side.size_px)
middle.add_child(side)
if state and bool(state.get_setting("inspector_collapsed", false)):
inspector.set_collapsed(true)
middle.add_child(inspector)
inspector._sync_splitter()
editing._build_selection_bar()
tray = ResultTray.new()
tray.setup(self)
var foot := PanelSplitter.new(self, true, "tray_height", ResultTray.HEIGHT, ResultTray.MIN_HEIGHT)
foot.size_changed.connect(tray.set_height)
tray.set_height(foot.size_px)
root.add_child(foot)
root.add_child(tray)
top_bar._build_toast()
undo_redo._build_edit_timer()
_save_timer = Timer.new()
_save_timer.one_shot = true
_save_timer.wait_time = SAVE_DELAY
_save_timer.timeout.connect(func() -> void:
_save_now()
)
add_child(_save_timer)
resized.connect(top_bar._place_toast)
# ---------- Cards ----------
func card_for(id: String) -> TableCard:
return cards.get(id)
func is_entry_lit(tid: String, eid: String) -> bool:
return lit_entries.has(Roller.entry_key(tid, eid))
## Rebuilds every card. Cards hidden in collapsed groups aren't built at all
## (card_for gives null for them) until their group expands; see
## _apply_group_visibility. Called from outside an edit (a board loaded or
## replaced), it also takes the board as the edit history's new baseline.
func _rebuild_cards() -> void:
if not undo_redo._keep_history:
undo_redo._sync_history()
for c in board.cards.get_children():
board.cards.remove_child(c)
c.queue_free()
cards.clear()
selection.clear()
grouping._rebuild_groups()
editing._update_selection_bar()
# A board loaded or replaced starts with nothing in the inspector; an
# undo keeps the selection (the inspector follows the board).
if inspector and not undo_redo._keep_history:
inspector.clear()
elif inspector:
inspector.sync()
func _refresh_lit() -> void:
view_rev += 1
for card in cards.values():
(card as TableCard).refresh_lit()
grouping._refresh_group_lits()
if inspector:
inspector.sync()
func set_mode(m: Mode) -> void:
if m == Mode.BUILD and rolling._choice_waiting("Answer the waiting question before building"):
top_bar._build_button.set_pressed_no_signal(mode == Mode.BUILD)
top_bar._play_button.set_pressed_no_signal(mode == Mode.PLAY)
return
mode = m
top_bar._play_button.set_pressed_no_signal(m == Mode.PLAY)
top_bar._build_button.set_pressed_no_signal(m == Mode.BUILD)
# Build mode's bar is full of tools, so its hint moves into the tooltip;
# the (empty) label still stretches to push the right-hand buttons over.
top_bar._hint.text = HINTS[m] if m == Mode.PLAY else ""
top_bar._hint.tooltip_text = HINTS[m]
top_bar._hint.custom_minimum_size.x = 60.0 if m == Mode.PLAY else 0.0
top_bar._build_tools.visible = m == Mode.BUILD
board.pipes.hover_key = ""
clear_selection()
inspector.visible = m == Mode.BUILD
if m != Mode.BUILD:
inspector.clear()
for card in cards.values():
(card as TableCard).rebuild()
for n in grouping._group_nodes.values():
(n as GroupCard).rebuild()
top_bar._update_endless_chip()
nav._nav_mode_changed()
## What every change to the board needs: a save soon, fresh caches and redraws.
func _board_changed() -> void:
if _saving_enabled:
_save_timer.start()
local_state._ref_cache.clear()
view_rev += 1
edit_rev += 1
top_bar._schedule_endless_check()
if mode == Mode.BUILD:
refresh_live()
if inspector:
inspector.sync()
## True when an expanded group, or a table that isn't hidden in a collapsed
## group, could still be collapsed.
func _any_expanded() -> bool:
for g in data.groups:
if not g.collapsed:
return true
var hidden := hidden_groups()
for t in data.tables:
if not t.collapsed and not hidden.has(t.id):
return true
return false
# ---------- Collapsing ----------
func toggle_collapse(tid: String) -> void:
var t := data.get_table(tid)
if t == null:
return
t.collapsed = not t.collapsed
card_for(tid).rebuild()
mark_dirty("", false)
## Collapses or expands every table and every group.
func set_all_collapsed(collapsed: bool) -> void:
for t in data.tables:
if t.collapsed != collapsed:
t.collapsed = collapsed
var card := card_for(t.id)
if card:
card.rebuild()
var changed := false
for g in data.groups:
if g.collapsed != collapsed:
g.collapsed = collapsed
changed = true
if changed:
grouping._rebuild_groups()
mark_dirty("", false)
## Re-renders the live cards (variables, sheets, questions). Called after a
## roll, after variable edits and after edits in Build, never per frame, so
## dice inside {= } don't re-roll all the time.
@ -373,37 +157,9 @@ func refresh_live() -> void:
for card in cards.values():
(card as TableCard).refresh_live()
func _add_modal(d: ModalCard) -> void:
add_child(d)
## Opens the system file dialog; `on_path` gets the chosen path.
func file_dialog(title: String, filters: Array, mode: FileDialog.FileMode, on_path: Callable, file_name: String = "") -> void:
var dlg := FileDialog.new()
dlg.use_native_dialog = true
dlg.access = FileDialog.ACCESS_FILESYSTEM
dlg.file_mode = mode
dlg.title = title
dlg.filters = PackedStringArray(filters)
dlg.current_file = file_name
dlg.file_selected.connect(on_path)
dlg.visibility_changed.connect(func() -> void:
if not dlg.visible:
dlg.queue_free.call_deferred()
)
add_child(dlg)
dlg.popup_centered_ratio(0.6)
## A save dialog that writes `text_for.call()` to the chosen file and says how it went.
func export_dialog(title: String, filter: String, file_name: String, text_for: Callable) -> void:
file_dialog(title, [filter], FileDialog.FILE_MODE_SAVE_FILE, func(path: String) -> void:
var err := TowerBoard.write_text_atomic(path, str(text_for.call()))
toast("Exported to %s" % path.get_file() if err == OK else "Couldn't write %s" % path.get_file())
, file_name)
## The shared hover pop-up for details.
func details() -> DetailsPopup:
if _details_popup == null:
@ -412,75 +168,13 @@ func details() -> DetailsPopup:
_details_popup.setup(self)
return _details_popup
# ---------- Input ----------
func _shortcut_input(ev: InputEvent) -> void:
var k := ev as InputEventKey
if k == null or not k.pressed:
return
if undo_redo._history_shortcut(k):
get_viewport().set_input_as_handled()
return
if k.echo:
return
if k.keycode == KEY_F and (k.ctrl_pressed or k.meta_pressed) and not k.alt_pressed:
nav.open_search()
get_viewport().set_input_as_handled()
elif k.keycode == KEY_M and not (k.ctrl_pressed or k.meta_pressed or k.alt_pressed or k.shift_pressed):
var f := get_viewport().gui_get_focus_owner()
if f is LineEdit or f is TextEdit:
return
nav.set_minimap_visible(not board.minimap.visible, true)
get_viewport().set_input_as_handled()
elif k.keycode == KEY_F1:
top_bar.help_menu.open()
get_viewport().set_input_as_handled()
func _unhandled_input(ev: InputEvent) -> void:
var k := ev as InputEventKey
if k == null or not k.pressed or k.echo or mode != Mode.BUILD:
return
if k.keycode == KEY_G and (k.ctrl_pressed or k.meta_pressed):
grouping.group_selection()
get_viewport().set_input_as_handled()
elif k.keycode == KEY_ESCAPE and not selection.is_empty():
clear_selection()
get_viewport().set_input_as_handled()
# ---------- Rules view (docs/PLAIN.md §6) ----------
## When there's no `state` (--sample), the rules view lives here.
var _rules_view_mem := "plain"
## "plain" (Describe's phrases) or "text" (the stored rule text).
func rules_view() -> String:
return state.rules_view() if state else _rules_view_mem
func rules_plain() -> bool:
return rules_view() == "plain"
## Shows rules as "plain" words or as "text"; saved as a setting. Emits
## rules_view_changed when it changes.
func set_rules_view(v: String) -> void:
if v != "plain" and v != "text":
return
if v == rules_view():
return
if state:
state.set_rules_view(v)
state.save()
_rules_view_mem = v
if inspector:
inspector.rebuild()
rules_view_changed.emit(v)
# ---------- Delegators: what other files call on Main ----------
func toast(message: String, undoable: bool = false) -> void:
@ -665,3 +359,52 @@ func inspector_selection() -> Dictionary:
func inspector_edited(tid: String, all_cards: bool = false) -> void:
inspecting.inspector_edited(tid, all_cards)
# ---------- Delegators to MainLayout ----------
func _save_now() -> void:
layout._save_now()
func _rebuild_cards() -> void:
layout._rebuild_cards()
func _refresh_lit() -> void:
layout._refresh_lit()
func set_mode(m: Mode) -> void:
layout.set_mode(m)
func _board_changed() -> void:
layout._board_changed()
func _any_expanded() -> bool:
return layout._any_expanded()
func toggle_collapse(tid: String) -> void:
layout.toggle_collapse(tid)
func set_all_collapsed(collapsed: bool) -> void:
layout.set_all_collapsed(collapsed)
## Opens the system file dialog; `on_path` gets the chosen path.
func file_dialog(title: String, filters: Array, mode: FileDialog.FileMode, on_path: Callable, file_name: String = "") -> void:
layout.file_dialog(title, filters, mode, on_path, file_name)
func export_dialog(title: String, filter: String, file_name: String, text_for: Callable) -> void:
layout.export_dialog(title, filter, file_name, text_for)
## "plain" (Describe's phrases) or "text" (the stored rule text).
func rules_view() -> String:
return layout.rules_view()
func rules_plain() -> bool:
return layout.rules_plain()
func set_rules_view(v: String) -> void:
layout.set_rules_view(v)
func _shortcut_input(ev: InputEvent) -> void:
layout._shortcut_input(ev)
func _unhandled_input(ev: InputEvent) -> void:
layout._unhandled_input(ev)

309
ui/main_layout.gd Normal file
View file

@ -0,0 +1,309 @@
class_name MainLayout
extends RefCounted
## Main's window-level plumbing: building the UI, opening/saving the library,
## mode switching, card rebuilds, collapsing, dialogs, shortcuts and the rules view.
var m: Main
func _init(p_main: Main) -> void:
m = p_main
## Migrates the old board.json if needed, then opens the last collection (or the
## first one, or a new "Fantasy Loot" made from the sample tables).
func _open_library() -> void:
m.state = StateStore.new()
m.library = LibraryStore.new("user://", m.state)
m.library.migrate_legacy()
var last := str(m.state.get_setting("last_collection", ""))
if last != "":
m.data = m.library.load_collection(last)
if m.data == null:
for entry in m.library.list():
m.data = m.library.load_collection(str(entry["id"]))
if m.data:
break
if m.data == null:
m.data = m.library.create("Fantasy Loot")
m.data.tables = SampleBoard.create().tables
m.library.save(m.data)
m.state.set_setting("last_collection", m.data.id)
func _save_now() -> void:
if m._saving_enabled and m.data and m.library:
m.library.save(m.data)
m.state.set_setting("last_collection", m.data.id)
m.state.save()
func _build_ui() -> void:
m.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
var root := VBoxContainer.new()
root.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
root.add_theme_constant_override("separation", 0)
m.add_child(root)
root.add_child(m.top_bar._build_top_bar())
var middle := HBoxContainer.new()
middle.add_theme_constant_override("separation", 0)
middle.size_flags_vertical = Control.SIZE_EXPAND_FILL
root.add_child(middle)
m.list_view = ListView.new()
m.list_view.setup(m)
var lside := PanelSplitter.new(m, false, "list_width", ListView.WIDTH, ListView.MIN_WIDTH)
lside.before = true
lside.size_changed.connect(m.list_view.set_width)
m.list_view.splitter = lside
m.list_view.set_width(lside.size_px)
middle.add_child(m.list_view)
middle.add_child(lside)
var list_on := m.state != null and bool(m.state.get_setting(ListView.SETTING, false))
m.list_view.visible = list_on
lside.visible = list_on
m.board = BoardView.new()
m.board.setup(m)
m.board.size_flags_horizontal = Control.SIZE_EXPAND_FILL
middle.add_child(m.board)
m.book = BookPanel.new()
m.book.setup(m)
var bside := PanelSplitter.new(m, false, "book_width", BookPanel.WIDTH, 260.0)
bside.size_changed.connect(m.book.set_width)
m.book.splitter = bside
m.book.set_width(bside.size_px)
middle.add_child(bside)
middle.add_child(m.book)
var book_on := m.state != null and bool(m.state.get_setting(BookPanel.SETTING, false))
m.book.visible = book_on
bside.visible = book_on
m.inspector = Inspector.new()
m.inspector.setup(m)
m.inspector.visible = false
# Drag handles size the inspector and the tray (kept in local settings).
var side := PanelSplitter.new(m, false, "inspector_width", Inspector.WIDTH, Inspector.MIN_WIDTH)
side.size_changed.connect(m.inspector.set_width)
m.inspector.splitter = side
m.inspector.set_width(side.size_px)
middle.add_child(side)
if m.state and bool(m.state.get_setting("inspector_collapsed", false)):
m.inspector.set_collapsed(true)
middle.add_child(m.inspector)
m.inspector._sync_splitter()
m.editing._build_selection_bar()
m.tray = ResultTray.new()
m.tray.setup(m)
var foot := PanelSplitter.new(m, true, "tray_height", ResultTray.HEIGHT, ResultTray.MIN_HEIGHT)
foot.size_changed.connect(m.tray.set_height)
m.tray.set_height(foot.size_px)
root.add_child(foot)
root.add_child(m.tray)
m.top_bar._build_toast()
m.undo_redo._build_edit_timer()
m._save_timer = Timer.new()
m._save_timer.one_shot = true
m._save_timer.wait_time = Main.SAVE_DELAY
m._save_timer.timeout.connect(func() -> void:
m._save_now()
)
m.add_child(m._save_timer)
m.resized.connect(m.top_bar._place_toast)
## Rebuilds every card. Cards hidden in collapsed groups aren't built at all
## (card_for gives null for them) until their group expands; see
## _apply_group_visibility. Called from outside an edit (a board loaded or
## replaced), it also takes the board as the edit history's new baseline.
func _rebuild_cards() -> void:
if not m.undo_redo._keep_history:
m.undo_redo._sync_history()
for c in m.board.cards.get_children():
m.board.cards.remove_child(c)
c.queue_free()
m.cards.clear()
m.selection.clear()
m.grouping._rebuild_groups()
m.editing._update_selection_bar()
# A board loaded or replaced starts with nothing in the inspector; an
# undo keeps the selection (the inspector follows the board).
if m.inspector and not m.undo_redo._keep_history:
m.inspector.clear()
elif m.inspector:
m.inspector.sync()
func _refresh_lit() -> void:
m.view_rev += 1
for card in m.cards.values():
(card as TableCard).refresh_lit()
m.grouping._refresh_group_lits()
if m.inspector:
m.inspector.sync()
func set_mode(new_mode: Main.Mode) -> void:
if new_mode == Main.Mode.BUILD and m.rolling._choice_waiting("Answer the waiting question before building"):
m.top_bar._build_button.set_pressed_no_signal(m.mode == Main.Mode.BUILD)
m.top_bar._play_button.set_pressed_no_signal(m.mode == Main.Mode.PLAY)
return
m.mode = new_mode
m.top_bar._play_button.set_pressed_no_signal(new_mode == Main.Mode.PLAY)
m.top_bar._build_button.set_pressed_no_signal(new_mode == Main.Mode.BUILD)
# Build mode's bar is full of tools, so its hint moves into the tooltip;
# the (empty) label still stretches to push the right-hand buttons over.
m.top_bar._hint.text = Main.HINTS[new_mode] if new_mode == Main.Mode.PLAY else ""
m.top_bar._hint.tooltip_text = Main.HINTS[new_mode]
m.top_bar._hint.custom_minimum_size.x = 60.0 if new_mode == Main.Mode.PLAY else 0.0
m.top_bar._build_tools.visible = new_mode == Main.Mode.BUILD
m.board.pipes.hover_key = ""
m.clear_selection()
m.inspector.visible = new_mode == Main.Mode.BUILD
if new_mode != Main.Mode.BUILD:
m.inspector.clear()
for card in m.cards.values():
(card as TableCard).rebuild()
for n in m.grouping._group_nodes.values():
(n as GroupCard).rebuild()
m.top_bar._update_endless_chip()
m.nav._nav_mode_changed()
## What every change to the board needs: a save soon, fresh caches and redraws.
func _board_changed() -> void:
if m._saving_enabled:
m._save_timer.start()
m.local_state._ref_cache.clear()
m.view_rev += 1
m.edit_rev += 1
m.top_bar._schedule_endless_check()
if m.mode == Main.Mode.BUILD:
m.refresh_live()
if m.inspector:
m.inspector.sync()
## True when an expanded group, or a table that isn't hidden in a collapsed
## group, could still be collapsed.
func _any_expanded() -> bool:
for g in m.data.groups:
if not g.collapsed:
return true
var hidden := m.hidden_groups()
for t in m.data.tables:
if not t.collapsed and not hidden.has(t.id):
return true
return false
func toggle_collapse(tid: String) -> void:
var t := m.data.get_table(tid)
if t == null:
return
t.collapsed = not t.collapsed
m.card_for(tid).rebuild()
m.mark_dirty("", false)
## Collapses or expands every table and every group.
func set_all_collapsed(collapsed: bool) -> void:
for t in m.data.tables:
if t.collapsed != collapsed:
t.collapsed = collapsed
var card := m.card_for(t.id)
if card:
card.rebuild()
var changed := false
for g in m.data.groups:
if g.collapsed != collapsed:
g.collapsed = collapsed
changed = true
if changed:
m.grouping._rebuild_groups()
m.mark_dirty("", false)
## Opens the system file dialog; `on_path` gets the chosen path.
func file_dialog(title: String, filters: Array, mode: FileDialog.FileMode, on_path: Callable, file_name: String = "") -> void:
var dlg := FileDialog.new()
dlg.use_native_dialog = true
dlg.access = FileDialog.ACCESS_FILESYSTEM
dlg.file_mode = mode
dlg.title = title
dlg.filters = PackedStringArray(filters)
dlg.current_file = file_name
dlg.file_selected.connect(on_path)
dlg.visibility_changed.connect(func() -> void:
if not dlg.visible:
dlg.queue_free.call_deferred()
)
m.add_child(dlg)
dlg.popup_centered_ratio(0.6)
## A save dialog that writes `text_for.call()` to the chosen file and says how it went.
func export_dialog(title: String, filter: String, file_name: String, text_for: Callable) -> void:
file_dialog(title, [filter], FileDialog.FILE_MODE_SAVE_FILE, func(path: String) -> void:
var err := TowerBoard.write_text_atomic(path, str(text_for.call()))
m.toast("Exported to %s" % path.get_file() if err == OK else "Couldn't write %s" % path.get_file())
, file_name)
func _shortcut_input(ev: InputEvent) -> void:
var k := ev as InputEventKey
if k == null or not k.pressed:
return
if m.undo_redo._history_shortcut(k):
m.get_viewport().set_input_as_handled()
return
if k.echo:
return
if k.keycode == KEY_F and (k.ctrl_pressed or k.meta_pressed) and not k.alt_pressed:
m.nav.open_search()
m.get_viewport().set_input_as_handled()
elif k.keycode == KEY_M and not (k.ctrl_pressed or k.meta_pressed or k.alt_pressed or k.shift_pressed):
var f := m.get_viewport().gui_get_focus_owner()
if f is LineEdit or f is TextEdit:
return
m.nav.set_minimap_visible(not m.board.minimap.visible, true)
m.get_viewport().set_input_as_handled()
elif k.keycode == KEY_F1:
m.top_bar.help_menu.open()
m.get_viewport().set_input_as_handled()
func _unhandled_input(ev: InputEvent) -> void:
var k := ev as InputEventKey
if k == null or not k.pressed or k.echo or m.mode != Main.Mode.BUILD:
return
if k.keycode == KEY_G and (k.ctrl_pressed or k.meta_pressed):
m.grouping.group_selection()
m.get_viewport().set_input_as_handled()
elif k.keycode == KEY_ESCAPE and not m.selection.is_empty():
m.clear_selection()
m.get_viewport().set_input_as_handled()
## "plain" (Describe's phrases) or "text" (the stored rule text).
func rules_view() -> String:
return m.state.rules_view() if m.state else m._rules_view_mem
func rules_plain() -> bool:
return rules_view() == "plain"
## Shows rules as "plain" words or as "text"; saved as a setting. Emits
## rules_view_changed when it changes.
func set_rules_view(v: String) -> void:
if v != "plain" and v != "text":
return
if v == rules_view():
return
if m.state:
m.state.set_rules_view(v)
m.state.save()
m._rules_view_mem = v
if m.inspector:
m.inspector.rebuild()
m.rules_view_changed.emit(v)

1
ui/main_layout.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cex4q3o63nsar