TableTower/core/state_store.gd
RobinFiredrake 6a460d17eb Batch rolls join the Earlier list with one sound; longer history
Batches saved to the history file but never reached the tray's Earlier
list, and played no sound. Now each roll shows there as "Name (2 of 5)"
and the batch plays one roll sound. Earlier keeps 30 rolls (was 6) and
the saved history 200 (was 50).

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

237 lines
6.7 KiB
GDScript

class_name StateStore
extends RefCounted
## Local state that is never exported: Card mode decks, persistent variables,
## roll history and small settings. Everything is keyed by collection and table
## ids, so renaming a collection or table doesn't break it.
##
## Stored as one file, <root>/state/state.json. Mutators only mark the store
## dirty (cheap); call save() to write, which does nothing if nothing changed.
## Decks are opaque Dictionaries (whatever DeckState.to_dict() produces).
const FORMAT_VERSION := 1
const HISTORY_CAP := 200
## Folder that contains state/. Default user://.
var root: String
var _data: Dictionary = {}
var _loaded := false
var _dirty := false
func _init(p_root: String = "user://") -> void:
root = p_root
func state_path() -> String:
return root.path_join("state/state.json")
# ---------- Decks ----------
func get_deck(cid: String, tid: String) -> Dictionary:
var by_c: Dictionary = _section("decks").get(cid, {})
var d: Variant = by_c.get(tid, {})
return (d as Dictionary).duplicate(true) if d is Dictionary else {}
func set_deck(cid: String, tid: String, deck: Dictionary) -> void:
_bucket("decks", cid)[tid] = deck.duplicate(true)
_dirty = true
## Reshuffle: forgets the deck so the next draw starts a fresh one.
func clear_deck(cid: String, tid: String) -> void:
var by_c: Dictionary = _section("decks").get(cid, {})
if by_c.erase(tid):
_dirty = true
# ---------- Persistent variables ----------
# {name: {"value": Variant (int, float or String), "source": table_id}}
# Numbers stay numbers: JSON gives whole numbers back as floats, so they are
# turned back into ints here.
func get_variables(cid: String) -> Dictionary:
var v: Variant = _section("variables").get(cid, {})
if not (v is Dictionary):
return {}
var out := (v as Dictionary).duplicate(true)
for k: Variant in out:
var rec: Variant = out[k]
if rec is Dictionary and (rec as Dictionary).has("value"):
rec["value"] = Expr.normalize(rec["value"])
return out
func set_variable(cid: String, var_name: String, value: Variant, source: String = "") -> void:
if not (value is int or value is float or value is String):
value = str(value)
_bucket("variables", cid)[var_name] = {"value": value, "source": source}
_dirty = true
func clear_variable(cid: String, var_name: String) -> void:
var by_c: Dictionary = _section("variables").get(cid, {})
if by_c.erase(var_name):
_dirty = true
func clear_variables(cid: String) -> void:
if _section("variables").erase(cid):
_dirty = true
# ---------- History ----------
# One global list, most recent first, capped at HISTORY_CAP. Callers put a
# "collection" id in each record; get_history(cid) filters by it.
func add_history(record: Dictionary) -> void:
var list: Array = _section_list("history")
list.push_front(record.duplicate(true))
if list.size() > HISTORY_CAP:
list.resize(HISTORY_CAP)
_dirty = true
## All records, or only those whose "collection" is cid when cid isn't empty.
func get_history(cid: String = "") -> Array[Dictionary]:
var out: Array[Dictionary] = []
for r in _section_list("history"):
if r is Dictionary and (cid == "" or str((r as Dictionary).get("collection", "")) == cid):
out.append((r as Dictionary).duplicate(true))
return out
## Clears all history, or only a collection's records when cid isn't empty.
func clear_history(cid: String = "") -> void:
var list: Array = _section_list("history")
if cid == "":
list.clear()
else:
for i in range(list.size() - 1, -1, -1):
if list[i] is Dictionary and str((list[i] as Dictionary).get("collection", "")) == cid:
list.remove_at(i)
_dirty = true
# ---------- Settings ----------
func get_setting(key: String, default: Variant = null) -> Variant:
return _section("settings").get(key, default)
func set_setting(key: String, value: Variant) -> void:
var s := _section("settings")
if not s.has(key) or s[key] != value:
s[key] = value
_dirty = true
## How rules are shown (docs/PLAIN.md §5): "plain" (the default; Describe's
## phrases) or "text" (the stored rule text).
const RULES_VIEW := "rules_view"
const RULES_VIEWS: Array[String] = ["plain", "text"]
func rules_view() -> String:
var v := str(get_setting(RULES_VIEW, "plain"))
return v if RULES_VIEWS.has(v) else "plain"
## True when rules show in plain words.
func rules_plain() -> bool:
return rules_view() == "plain"
## Sets "plain" or "text" (anything else is ignored).
func set_rules_view(v: String) -> void:
if RULES_VIEWS.has(v):
set_setting(RULES_VIEW, v)
# ---------- Forgetting ----------
## Drops everything stored for a collection (decks, variables, its history).
func forget_collection(cid: String) -> void:
_section("decks").erase(cid)
_section("variables").erase(cid)
clear_history(cid)
if str(_section("settings").get("last_collection", "")) == cid:
_section("settings").erase("last_collection")
_dirty = true
## Drops a table's deck and the variables it set.
func forget_table(cid: String, tid: String) -> void:
clear_deck(cid, tid)
var vars: Dictionary = _section("variables").get(cid, {})
for k in vars.keys():
var v: Variant = vars[k]
if v is Dictionary and str((v as Dictionary).get("source", "")) == tid:
vars.erase(k)
_dirty = true
# ---------- Saving ----------
func is_dirty() -> bool:
return _dirty
## Writes the file if anything changed. Returns false only on a write error.
func save() -> bool:
if not _loaded or not _dirty:
return true
var out := _data.duplicate()
out["format_version"] = FORMAT_VERSION
var err := TowerBoard.write_text_atomic(state_path(), JSON.stringify(out, " "))
if err != OK:
push_warning("Couldn't save local state to %s: %s" % [state_path(), error_string(err)])
return false
_dirty = false
return true
## Re-reads the file, dropping unsaved changes. A corrupt file is moved aside to
## state.json.corrupt and the store starts empty.
func reload() -> void:
_loaded = true
_dirty = false
_data = {}
var path := state_path()
if not FileAccess.file_exists(path):
return
var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(path))
if parsed is Dictionary:
_data = parsed
return
push_warning("Local state file %s is unreadable; starting fresh (old copy kept as .corrupt)." % path)
DirAccess.rename_absolute(path, path + ".corrupt")
# ---------- Internals ----------
func _ensure() -> void:
if not _loaded:
reload()
func _section(key: String) -> Dictionary:
_ensure()
if not (_data.get(key) is Dictionary):
_data[key] = {}
return _data[key]
func _section_list(key: String) -> Array:
_ensure()
if not (_data.get(key) is Array):
_data[key] = []
return _data[key]
func _bucket(section: String, cid: String) -> Dictionary:
var s := _section(section)
if not (s.get(cid) is Dictionary):
s[cid] = {}
return s[cid]