TableTower/ui/main_state.gd
RobinFiredrake 0202312688 Split ui/main.gd into area helpers (no behaviour change)
Main (3679 lines) becomes a shell: shared state, start-up, cards, input,
rules view and one-line delegators for the methods other files call. Each
area moves with its state into a RefCounted helper holding a back-reference
(m: Main):

  main_cli.gd          command-line and screenshot flags
  main_top_bar.gd      top bar, toast, endless-loop chip
  main_editing.gd      add/delete cards, results and pipes, selection bar
  main_groups.gd       groups and card drags
  main_templates.gd    templates
  main_rolling.gd      rolling, choice questions, playback, session seed, copy
  main_collections.gd  collections, import/export, table settings, test board
  main_state.gd        decks, variables, roll history (local state)
  main_navigation.gd   search, focus, minimap, arrange/pack
  main_history.gd      undo/redo and mark_dirty
  main_inspector.gd    inspector selection and refresh

Tests that reached moved private members now go through the helper
(main.undo_redo.edits, main.rolling.pending_choice(), ...).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:14:19 -06:00

255 lines
8.1 KiB
GDScript

class_name MainState
extends RefCounted
## Main's local state for the current collection: decks, persistent
## variables and roll history (StateStore), and the variable actions.
## Everything here is keyed by the current collection id (data.id). With saving
## disabled (--sample / --screenshot) `state` is null and it all stays in memory.
var m: Main
var _ref_cache: Dictionary = {} # entry text -> Array[String] of referenced table ids
func _init(p_main: Main) -> void:
m = p_main
## Loads the current collection's decks, persistent variables and roll history.
## Call it again after switching `data` to another collection (then rebuild the
## cards and call tray.render()).
func load_local_state() -> void:
m.decks = {}
m.persistent_vars = {}
m.history.clear()
m.current = {}
m.lit_entries.clear()
m.lit_pipes.clear()
m.lit_texts.clear()
_ref_cache.clear()
if m.state == null or m.data == null:
return
m.persistent_vars = m.state.get_variables(m.data.id)
for t in m.data.tables:
var d := m.state.get_deck(m.data.id, t.id)
if not d.is_empty():
m.decks[t.id] = DeckState.from_dict(d)
var recs := m.state.get_history(m.data.id)
for i in recs.size():
var rec: Dictionary = recs[i]
if not (rec.get("steps") is Array):
continue
rec["all"] = rec["steps"]
rec["done"] = true
if m.current.is_empty():
m.current = rec
elif m.history.size() < Main.HISTORY_SIZE:
rec["archived"] = true
m.history.append(rec)
## After a roll: saves the decks, any changed persistent variables and the
## history record.
func _store_roll(ctx: RollContext) -> void:
if m.state == null:
return
_store_decks()
if ctx.persistent_changed:
_store_variables()
m.state.add_history({"collection": m.data.id, "root": m.current["root"], "root_name": m.current["root_name"],
"time": m.current["time"], "steps": m.current["all"], "chain_vars": m.current.get("chain_vars", {})})
m.state.save()
func _store_decks() -> void:
if m.state == null:
return
for tid: String in m.decks:
m.state.set_deck(m.data.id, tid, (m.decks[tid] as DeckState).to_dict())
func _store_variables() -> void:
if m.state == null:
return
m.state.clear_variables(m.data.id)
for n: String in m.persistent_vars:
var v: Variant = m.persistent_vars[n]
if v is Dictionary:
m.state.set_variable(m.data.id, n, v.get("value", ""), str(v.get("source", "")))
else:
m.state.set_variable(m.data.id, n, str(v))
## A deleted table's deck and the variables it set are forgotten.
func forget_table_state(tid: String) -> void:
m.decks.erase(tid)
for n in m.persistent_vars.keys():
var v: Variant = m.persistent_vars[n]
if v is Dictionary and str(v.get("source", "")) == tid:
m.persistent_vars.erase(n)
if m.state:
m.state.forget_table(m.data.id, tid)
m.state.save()
if m.tray:
m.tray.render()
## Vector2i(cards left, total) for a card-mode table.
func cards_left(tid: String) -> Vector2i:
var t := m.data.get_table(tid)
if t == null:
return Vector2i.ZERO
var deck: DeckState = m.decks.get(tid)
return deck.cards_left(t) if deck else DeckState.new().cards_left(t)
func reshuffle_table(tid: String) -> void:
var t := m.data.get_table(tid)
if t == null:
return
m.decks.erase(tid)
if m.state:
m.state.clear_deck(m.data.id, tid)
m.state.save()
var card := m.card_for(tid)
if card:
card.update_deck()
m.toast("Reshuffled %s" % Formatter.strip_tags(t.name))
## The expanded text an entry showed in the last roll, or "" if it isn't lit.
func lit_text(tid: String, eid: String) -> String:
return str(m.lit_texts.get(Roller.entry_key(tid, eid), ""))
## Ids of the tables an entry's text references (cached until the next edit).
func ref_targets_for(e: TableEntry) -> Array[String]:
if not _ref_cache.has(e.text):
_ref_cache[e.text] = Roller.ref_targets(m.data, e.text)
return _ref_cache[e.text]
# ----- Variables -----
func set_variable(name: String, value: String) -> void:
var old: Variant = m.persistent_vars.get(name)
var source := str(old.get("source", "")) if old is Dictionary else ""
# A number stays a number when the new text is one too.
var was: Variant = old.get("value") if old is Dictionary else null
var card := variable_card(name)
if source == "" and card:
source = card.id
var as_number := Expr.is_number(was) or (card != null and card.var_type == "number")
var typed: Variant = Expr.to_value(value) if as_number and Expr.is_number(value) else value
m.persistent_vars[name] = {"value": typed, "source": source}
_variables_changed()
func clear_variable(name: String) -> void:
if not m.persistent_vars.erase(name):
return
_variables_changed()
m.toast("Cleared {@%s}" % name)
## The variable card declaring `name` (no "@"), or null.
func variable_card(name: String) -> RollTable:
for t in m.data.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name == name:
return t
return null
## Every board variable name: the set ones and the ones variable cards declare.
func variable_names() -> Array[String]:
var seen := {}
for n: String in m.persistent_vars:
seen[n] = true
for t in m.data.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "":
seen[t.var_name] = true
var out: Array[String] = []
for n: String in seen:
out.append(n)
out.sort_custom(func(a: String, b: String) -> bool: return a.naturalnocasecmp_to(b) < 0)
return out
## `reset @name`: a declared variable goes back to its starting value, an
## undeclared one is cleared.
func reset_variable(name: String) -> void:
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks)
var err := Effects.reset_one(name, ctx)
_variables_changed()
if err != "":
m.toast("Couldn't reset @%s: %s" % [name, err])
else:
var v: Variant = ctx.get_value("@" + name)
m.toast("Reset @%s%s" % [name, "" if v == null else " to " + Expr.format_value(v)])
## Resets every board variable (see reset_variable).
func reset_all_variables() -> void:
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks)
for n in variable_names():
Effects.reset_one(n, ctx)
_variables_changed()
m.toast("Reset every variable")
## Saves the variables and re-renders what shows them.
func _variables_changed() -> void:
_store_variables()
if m.state:
m.state.save()
m.refresh_live()
m.tray.render()
## Rolls the variable's source table again and saves the new result.
func reroll_variable(name: String) -> void:
var v: Variant = m.persistent_vars.get(name)
var source := str(v.get("source", "")) if v is Dictionary else ""
var t := m.data.get_table(source)
if t == null:
m.toast("{@%s} has no table to re-roll from" % name)
return
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks)
var n := Roller.roll(m.data, source, m.rng, 0, m.decks, ctx)
if n.is_empty() or n.has("stop"):
m.toast("Couldn't re-roll {@%s}: %s" % [name, Formatter.strip_tags(str(n.get("summary", "no result")))])
return
var value := Formatter.to_export_bbcode(str(n["summary"]))
m.persistent_vars[name] = {"value": value, "source": source}
_store_decks()
_store_variables()
if m.state:
m.state.save()
m._refresh_lit()
m.refresh_live()
m.tray.render()
m.toast("{@%s} is now %s" % [name, Formatter.strip_tags(value)])
## Re-rolling only makes sense for a text value a roll table gave (a pipe's
## "save as" or a {@var|Table}); numbers and logic-card values can't be.
func can_reroll_variable(name: String) -> bool:
var v: Variant = m.persistent_vars.get(name)
if not (v is Dictionary) or variable_card(name) != null:
return false
if Expr.is_number((v as Dictionary).get("value")):
return false
var t := m.data.get_table(str((v as Dictionary).get("source", "")))
return t != null and t.kind == RollTable.KIND_ROLL
## Sets a collection member's saved value (@<stem>_<item>), keeping numbers
## as numbers. Members are local values like the Variables panel's.
func set_collection_member(t: RollTable, item: String, value: String) -> void:
var n := "%s_%s" % [t.var_name, item]
m.persistent_vars[n] = {"value": Expr.to_value(value) if Expr.is_number(value) else value, "source": t.id}
_variables_changed()
func remove_collection_member(t: RollTable, item: String) -> void:
if m.persistent_vars.erase("%s_%s" % [t.var_name, item]):
_variables_changed()