TableTower/ui/main_state.gd
RobinFiredrake edb49fce27 Ledger entries are saved on the card and editable on the spread
The entries were only saved values of the spread, so copies, exports and
imports lost them. Now a Ledger card lists its entries (name and starting
value) in the spread file; current values stay saved values. Build mode
edits them on the card too. Older spreads take in the entries made on the
card when they open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:36:03 -06:00

318 lines
10 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()
m.lit_columns.clear()
_ref_cache.clear()
if m.data != null and m.state == null:
LedgerMembers.sync(m.data, m.persistent_vars)
if m.state == null or m.data == null:
return
m.persistent_vars = m.state.get_variables(m.data.id)
_sync_ledgers()
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)
var left := deck.cards_left(t) if deck else DeckState.new().cards_left(t)
# Draws of an animated roll count as still in the deck until they show.
left.x = mini(left.y, left.x + m.rolling.deck_reveal.held_total(tid))
return left
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("Shuffled %s" % Formatter.strip_tags(t.name))
## Shuffles every Deck-mode card back to full.
func reshuffle_all() -> void:
var n := 0
for t in m.data.tables:
if t.card_mode:
m.decks.erase(t.id)
if m.state:
m.state.clear_deck(m.data.id, t.id)
var card := m.card_for(t.id)
if card:
card.update_deck()
n += 1
if m.state:
m.state.save()
m.toast("Shuffled %d %s" % [n, "deck" if n == 1 else "decks"])
## 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
if card != null and card.is_scale():
typed = Scales.store(card.steps, 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")
## Older spreads: Ledger cards take in the entries kept only as saved values
## (and the spread is saved with them). Then every Ledger entry gets a saved
## value. See LedgerMembers.
func _sync_ledgers() -> void:
if LedgerMembers.adopt(m.data, m.persistent_vars) and m.library and m.state:
m.library.save(m.data)
if LedgerMembers.sync(m.data, m.persistent_vars):
_store_variables()
if m.state:
m.state.save()
## Saves the variables and re-renders what shows them.
func _variables_changed() -> void:
LedgerMembers.sync(m.data, m.persistent_vars)
_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()
# ---------- Striped rows ----------
const STRIPED_ROWS := "striped_rows"
## Used when saving is off (--sample / --screenshot) and `state` is null.
var _striped_mem := true
## True when every second result row on a card is tinted (on by default).
func striped_rows() -> bool:
return bool(m.state.get_setting(STRIPED_ROWS, true)) if m.state else _striped_mem
## Turns the stripes on or off, saves the choice and restyles every row.
func set_striped_rows(on: bool) -> void:
_striped_mem = on
if m.state:
m.state.set_setting(STRIPED_ROWS, on)
m.state.save()
for c: Variant in m.cards.values():
var card := c as TableCard
for eid: String in card.rows:
card.rows_ui.restate(eid)