Add import/export converters: JSON, JSON Canvas, Mermaid, DOT, GraphML

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
RobinFiredrake 2026-11-08 12:14:56 -06:00
parent 60c2d03147
commit cd4e13c85a
12 changed files with 1493 additions and 0 deletions

392
io/canvas_io.gd Normal file
View file

@ -0,0 +1,392 @@
class_name CanvasIO
extends RefCounted
## JSON Canvas 1.0 (jsoncanvas.org) export and import.
##
## Each table is a group node, each entry a text node inside it, each pipe an
## edge from the entry to the target group. Inline [[references]] become edges
## too, coloured and labelled "ref". TableTower's own data rides along in a
## "tabletower" object on nodes, so a round trip is exact; without it, import
## rebuilds what it can from the visible text and labels.
const GROUP_W := 340
const ENTRY_W := 300
const PAD := 20
const GAP := 10
const REF_COLOR := "6"
const _CHARS_PER_LINE := 34
const _RANGE_RE := "^\\s*(\\d+)\\s*[–—-]\\s*(\\d+)\\s*:\\s*(.*)$"
const _WEIGHT_RE := "^\\s*(\\d+(?:\\.\\d+)?)\\s*[×xX]\\s+(.*)$"
const _LABEL_RE := "^\\s*(?:[×xX]\\s*(\\d+))?\\s*(?:(?:→|->)\\s*(.*?))?\\s*$"
# ---------------------------------------------------------------- export
## JSON Canvas text for a collection Dictionary.
static func export_canvas(collection: Dictionary) -> String:
var c := JsonIO.canonical(collection)
var nodes: Array = []
var edges: Array = []
var group_ids := {} # table id -> node id
var entry_ids := {} # "tableid\tentryid" -> node id
var tables: Array = c["tables"]
for ti in tables.size():
var t: Dictionary = tables[ti]
var gid := "t%d" % ti
group_ids[t["id"]] = gid
var dmax := JsonIO.dice_max(str(t.get("dice", "")))
var y := int(t["y"]) + PAD
var x := int(t["x"]) + PAD
var entries: Array = t["entries"]
for ei in entries.size():
var e: Dictionary = entries[ei]
var text := _visible_text(e, dmax)
var h := _node_height(text)
var nid := "t%de%d" % [ti, ei]
entry_ids["%s\t%s" % [t["id"], e["id"]]] = nid
nodes.append({
"id": nid, "type": "text", "text": text,
"x": x, "y": y, "width": ENTRY_W, "height": h,
"tabletower": _entry_extra(e),
})
y += h + GAP
var group_h := maxi(y - int(t["y"]) + (PAD - GAP if not entries.is_empty() else 40), 80)
var extra := {"id": t["id"]}
for key in ["details", "tags", "dice", "card_mode", "deck_empty", "collapsed"]:
if t.has(key):
extra[key] = t[key]
nodes.push_front({
"id": gid, "type": "group", "label": t["name"],
"x": t["x"], "y": t["y"], "width": GROUP_W, "height": group_h,
"tabletower": extra,
})
# Groups first in the file so they draw underneath their entries.
var ordered: Array = []
for n in nodes:
if n["type"] == "group":
ordered.append(n)
ordered.reverse()
for n in nodes:
if n["type"] != "group":
ordered.append(n)
var edge_n := 0
for link in JsonIO.links(c):
var target := str(link["target"])
if target == "" or not group_ids.has(target):
continue
var from_id: String = entry_ids["%s\t%s" % [link["from_table"], link["from_entry"]]]
var edge := {
"id": "edge%d" % edge_n, "fromNode": from_id, "fromSide": "right",
"toNode": group_ids[target], "toSide": "left",
"tabletower": {"kind": link["kind"]},
}
if link["label"] != "":
edge["label"] = link["label"]
if link["kind"] == "ref":
edge["color"] = REF_COLOR
edges.append(edge)
edge_n += 1
var doc := {
"nodes": ordered, "edges": edges,
"tabletower": {"format_version": JsonIO.FORMAT_VERSION, "id": c["id"], "name": c["name"]},
}
return JSON.stringify(doc, "\t", false)
static func _entry_extra(e: Dictionary) -> Dictionary:
var extra := {"id": e["id"], "text": e["text"]}
for key in ["details", "weight", "range", "pipes"]:
if e.has(key):
extra[key] = e[key]
return extra
static func _visible_text(e: Dictionary, dmax: int) -> String:
var plain := JsonIO.strip_bbcode(str(e["text"]))
if e.has("range"):
var r: Array = e["range"]
return "%s: %s" % [JsonIO.range_text(int(r[0]), int(r[1]), dmax), plain]
var w: Variant = e.get("weight", 1)
if w != 1:
return "%s × %s" % [str(w), plain]
return plain
static func _node_height(text: String) -> int:
var lines := 0
for part in text.split("\n"):
lines += maxi(1, ceili(float(part.length()) / _CHARS_PER_LINE))
return 40 + 22 * (lines - 1)
# ---------------------------------------------------------------- import
## Returns {"ok": bool, "collection": Dictionary, "guesses": Array[String],
## "errors": Array[String], "warnings": Array[String]}. Collection ids and
## names fall back to defaults when the canvas has no TableTower data.
static func import_canvas(text: String, sanitize: Callable = Callable()) -> Dictionary:
var guesses: Array[String] = []
var errors: Array[String] = []
var warnings: Array[String] = []
var result := {"ok": false, "collection": {}, "guesses": guesses, "errors": errors, "warnings": warnings}
var json := JSON.new()
if json.parse(text) != OK:
errors.append("Not valid JSON (line %d): %s" % [json.get_error_line(), json.get_error_message()])
return result
if not (json.data is Dictionary):
errors.append("Not a JSON Canvas (expected an object with nodes and edges).")
return result
var doc: Dictionary = json.data
var raw_nodes: Variant = doc.get("nodes", [])
var raw_edges: Variant = doc.get("edges", [])
if not (raw_nodes is Array) or not (raw_edges is Array):
errors.append("Not a JSON Canvas (\"nodes\" and \"edges\" must be lists).")
return result
var groups: Array[Dictionary] = []
var texts: Array[Dictionary] = []
var skipped := 0
for n in raw_nodes:
if not (n is Dictionary) or not n.has("id"):
continue
var type := str(n.get("type", ""))
if type == "group":
groups.append(n)
elif type == "text":
texts.append(n)
else:
skipped += 1
if skipped > 0:
guesses.append("Ignored %d file/link node(s); only groups and text nodes become tables and entries." % skipped)
if groups.is_empty():
errors.append("The canvas has no group nodes, so there are no tables to import.")
return result
var doc_extra: Dictionary = doc.get("tabletower", {}) if doc.get("tabletower") is Dictionary else {}
var used := {}
var group_table := {} # group node id -> table dict
var tables: Array = []
var used_fallback_ids := false
for g in groups:
var extra: Dictionary = g.get("tabletower", {}) if g.get("tabletower") is Dictionary else {}
var t := {"x": int(JsonIO._num(g.get("x", 0), 0)), "y": int(JsonIO._num(g.get("y", 0), 0)), "entries": []}
var label := str(g.get("label", "")).strip_edges()
if label == "":
label = "Table %d" % (tables.size() + 1)
guesses.append("A group had no label; named it \"%s\"." % label)
t["name"] = label
var gid := str(extra.get("id", ""))
if gid == "" or used.has(gid):
gid = JsonIO.unique_id(JsonIO.slug(label, "table"), used)
used_fallback_ids = true
else:
used[gid] = true
t["id"] = gid
for key in ["details", "tags", "dice", "card_mode", "deck_empty", "collapsed"]:
if extra.has(key):
t[key] = extra[key]
t["_rich"] = not extra.is_empty()
group_table[str(g["id"])] = t
tables.append(t)
if used_fallback_ids:
guesses.append("Table ids were made up from the group labels.")
# Assign text nodes to the group containing their centre; reading order is top to bottom.
var sorted_texts := texts.duplicate()
var order := {}
for i in sorted_texts.size():
order[str(sorted_texts[i]["id"])] = i
sorted_texts.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
var ya := float(a.get("y", 0))
var yb := float(b.get("y", 0))
if ya != yb:
return ya < yb
var xa := float(a.get("x", 0))
var xb := float(b.get("x", 0))
if xa != xb:
return xa < xb
return order[str(a["id"])] < order[str(b["id"])])
var node_entry := {} # text node id -> {table, entry}
var loose := 0
for tn in sorted_texts:
var owner := _containing_group(tn, groups)
if owner.is_empty():
loose += 1
continue
var table: Dictionary = group_table[str(owner["id"])]
var entry := _entry_from_node(tn, table)
(table["entries"] as Array).append(entry)
node_entry[str(tn["id"])] = {"table": table, "entry": entry}
if loose > 0:
guesses.append("Ignored %d text node(s) that are not inside any group." % loose)
# Fallback structure for groups without TableTower data.
for t2 in tables:
if t2["_rich"]:
continue
_infer_dice(t2, guesses)
for t3 in tables:
t3.erase("_rich")
# Pipes from edges, only for entries that did not carry their own pipes.
var edge_pipes := 0
for ed in raw_edges:
if not (ed is Dictionary):
continue
var from_id := str(ed.get("fromNode", ""))
var to_id := str(ed.get("toNode", ""))
var edge_extra: Dictionary = ed.get("tabletower", {}) if ed.get("tabletower") is Dictionary else {}
var label2 := str(ed.get("label", "")).strip_edges()
if edge_extra.get("kind", "") == "ref" or _is_ref_label(label2):
continue # references come back from the entry text
if not node_entry.has(from_id):
continue
var holder: Dictionary = node_entry[from_id]
var entry2: Dictionary = holder["entry"]
if entry2.get("_has_pipes", false):
continue
var target := _edge_target_table(to_id, group_table, node_entry)
if target.is_empty():
continue
if not group_table.has(to_id):
guesses.append("An edge pointed at an entry; used its table \"%s\" instead." % str(target["name"]))
var pipe: Variant = _pipe_from_label(str(target["id"]), label2)
if not entry2.has("pipes"):
entry2["pipes"] = []
(entry2["pipes"] as Array).append(pipe)
edge_pipes += 1
for t4 in tables:
for e in t4["entries"]:
e.erase("_has_pipes")
if edge_pipes > 0:
guesses.append("Built %d pipe(s) from edges and their labels." % edge_pipes)
var raw := {
"format_version": JsonIO.FORMAT_VERSION,
"id": str(doc_extra.get("id", "")),
"name": str(doc_extra.get("name", "")),
"tables": tables,
}
if doc_extra.is_empty():
guesses.append("No collection name in the canvas; using a default.")
var imported := JsonIO.import_dict(raw, sanitize)
for w in imported["warnings"]:
warnings.append(w)
for er in imported["errors"]:
errors.append(er)
result["ok"] = imported["ok"]
result["collection"] = imported["collection"]
return result
static func _containing_group(node: Dictionary, groups: Array[Dictionary]) -> Dictionary:
var cx := float(node.get("x", 0)) + float(node.get("width", 0)) / 2.0
var cy := float(node.get("y", 0)) + float(node.get("height", 0)) / 2.0
var best: Dictionary = {}
var best_area := INF
for g in groups:
var gx := float(g.get("x", 0))
var gy := float(g.get("y", 0))
var gw := float(g.get("width", 0))
var gh := float(g.get("height", 0))
if cx >= gx and cx <= gx + gw and cy >= gy and cy <= gy + gh and gw * gh < best_area:
best = g
best_area = gw * gh
return best
## Builds an entry; uses the node's tabletower data when present, else parses its text.
static func _entry_from_node(tn: Dictionary, table: Dictionary) -> Dictionary:
var extra: Dictionary = tn.get("tabletower", {}) if tn.get("tabletower") is Dictionary else {}
if extra.has("text"):
var e := {"id": str(extra.get("id", "")), "text": str(extra["text"])}
for key in ["details", "weight", "range", "pipes"]:
if extra.has(key):
e[key] = extra[key]
e["_has_pipes"] = extra.has("pipes")
return e
var raw := str(tn.get("text", "")).strip_edges()
var e2 := {"id": "", "text": raw}
var m := RegEx.create_from_string(_RANGE_RE).search(raw)
if m != null:
e2["text"] = m.get_string(3).strip_edges()
e2["range"] = [m.get_string(1), m.get_string(2)] # raw digits, fixed up in _infer_dice
else:
var wm := RegEx.create_from_string(_WEIGHT_RE).search(raw)
if wm != null:
e2["text"] = wm.get_string(2).strip_edges()
e2["weight"] = JsonIO._num(wm.get_string(1).to_float(), 1)
e2["_has_pipes"] = false
return e2
## For tables rebuilt from text: fixes up range numbers ("00" wraps to the top
## of the die) and infers the dice from the highest range.
static func _infer_dice(t: Dictionary, guesses: Array[String]) -> void:
var ranged: Array = []
for e in t["entries"]:
if e.has("range") and e["range"][0] is String:
ranged.append(e)
if ranged.is_empty():
return
var top := 0
for e in ranged:
for v in e["range"]:
top = maxi(top, int(v))
var wrap := 10
while wrap < top:
wrap *= 10
var any_wrapped := false
for e in ranged:
var r: Array = e["range"]
var nums: Array = []
for v in r:
var s: String = v
var n := s.to_int()
if n == 0:
n = wrap
any_wrapped = true
nums.append(n)
e["range"] = nums
top = maxi(top, int(nums[1]))
if not t.has("dice"):
t["dice"] = "1d%d" % top
guesses.append("Table \"%s\": ranges found, so it is a ranged table; guessed dice 1d%d." % [str(t["name"]), top])
if any_wrapped:
guesses.append("Table \"%s\": read \"00\" as %d." % [str(t["name"]), wrap])
if ranged.size() < (t["entries"] as Array).size():
guesses.append("Table \"%s\": only some entries have ranges; the rest are kept without one." % str(t["name"]))
static func _is_ref_label(label: String) -> bool:
var l := label.to_lower()
return l == "ref" or l.begins_with("ref ") or l.begins_with("ref→")
static func _edge_target_table(to_id: String, group_table: Dictionary, node_entry: Dictionary) -> Dictionary:
if group_table.has(to_id):
return group_table[to_id]
if node_entry.has(to_id):
return node_entry[to_id]["table"]
return {}
## "×2 → weapon" -> {"table", "count": 2, "save_as": "weapon"}; "" -> plain table id.
static func _pipe_from_label(table_id: String, label: String) -> Variant:
if label == "":
return table_id
var m := RegEx.create_from_string(_LABEL_RE).search(label)
if m == null:
return table_id
var count := m.get_string(1).to_int() if m.get_string(1) != "" else 1
var save_as := m.get_string(2).strip_edges()
if count == 1 and save_as == "":
return table_id
var p := {"table": table_id}
if m.get_string(1) != "":
p["count"] = count
if save_as != "":
p["save_as"] = save_as
return p

