TableTower/io/json_io.gd

380 lines
14 KiB
GDScript3
Raw Normal View History

class_name JsonIO
extends RefCounted
## JSON import and export of a collection, plus the shared helpers every other
## exporter uses. Everything works on plain collection Dictionaries (the JSON
## form), never on the model classes.
##
## Canonical collection form:
## {"format_version": 2, "id", "name", "tables": [table, ...], ["groups": [group, ...]]}
## group: id, name, x, y, w, h, [collapsed], [details], members (table ids)
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [dice_mod], [card_mode],
## [deck_empty], [kind], [choice], [prompt], [save_as], [options_from],
## [options_where], [min], [max],
## [loop], [loop_expr], [var_name], [var_type], [initial],
## [check_dice], [check_mod], [check_cmp], [check_target],
## [inputs: [{name, [label], [default]}, ...]], entries
## entry: id, text, [details], [weight], [range], [effects], [when], [show_if],
## [pipes]
## pipe: a table id String, or {"table": id, "count": n or "<expression>",
## "save_as": name, "when": "<expression>", "otherwise": true,
## "with": {input name: "<expression>"}}
## ("otherwise" is dropped when the pipe has a "when")
## The logic-card keys (docs/LOGIC.md §9) are Strings, and are left out when
## they have their default value.
const FORMAT_VERSION := 2
const _DICE_RE := "^\\s*(\\d+)\\s*[dD]\\s*(\\d+)\\s*$"
const _BBCODE_RE := "(?<!\\[)\\[/?[A-Za-z_]+(?:[= ][^\\]\\[]*)?\\](?!\\])"
const _REF_RE := "\\[\\[(.+?)\\]\\]"
# ---------------------------------------------------------------- export
## Pretty JSON text for a collection. Only known keys are written, so local
## state (card draws, variables, history) can never leak into an export.
static func export_json(collection: Dictionary) -> String:
return JSON.stringify(canonical(collection), " ", false)
## Returns {"ok": bool, "collection": Dictionary, "errors": Array[String],
## "warnings": Array[String]}. `sanitize` is called with every user-visible
## string (names, details, tags, entry text, variable names) and must return
## the cleaned string. The default leaves strings unchanged.
static func import_json(text: String, sanitize: Callable = Callable()) -> Dictionary:
var json := JSON.new()
var errors: Array[String] = []
var warnings: Array[String] = []
if json.parse(text) != OK:
errors.append("Not valid JSON (line %d): %s" % [json.get_error_line(), json.get_error_message()])
return {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
if not (json.data is Dictionary):
errors.append("The file is not a spread (expected a JSON object).")
return {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
return import_dict(json.data, sanitize)
## Validates and cleans an already-parsed collection (used by every importer).
## Gives tables and entries fresh ids where they are missing or collide, and
## keeps pipes pointing at the right tables. Same result shape as import_json.
static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Dictionary:
var errors: Array[String] = []
var warnings: Array[String] = []
var result := {"ok": false, "collection": {}, "errors": errors, "warnings": warnings}
var fv: Variant = _num(data.get("format_version", 1), 1)
if (fv is int or fv is float) and fv > FORMAT_VERSION:
errors.append("format_version %s is newer than this version supports (%d)." % [str(fv), FORMAT_VERSION])
if not (data.get("tables") is Array):
errors.append("The spread has no \"tables\" list.")
return result
var raw_tables: Array = data["tables"]
for ti in raw_tables.size():
var rt: Variant = raw_tables[ti]
if not (rt is Dictionary):
errors.append("Table #%d is not an object." % (ti + 1))
continue
var re_list: Variant = rt.get("entries", [])
if not (re_list is Array):
errors.append("Table #%d: \"entries\" is not a list." % (ti + 1))
continue
for ei in (re_list as Array).size():
var re: Variant = re_list[ei]
if not (re is Dictionary or re is String):
errors.append("Table #%d, entry #%d is not an object or text." % [ti + 1, ei + 1])
if not errors.is_empty():
return result
var c := canonical(data)
var clean := func(s: String) -> String:
if sanitize.is_null():
return s
return str(sanitize.call(s))
c["name"] = clean.call(str(c["name"]))
if str(c["name"]) == "":
c["name"] = "Untitled spread"
warnings.append("The spread had no name; called it \"Untitled spread\".")
if str(c["id"]) == "":
c["id"] = slug(str(c["name"]), "collection")
var tables: Array = c["tables"]
# Reserve the first occurrence of every given table id, then hand out new ones.
var used := {}
var id_map := {} # original id -> final id
var needs_id: Array[int] = []
for i in tables.size():
var t: Dictionary = tables[i]
var tid: String = t["id"]
if tid != "" and not used.has(tid):
used[tid] = true
id_map[tid] = tid
else:
needs_id.append(i)
for i in needs_id:
var t2: Dictionary = tables[i]
var old: String = t2["id"]
var fresh := unique_id(slug(str(t2["name"]), "table"), used)
if old != "":
warnings.append("Table id \"%s\" was used twice; \"%s\" is now \"%s\"." % [old, str(t2["name"]), fresh])
t2["id"] = fresh
var by_name := {}
for t3 in tables:
var key := str(t3["name"]).to_lower()
if not by_name.has(key):
by_name[key] = t3["id"]
for t4 in tables:
var t5: Dictionary = t4
t5["name"] = clean.call(str(t5["name"]))
if t5.has("details"):
t5["details"] = clean.call(str(t5["details"]))
for key in ["prompt", "initial"]:
if t5.has(key):
t5[key] = clean.call(str(t5[key]))
if t5.has("inputs"):
for inp: Dictionary in t5["inputs"]:
for key in ["name", "label", "default"]:
if inp.has(key):
inp[key] = clean.call(str(inp[key]))
if t5.has("tags"):
var tags: Array = []
for tag in t5["tags"]:
tags.append(clean.call(str(tag)))
t5["tags"] = tags
var elist: Array = t5["entries"]
# Entry ids only need to be unique within their table.
var seen := {}
var redo: Array[Dictionary] = []
for e in elist:
var eid: String = e["id"]
if eid == "" or seen.has(eid):
redo.append(e)
else:
seen[eid] = true
var enext := 1
for e1 in redo:
while seen.has("e%d" % enext):
enext += 1
e1["id"] = "e%d" % enext
seen[e1["id"]] = true
for e2 in elist:
var ed: Dictionary = e2
ed["text"] = clean.call(str(ed["text"]))
if ed.has("details"):
ed["details"] = clean.call(str(ed["details"]))
if ed.has("effects"):
ed["effects"] = clean.call(str(ed["effects"]))
if ed.has("when"):
ed["when"] = clean.call(str(ed["when"]))
if ed.has("show_if"):
ed["show_if"] = clean.call(str(ed["show_if"]))
if ed.has("range"):
var r: Array = ed["range"]
if int(r[0]) > int(r[1]):
warnings.append("\"%s\": range %d-%d is backwards; dropped." % [str(ed["text"]), int(r[0]), int(r[1])])
ed.erase("range")
if ed.has("pipes"):
var pipes: Array = []
for p in ed["pipes"]:
var info := pipe_info(p)
var target: String = info["table"]
if id_map.has(target):
target = id_map[target]
elif by_name.has(target.to_lower()):
target = by_name[target.to_lower()]
else:
warnings.append("\"%s\" threads to unknown table \"%s\"." % [str(ed["text"]), target])
if p is Dictionary:
var np: Dictionary = (p as Dictionary).duplicate()
np["table"] = target
if np.has("save_as"):
np["save_as"] = clean.call(str(np["save_as"]))
if np.has("when"):
np["when"] = clean.call(str(np["when"]))
if np.get("with") is Dictionary:
var wd := {}
for k: String in np["with"]:
wd[clean.call(k)] = clean.call(str(np["with"][k]))
np["with"] = wd
pipes.append(np)
else:
pipes.append(target)
ed["pipes"] = pipes
_import_groups(c, id_map, by_name, clean, warnings)
result["ok"] = true
result["collection"] = c
return result
## Groups on import: members follow renamed table ids (or match a table by
## name); unknown members are dropped, a table stays in its first group only,
## and group ids are made unique.
static func _import_groups(c: Dictionary, id_map: Dictionary, by_name: Dictionary, clean: Callable, warnings: Array[String]) -> void:
if not c.has("groups"):
return
var taken := {}
var gids := {}
for g: Dictionary in c["groups"]:
g["name"] = clean.call(str(g["name"]))
if g.has("details"):
g["details"] = clean.call(str(g["details"]))
var gid := str(g["id"])
if gid == "" or gids.has(gid):
gid = unique_id(slug(str(g["name"]), "group"), gids)
g["id"] = gid
else:
gids[gid] = true
var keep: Array = []
for m: String in g["members"]:
var target := ""
if id_map.has(m):
target = id_map[m]
elif by_name.has(m.to_lower()):
target = by_name[m.to_lower()]
if target == "":
warnings.append("Group \"%s\" lists unknown table \"%s\"; left out." % [str(g["name"]), m])
elif taken.has(target):
warnings.append("\"%s\" was in more than one group; kept in the first." % m)
else:
taken[target] = true
keep.append(target)
g["members"] = keep
# -------------------------------------------------------------- helpers
## Turns whole floats (as JSON parsing gives) into ints; returns `fallback`
## for anything that isn't a number.
static func _num(v: Variant, fallback: Variant) -> Variant:
if v is int:
return v
if v is float:
return int(v) if is_equal_approx(v, roundf(v)) else v
if v is String and (v as String).is_valid_float():
return _num((v as String).to_float(), fallback)
return fallback
## Lower-case identifier text: "Melee Weapons" -> "melee_weapons".
static func slug(text: String, fallback: String = "item") -> String:
var re := RegEx.create_from_string("[^a-z0-9]+")
var s := re.sub(text.to_lower(), "_", true)
s = s.trim_prefix("_").trim_suffix("_")
return s if s != "" else fallback
## `base`, or `base_2`, `base_3`... whichever isn't in `used`; marks it used.
static func unique_id(base: String, used: Dictionary) -> String:
var id := base
var n := 2
while used.has(id):
id = "%s_%d" % [base, n]
n += 1
used[id] = true
return id
## Normalizes a pipe (String or Dictionary) to {"table", "count", "save_as",
## "count_expr", "when", "otherwise", "with"} ("with": {name: expression},
## {} for none). An expression count ("@terms") reads as
## count 1, with the expression in "count_expr" ("" otherwise). "when" is the
## pipe's condition ("" for none); "otherwise" is true only without one.
static func pipe_info(p: Variant) -> Dictionary:
if p is Dictionary:
var c: Variant = p.get("count", 1)
var expr := ""
if c is String and _num(c, null) == null and (c as String).strip_edges() != "":
expr = (c as String).strip_edges()
var w := str(p.get("when", "")).strip_edges() if p.get("when") != null else ""
return {"table": str(p.get("table", "")), "count": int(_num(c, 1)), "save_as": str(p.get("save_as", "")), "count_expr": expr,
"when": w, "otherwise": w == "" and p.get("otherwise", false) is bool and bool(p.get("otherwise", false)),
"with": JsonCanon._canon_with(p.get("with"))}
return {"table": str(p), "count": 1, "save_as": "", "count_expr": "", "when": "", "otherwise": false, "with": {}}
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon"
## ("×@terms" for an expression count), led by "if <condition>" or
## "otherwise" on a conditional pipe ("if @str >= 8 ×2").
static func pipe_label(info: Dictionary) -> String:
var parts: Array[String] = []
if str(info.get("when", "")) != "":
parts.append("if " + str(info["when"]))
elif bool(info.get("otherwise", false)):
parts.append("otherwise")
if str(info.get("count_expr", "")) != "":
parts.append("×" + str(info["count_expr"]))
elif int(info["count"]) != 1:
parts.append("×%d" % int(info["count"]))
if str(info["save_as"]) != "":
parts.append("→ " + str(info["save_as"]))
var wv: Dictionary = info.get("with", {})
for k: String in wv:
parts.append("%s=%s" % [k, wv[k]])
return " ".join(parts)
## Removes BBCode tags such as [b] or [color=red]. `[[Table]]` references stay.
static func strip_bbcode(text: String) -> String:
return RegEx.create_from_string(_BBCODE_RE).sub(text, "", true)
## Inline references in entry text: Array of {"name", "var"}.
static func find_refs(text: String) -> Array[Dictionary]:
var out: Array[Dictionary] = []
for m in RegEx.create_from_string(_REF_RE).search_all(text):
var inner := m.get_string(1)
var parts := inner.split("->", true, 1)
var ref_name := parts[0].strip_edges()
if ref_name == "":
continue
out.append({"name": ref_name, "var": parts[1].strip_edges() if parts.size() > 1 else ""})
return out
## Highest value a dice string can roll ("1d100" -> 100, "2d6" -> 12); 0 if unparsable.
static func dice_max(dice: String) -> int:
var m := RegEx.create_from_string(_DICE_RE).search(dice)
if m == null:
return 0
return m.get_string(1).to_int() * m.get_string(2).to_int()
## Imports a converted collection (`raw`) and adds its warnings, errors and
## result to an importer's `result` ({ok, collection, errors, warnings, ...}).
static func finish_import(raw: Dictionary, sanitize: Callable, result: Dictionary) -> Dictionary:
var imported := import_dict(raw, sanitize)
(result["warnings"] as Array).append_array(imported["warnings"])
(result["errors"] as Array).append_array(imported["errors"])
result["ok"] = imported["ok"]
result["collection"] = imported["collection"]
return result
static func canonical(src: Dictionary) -> Dictionary:
return JsonCanon.canonical(src)
static func entry_line(e: Dictionary, dmax: int) -> String:
return JsonLinks.entry_line(e, dmax)
static func links(collection: Dictionary) -> Array[Dictionary]:
return JsonLinks.links(collection)
static func range_text(lo: int, hi: int, dmax: int) -> String:
return JsonLinks.range_text(lo, hi, dmax)
static func table_id_by_name(collection: Dictionary, table_name: String) -> String:
return JsonLinks.table_id_by_name(collection, table_name)
static func _canon_table(td: Dictionary) -> Dictionary:
return JsonCanon._canon_table(td)