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, /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 := 50 ## 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 # ---------- 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]