1
io/canvas_io.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://ds3weqyiwglho

100
io/dot_exporter.gd Normal file
View file

@ -0,0 +1,100 @@
class_name DotExporter
extends RefCounted
## Graphviz DOT export. Each table is an HTML-like label listing its entries;
## pipes and inline [[references]] are edges from the entry's port to the
## target table (references are dashed). Import is not supported.
## Entries beyond this many are folded into one "... and N more" row, unless
## they have a connection.
const MAX_ROWS := 30
## DOT source for a collection Dictionary.
static func export_dot(collection: Dictionary) -> String:
var c := JsonIO.canonical(collection)
var out: Array[String] = []
out.append("digraph TableTower {")
out.append("\tlabel=\"%s\";" % escape_string(str(c["name"])))
out.append("\tlabelloc=t;")
out.append("\trankdir=LR;")
out.append("\tnode [shape=plain, fontname=\"Helvetica\"];")
out.append("\tedge [fontname=\"Helvetica\", fontsize=10];")
var tables: Array = c["tables"]
var node_of := {}
for i in tables.size():
node_of[tables[i]["id"]] = "t%d" % i
var links := JsonIO.links(c)
var linked := {} # "ti:ei" -> true
for link in links:
linked["%d:%d" % [link["table_index"], link["entry_index"]]] = true
for i in tables.size():
var t: Dictionary = tables[i]
var title := JsonIO.strip_bbcode(str(t["name"]))
if t.has("dice"):
title += " (%s)" % t["dice"]
var dmax := JsonIO.dice_max(str(t.get("dice", "")))
var rows: Array[String] = []
rows.append("<TR><TD PORT=\"head\" BGCOLOR=\"#dddddd\"><B>%s</B></TD></TR>" % escape_html(title))
var entries: Array = t["entries"]
var shown := 0
var hidden := 0
for ei in entries.size():
var e: Dictionary = entries[ei]
if shown >= MAX_ROWS and not linked.has("%d:%d" % [i, ei]):
hidden += 1
continue
shown += 1
rows.append("<TR><TD PORT=\"e%d\" ALIGN=\"LEFT\">%s</TD></TR>" % [ei, escape_html(_row_text(e, dmax))])
if hidden > 0:
rows.append("<TR><TD ALIGN=\"LEFT\"><I>… and %d more</I></TD></TR>" % hidden)
out.append("\t%s [label=<<TABLE BORDER=\"1\" CELLBORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"4\">%s</TABLE>>];" % [node_of[t["id"]], "".join(rows)])
var missing := {}
var edges: Array[String] = []
for link in links:
var target: String
if link["target"] != "":
target = "%s:head:w" % node_of[link["target"]]
else:
var key: String = str(link["target_name"]).to_lower()
if not missing.has(key):
missing[key] = {"id": "m%d" % missing.size(), "name": link["target_name"]}
target = "%s:w" % missing[key]["id"]
var from := "%s:e%d:e" % [node_of[link["from_table"]], link["entry_index"]]
var attrs: Array[String] = []
if link["label"] != "":
attrs.append("label=\"%s\"" % escape_string(str(link["label"])))
if link["kind"] == "ref":
attrs.append("style=dashed")
if link["target"] == "":
attrs.append("color=red")
edges.append("\t%s -> %s%s;" % [from, target, (" [" + ", ".join(attrs) + "]") if not attrs.is_empty() else ""])
for key in missing:
out.append("\t%s [label=\"%s\", shape=box, style=dashed, color=red, fontcolor=red];" % [missing[key]["id"], escape_string("missing: " + str(missing[key]["name"]))])
out.append_array(edges)
out.append("}")
return "\n".join(out) + "\n"
## Escapes text for a double-quoted DOT string.
static func escape_string(text: String) -> String:
return text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "").replace("\n", "\\n")
## Escapes text for an HTML-like DOT label.
static func escape_html(text: String) -> String:
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("\n", " ")
static func _row_text(e: Dictionary, dmax: int) -> String:
var plain := JsonIO.strip_bbcode(str(e["text"]))
if e.has("range"):
var r: Array = e["range"]
return "%s: %s" % [JsonIO.range_text(int(r[0]), int(r[1]), dmax), plain]
var w: Variant = e.get("weight", 1)
if w != 1:
return "%s × %s" % [str(w), plain]
return plain

