TableTower/io/graphml_io.gd
RobinFiredrake 0f3e8c278f Remove duplicated code found by the coderstanding audit
- Style.menu_button / font_colors / field_colors replace five copies of the
  "copy a bar button's skin onto a MenuButton" block, nine single-colour
  font loops and four field colour blocks.
- GroupCard uses TableCard.vbox/hbox instead of its own copies.
- InspectorKit.focused_tag / clear / refocus / as_text_link replace the
  focus-keeping render frame and "Edit as text" link shared by the
  condition and effects builders.
- InspectorCard._setting_line replaces three copies of a bound setting field.
- Main.file_dialog / export_dialog replace four FileDialog setups.
- JsonIO.entry_line / finish_import replace copies in canvas_io,
  dot_exporter and graphml_io.
- Dead code: TableCard's unused inline-editor fields and the no-op
  --edit-details / --edit-effects flags, an unused error counter in the
  tray, and an unreachable "settings not available" fallback.

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

238 lines
8.8 KiB
GDScript

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,
}
return JsonIO.finish_import(raw, sanitize, result)