diff --git a/tests/test_shell.gd b/tests/test_shell.gd
new file mode 100644
index 0000000..b9fa667
--- /dev/null
+++ b/tests/test_shell.gd
@@ -0,0 +1,174 @@
+extends SceneTree
+## Headless checks for the app-shell logic: table settings, collections, import.
+## Run: godot --headless --path . -s res://tests/test_shell.gd
+
+const ROOT := "user://test_shell_tmp"
+
+var _failures := 0
+
+
+func _init() -> void:
+ _wipe(ROOT)
+ _test_settings()
+ _test_ranges()
+ _test_wrap()
+ _test_collections()
+ _test_import()
+ _test_export()
+ _wipe(ROOT)
+ print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
+ quit(1 if _failures else 0)
+
+
+func _plain_table(n: int = 4) -> RollTable:
+ var t := RollTable.new("t", "Loot")
+ for i in n:
+ t.entries.append(TableEntry.new("e%d" % i, "Item %d" % i))
+ return t
+
+
+func _test_settings() -> void:
+ var t := _plain_table()
+ var r := TableSettingsDialog.apply_settings(t, {"name": " Gems ", "details": "[b]x[/b]", "tags": "a, b ,, a",
+ "ranged": false, "dice": "1d100", "card_mode": true, "deck_empty": "stop"})
+ _check(r["ok"], "plain settings apply")
+ _check(t.name == "Gems" and t.details == "[b]x[/b]", "name trimmed, details kept")
+ _check(t.tags == ["a", "b"], "tags split and de-duplicated")
+ _check(t.card_mode and t.deck_empty == "stop", "card mode and deck_empty set")
+ _check(r["deck_reset"], "card mode change resets the deck")
+
+ var bad := TableSettingsDialog.apply_settings(t, {"ranged": true, "dice": "banana", "name": "Changed"})
+ _check(not bad["ok"] and t.name == "Gems" and not t.is_ranged(), "invalid dice changes nothing")
+
+ var ok := TableSettingsDialog.apply_settings(t, {"ranged": true, "dice": "2d6", "name": "Gems",
+ "card_mode": true, "deck_empty": "stop"})
+ _check(ok["ok"] and t.is_ranged() and t.dice == "2d6", "converted to ranged 2d6")
+ _check(t.range_problems() == "", "default ranges cover 2d6 cleanly: '%s'" % t.range_problems())
+ var back := TableSettingsDialog.apply_settings(t, {"ranged": false, "dice": "2d6", "name": "Gems",
+ "card_mode": true, "deck_empty": "stop"})
+ _check(back["ok"] and not t.is_ranged(), "converted back to plain drops ranges")
+ _check(t.to_dict().has("dice") == false, "plain table saves no dice")
+
+ var r2 := TableSettingsDialog.apply_settings(t, {"ranged": true, "dice": "1d20", "name": "Gems"})
+ _check(r2["ok"] and t.dice == "1d20" and t.range_problems() == "", "ranged 1d20 is clean")
+ var r3 := TableSettingsDialog.apply_settings(t, {"ranged": true, "dice": "1d8", "name": "Gems"})
+ _check(r3["ok"] and t.dice == "1d8" and t.range_problems() != "", "shrinking dice reports range problems")
+
+
+func _test_ranges() -> void:
+ # Weighted: 1 and 3 on a d100 -> 25 and 75 values.
+ var t := _plain_table(2)
+ t.entries[0].weight = 1
+ t.entries[1].weight = 3
+ t.dice = "1d100"
+ TableSettingsDialog.assign_ranges(t)
+ _check(t.entries[0].range_lo == 1 and t.entries[0].range_hi == 25, "weight 1 of 4 gets 1-25")
+ _check(t.entries[1].range_lo == 26 and t.entries[1].range_hi == 100, "weight 3 of 4 gets 26-100")
+ # More entries than values: everything stays valid and in span.
+ var many := _plain_table(8)
+ many.dice = "1d6"
+ TableSettingsDialog.assign_ranges(many)
+ var lit := 0
+ for e in many.entries:
+ if e.has_range:
+ lit += 1
+ _check(e.range_lo >= 1 and e.range_hi <= 6 and e.range_lo <= e.range_hi, "range inside 1d6")
+ _check(lit == 6, "six values -> six ranges, got %d" % lit)
+ # Weight 0 entries get no range; extra pipes are dropped.
+ var z := _plain_table(3)
+ z.entries[1].weight = 0
+ z.entries[0].pipes = ["a", "b"] as Array[String]
+ TableSettingsDialog.assign_ranges(z)
+ _check(not z.entries[1].has_range and z.entries[0].pipes.size() == 1, "weight 0 skipped, extra pipe dropped")
+ _check(z.entries[2].range_hi == 100, "last live entry reaches the top")
+
+
+func _test_wrap() -> void:
+ var r := TableSettingsDialog.wrap_text("hello world", Vector2i(0, 5), "[b]", "[/b]")
+ _check(r["text"] == "[b]hello[/b] world" and r["caret"] == 12, "bold wraps selection")
+ var r2 := TableSettingsDialog.wrap_text("ab", Vector2i(1, 1), "[i]", "[/i]")
+ _check(r2["text"] == "a[i][/i]b" and r2["caret"] == 4, "empty selection inserts a pair")
+
+
+func _test_collections() -> void:
+ var state := StateStore.new(ROOT)
+ var lib := LibraryStore.new(ROOT, state)
+ var a := CollectionSwitcher.create_collection(lib, null, "Alpha")
+ a.tables.append(_plain_table())
+ var b := CollectionSwitcher.create_collection(lib, a, "Beta")
+ _check(lib.list().size() == 2, "two collections after create")
+ _check(lib.load_collection(a.id).tables.size() == 1, "creating saves the current collection first")
+ var back := CollectionSwitcher.switch_collection(lib, b, a.id)
+ _check(back != null and back.id == a.id and back.tables.size() == 1, "switch loads the other collection")
+ _check(CollectionSwitcher.switch_collection(lib, a, "missing") == null, "switch to a missing id is null")
+ _check(not CollectionSwitcher.rename_collection(lib, a, " "), "blank rename refused")
+ _check(CollectionSwitcher.rename_collection(lib, a, "Alpha Prime"), "rename works")
+ _check(lib.load_collection(a.id).name == "Alpha Prime" and a.id == "alpha", "rename keeps the id")
+ var copy := CollectionSwitcher.duplicate_collection(lib, a, "Alpha copy")
+ _check(copy != null and copy.id != a.id and copy.tables.size() == 1, "duplicate copies the tables")
+ state.set_variable(a.id, "x", "1")
+ var next := CollectionSwitcher.delete_collection(lib, copy)
+ _check(next != null and next.id != copy.id and not lib.exists(copy.id), "delete returns another collection")
+ _check(state.get_variables(a.id).has("x"), "delete leaves other collections' state")
+ for e in lib.list():
+ var c := lib.load_collection(str(e["id"]))
+ CollectionSwitcher.delete_collection(lib, c)
+ _check(lib.list().size() == 1, "deleting the last collection leaves a fresh empty one")
+
+
+func _test_import() -> void:
+ var lib := LibraryStore.new(ROOT, StateStore.new(ROOT))
+ var before := lib.list().size()
+ var canvas := JSON.stringify({
+ "nodes": [
+ {"id": "g1", "type": "group", "label": "Loot [url=https://x.example]link[/url]", "x": 0, "y": 0, "width": 400, "height": 300},
+ {"id": "n1", "type": "text", "text": "Coins [img]res://icon.svg[/img][b]bold[/b]", "x": 10, "y": 40, "width": 300, "height": 60},
+ {"id": "n2", "type": "text", "text": "A [color=red]gem[/color]", "x": 10, "y": 120, "width": 300, "height": 60},
+ ],
+ "edges": [],
+ })
+ var r := IoMenu.import_as_collection(lib, canvas, "loot.canvas")
+ _check(r["ok"], "canvas import ok: %s" % str(r["errors"]))
+ var b: TowerBoard = r["board"]
+ _check(b != null and lib.list().size() == before + 1 and lib.exists(b.id), "import adds a new collection")
+ var all := ""
+ for t in b.tables:
+ all += t.name + "|"
+ for e in t.entries:
+ all += e.text + "|"
+ _check(not all.contains("[url") and not all.contains("[img") and not all.contains("res://"), "import is sanitized: " + all)
+ _check(all.contains("[b]bold[/b]") and all.contains("[color=red]gem[/color]"), "safe tags survive: " + all)
+ var r2 := IoMenu.import_as_collection(lib, canvas, "loot.canvas")
+ _check(r2["ok"] and r2["board"].id != b.id, "importing twice makes two collections")
+ var bad := IoMenu.import_as_collection(lib, "{not json", "x.json")
+ _check(not bad["ok"] and not (bad["errors"] as Array).is_empty() and lib.list().size() == before + 2, "bad file adds nothing")
+ _check(IoMenu.detect_format("a.canvas", "") == "canvas" and IoMenu.detect_format("a", "") == "graphml", "format detection")
+
+
+func _test_export() -> void:
+ var s := SampleBoard.create()
+ s.name = "Sample"
+ for f in IoMenu.EXPORTS:
+ var text := IoMenu.export_text(f["key"], s)
+ _check(text.length() > 50, "export %s has content" % f["key"])
+ _check(IoMenu.export_text("mermaid_md", s).contains("```mermaid"), "markdown export has a mermaid fence")
+ _check(IoMenu.export_text("json", s).contains("\"tables\""), "json export has tables")
+ _check(IoMenu.default_file_name(s, IoMenu.EXPORTS[1]) == "sample.canvas", "default file name")
+
+
+func _wipe(path: String) -> void:
+ var abs := ProjectSettings.globalize_path(path)
+ if not DirAccess.dir_exists_absolute(abs):
+ return
+ var d := DirAccess.open(abs)
+ for sub in d.get_directories():
+ _wipe(path.path_join(sub))
+ for f in d.get_files():
+ DirAccess.remove_absolute(abs.path_join(f))
+ DirAccess.remove_absolute(abs)
+
+
+func _check(cond: bool, msg: String) -> void:
+ if not cond:
+ _failures += 1
+ print("FAIL: ", msg)
diff --git a/tests/test_shell.gd.uid b/tests/test_shell.gd.uid
new file mode 100644
index 0000000..0ff6239
--- /dev/null
+++ b/tests/test_shell.gd.uid
@@ -0,0 +1 @@
+uid://dpooyjdrrmwk2
diff --git a/ui/collection_switcher.gd b/ui/collection_switcher.gd
new file mode 100644
index 0000000..7951665
--- /dev/null
+++ b/ui/collection_switcher.gd
@@ -0,0 +1,122 @@
+class_name CollectionSwitcher
+extends MenuButton
+## Top-bar dropdown that names the current collection and offers switching,
+## New, Rename, Duplicate and Delete. The storage rules are static functions
+## (create_collection and friends) so tests can run them on a temporary
+## LibraryStore; Main does the UI side (rebuilding cards, dialogs).
+
+const ID_NEW := 1000
+const ID_RENAME := 1001
+const ID_DUPLICATE := 1002
+const ID_DELETE := 1003
+const MAX_LABEL := 22
+
+var main: Main
+var _ids: Array[String] = []
+
+
+func setup(p_main: Main) -> void:
+ main = p_main
+ var ref := ModalCard.bar_menu_button("")
+ for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]:
+ add_theme_stylebox_override(n, ref.get_theme_stylebox(n))
+ for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
+ add_theme_color_override(c, ref.get_theme_color(c))
+ add_theme_color_override("font_disabled_color", Style.ON_FELT)
+ add_theme_font_override("font", Style.body_bold())
+ add_theme_font_size_override("font_size", 15)
+ ref.free()
+ mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
+ flat = false
+ tooltip_text = "Collections"
+ ModalCard.style_popup(get_popup())
+ get_popup().about_to_popup.connect(_fill)
+ get_popup().id_pressed.connect(_on_id)
+ refresh()
+
+
+func refresh() -> void:
+ var n := main.data.name if main.data.name != "" else "Untitled"
+ text = "%s ▾" % (n if n.length() <= MAX_LABEL else n.substr(0, MAX_LABEL - 1) + "…")
+ tooltip_text = "Collection: %s" % n
+
+
+func _fill() -> void:
+ var pm := get_popup()
+ pm.clear()
+ _ids.clear()
+ var can := main.collections_enabled()
+ if can:
+ for entry in main.library.list():
+ var id := str(entry["id"])
+ var current := id == main.data.id
+ pm.add_item(("● " if current else " ") + str(entry["name"]), _ids.size())
+ _ids.append(id)
+ else:
+ pm.add_item("● " + main.data.name, 0)
+ pm.set_item_disabled(0, true)
+ _ids.append(main.data.id)
+ pm.add_separator()
+ pm.add_item("New collection…", ID_NEW)
+ pm.add_item("Rename…", ID_RENAME)
+ pm.add_item("Duplicate", ID_DUPLICATE)
+ pm.add_item("Delete…", ID_DELETE)
+ if not can:
+ for id in [ID_NEW, ID_RENAME, ID_DUPLICATE, ID_DELETE]:
+ pm.set_item_disabled(pm.get_item_index(id), true)
+ pm.add_separator()
+ pm.add_item("Saving is off in this session", -1)
+ pm.set_item_disabled(pm.item_count - 1, true)
+
+
+func _on_id(id: int) -> void:
+ match id:
+ ID_NEW: main.new_collection()
+ ID_RENAME: main.rename_collection()
+ ID_DUPLICATE: main.duplicate_collection()
+ ID_DELETE: main.delete_collection()
+ _:
+ if id >= 0 and id < _ids.size() and _ids[id] != main.data.id:
+ main.switch_collection(_ids[id])
+
+
+# ---------- Storage rules (no UI) ----------
+
+## Saves `current`, then makes and returns a new empty collection.
+static func create_collection(library: LibraryStore, current: TowerBoard, coll_name: String) -> TowerBoard:
+ if current:
+ library.save(current)
+ return library.create(coll_name)
+
+
+## Saves `current`, then loads another collection. Null if it can't be loaded.
+static func switch_collection(library: LibraryStore, current: TowerBoard, id: String) -> TowerBoard:
+ if current:
+ library.save(current)
+ return library.load_collection(id)
+
+
+## Renames `current` in memory and on disk. False for a blank name.
+static func rename_collection(library: LibraryStore, current: TowerBoard, new_name: String) -> bool:
+ if new_name.strip_edges() == "":
+ return false
+ current.name = new_name.strip_edges()
+ return library.save(current)
+
+
+## Saves `current` and returns its copy (new id, no local state), or null.
+static func duplicate_collection(library: LibraryStore, current: TowerBoard, new_name: String = "") -> TowerBoard:
+ library.save(current)
+ return library.duplicate(current.id, new_name)
+
+
+## Deletes `current` with its local state. Returns the collection to show next:
+## the first remaining one, or a fresh empty one if it was the last.
+static func delete_collection(library: LibraryStore, current: TowerBoard) -> TowerBoard:
+ if not library.delete(current.id):
+ return null
+ for entry in library.list():
+ var b := library.load_collection(str(entry["id"]))
+ if b:
+ return b
+ return library.create("Untitled")
diff --git a/ui/collection_switcher.gd.uid b/ui/collection_switcher.gd.uid
new file mode 100644
index 0000000..9c3d7cb
--- /dev/null
+++ b/ui/collection_switcher.gd.uid
@@ -0,0 +1 @@
+uid://b08qeiv25l87s
diff --git a/ui/io_menu.gd b/ui/io_menu.gd
new file mode 100644
index 0000000..2aa883e
--- /dev/null
+++ b/ui/io_menu.gd
@@ -0,0 +1,160 @@
+class_name IoMenu
+extends MenuButton
+## The Build-mode "Board ▾" menu (reset, 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_EXPORT := 100
+
+## Export formats: label, file extension, FileDialog filter.
+const EXPORTS := [
+ {"key": "json", "label": "TableTower JSON", "ext": "json", "filter": "*.json ; TableTower 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 ; TableTower, JSON Canvas or GraphML",
+ "*.json ; TableTower JSON",
+ "*.canvas ; JSON Canvas",
+ "*.graphml, *.xml ; GraphML",
+]
+
+signal reset_requested
+signal import_requested
+signal export_requested(format: Dictionary)
+
+
+func setup(can_reset: bool, can_import: bool) -> void:
+ var ref := ModalCard.bar_menu_button("")
+ for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]:
+ add_theme_stylebox_override(n, ref.get_theme_stylebox(n))
+ for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
+ add_theme_color_override(c, ref.get_theme_color(c))
+ add_theme_font_size_override("font_size", 15)
+ ref.free()
+ mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
+ flat = false
+ text = "Board ▾"
+ tooltip_text = "Reset, import and export"
+ var pm := get_popup()
+ ModalCard.style_popup(pm)
+ pm.add_item("Reset sample", ID_RESET)
+ pm.add_separator("Import")
+ pm.add_item("Import as new collection…", ID_IMPORT)
+ pm.set_item_disabled(pm.get_item_index(ID_IMPORT), not can_import)
+ pm.add_separator("Export this collection")
+ for i in EXPORTS.size():
+ pm.add_item("Export as " + str(EXPORTS[i]["label"]) + "…", ID_EXPORT + i)
+ pm.id_pressed.connect(func(id: int) -> void:
+ if id == ID_RESET:
+ reset_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])
+ )
+
+
+# ---------- 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 collection"
+ b.id = library.unique_id(LibraryStore.slugify(b.name))
+ if not library.save(b):
+ (out["errors"] as Array).append("Couldn't save the imported collection.")
+ 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.COPPER_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
diff --git a/ui/io_menu.gd.uid b/ui/io_menu.gd.uid
new file mode 100644
index 0000000..c856004
--- /dev/null
+++ b/ui/io_menu.gd.uid
@@ -0,0 +1 @@
+uid://scc3qijhaa05
diff --git a/ui/main.gd b/ui/main.gd
index 4cbaaf2..a3b07a2 100644
--- a/ui/main.gd
+++ b/ui/main.gd
@@ -165,6 +165,11 @@ func _build_top_bar() -> Control:
seg_row.add_child(_build_button)
h.add_child(seg)
+ _switcher = CollectionSwitcher.new()
+ _switcher.size_flags_vertical = SIZE_SHRINK_CENTER
+ _switcher.setup(self)
+ h.add_child(_switcher)
+
_hint = Style.make_label(HINTS[mode], Style.body(), 15, Style.ON_FELT_MUTED)
_hint.size_flags_horizontal = SIZE_EXPAND_FILL
_hint.size_flags_vertical = SIZE_SHRINK_CENTER
@@ -178,12 +183,18 @@ func _build_top_bar() -> Control:
var add := Style.bar_button("+ Table", true)
add.pressed.connect(add_table)
tools.add_child(add)
- var reset := Style.bar_button("Reset sample")
- reset.pressed.connect(reset_sample)
- tools.add_child(reset)
+ _board_menu = IoMenu.new()
+ _board_menu.setup(true, collections_enabled())
+ _board_menu.reset_requested.connect(reset_sample)
+ _board_menu.import_requested.connect(import_collection)
+ _board_menu.export_requested.connect(export_collection)
+ tools.add_child(_board_menu)
tools.visible = false
h.add_child(tools)
+ _endless_chip = _make_endless_chip()
+ h.add_child(_endless_chip)
+
_collapse_all = Style.bar_button("Collapse all")
_collapse_all.tooltip_text = "Collapse or expand every table at once"
_collapse_all.pressed.connect(func() -> void: set_all_collapsed(_any_expanded()))
@@ -323,12 +334,14 @@ func set_mode(m: Mode) -> void:
board.pipes.hover_key = ""
for card in cards.values():
(card as TableCard).rebuild()
+ _update_endless_chip()
func mark_dirty() -> void:
if _saving_enabled:
_save_timer.start()
_update_collapse_all()
+ _update_endless_chip()
func _any_expanded() -> bool:
@@ -640,6 +653,7 @@ func _run_cli(args: PackedStringArray) -> void:
set_all_collapsed(false)
if args.has("--collapse-all"):
set_all_collapsed(true)
+ _run_shell_cli(args)
var roll := _arg_value(args, "--roll")
if roll != "":
start_roll(roll)
@@ -652,3 +666,238 @@ func _run_cli(args: PackedStringArray) -> void:
img.save_png(shot)
print("Saved screenshot to ", shot)
get_tree().quit()
+
+
+# ---------- App shell: collections, import/export, table settings ----------
+# (Added by the shell UI. Pure rules live in CollectionSwitcher, IoMenu and
+# TableSettingsDialog.)
+
+var _switcher: CollectionSwitcher
+var _board_menu: IoMenu
+var _endless_chip: PanelContainer
+var _endless_label: Label
+
+
+## True when collections can be listed and saved (not --sample / --screenshot).
+func collections_enabled() -> bool:
+ return _saving_enabled and library != null and state != null
+
+
+func _add_modal(d: ModalCard) -> void:
+ add_child(d)
+
+
+## Opens the settings dialog for a table (Build mode editor).
+func open_table_settings(table_id: String) -> void:
+ var t := data.get_table(table_id)
+ if t == null:
+ return
+ var d := TableSettingsDialog.new(t)
+ var snap := _snapshot()
+ d.applied.connect(func(result: Dictionary) -> void:
+ if result.get("deck_reset", false) and state and data.id != "":
+ state.clear_deck(data.id, t.id)
+ var card := card_for(t.id)
+ if card:
+ card.rebuild()
+ mark_dirty()
+ toast("Updated %s" % t.name, snap)
+ )
+ _add_modal(d)
+
+
+# ----- Collections -----
+
+func switch_collection(id: String) -> void:
+ if not collections_enabled() or id == data.id:
+ return
+ _save_timer.stop()
+ var b := CollectionSwitcher.switch_collection(library, data, id)
+ if b == null:
+ toast("Couldn't open that collection")
+ return
+ _show_collection(b)
+
+
+## Swaps the board to `b`: resets lit state and the current result, rebuilds
+## the cards, fits the view and remembers it as the last collection.
+func _show_collection(b: TowerBoard) -> void:
+ data = b
+ lit_entries.clear()
+ lit_pipes.clear()
+ current = {}
+ _token += 1
+ board.pipes.pulse_key = ""
+ _rebuild_cards()
+ tray.render()
+ if state:
+ state.set_setting("last_collection", data.id)
+ state.save()
+ _switcher.refresh()
+ _update_endless_chip()
+ await get_tree().process_frame
+ await get_tree().process_frame
+ board.fit()
+
+
+func new_collection() -> void:
+ if not collections_enabled():
+ return
+ _add_modal(ModalCard.ask_text("New collection", "Name", "", "Create", func(n: String) -> void:
+ _show_collection(CollectionSwitcher.create_collection(library, data, n))
+ toast("Created “%s”" % data.name)
+ ))
+
+
+func rename_collection() -> void:
+ if not collections_enabled():
+ return
+ _add_modal(ModalCard.ask_text("Rename collection", "Name", data.name, "Rename", func(n: String) -> void:
+ if CollectionSwitcher.rename_collection(library, data, n):
+ _switcher.refresh()
+ ))
+
+
+func duplicate_collection() -> void:
+ if not collections_enabled():
+ return
+ var copy := CollectionSwitcher.duplicate_collection(library, data, data.name + " copy")
+ if copy == null:
+ toast("Couldn't duplicate the collection")
+ return
+ _show_collection(copy)
+ toast("Duplicated as “%s”" % copy.name)
+
+
+func delete_collection() -> void:
+ if not collections_enabled():
+ return
+ var msg := "Delete “%s” and its saved decks, variables and history? This can't be undone." % data.name
+ _add_modal(ModalCard.confirm("Delete collection", msg, "Delete", func() -> void:
+ var gone := data.name
+ var next := CollectionSwitcher.delete_collection(library, data)
+ if next:
+ _show_collection(next)
+ toast("Deleted “%s”" % gone)
+ , true))
+
+
+# ----- Import and export -----
+
+func export_collection(format: Dictionary) -> void:
+ var dlg := FileDialog.new()
+ dlg.use_native_dialog = true
+ dlg.access = FileDialog.ACCESS_FILESYSTEM
+ dlg.file_mode = FileDialog.FILE_MODE_SAVE_FILE
+ dlg.title = "Export as " + str(format["label"])
+ dlg.filters = PackedStringArray([format["filter"]])
+ dlg.current_file = IoMenu.default_file_name(data, format)
+ dlg.file_selected.connect(func(path: String) -> void:
+ var err := TowerBoard.write_text_atomic(path, IoMenu.export_text(str(format["key"]), data))
+ toast("Exported to %s" % path.get_file() if err == OK else "Couldn't write %s" % path.get_file())
+ )
+ dlg.visibility_changed.connect(func() -> void:
+ if not dlg.visible:
+ dlg.queue_free.call_deferred()
+ )
+ add_child(dlg)
+ dlg.popup_centered_ratio(0.6)
+
+
+func import_collection() -> void:
+ if not collections_enabled():
+ return
+ var dlg := FileDialog.new()
+ dlg.use_native_dialog = true
+ dlg.access = FileDialog.ACCESS_FILESYSTEM
+ dlg.file_mode = FileDialog.FILE_MODE_OPEN_FILE
+ dlg.title = "Import as a new collection"
+ dlg.filters = PackedStringArray(IoMenu.IMPORT_FILTERS)
+ dlg.file_selected.connect(_import_file)
+ dlg.visibility_changed.connect(func() -> void:
+ if not dlg.visible:
+ dlg.queue_free.call_deferred()
+ )
+ add_child(dlg)
+ dlg.popup_centered_ratio(0.6)
+
+
+func _import_file(path: String) -> void:
+ if not FileAccess.file_exists(path):
+ toast("Couldn't read %s" % path.get_file())
+ return
+ _save_now()
+ var r := IoMenu.import_as_collection(library, FileAccess.get_file_as_string(path), path.get_file())
+ if r["ok"]:
+ _show_collection(r["board"])
+ var has_report: bool = not (r["errors"] as Array).is_empty() or not (r["warnings"] as Array).is_empty() \
+ or not (r["guesses"] as Array).is_empty()
+ if has_report or not r["ok"]:
+ _add_modal(IoMenu.report_dialog(
+ "Imported “%s”" % r["board"].name if r["ok"] else "Couldn't import %s" % path.get_file(), r))
+ elif r["ok"]:
+ toast("Imported “%s” as a new collection" % r["board"].name)
+
+
+# ----- Endless-loop warning -----
+
+func _make_endless_chip() -> PanelContainer:
+ var chip := PanelContainer.new()
+ chip.add_theme_stylebox_override("panel", Style.box(Style.WARN_BG, 8, [10, 4, 10, 4]))
+ chip.size_flags_vertical = SIZE_SHRINK_CENTER
+ _endless_label = Style.make_label("", Style.body_bold(), 14, Style.WARN_INK)
+ _endless_label.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
+ chip.add_child(_endless_label)
+ chip.custom_minimum_size.x = 0
+ chip.hide()
+ return chip
+
+
+func _update_endless_chip() -> void:
+ if _endless_chip == null or data == null:
+ return
+ var ids := Roller.endless_cycles(data)
+ if mode != Mode.BUILD or ids.is_empty():
+ _endless_chip.hide()
+ return
+ var names := PackedStringArray()
+ for id in ids:
+ var t := data.get_table(id)
+ names.append(t.name if t else id)
+ var list := ", ".join(names)
+ _endless_label.text = "⚠ Endless loop: " + list
+ var w := Style.body_bold().get_string_size(_endless_label.text, HORIZONTAL_ALIGNMENT_LEFT, -1, 14).x
+ _endless_label.custom_minimum_size.x = clampf(w + 4.0, 120.0, 300.0)
+ _endless_chip.tooltip_text = "These tables can never finish rolling, because every result leads back into a loop:\n" + "\n".join(names)
+ _endless_chip.show()
+
+
+# ----- Extra screenshot flags -----
+# --open-settings=
open the settings dialog
+# --demo-import= show the import report for a file (nothing is saved)
+# --demo-endless pipe the first two tables into each other
+# --menu=board|collections pop up a top-bar menu
+
+func _run_shell_cli(args: PackedStringArray) -> void:
+ var tid := _arg_value(args, "--open-settings")
+ if tid != "":
+ open_table_settings(tid)
+ var file := _arg_value(args, "--demo-import")
+ if file != "":
+ var text := FileAccess.get_file_as_string(file)
+ var r := IoMenu.parse_import(text, IoMenu.detect_format(file, text))
+ _add_modal(IoMenu.report_dialog("Imported “%s”" % file.get_file().get_basename(), r))
+ if args.has("--demo-endless") and data.tables.size() >= 2:
+ var a := data.tables[0]
+ var b := data.tables[1]
+ for e in a.entries:
+ e.pipes = [b.id] as Array[String]
+ for e in b.entries:
+ e.pipes = [a.id] as Array[String]
+ _rebuild_cards()
+ mark_dirty()
+ var menu := _arg_value(args, "--menu")
+ if menu == "board":
+ _board_menu.show_popup()
+ elif menu == "collections":
+ _switcher.show_popup()
diff --git a/ui/modal_card.gd b/ui/modal_card.gd
new file mode 100644
index 0000000..3f4c07c
--- /dev/null
+++ b/ui/modal_card.gd
@@ -0,0 +1,276 @@
+class_name ModalCard
+extends Control
+## A card-styled modal dialog: dimmed backdrop, a paper-coloured card with a
+## Rokkitt title, a scrolling body and a right-aligned footer of buttons.
+## Add it to the app with `host.add_child(dialog)`; it frees itself on close().
+
+signal closed
+
+var card: PanelContainer
+var body: VBoxContainer
+var footer: HBoxContainer
+var title_label: Label
+var close_on_backdrop := true
+
+var _scroll: ScrollContainer
+var _width := 520.0
+
+
+func _init(title: String = "", width: float = 520.0) -> void:
+ _width = width
+ set_anchors_and_offsets_preset(PRESET_FULL_RECT)
+ mouse_filter = Control.MOUSE_FILTER_STOP
+ theme = make_theme()
+
+ var dim := ColorRect.new()
+ dim.color = Color(0, 0, 0, 0.55)
+ dim.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
+ dim.gui_input.connect(func(ev: InputEvent) -> void:
+ if close_on_backdrop and ev is InputEventMouseButton and ev.pressed:
+ close()
+ )
+ add_child(dim)
+
+ var center := CenterContainer.new()
+ center.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
+ center.mouse_filter = Control.MOUSE_FILTER_IGNORE
+ add_child(center)
+
+ card = PanelContainer.new()
+ var sb := Style.box(Style.CARD, 14, [26, 22, 26, 20])
+ sb.shadow_color = Color(0, 0, 0, 0.5)
+ sb.shadow_size = 28
+ sb.shadow_offset = Vector2(0, 12)
+ card.add_theme_stylebox_override("panel", sb)
+ card.custom_minimum_size.x = width
+ center.add_child(card)
+
+ var col := VBoxContainer.new()
+ col.add_theme_constant_override("separation", 14)
+ card.add_child(col)
+ title_label = Style.make_label(title, Style.display(), 28, Style.INK)
+ title_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
+ col.add_child(title_label)
+
+ _scroll = ScrollContainer.new()
+ _scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED
+ _scroll.size_flags_vertical = SIZE_EXPAND_FILL
+ col.add_child(_scroll)
+ body = VBoxContainer.new()
+ body.add_theme_constant_override("separation", 12)
+ body.size_flags_horizontal = SIZE_EXPAND_FILL
+ _scroll.add_child(body)
+
+ footer = HBoxContainer.new()
+ footer.add_theme_constant_override("separation", 10)
+ footer.alignment = BoxContainer.ALIGNMENT_END
+ col.add_child(footer)
+
+
+func _ready() -> void:
+ resized.connect(_fit)
+ _fit()
+ await get_tree().process_frame
+ _fit()
+
+
+func _fit() -> void:
+ card.custom_minimum_size.x = minf(_width, maxf(240.0, size.x - 32.0))
+ var want := body.get_combined_minimum_size().y
+ _scroll.custom_minimum_size.y = clampf(minf(want, size.y - 190.0), 40.0, 4000.0)
+
+
+func _input(event: InputEvent) -> void:
+ if event.is_action_pressed("ui_cancel") and is_inside_tree():
+ get_viewport().set_input_as_handled()
+ close()
+
+
+func close() -> void:
+ closed.emit()
+ queue_free()
+
+
+# ---------- Building blocks ----------
+
+## kind: "primary" (felt), "plain" (outlined) or "danger".
+func add_button(text: String, kind: String, on_press: Callable) -> Button:
+ var b := make_button(text, kind)
+ b.pressed.connect(on_press)
+ footer.add_child(b)
+ return b
+
+
+static func make_button(text: String, kind: String = "plain") -> Button:
+ var b := Button.new()
+ b.text = text
+ b.add_theme_font_override("font", Style.body_bold())
+ b.add_theme_font_size_override("font_size", 16)
+ var m := [16, 7, 16, 7]
+ match kind:
+ "primary":
+ Style.skin_button(b, Style.box(Style.FELT, 8, m), Style.box(Style.FELT_HOVER, 8, m),
+ Style.box(Style.FELT_HOVER, 8, m), Style.BRASS)
+ "danger":
+ Style.skin_button(b, Style.box(Style.DANGER_INK, 8, m), Style.box(Style.DANGER_INK.lightened(0.12), 8, m),
+ Style.box(Style.DANGER_INK.lightened(0.12), 8, m), Color.WHITE)
+ _:
+ var n := Style.bordered(Style.box(Color(0, 0, 0, 0), 8, m), 1, Style.DASH)
+ var h := Style.bordered(Style.box(Style.HOVER_ROW, 8, m), 1, Style.DASH)
+ Style.skin_button(b, n, h, h, Style.INK)
+ b.add_theme_color_override("font_disabled_color", Style.MUTED)
+ return b
+
+
+## Small caps heading above a group of fields.
+static func section(text: String) -> Label:
+ var l := Style.make_label(text.to_upper(), Style.caps(), 12, Style.MUTED)
+ return l
+
+
+static func note(text: String, color: Color = Style.MUTED) -> Label:
+ var l := Style.make_label(text, Style.body(), 14, color)
+ l.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
+ l.size_flags_horizontal = SIZE_EXPAND_FILL
+ return l
+
+
+## A label above a control, as one block.
+static func field(heading: String, control: Control) -> VBoxContainer:
+ var v := VBoxContainer.new()
+ v.add_theme_constant_override("separation", 4)
+ v.add_child(section(heading))
+ v.add_child(control)
+ return v
+
+
+## A segmented choice: options are strings; returns the row. `on_change` gets the index.
+static func segmented(options: Array, selected: int, on_change: Callable) -> PanelContainer:
+ var seg := PanelContainer.new()
+ seg.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.07), 9, [3, 3, 3, 3]))
+ seg.size_flags_horizontal = SIZE_SHRINK_BEGIN
+ var row := HBoxContainer.new()
+ row.add_theme_constant_override("separation", 0)
+ seg.add_child(row)
+ var group := ButtonGroup.new()
+ for i in options.size():
+ var b := Button.new()
+ b.text = str(options[i])
+ b.toggle_mode = true
+ b.button_group = group
+ b.add_theme_font_override("font", Style.body_bold())
+ b.add_theme_font_size_override("font_size", 15)
+ var normal := Style.box(Color(0, 0, 0, 0), 7, [14, 5, 14, 5])
+ var hover := Style.box(Color(0, 0, 0, 0.06), 7, [14, 5, 14, 5])
+ var pressed := Style.box(Style.FELT, 7, [14, 5, 14, 5])
+ Style.skin_button(b, normal, hover, pressed, Style.MUTED, Style.INK, Style.BRASS)
+ b.set_pressed_no_signal(i == selected)
+ b.pressed.connect(on_change.bind(i))
+ row.add_child(b)
+ return seg
+
+
+static func style_line_edit(le: LineEdit) -> void:
+ le.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.DASH))
+ le.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 7, [10, 6, 10, 6]), 1, Style.COPPER))
+ le.add_theme_color_override("font_color", Style.INK)
+ le.add_theme_color_override("caret_color", Style.INK)
+ le.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
+ le.add_theme_color_override("font_placeholder_color", Style.MUTED)
+ le.add_theme_constant_override("minimum_character_width", 4)
+ le.size_flags_horizontal = SIZE_EXPAND_FILL
+
+
+static func style_text_edit(te: TextEdit) -> void:
+ te.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 7, [10, 7, 10, 7]), 1, Style.DASH))
+ te.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color.WHITE, 7, [10, 7, 10, 7]), 1, Style.COPPER))
+ te.add_theme_color_override("font_color", Style.INK)
+ te.add_theme_color_override("caret_color", Style.INK)
+ te.add_theme_color_override("selection_color", Color(Style.BRASS, 0.55))
+ te.add_theme_color_override("font_placeholder_color", Style.MUTED)
+ te.add_theme_color_override("background_color", Color(0, 0, 0, 0))
+
+
+## Styles a popup menu like a small card (used by the top-bar menus too).
+static func style_popup(pm: PopupMenu) -> void:
+ pm.add_theme_stylebox_override("panel", Style.bordered(Style.box(Style.CARD, 10, [6, 6, 6, 6]), 1, Style.DASH))
+ pm.add_theme_stylebox_override("hover", Style.box(Style.HOVER_ROW, 6))
+ pm.add_theme_stylebox_override("separator", Style.box(Style.RULE, 0, [0, 0, 0, 0]))
+ pm.add_theme_color_override("font_color", Style.INK)
+ pm.add_theme_color_override("font_hover_color", Style.INK)
+ pm.add_theme_color_override("font_disabled_color", Style.MUTED)
+ pm.add_theme_color_override("font_separator_color", Style.MUTED)
+ pm.add_theme_font_override("font", Style.body())
+ pm.add_theme_font_size_override("font_size", 16)
+ pm.add_theme_constant_override("v_separation", 8)
+ pm.add_theme_constant_override("item_start_padding", 8)
+ pm.add_theme_constant_override("item_end_padding", 8)
+
+
+## A top-bar styled MenuButton (same look as Style.bar_button).
+static func bar_menu_button(text: String) -> MenuButton:
+ var mb := MenuButton.new()
+ mb.text = text
+ var ref := Style.bar_button(text)
+ for n in ["normal", "hover", "pressed", "hover_pressed", "disabled", "focus"]:
+ mb.add_theme_stylebox_override(n, ref.get_theme_stylebox(n))
+ for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
+ mb.add_theme_color_override(c, ref.get_theme_color(c))
+ mb.add_theme_color_override("font_disabled_color", Style.ON_FELT_MUTED)
+ mb.add_theme_font_size_override("font_size", 15)
+ mb.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
+ mb.flat = false
+ style_popup(mb.get_popup())
+ ref.free()
+ return mb
+
+
+static func make_theme() -> Theme:
+ var th := Style.card_theme()
+ th.set_color("default_color", "RichTextLabel", Style.INK)
+ th.set_font("normal_font", "RichTextLabel", Style.body())
+ th.set_font("bold_font", "RichTextLabel", Style.body_bold())
+ th.set_font("italics_font", "RichTextLabel", Style.body_italic())
+ th.set_font_size("normal_font_size", "RichTextLabel", 16)
+ th.set_font_size("bold_font_size", "RichTextLabel", 16)
+ th.set_font_size("italics_font_size", "RichTextLabel", 16)
+ th.set_color("font_color", "TooltipLabel", Style.INK)
+ th.set_stylebox("panel", "TooltipPanel", Style.box(Style.CARD, 6, [8, 5, 8, 5]))
+ return th
+
+
+# ---------- Ready-made dialogs ----------
+
+## Asks for one line of text; calls on_ok(text) with non-blank text.
+static func ask_text(title: String, prompt: String, initial: String, ok_text: String, on_ok: Callable) -> ModalCard:
+ var d := ModalCard.new(title, 420.0)
+ var le := LineEdit.new()
+ le.text = initial
+ style_line_edit(le)
+ d.body.add_child(field(prompt, le))
+ var accept := func() -> void:
+ var t := le.text.strip_edges()
+ if t == "":
+ return
+ d.close()
+ on_ok.call(t)
+ le.text_submitted.connect(func(_t: String) -> void: accept.call())
+ d.add_button("Cancel", "plain", d.close)
+ d.add_button(ok_text, "primary", accept)
+ d.ready.connect(func() -> void:
+ le.grab_focus()
+ le.select_all()
+ )
+ return d
+
+
+## A yes/no question; calls on_ok when confirmed. `danger` makes the button red.
+static func confirm(title: String, message: String, ok_text: String, on_ok: Callable, danger: bool = false) -> ModalCard:
+ var d := ModalCard.new(title, 420.0)
+ d.body.add_child(note(message, Style.INK))
+ d.add_button("Cancel", "plain", d.close)
+ d.add_button(ok_text, "danger" if danger else "primary", func() -> void:
+ d.close()
+ on_ok.call()
+ )
+ return d
diff --git a/ui/modal_card.gd.uid b/ui/modal_card.gd.uid
new file mode 100644
index 0000000..2a5db92
--- /dev/null
+++ b/ui/modal_card.gd.uid
@@ -0,0 +1 @@
+uid://ceo7ujpvqc4c
diff --git a/ui/table_settings_dialog.gd b/ui/table_settings_dialog.gd
new file mode 100644
index 0000000..5e7b867
--- /dev/null
+++ b/ui/table_settings_dialog.gd
@@ -0,0 +1,347 @@
+class_name TableSettingsDialog
+extends ModalCard
+## Build-mode editor for one table's name, details, tags, type and card mode.
+## The editing rules live in static functions (apply_settings and friends) so
+## they can be tested without a window.
+
+signal applied(settings: Dictionary)
+
+const COLORS := [
+ ["Red", Color("#a33a2c")],
+ ["Copper", Color("#b8703a")],
+ ["Green", Color("#2f6b4f")],
+ ["Blue", Color("#2f5d8a")],
+ ["Purple", Color("#6b3f8a")],
+]
+
+var table: RollTable
+
+var _name: LineEdit
+var _details: TextEdit
+var _preview: RichTextLabel
+var _tags: LineEdit
+var _dice: LineEdit
+var _dice_row: Control
+var _type_note: Label
+var _problem: Label
+var _deck_block: Control
+var _ranged := false
+var _card_mode := false
+var _deck_empty := "reshuffle"
+
+
+func _init(p_table: RollTable = null) -> void:
+ super._init("Table settings", 560.0)
+ table = p_table
+ _ranged = table.is_ranged()
+ _card_mode = table.card_mode
+ _deck_empty = table.deck_empty
+ _build()
+
+
+func _build() -> void:
+ _name = LineEdit.new()
+ _name.text = table.name
+ _name.placeholder_text = "Table name"
+ style_line_edit(_name)
+ _name.text_changed.connect(func(_t: String) -> void: _refresh())
+ body.add_child(field("Name", _name))
+
+ _details = TextEdit.new()
+ _details.text = table.details
+ _details.placeholder_text = "What this table is for. BBCode is allowed."
+ _details.custom_minimum_size.y = 84
+ _details.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
+ style_text_edit(_details)
+ _details.text_changed.connect(_refresh)
+ var tools := HBoxContainer.new()
+ tools.add_theme_constant_override("separation", 6)
+ tools.add_child(_tool_button("B", "Bold", func() -> void: _wrap_selection("[b]", "[/b]")))
+ tools.add_child(_tool_button("I", "Italic", func() -> void: _wrap_selection("[i]", "[/i]")))
+ var color := make_button("Color ▾", "plain")
+ color.pressed.connect(func() -> void: _color_menu(color))
+ color.add_theme_font_size_override("font_size", 14)
+ tools.add_child(color)
+ var dbox := VBoxContainer.new()
+ dbox.add_theme_constant_override("separation", 6)
+ dbox.add_child(section("Details"))
+ dbox.add_child(tools)
+ dbox.add_child(_details)
+ _preview = RichTextLabel.new()
+ _preview.bbcode_enabled = true
+ _preview.fit_content = true
+ _preview.scroll_active = false
+ _preview.custom_minimum_size.y = 24
+ var pbox := PanelContainer.new()
+ pbox.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.05), 7, [10, 7, 10, 7]))
+ pbox.add_child(_preview)
+ dbox.add_child(pbox)
+ body.add_child(dbox)
+
+ _tags = LineEdit.new()
+ _tags.text = ", ".join(table.tags)
+ _tags.placeholder_text = "loot, treasure, magic"
+ style_line_edit(_tags)
+ body.add_child(field("Tags (comma-separated)", _tags))
+
+ var type_box := VBoxContainer.new()
+ type_box.add_theme_constant_override("separation", 6)
+ type_box.add_child(section("Table type"))
+ type_box.add_child(segmented(["Plain", "Ranged (dice)"], 1 if _ranged else 0, func(i: int) -> void:
+ _ranged = i == 1
+ _refresh()
+ ))
+ _dice = LineEdit.new()
+ _dice.text = table.dice
+ _dice.placeholder_text = "1d100"
+ _dice.custom_minimum_size.x = 140
+ style_line_edit(_dice)
+ _dice.size_flags_horizontal = SIZE_SHRINK_BEGIN
+ _dice.text_changed.connect(func(_t: String) -> void: _refresh())
+ var drow := HBoxContainer.new()
+ drow.add_theme_constant_override("separation", 10)
+ var dl := Style.make_label("Dice", Style.body(), 15, Style.INK)
+ dl.size_flags_vertical = SIZE_SHRINK_CENTER
+ drow.add_child(dl)
+ drow.add_child(_dice)
+ var eg := note("e.g. 1d100, 2d6, 1d8+2")
+ eg.size_flags_vertical = SIZE_SHRINK_CENTER
+ drow.add_child(eg)
+ _dice_row = drow
+ type_box.add_child(drow)
+ _type_note = note("")
+ type_box.add_child(_type_note)
+ _problem = note("", Style.WARN_INK)
+ type_box.add_child(_problem)
+ body.add_child(type_box)
+
+ var card_box := VBoxContainer.new()
+ card_box.add_theme_constant_override("separation", 6)
+ card_box.add_child(section("Card mode"))
+ card_box.add_child(segmented(["Off", "On"], 1 if _card_mode else 0, func(i: int) -> void:
+ _card_mode = i == 1
+ _refresh()
+ ))
+ card_box.add_child(note("Entries are dealt like cards, without repeats, until the deck runs out."))
+ var deck := VBoxContainer.new()
+ deck.add_theme_constant_override("separation", 6)
+ deck.add_child(section("When the deck runs out"))
+ deck.add_child(segmented(["Reshuffle", "Stop"], 1 if _deck_empty == "stop" else 0, func(i: int) -> void:
+ _deck_empty = "stop" if i == 1 else "reshuffle"
+ _refresh()
+ ))
+ _deck_block = deck
+ card_box.add_child(deck)
+ body.add_child(card_box)
+
+ add_button("Close", "plain", close)
+ add_button("Apply", "primary", _on_apply)
+ _refresh()
+
+
+func _tool_button(text: String, tip: String, on_press: Callable) -> Button:
+ var b := make_button(text, "plain")
+ b.tooltip_text = tip
+ b.custom_minimum_size.x = 36
+ b.add_theme_font_size_override("font_size", 14)
+ b.pressed.connect(on_press)
+ return b
+
+
+func _color_menu(anchor: Control) -> void:
+ var pm := PopupMenu.new()
+ style_popup(pm)
+ for i in COLORS.size():
+ pm.add_item(COLORS[i][0], i)
+ pm.id_pressed.connect(func(id: int) -> void:
+ _wrap_selection("[color=%s]" % (COLORS[id][1] as Color).to_html(false), "[/color]")
+ )
+ pm.popup_hide.connect(pm.queue_free)
+ add_child(pm)
+ pm.popup(Rect2i(Vector2i(anchor.get_screen_position()) + Vector2i(0, int(anchor.size.y)), Vector2i(0, 0)))
+
+
+## Wraps the selected text in the tags, or inserts an empty pair at the caret.
+func _wrap_selection(open: String, close_tag: String) -> void:
+ var r := wrap_text(_details.text, _selection_range(), open, close_tag)
+ _details.text = r["text"]
+ _set_caret_at_offset(int(r["caret"]))
+ _details.grab_focus()
+ _refresh()
+
+
+func _selection_range() -> Vector2i:
+ if _details.has_selection():
+ return Vector2i(_offset_of(_details.get_selection_from_line(), _details.get_selection_from_column()),
+ _offset_of(_details.get_selection_to_line(), _details.get_selection_to_column()))
+ var c := _offset_of(_details.get_caret_line(), _details.get_caret_column())
+ return Vector2i(c, c)
+
+
+func _offset_of(line: int, col: int) -> int:
+ var off := 0
+ for i in line:
+ off += _details.get_line(i).length() + 1
+ return off + col
+
+
+func _set_caret_at_offset(off: int) -> void:
+ var line := 0
+ while line < _details.get_line_count() - 1 and off > _details.get_line(line).length():
+ off -= _details.get_line(line).length() + 1
+ line += 1
+ _details.set_caret_line(line)
+ _details.set_caret_column(clampi(off, 0, _details.get_line(line).length()))
+
+
+func settings() -> Dictionary:
+ return {
+ "name": _name.text, "details": _details.text, "tags": _tags.text,
+ "ranged": _ranged, "dice": _dice.text.strip_edges(),
+ "card_mode": _card_mode, "deck_empty": _deck_empty,
+ }
+
+
+func _refresh() -> void:
+ if _preview == null:
+ return
+ var det := _details.text
+ _preview.text = Formatter.close_open_tags(det) if det.strip_edges() != "" else "[color=#69726b]Preview appears here.[/color]"
+ _dice_row.visible = _ranged
+ _deck_block.visible = _card_mode
+ var s := settings()
+ var dice_ok := not _ranged or Dice.is_valid_text(s["dice"])
+ _dice.add_theme_color_override("font_color", Style.INK if dice_ok else Style.WARN_INK)
+ var msgs := PackedStringArray()
+ if _ranged and not table.is_ranged():
+ msgs.append("Each entry gets a range sized by its weight; adjust them on the card.")
+ if _ranged and extra_pipe_count(table) > 0:
+ msgs.append("A range takes one pipe, so extra pipes on an entry will be dropped.")
+ if not _ranged and table.is_ranged():
+ msgs.append("Ranges are removed; entries become plain picks.")
+ _type_note.text = " ".join(msgs)
+ _type_note.visible = not msgs.is_empty()
+ var problem := ""
+ if not dice_ok:
+ problem = "“%s” is not a valid dice expression." % s["dice"]
+ else:
+ var clone := RollTable.from_dict(table.to_dict())
+ apply_settings(clone, s)
+ problem = clone.range_problems()
+ _problem.text = problem
+ _problem.visible = problem != ""
+ if is_inside_tree():
+ _fit()
+
+
+func _on_apply() -> void:
+ var s := settings()
+ var r := apply_settings(table, s)
+ if not r["ok"]:
+ _problem.text = r["error"]
+ _problem.visible = true
+ return
+ applied.emit(r)
+ close()
+
+
+# ---------- Pure editing logic ----------
+
+## Wraps text[sel.x:sel.y] in open/close_tag. With an empty range, inserts the
+## pair. Returns {text, caret}: the caret sits inside an inserted pair, or
+## after the closing tag of a wrapped selection.
+static func wrap_text(text: String, sel: Vector2i, open: String, close_tag: String) -> Dictionary:
+ var a := clampi(mini(sel.x, sel.y), 0, text.length())
+ var b := clampi(maxi(sel.x, sel.y), 0, text.length())
+ var out := text.substr(0, a) + open + text.substr(a, b - a) + close_tag + text.substr(b)
+ var caret := a + open.length() if a == b else b + open.length() + close_tag.length()
+ return {"text": out, "caret": caret}
+
+
+## "a, b ,, a" -> ["a", "b"].
+static func parse_tags(text: String) -> Array[String]:
+ var out: Array[String] = []
+ for part in text.split(","):
+ var t := part.strip_edges()
+ if t != "" and not out.has(t):
+ out.append(t)
+ return out
+
+
+## Number of pipes beyond the first, summed over entries (lost when going ranged).
+static func extra_pipe_count(t: RollTable) -> int:
+ var n := 0
+ for e in t.entries:
+ n += maxi(0, e.pipes.size() - 1)
+ return n
+
+
+## Applies a settings Dictionary (name, details, tags, ranged, dice, card_mode,
+## deck_empty) to the table. Returns {ok, error, deck_reset}: on a bad dice
+## expression nothing is changed. deck_reset says the card deck no longer fits
+## (type, dice or card mode changed), so a saved deck should be cleared.
+static func apply_settings(t: RollTable, s: Dictionary) -> Dictionary:
+ var ranged: bool = s.get("ranged", false)
+ var dice := str(s.get("dice", t.dice)).strip_edges()
+ if ranged and not Dice.is_valid_text(dice):
+ return {"ok": false, "error": "“%s” is not a valid dice expression." % dice, "deck_reset": false}
+ var was_ranged := t.is_ranged()
+ var old_dice := t.dice
+ var old_card := t.card_mode
+ var new_name := str(s.get("name", t.name)).strip_edges()
+ if new_name != "":
+ t.name = new_name
+ t.details = str(s.get("details", t.details))
+ t.tags = parse_tags(str(s.get("tags", "")))
+ t.card_mode = bool(s.get("card_mode", t.card_mode))
+ t.deck_empty = "stop" if str(s.get("deck_empty", t.deck_empty)) == "stop" else "reshuffle"
+ if ranged:
+ t.dice = dice
+ if not was_ranged:
+ assign_ranges(t)
+ elif was_ranged:
+ drop_ranges(t)
+ var deck_reset := was_ranged != ranged or old_card != t.card_mode or (ranged and old_dice != t.dice)
+ return {"ok": true, "error": "", "deck_reset": deck_reset}
+
+
+## Gives entries ranges on the table's dice, sized by weight (at least one
+## value each while there is room). Entries of weight 0 get no range. Each
+## entry keeps only its first pipe, since a range takes one pipe.
+static func assign_ranges(t: RollTable) -> void:
+ var d := t.dice_obj()
+ var lo := d.min_value()
+ var hi := d.max_value()
+ var live: Array[TableEntry] = []
+ var total := 0
+ for e in t.entries:
+ e.has_range = false
+ if e.weight > 0:
+ live.append(e)
+ total += e.weight
+ while e.pipes.size() > 1:
+ e.remove_pipe(e.pipes[e.pipes.size() - 1])
+ var span := hi - lo + 1
+ var cum := 0
+ var prev := lo - 1
+ for i in live.size():
+ var e := live[i]
+ if prev >= hi:
+ break
+ cum += e.weight
+ var end := lo - 1 + roundi(float(span) * cum / total)
+ end = mini(end, hi - (live.size() - 1 - i))
+ end = clampi(maxi(end, prev + 1), prev + 1, hi)
+ if i == live.size() - 1:
+ end = hi
+ e.has_range = true
+ e.range_lo = prev + 1
+ e.range_hi = end
+ prev = end
+
+
+static func drop_ranges(t: RollTable) -> void:
+ for e in t.entries:
+ e.has_range = false
+ e.range_lo = 1
+ e.range_hi = 1
diff --git a/ui/table_settings_dialog.gd.uid b/ui/table_settings_dialog.gd.uid
new file mode 100644
index 0000000..72fe1d1
--- /dev/null
+++ b/ui/table_settings_dialog.gd.uid
@@ -0,0 +1 @@
+uid://cql8vbrr3s6ti