1
io/dot_exporter.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://bnjvob7342dt6

245
io/graphml_io.gd Normal file
View file

@ -0,0 +1,245 @@
class_name GraphMLIO
extends RefCounted
## GraphML export and import. Tables are nodes, pipes and inline [[references]]
## are edges. TableTower fields are declared with <key> definitions, and each
## table node carries its entries as a JSON string, so a round trip is exact.
## Foreign GraphML (no entries data) imports as one table per node, with one
## entry per outgoing edge.
const _NS := "http://graphml.graphdrawing.org/xmlns"
# [attr.name, attr.type, applies to]
const _KEYS := [
["format_version", "int", "graph"],
["collection_id", "string", "graph"],
["collection_name", "string", "graph"],
["table_id", "string", "node"],
["name", "string", "node"],
["x", "int", "node"],
["y", "int", "node"],
["collapsed", "boolean", "node"],
["details", "string", "node"],
["tags", "string", "node"],
["dice", "string", "node"],
["card_mode", "string", "node"],
["deck_empty", "string", "node"],
["entries", "string", "node"],
["kind", "string", "edge"],
["label", "string", "edge"],
["entry", "string", "edge"],
["count", "int", "edge"],
["save_as", "string", "edge"],
]
# ---------------------------------------------------------------- export
## GraphML text for a collection Dictionary.
static func export_graphml(collection: Dictionary) -> String:
var c := JsonIO.canonical(collection)
var out: Array[String] = []
out.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
out.append("<graphml xmlns=\"%s\">" % _NS)
for k in _KEYS:
out.append("\t<key id=\"%s_%s\" for=\"%s\" attr.name=\"%s\" attr.type=\"%s\"/>" % [k[2], k[0], k[2], k[0], k[1]])
out.append("\t<graph id=\"G\" edgedefault=\"directed\">")
out.append(_data("graph", "format_version", str(c["format_version"]), 2))
out.append(_data("graph", "collection_id", str(c["id"]), 2))
out.append(_data("graph", "collection_name", str(c["name"]), 2))
var tables: Array = c["tables"]
var node_of := {}
for i in tables.size():
var t: Dictionary = tables[i]
node_of[t["id"]] = "n%d" % i
out.append("\t\t<node id=\"n%d\">" % i)
out.append(_data("node", "table_id", str(t["id"]), 3))
out.append(_data("node", "name", str(t["name"]), 3))
out.append(_data("node", "x", str(t["x"]), 3))
out.append(_data("node", "y", str(t["y"]), 3))
if t.has("collapsed"):
out.append(_data("node", "collapsed", "true", 3))
for key in ["details", "dice"]:
if t.has(key):
out.append(_data("node", key, str(t[key]), 3))
for key in ["tags", "card_mode", "deck_empty"]:
if t.has(key):
out.append(_data("node", key, JSON.stringify(t[key]), 3))
out.append(_data("node", "entries", JSON.stringify(t["entries"]), 3))
out.append("\t\t</node>")
var missing := {}
var edge_lines: Array[String] = []
var ei := 0
for link in JsonIO.links(c):
var target: String
if link["target"] != "":
target = node_of[link["target"]]
else:
var key2: String = str(link["target_name"]).to_lower()
if not missing.has(key2):
missing[key2] = {"id": "x%d" % missing.size(), "name": link["target_name"]}
target = missing[key2]["id"]
edge_lines.append("\t\t<edge id=\"e%d\" source=\"%s\" target=\"%s\">" % [ei, node_of[link["from_table"]], target])
edge_lines.append(_data("edge", "kind", str(link["kind"]), 3))
if link["label"] != "":
edge_lines.append(_data("edge", "label", str(link["label"]), 3))
edge_lines.append(_data("edge", "entry", str(link["from_entry"]), 3))
if link["kind"] == "pipe":
edge_lines.append(_data("edge", "count", str(link["count"]), 3))
if link["save_as"] != "":
edge_lines.append(_data("edge", "save_as", str(link["save_as"]), 3))
edge_lines.append("\t\t</edge>")
ei += 1
# Missing targets are kept visible as placeholder nodes without a table_id.
for key3 in missing:
out.append("\t\t<node id=\"%s\">" % missing[key3]["id"])
out.append(_data("node", "name", "missing: " + str(missing[key3]["name"]), 3))
out.append("\t\t</node>")
out.append_array(edge_lines)
out.append("\t</graph>")
out.append("</graphml>")
return "\n".join(out) + "\n"
static func _data(scope: String, attr: String, value: String, indent: int) -> String:
return "%s<data key=\"%s_%s\">%s</data>" % ["\t".repeat(indent), scope, attr, value.xml_escape(true)]
# ---------------------------------------------------------------- import
## Returns {"ok": bool, "collection": Dictionary, "guesses": Array[String],
## "errors": Array[String], "warnings": Array[String]}.
static func import_graphml(text: String, sanitize: Callable = Callable()) -> Dictionary:
var guesses: Array[String] = []
var errors: Array[String] = []
var warnings: Array[String] = []
var result := {"ok": false, "collection": {}, "guesses": guesses, "errors": errors, "warnings": warnings}
var key_name := {} # key id -> attr.name
var graph_data := {}
var nodes: Array[Dictionary] = [] # {"xml_id", "data"}
var edges: Array[Dictionary] = [] # {"source", "target", "data"}
var current: Dictionary = {}
var cur_key := ""
var cur_text := ""
var in_data := false
var depth_graph := 0
var saw_graphml := false
var p := XMLParser.new()
if p.open_buffer(text.to_utf8_buffer()) != OK:
errors.append("Couldn't read the XML.")
return result
while true:
var err := p.read()
if err == ERR_FILE_EOF:
break
if err != OK:
errors.append("The XML is malformed.")
return result
var t := p.get_node_type()
if t == XMLParser.NODE_ELEMENT:
var tag := p.get_node_name()
match tag:
"graphml":
saw_graphml = true
"key":
key_name[p.get_named_attribute_value_safe("id")] = p.get_named_attribute_value_safe("attr.name")
"graph":
depth_graph += 1
current = graph_data if depth_graph == 1 else current
"node":
current = {}
nodes.append({"xml_id": p.get_named_attribute_value_safe("id"), "data": current})
"edge":
current = {}
edges.append({"source": p.get_named_attribute_value_safe("source"), "target": p.get_named_attribute_value_safe("target"), "data": current})
"data":
cur_key = p.get_named_attribute_value_safe("key")
cur_text = ""
in_data = not p.is_empty()
if not in_data:
current[key_name.get(cur_key, cur_key)] = ""
elif t == XMLParser.NODE_TEXT or t == XMLParser.NODE_CDATA:
if in_data:
cur_text += p.get_node_data()
elif t == XMLParser.NODE_ELEMENT_END:
var etag := p.get_node_name()
if etag == "data" and in_data:
current[key_name.get(cur_key, cur_key)] = cur_text
in_data = false
elif etag == "node" or etag == "edge":
current = graph_data
if not saw_graphml:
errors.append("Not a GraphML file (no <graphml> element).")
return result
if nodes.is_empty():
errors.append("The GraphML file has no nodes.")
return result
var tables: Array = []
var used := {}
var xml_to_table := {} # xml node id -> table id
var rich := false
for n in nodes:
var d: Dictionary = n["data"]
if not d.has("table_id") and d.has("name") and str(d["name"]).begins_with("missing: ") and not d.has("entries"):
continue # placeholder for a pipe to a missing table
var tname := str(d.get("name", d.get("label", d.get("table_name", ""))))
if tname == "":
tname = str(n["xml_id"])
guesses.append("Node \"%s\" had no name; used its id." % tname)
var t2 := {"name": tname, "x": d.get("x", 0), "y": d.get("y", 0), "entries": []}
var tid := str(d.get("table_id", ""))
if tid == "" or used.has(tid):
tid = JsonIO.unique_id(JsonIO.slug(tname, "table"), used)
else:
used[tid] = true
t2["id"] = tid
xml_to_table[n["xml_id"]] = tid
if str(d.get("collapsed", "")) == "true":
t2["collapsed"] = true
for key in ["details", "dice"]:
if d.has(key) and str(d[key]) != "":
t2[key] = d[key]
for key in ["tags", "card_mode", "deck_empty"]:
if d.has(key):
var parsed: Variant = JSON.parse_string(str(d[key]))
t2[key] = parsed if parsed != null else d[key]
if d.has("entries"):
var ents: Variant = JSON.parse_string(str(d["entries"]))
if ents is Array:
t2["entries"] = ents
rich = true
else:
warnings.append("Table \"%s\": couldn't read its entries." % tname)
tables.append(t2)
if not rich:
guesses.append("No TableTower data in this file; each node became a table and each edge an entry with a pipe.")
var by_table := {}
for t3 in tables:
by_table[t3["id"]] = t3
for ed in edges:
if not xml_to_table.has(ed["source"]) or not xml_to_table.has(ed["target"]):
continue
var src: Dictionary = by_table[xml_to_table[ed["source"]]]
var ed_data: Dictionary = ed["data"]
var etext := str(ed_data.get("label", ed_data.get("name", "")))
if etext == "":
etext = "Go to " + str(by_table[xml_to_table[ed["target"]]]["name"])
(src["entries"] as Array).append({"text": etext, "pipes": [xml_to_table[ed["target"]]]})
var raw := {
"format_version": JsonIO.FORMAT_VERSION,
"id": str(graph_data.get("collection_id", "")),
"name": str(graph_data.get("collection_name", "")),
"tables": tables,
}
var imported := JsonIO.import_dict(raw, sanitize)
for w in imported["warnings"]:
warnings.append(w)
for er in imported["errors"]:
errors.append(er)
result["ok"] = imported["ok"]
result["collection"] = imported["collection"]
return result

