TableTower/ui/io_menu.gd

173 lines
6.8 KiB
GDScript3
Raw Permalink Normal View History

class_name IoMenu
extends MenuButton
## The Build-mode "Spread ▾" menu (test, reset, arrange, import, export) plus the import and
## export logic as static functions, so it can be tested without a window.
const ID_RESET := 1
const ID_IMPORT := 2
const ID_TEST := 3
const ID_PACK := 4
const ID_EXPORT := 100
## Export formats: label, file extension, FileDialog filter.
const EXPORTS := [
{"key": "json", "label": "Table Tarot JSON", "ext": "json", "filter": "*.json ; Table Tarot JSON"},
{"key": "canvas", "label": "JSON Canvas", "ext": "canvas", "filter": "*.canvas ; JSON Canvas"},
{"key": "mermaid", "label": "Mermaid diagram (.mmd)", "ext": "mmd", "filter": "*.mmd ; Mermaid"},
{"key": "mermaid_md", "label": "Mermaid in Markdown (.md)", "ext": "md", "filter": "*.md ; Markdown"},
{"key": "dot", "label": "Graphviz DOT", "ext": "dot", "filter": "*.dot, *.gv ; Graphviz DOT"},
{"key": "graphml", "label": "GraphML", "ext": "graphml", "filter": "*.graphml, *.xml ; GraphML"},
]
const IMPORT_FILTERS: Array[String] = [
"*.json, *.canvas, *.graphml, *.xml ; Table Tarot, JSON Canvas or GraphML",
"*.json ; Table Tarot JSON",
"*.canvas ; JSON Canvas",
"*.graphml, *.xml ; GraphML",
]
signal reset_requested
signal import_requested
signal export_requested(format: Dictionary)
signal test_requested
signal pack_requested
func setup(can_reset: bool, can_import: bool) -> void:
Style.menu_button("Spread ▾", false, self)
tooltip_text = "Test, arrange, import and export the spread"
var pm := get_popup()
ModalCard.style_popup(pm)
pm.add_item("Test spread…", ID_TEST)
pm.add_item("Reset sample", ID_RESET)
pm.add_separator("Arrange")
pm.add_item("Pack collapsed groups", ID_PACK)
pm.set_item_tooltip(pm.get_item_index(ID_PACK), "Move collapsed groups and the cards between them together, closing the gaps, in reading order")
pm.add_separator("Import")
pm.add_item("Import as new spread…", ID_IMPORT)
pm.set_item_disabled(pm.get_item_index(ID_IMPORT), not can_import)
pm.add_separator("Export this spread")
pm.add_item("Export as " + str(EXPORTS[0]["label"]) + "… (full copy)", ID_EXPORT)
pm.set_item_tooltip(pm.get_item_index(ID_EXPORT), "Everything on the spread, ready to import again or share")
# Formats for other tools (diagram and graph programs) sit one level down.
var other := PopupMenu.new()
ModalCard.style_popup(other)
for i in range(1, EXPORTS.size()):
other.add_item(str(EXPORTS[i]["label"]) + "…", ID_EXPORT + i)
pm.add_child(other)
pm.add_submenu_node_item("Export as a diagram (cards and threads only)", other)
pm.set_item_tooltip(pm.item_count - 1, "For diagram and mind-map tools. Settings, values, groups and pictures are left out, so importing one back is not a full copy.")
var on_id := func(id: int) -> void:
if id == ID_RESET:
reset_requested.emit()
elif id == ID_TEST:
test_requested.emit()
elif id == ID_PACK:
pack_requested.emit()
elif id == ID_IMPORT:
import_requested.emit()
elif id >= ID_EXPORT and id < ID_EXPORT + EXPORTS.size():
export_requested.emit(EXPORTS[id - ID_EXPORT])
pm.id_pressed.connect(on_id)
other.id_pressed.connect(on_id)
# ---------- Export ----------
## Text for one export format. Works from the board's saved form only, so local
## state (decks, variables, history) can never end up in an export.
static func export_text(format_key: String, board: TowerBoard) -> String:
var c := board.to_dict()
match format_key:
"canvas": return CanvasIO.export_canvas(c)
"mermaid": return MermaidExporter.export_mermaid(c)
"mermaid_md": return "# %s\n\n```mermaid\n%s\n```\n" % [board.name, MermaidExporter.export_mermaid(c).strip_edges()]
"dot": return DotExporter.export_dot(c)
"graphml": return GraphMLIO.export_graphml(c)
_: return JsonIO.export_json(c)
static func default_file_name(board: TowerBoard, format: Dictionary) -> String:
return "%s.%s" % [LibraryStore.slugify(board.name), format["ext"]]
# ---------- Import ----------
## Guesses the format from the file name, then from the text.
static func detect_format(file_name: String, text: String) -> String:
match file_name.get_extension().to_lower():
"canvas": return "canvas"
"graphml", "xml": return "graphml"
"json": return "json"
var t := text.strip_edges()
if t.begins_with("<"):
return "graphml"
if t.begins_with("{") and t.contains("\"nodes\"") and not t.contains("\"tables\""):
return "canvas"
return "json"
## Parses text with the right importer. Same result shape as the importers:
## {ok, collection, errors, warnings, guesses}.
static func parse_import(text: String, format_key: String) -> Dictionary:
var sanitize: Callable = Formatter.sanitize_import
var r: Dictionary
match format_key:
"canvas": r = CanvasIO.import_canvas(text, sanitize)
"graphml": r = GraphMLIO.import_graphml(text, sanitize)
_: r = JsonIO.import_json(text, sanitize)
for k in ["errors", "warnings", "guesses"]:
if not r.has(k):
r[k] = []
return r
## Imports text as a NEW collection in the library: sanitized, converted with
## TowerBoard.load_dict and saved under a fresh id. Result: {ok, board, errors,
## warnings, guesses}; board is null on failure. Nothing existing is touched.
static func import_as_collection(library: LibraryStore, text: String, file_name: String) -> Dictionary:
var r := parse_import(text, detect_format(file_name, text))
var out := {"ok": false, "board": null, "errors": r["errors"], "warnings": r["warnings"], "guesses": r["guesses"]}
if not r["ok"]:
return out
var b := TowerBoard.new()
if not b.load_dict(r["collection"]):
(out["errors"] as Array).append("The file didn't contain any tables.")
return out
if b.name.strip_edges() == "":
b.name = file_name.get_file().get_basename()
if b.name.strip_edges() == "":
b.name = "Imported spread"
b.id = library.unique_id(LibraryStore.slugify(b.name))
if not library.save(b):
(out["errors"] as Array).append("Couldn't save the imported spread.")
return out
out["ok"] = true
out["board"] = b
return out
## Card-styled report of an import: errors, warnings and guesses.
static func report_dialog(title: String, result: Dictionary) -> ModalCard:
var d := ModalCard.new(title, 540.0)
var any := false
for spec in [["errors", "Problems", Style.WARN_INK], ["warnings", "Warnings", Style.TRIM_DARK],
["guesses", "Guesses made", Style.INK]]:
var items: Array = result.get(spec[0], [])
if items.is_empty():
continue
any = true
d.body.add_child(ModalCard.section("%s (%d)" % [spec[1], items.size()]))
for m in items:
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 8)
var dot := Style.make_label("•", Style.body_bold(), 16, spec[2])
dot.size_flags_vertical = SIZE_SHRINK_BEGIN
row.add_child(dot)
row.add_child(ModalCard.note(str(m), Style.INK))
d.body.add_child(row)
if not any:
d.body.add_child(ModalCard.note("Nothing to report."))
d.add_button("Done", "primary", d.close)
return d