1
io/graphml_io.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cwe1qbrqrqr1u

405
io/json_io.gd Normal file
View file

@ -0,0 +1,405 @@
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, ...]}
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
## [deck_empty], entries
## entry: id, text, [details], [weight], [range], [pipes]
## pipe: a table id String, or {"table": id, "count": n, "save_as": name}
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 collection (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 collection 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 collection"
warnings.append("The collection had no name; called it \"Untitled collection\".")
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"]))
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("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\" pipes 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"]))
pipes.append(np)
else:
pipes.append(target)
ed["pipes"] = pipes
result["ok"] = true
result["collection"] = c
return result
# ------------------------------------------------------------ canonical
## Normalizes a collection to format version 2: legacy keys are converted
## (`die` -> `dice`, `triggers` -> `pipes`, `collection` -> `name`), missing
## optional keys are tolerated and unknown keys are dropped.
static func canonical(src: Dictionary) -> Dictionary:
var tables: Array = []
var src_tables: Variant = src.get("tables", [])
if src_tables is Array:
for t in src_tables:
if t is Dictionary:
tables.append(_canon_table(t))
var cname := str(src.get("name", src.get("collection", "")))
return {"format_version": FORMAT_VERSION, "id": str(src.get("id", "")), "name": cname, "tables": tables}
static func _canon_table(td: Dictionary) -> Dictionary:
var t := {
"id": str(td.get("id", "")),
"name": str(td.get("name", "")),
"x": int(_num(td.get("x", 0), 0)),
"y": int(_num(td.get("y", 0), 0)),
}
if bool(td.get("collapsed", false)):
t["collapsed"] = true
var details := str(td.get("details", ""))
if details != "":
t["details"] = details
var tags: Array = []
var src_tags: Variant = td.get("tags", [])
if src_tags is Array:
for tag in src_tags:
tags.append(str(tag))
if not tags.is_empty():
t["tags"] = tags
var dice := str(td.get("dice", "")).strip_edges()
if dice == "" and td.has("die"):
var die: Variant = _num(td["die"], 0)
if (die is int or die is float) and die > 0:
dice = "1d%d" % int(die)
if dice != "":
t["dice"] = dice
for key in ["card_mode", "deck_empty"]:
var v: Variant = td.get(key)
if v != null and not (v is bool and not v) and not (v is String and v == ""):
t[key] = v
var entries: Array = []
var src_entries: Variant = td.get("entries", [])
if src_entries is Array:
for e in src_entries:
entries.append(_canon_entry(e))
t["entries"] = entries
return t
static func _canon_entry(ev: Variant) -> Dictionary:
if ev is String:
return {"id": "", "text": ev}
var ed: Dictionary = ev
var e := {"id": str(ed.get("id", "")), "text": str(ed.get("text", ""))}
var details := str(ed.get("details", ""))
if details != "":
e["details"] = details
var w: Variant = _num(ed.get("weight", 1), 1)
if (w is int or w is float) and w != 1:
e["weight"] = w
var r: Variant = ed.get("range")
if r is Array and (r as Array).size() == 2:
e["range"] = [int(_num(r[0], 0)), int(_num(r[1], 0))]
var src_pipes: Variant = ed.get("pipes", ed.get("triggers", []))
var pipes: Array = []
if src_pipes is Array:
for p in src_pipes:
if p is String and p != "":
pipes.append(p)
elif p is Dictionary and str(p.get("table", "")) != "":
var np := {"table": str(p["table"])}
if p.has("count"):
np["count"] = int(_num(p["count"], 1))
if str(p.get("save_as", "")) != "":
np["save_as"] = str(p["save_as"])
pipes.append(np)
if not pipes.is_empty():
e["pipes"] = pipes
return e
# -------------------------------------------------------------- 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"}.
static func pipe_info(p: Variant) -> Dictionary:
if p is Dictionary:
return {"table": str(p.get("table", "")), "count": int(_num(p.get("count", 1), 1)), "save_as": str(p.get("save_as", ""))}
return {"table": str(p), "count": 1, "save_as": ""}
## Edge label for a pipe: "" (plain), "×2", "→ weapon" or "×2 → weapon".
static func pipe_label(info: Dictionary) -> String:
var parts: Array[String] = []
if int(info["count"]) != 1:
parts.append("×%d" % int(info["count"]))
if str(info["save_as"]) != "":
parts.append("→ " + str(info["save_as"]))
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()
## Id of the table whose name matches (case-insensitive), or "".
static func table_id_by_name(collection: Dictionary, table_name: String) -> String:
var want := table_name.strip_edges().to_lower()
for t in collection.get("tables", []):
if str(t.get("name", "")).to_lower() == want:
return str(t.get("id", ""))
return ""
## Every connection in a collection, pipes and inline references, in
## table/entry order. Each item: kind ("pipe" or "ref"), table_index,
## entry_index, from_table, from_entry (ids), target (table id, or "" when the
## table is missing), target_name (as written), label, count, save_as,
## entry_text (BBCode stripped). Expects a canonical collection.
static func links(collection: Dictionary) -> Array[Dictionary]:
var out: Array[Dictionary] = []
var tables: Array = collection.get("tables", [])
var ids := {}
for t in tables:
ids[str(t["id"])] = true
for ti in tables.size():
var t2: Dictionary = tables[ti]
var elist: Array = t2.get("entries", [])
for ei in elist.size():
var e: Dictionary = elist[ei]
for p in e.get("pipes", []):
var info := pipe_info(p)
var tgt: String = info["table"]
out.append({
"kind": "pipe", "table_index": ti, "entry_index": ei,
"from_table": t2["id"], "from_entry": e["id"],
"target": tgt if ids.has(tgt) else "", "target_name": tgt,
"label": pipe_label(info), "count": info["count"], "save_as": info["save_as"],
"entry_text": strip_bbcode(str(e["text"])),
})
for ref in find_refs(str(e["text"])):
var rid := table_id_by_name(collection, ref["name"])
out.append({
"kind": "ref", "table_index": ti, "entry_index": ei,
"from_table": t2["id"], "from_entry": e["id"],
"target": rid, "target_name": ref["name"],
"label": ("ref → " + ref["var"]) if ref["var"] != "" else "ref",
"count": 1, "save_as": ref["var"],
"entry_text": strip_bbcode(str(e["text"])),
})
return out
## Display label for a table number range, zero padded; the top of a d100 or
## d1000 reads as zeros ("96–00").
static func range_text(lo: int, hi: int, dmax: int) -> String:
return "%s–%s" % [_num_text(lo, dmax), _num_text(hi, dmax)]
static func _num_text(n: int, dmax: int) -> String:
if dmax >= 100 and _is_power_of_ten(dmax):
if n == dmax:
return "0".repeat(str(dmax - 1).length())
return str(n).pad_zeros(str(dmax - 1).length())
return str(n).pad_zeros(str(maxi(dmax, 1)).length())
static func _is_power_of_ten(n: int) -> bool:
while n >= 10 and n % 10 == 0:
n /= 10
return n == 1

1
io/json_io.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cnxt27u466kyx

71
io/mermaid_exporter.gd Normal file
View file

@ -0,0 +1,71 @@
class_name MermaidExporter
extends RefCounted
## Mermaid flowchart export (renders in Forgejo and GitHub Markdown).
## One node per table, solid arrows for pipes, dashed arrows for inline
## [[references]]. Pipes to tables that don't exist point at a red dashed
## "missing" node.
const MAX_EDGE_TEXT := 32
## Mermaid source ("graph LR ...") for a collection Dictionary.
static func export_mermaid(collection: Dictionary) -> String:
var c := JsonIO.canonical(collection)
var lines: Array[String] = ["graph LR"]
var node_of := {} # table id -> mermaid node id
var tables: Array = c["tables"]
for i in tables.size():
var t: Dictionary = tables[i]
node_of[t["id"]] = "t%d" % i
var label := JsonIO.strip_bbcode(str(t["name"]))
if t.has("dice"):
label += " (%s)" % t["dice"]
lines.append("\tt%d[\"%s\"]" % [i, escape_label(label)])
var missing := {} # target name -> mermaid node id
var edges: Array[String] = []
for link in JsonIO.links(c):
var target: String
if link["target"] != "":
target = node_of[link["target"]]
else:
var mkey: String = str(link["target_name"]).to_lower()
if not missing.has(mkey):
missing[mkey] = "m%d" % missing.size()
target = missing[mkey]
var from: String = node_of[link["from_table"]]
var text := _short(str(link["entry_text"]))
var extra := str(link["label"])
if link["kind"] == "pipe":
var label2 := text if extra == "" else "%s · %s" % [text, extra]
edges.append("\t%s -->|\"%s\"| %s" % [from, escape_label(label2), target])
else:
edges.append("\t%s -.->|\"%s\"| %s" % [from, escape_label("%s · %s" % [text, extra]), target])
for key in missing:
var shown := "missing: " + _name_for_missing(c, key)
lines.append("\t%s[\"%s\"]:::missing" % [missing[key], escape_label(shown)])
lines.append_array(edges)
if not missing.is_empty():
lines.append("\tclassDef missing stroke:#d33,stroke-dasharray:4 3,color:#d33")
return "\n".join(lines) + "\n"
## Makes text safe inside a double-quoted Mermaid label using entity codes.
static func escape_label(text: String) -> String:
var s := text.replace("\r", " ").replace("\n", " ")
s = s.replace("#", "#35;")
for pair in [["\"", "#quot;"], ["&", "#38;"], ["<", "#lt;"], [">", "#gt;"], ["[", "#91;"], ["]", "#93;"], ["{", "#123;"], ["}", "#125;"], ["|", "#124;"], ["`", "#96;"], ["\\", "#92;"]]:
s = s.replace(pair[0], pair[1])
return s
static func _short(text: String) -> String:
var t := text.replace("\n", " ").strip_edges()
return t if t.length() <= MAX_EDGE_TEXT else t.substr(0, MAX_EDGE_TEXT - 1) + "…"
## The first spelling of a missing target (keys are lower-cased).
static func _name_for_missing(c: Dictionary, key: String) -> String:
for link in JsonIO.links(c):
if link["target"] == "" and str(link["target_name"]).to_lower() == key:
return str(link["target_name"])
return key

View file

@ -0,0 +1 @@
uid://47n4wgfy3851

274
tests/test_io.gd Normal file
View file

@ -0,0 +1,274 @@
extends SceneTree
## Headless checks for the import/export converters.
## Run: godot --headless --path . -s res://tests/test_io.gd
const TMP_DIR := "user://test_io_tmp/"
var _failures := 0
func _init() -> void:
DirAccess.make_dir_recursive_absolute(TMP_DIR)
_test_json()
_test_canvas()
_test_canvas_stripped()
_test_mermaid_dot()
_test_graphml()
_cleanup()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
## Two tables with weights, ranges, count/save_as pipes, an inline reference, a
## missing target, BBCode, quotes and brackets.
func _small() -> Dictionary:
return {
"format_version": 2, "id": "demo", "name": "Demo \"Set\"",
"tables": [
{"id": "loot", "name": "Loot", "x": 40, "y": 60, "details": "Treasure [b]stuff[/b]\nline 2", "tags": ["a", "b"], "entries": [
{"id": "e1", "text": "Gold coins", "weight": 3},
{"id": "e2", "text": "[b]Melee[/b] weapon \"sharp\" [1]", "details": "A [i]nice[/i] one",
"pipes": [{"table": "weapons", "count": 2, "save_as": "weapon"}, "ghost"]},
{"id": "e3", "text": "Try [[Weapons -> w2]] again"},
]},
{"id": "weapons", "name": "Weapons", "x": 420, "y": 80, "dice": "1d6", "card_mode": true, "entries": [
{"id": "e1", "text": "Dagger", "range": [1, 2]},
{"id": "e2", "text": "Sword", "range": [3, 5], "pipes": ["loot"]},
{"id": "e3", "text": "Warhammer", "range": [6, 6]},
]},
],
}
func _test_json() -> void:
var sample := SampleBoard.create().to_dict()
var text := JsonIO.export_json(sample)
var res := JsonIO.import_json(text)
_check(res["ok"], "sample JSON imports")
var col: Dictionary = res["collection"]
var canon := JsonIO.canonical(sample)
_check(col["tables"] == canon["tables"], "sample JSON round-trips its tables")
_check(col["format_version"] == 2 and str(col["id"]) != "" and str(col["name"]) != "", "legacy file gets version 2, id and name")
var wild: Dictionary = {}
for t in col["tables"]:
if t["id"] == "wilderness":
wild = t
_check(wild.get("dice", "") == "1d100" and not wild.has("die"), "legacy die: 100 becomes dice 1d100")
var small := _small()
var res2 := JsonIO.import_json(JsonIO.export_json(small))
_check(res2["ok"] and res2["collection"] == JsonIO.canonical(small), "small collection round-trips exactly")
_check(not JsonIO.export_json({"tables": [], "state": {"draws": 1}}).contains("state"), "export drops unknown/local keys")
# Legacy keys: triggers, die, collection name.
var legacy := JsonIO.import_json('{"format_version":1,"collection":"Old","tables":[{"id":"a","name":"A","die":20,"entries":[{"text":"x","triggers":["a"]}]}]}')
_check(legacy["ok"] and legacy["collection"]["name"] == "Old", "legacy collection key becomes name")
var lt: Dictionary = legacy["collection"]["tables"][0]
_check(lt["dice"] == "1d20" and lt["entries"][0]["pipes"] == ["a"] and lt["entries"][0]["id"] == "e1", "legacy die/triggers/missing entry id handled")
# Id collisions: duplicate and missing table ids, duplicate entry ids; pipes keep pointing right.
var dup := {"tables": [
{"id": "t", "name": "First", "entries": [{"id": "x", "text": "a", "pipes": ["t"]}, {"id": "x", "text": "b"}]},
{"id": "t", "name": "Second", "entries": [{"text": "c", "pipes": ["First"]}]},
{"name": "Third Table", "entries": [{"text": "d", "pipes": ["t"]}]},
]}
var dres := JsonIO.import_dict(dup)
_check(dres["ok"], "colliding ids still import")
var dt: Array = dres["collection"]["tables"]
var ids := {}
for t in dt:
ids[t["id"]] = true
_check(ids.size() == 3, "table ids are unique after import")
_check(dt[0]["id"] == "t" and dt[1]["id"] != "t" and dt[2]["id"] == "third_table", "first keeps id, others get fresh ones")
_check(dt[0]["entries"][0]["id"] != dt[0]["entries"][1]["id"], "duplicate entry ids are fixed")
_check(dt[1]["entries"][0]["pipes"] == ["t"], "pipe by table name is resolved to the id")
_check(dt[2]["entries"][0]["pipes"] == ["t"], "pipe to the original id keeps pointing at the first table")
# Validation.
_check(not JsonIO.import_json("not json")["ok"], "garbage is rejected")
_check(not JsonIO.import_json("[1,2]")["ok"], "non-object is rejected")
_check(not JsonIO.import_json('{"nope":1}')["ok"], "missing tables is rejected")
_check(not JsonIO.import_json('{"tables":[3]}')["ok"], "non-object table is rejected")
_check(not JsonIO.import_json('{"format_version":9,"tables":[]}')["ok"], "future version is rejected")
_check((JsonIO.import_json("not json")["errors"] as Array).size() == 1, "errors are listed")
# Sanitize hook reaches every visible string.
var san := func(s: String) -> String: return s.replace("[b]", "").replace("[/b]", "").to_upper()
var sres := JsonIO.import_json(JsonIO.export_json(small), san)
var st: Dictionary = sres["collection"]["tables"][0]
_check(st["name"] == "LOOT" and st["entries"][1]["text"].begins_with("MELEE WEAPON"), "sanitize applies to names and entry text")
_check(st["details"] == "TREASURE STUFF\nLINE 2" and st["tags"] == ["A", "B"], "sanitize applies to details and tags")
_check(st["entries"][1]["pipes"][0]["save_as"] == "WEAPON" and st["entries"][1]["pipes"][0]["table"] == "weapons", "sanitize touches save_as but not ids")
func _test_canvas() -> void:
var small := _small()
var text := CanvasIO.export_canvas(small)
var doc: Variant = JSON.parse_string(text)
_check(doc is Dictionary and doc["nodes"] is Array and doc["edges"] is Array, "canvas is valid JSON with nodes and edges")
var groups := 0
var texts: Array[String] = []
for n in doc["nodes"]:
if n["type"] == "group":
groups += 1
else:
texts.append(n["text"])
_check(groups == 2, "canvas has a group per table")
_check(texts.has("3 × Gold coins") and texts.has("1–2: Dagger") and texts.has("6–6: Warhammer"), "canvas text shows weights and ranges (%s)" % str(texts))
var labels: Array[String] = []
for e in doc["edges"]:
labels.append(str(e.get("label", "")))
_check(labels.has("×2 → weapon") and labels.has("ref → w2"), "canvas edge labels (%s)" % str(labels))
_check(doc["edges"].size() == 3, "canvas edges: 2 pipes + 1 ref (missing target skipped), got %d" % doc["edges"].size())
var res := CanvasIO.import_canvas(text)
_check(res["ok"], "canvas imports")
var want := JsonIO.canonical(small)
var got: Dictionary = res["collection"]
_check(got["tables"] == want["tables"], "canvas round trip keeps every field")
_check(got["id"] == "demo" and got["name"] == small["name"], "canvas round trip keeps collection id and name")
# Group sizing: entries sit inside their group.
var ok_inside := true
var group_rects := {}
for n in doc["nodes"]:
if n["type"] == "group":
group_rects[n["id"]] = Rect2(n["x"], n["y"], n["width"], n["height"])
for n in doc["nodes"]:
if n["type"] == "text":
var r := Rect2(n["x"], n["y"], n["width"], n["height"])
var inside := false
for gr in group_rects.values():
if (gr as Rect2).encloses(r):
inside = true
ok_inside = ok_inside and inside
_check(ok_inside, "every entry node fits inside a group")
var sample := SampleBoard.create().to_dict()
var big := CanvasIO.import_canvas(CanvasIO.export_canvas(sample))
_check(big["ok"] and big["collection"]["tables"] == JsonIO.canonical(sample)["tables"], "sample board survives a canvas round trip")
func _test_canvas_stripped() -> void:
var text := CanvasIO.export_canvas(_small())
var doc: Dictionary = JSON.parse_string(text)
doc.erase("tabletower")
for n in doc["nodes"]:
n.erase("tabletower")
for e in doc["edges"]:
e.erase("tabletower")
var res := CanvasIO.import_canvas(JSON.stringify(doc))
_check(res["ok"], "stripped canvas imports")
_check(not (res["guesses"] as Array).is_empty(), "stripped canvas reports guesses")
var tables: Array = res["collection"]["tables"]
_check(tables.size() == 2, "stripped: two tables")
var loot: Dictionary = tables[0]
var weapons: Dictionary = tables[1]
_check(loot["name"] == "Loot" and loot["x"] == 40 and loot["y"] == 60, "stripped: name and position")
_check(loot["entries"].size() == 3 and loot["entries"][0]["text"] == "Gold coins" and loot["entries"][0]["weight"] == 3, "stripped: weighted entry recovered")
_check(not loot.has("dice"), "stripped: unranged table has no dice")
_check(weapons.get("dice", "") == "1d6", "stripped: dice inferred from ranges")
_check(weapons["entries"][1]["range"] == [3, 5] and weapons["entries"][1]["text"] == "Sword", "stripped: ranges recovered")
_check(loot["entries"][1]["text"] == "Melee weapon \"sharp\" [1]", "stripped: BBCode is gone from visible text")
var pipe: Variant = loot["entries"][1].get("pipes", [])[0]
_check(pipe is Dictionary and pipe["table"] == weapons["id"] and pipe["count"] == 2 and pipe["save_as"] == "weapon", "stripped: count and save_as parsed from edge label")
_check(weapons["entries"][1].get("pipes", []) == [loot["id"]], "stripped: plain pipe becomes a table id")
_check(not loot["entries"][2].has("pipes"), "stripped: reference edges do not become pipes")
var found := false
for g in res["guesses"]:
found = found or (g as String).contains("1d6")
_check(found, "stripped: dice guess is reported")
# A d100 table written with 00 for the top.
var d100 := CanvasIO.import_canvas(CanvasIO.export_canvas({"tables": [{"id": "w", "name": "W", "dice": "1d100", "entries": [
{"text": "low", "range": [1, 95]}, {"text": "high", "range": [96, 100]}]}]}).replace("\"tabletower\"", "\"zz\""))
var wt: Dictionary = d100["collection"]["tables"][0]
_check(wt["entries"][1]["range"] == [96, 100] and wt["dice"] == "1d100", "stripped: 96–00 reads as 96-100")
_check(not CanvasIO.import_canvas("{}")["collection"].has("tables") or not CanvasIO.import_canvas("{}")["ok"], "empty canvas is not ok")
_check(not CanvasIO.import_canvas("nope")["ok"], "invalid canvas JSON is not ok")
func _test_mermaid_dot() -> void:
var small := _small()
var m := MermaidExporter.export_mermaid(small)
_check(m.begins_with("graph LR"), "mermaid starts with graph LR")
_check(m.contains("t0[\"Loot\"]") and m.contains("t1[\"Weapons (1d6)\"]"), "mermaid nodes, dice in label")
_check(m.contains("t0 -->|\"") and m.contains("×2 → weapon") and m.contains("| t1"), "mermaid pipe edge with count and save_as")
_check(m.contains("t0 -.->|\"") , "mermaid dashed edge for reference")
_check(m.contains("t1 -->|\"Sword") and m.contains("| t0"), "mermaid pipe back to Loot")
_check(m.contains("missing: ghost") and m.contains(":::missing"), "mermaid marks the missing target")
_check(not m.contains("[b]") and not m.contains("[/b]"), "mermaid strips BBCode")
_check(m.contains("#quot;sharp#quot;") and m.contains("#91;1#93;"), "mermaid escapes quotes and brackets")
for line in m.split("\n"):
if line.contains("-->|") or line.contains("-.->|"):
# Between the pipes there must be exactly one quoted string.
var inner: String = line.get_slice("|", 1)
_check(inner.begins_with("\"") and inner.ends_with("\"") and inner.count("\"") == 2, "mermaid label is one clean quoted string: " + line)
var d := DotExporter.export_dot(small)
_check(d.begins_with("digraph TableTower {") and d.strip_edges().ends_with("}"), "dot has a digraph wrapper")
_check(d.contains("Weapons (1d6)") and d.contains("PORT=\"e1\""), "dot table labels and entry ports")
_check(d.contains("t0:e1:e -> t1:head:w [label=\"×2 → weapon\"]"), "dot pipe edge from entry port to table")
_check(d.contains("t0:e2:e -> t1:head:w [label=\"ref → w2\", style=dashed]"), "dot dashed reference edge")
_check(d.contains("t1:e1:e -> t0:head:w;"), "dot plain pipe edge")
_check(d.contains("missing: ghost") and d.contains("color=red"), "dot marks the missing target")
_check(d.contains("&quot;sharp&quot;") and not d.contains("[b]"), "dot escapes quotes in HTML labels and strips BBCode")
_check(d.contains("label=\"Demo \\\"Set\\\"\""), "dot escapes quotes in strings")
_check(DotExporter.escape_string("a\"b\\c\nd") == "a\\\"b\\\\c\\nd", "dot string escaping")
_check(DotExporter.escape_html("<a&b>") == "&lt;a&amp;b&gt;", "dot html escaping")
# Big tables don't explode.
var sm := MermaidExporter.export_mermaid(SampleBoard.create().to_dict())
var sd := DotExporter.export_dot(SampleBoard.create().to_dict())
_check(sm.contains("graph LR") and sd.contains("more"), "sample board exports to mermaid and dot")
func _test_graphml() -> void:
var small := _small()
var text := GraphMLIO.export_graphml(small)
_check(text.contains("<key id=\"node_dice\"") and text.contains("<edge ") and text.contains("&quot;sharp"), "graphml has keys, edges and escaped text")
var p := XMLParser.new()
p.open_buffer(text.to_utf8_buffer())
var parsed := true
while true:
var err := p.read()
if err == ERR_FILE_EOF:
break
if err != OK:
parsed = false
break
_check(parsed, "graphml is well-formed XML")
var res := GraphMLIO.import_graphml(text)
_check(res["ok"], "graphml imports: " + str(res["errors"]))
_check(res["collection"] == JsonIO.canonical(small), "graphml round trip keeps everything")
var sample := SampleBoard.create().to_dict()
var big := GraphMLIO.import_graphml(GraphMLIO.export_graphml(sample))
_check(big["ok"] and big["collection"]["tables"] == JsonIO.canonical(sample)["tables"], "sample board survives a graphml round trip")
# Foreign GraphML: nodes become tables, edges entries.
var foreign := '<?xml version="1.0"?><graphml xmlns="http://graphml.graphdrawing.org/xmlns"><key id="d0" for="node" attr.name="name" attr.type="string"/><graph edgedefault="directed"><node id="a"><data key="d0">Alpha</data></node><node id="b"><data key="d0">Beta</data></node><edge source="a" target="b"/></graph></graphml>'
var fres := GraphMLIO.import_graphml(foreign)
_check(fres["ok"] and fres["collection"]["tables"].size() == 2 and not (fres["guesses"] as Array).is_empty(), "foreign graphml imports with guesses")
_check(fres["collection"]["tables"][0]["entries"][0]["pipes"] == ["beta"], "foreign graphml edge becomes a pipe")
_check(not GraphMLIO.import_graphml("<nope/>")["ok"], "non-graphml is rejected")
# Write a file once to make sure the text survives disk.
var path := TMP_DIR + "x.graphml"
var f := FileAccess.open(path, FileAccess.WRITE)
f.store_string(text)
f.close()
_check(GraphMLIO.import_graphml(FileAccess.get_file_as_string(path))["collection"] == JsonIO.canonical(small), "graphml survives a file")
func _cleanup() -> void:
var dir := DirAccess.open(TMP_DIR)
if dir != null:
for f in dir.get_files():
dir.remove(f)
DirAccess.remove_absolute(TMP_DIR)
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print(" ✗ ", what)

1
tests/test_io.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://7axb3khxugbb