Split ui/main.gd into area helpers (no behaviour change)

Main (3679 lines) becomes a shell: shared state, start-up, cards, input,
rules view and one-line delegators for the methods other files call. Each
area moves with its state into a RefCounted helper holding a back-reference
(m: Main):

  main_cli.gd          command-line and screenshot flags
  main_top_bar.gd      top bar, toast, endless-loop chip
  main_editing.gd      add/delete cards, results and pipes, selection bar
  main_groups.gd       groups and card drags
  main_templates.gd    templates
  main_rolling.gd      rolling, choice questions, playback, session seed, copy
  main_collections.gd  collections, import/export, table settings, test board
  main_state.gd        decks, variables, roll history (local state)
  main_navigation.gd   search, focus, minimap, arrange/pack
  main_history.gd      undo/redo and mark_dirty
  main_inspector.gd    inspector selection and refresh

Tests that reached moved private members now go through the helper
(main.undo_redo.edits, main.rolling.pending_choice(), ...).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
RobinFiredrake 2026-11-09 08:14:19 -06:00
parent f3912fb026
commit 0202312688
30 changed files with 3825 additions and 3520 deletions

View file

@ -24,7 +24,7 @@ func _init() -> void:
main.set_anchors_preset(Control.PRESET_TOP_LEFT)
main.size = Vector2(1280, 800)
main.rng.seed = 5
main.prompt_hook = main._ask_player
main.prompt_hook = main.rolling._ask_player
_add_tables()
await process_frame
@ -99,7 +99,7 @@ func _ask() -> ChoiceDialog:
main.start_roll("t_ask")
await process_frame
await process_frame
return main.pending_choice()
return main.rolling.pending_choice()
func _key(code: Key, ctrl: bool = false) -> InputEventKey:
@ -162,7 +162,7 @@ func _test_preview_content() -> void:
_check(_has(q, "×@terms"), "an expression pipe count shows")
q.free()
_check(d.preview_for_option(2) == null, "an option with nothing to show has no preview")
main.cancel_choice()
main.rolling.cancel_choice()
await process_frame
@ -182,7 +182,7 @@ func _test_keyboard_focus() -> void:
d._options[2].grab_focus()
await process_frame
_check(not d.preview_panel.visible, "an option with nothing to show hides the panel")
main.cancel_choice()
main.rolling.cancel_choice()
await process_frame
@ -200,7 +200,7 @@ func _test_minimize() -> void:
_check(d.mouse_filter == Control.MOUSE_FILTER_IGNORE, "the board gets the mouse while minimized")
_check(not d._dim.visible, "the dim goes away")
_check(not d.preview_panel.visible, "the preview hides")
_check(not d.reply.finished and main.pending_choice() == d, "the question is still waiting")
_check(not d.reply.finished and main.rolling.pending_choice() == d, "the question is still waiting")
d._input(_key(KEY_M))
_check(not d.minimized and d.card.is_visible_in_tree() and not d.pill.visible, "M again restores it")
_check(d._options[1].has_focus(), "the focused option is focused again")
@ -212,7 +212,7 @@ func _test_minimize() -> void:
_check(not d.reply.finished, "Esc does nothing while minimized")
d._input(_key(KEY_TAB))
_check(not d.minimized, "Tab restores")
main.cancel_choice()
main.rolling.cancel_choice()
await process_frame
@ -221,11 +221,11 @@ func _test_waiting_question() -> void:
if d == null:
_check(false, "the question opens for the waiting test")
return
var token: int = main._token
var token: int = main.rolling._token
d.minimize()
main.start_roll("t_loot")
await process_frame
_check(main.pending_choice() == d and not d.reply.finished and main._token == token, "a die click doesn't cancel the waiting question")
_check(main.rolling.pending_choice() == d and not d.reply.finished and main.rolling._token == token, "a die click doesn't cancel the waiting question")
_check(d.toast_panel.visible and _has(d.toast_panel, "Answer the waiting question first"), "a toast asks for the answer first")
var has_show := false
for c in (d.toast_panel.get_child(0) as Node).get_children():
@ -238,7 +238,7 @@ func _test_waiting_question() -> void:
main.set_mode(Main.Mode.BUILD)
_check(main.mode == Main.Mode.BUILD, "Build is a normal mode switch again")
main.set_mode(Main.Mode.PLAY)
main.cancel_choice()
main.rolling.cancel_choice()
await process_frame
@ -259,14 +259,14 @@ func _test_cancel_from_pill() -> void:
_check(got[0] == null and d.reply.finished, "the pill's Cancel answers Cancel")
await process_frame
await process_frame
_check(main.pending_choice() == null, "the dialog is gone")
_check(main.rolling.pending_choice() == null, "the dialog is gone")
# A roll can start again.
main.cancel_choice()
main.rolling.cancel_choice()
main.start_roll("t_ask")
await process_frame
await process_frame
_check(main.pending_choice() != null, "a new roll can start after cancelling")
main.cancel_choice()
_check(main.rolling.pending_choice() != null, "a new roll can start after cancelling")
main.rolling.cancel_choice()
await process_frame

View file

@ -148,14 +148,14 @@ func _group() -> TableGroup:
func _test_group_from_selection() -> void:
main.set_mode(Main.Mode.BUILD)
main.set_selection(["a", "b"])
main.editing.set_selection(["a", "b"])
_check(main.card_for("a").is_selected() and main.selection.size() == 2, "cards show as selected")
_check(main._sel_bar.visible, "the selection toolbar shows in Build")
var g := main.group_selection()
_check(main.editing._sel_bar.visible, "the selection toolbar shows in Build")
var g := main.grouping.group_selection()
for i in 3:
await process_frame
_check(g != null and g.members == ["a", "b"], "Group makes a group of the selection")
_check(main.selection.is_empty() and not main._sel_bar.visible, "grouping clears the selection")
_check(main.selection.is_empty() and not main.editing._sel_bar.visible, "grouping clears the selection")
var node := main.group_node(g.id)
_check(node != null and node.get_parent() == main.board.groups, "an expanded group's frame sits behind the pipes")
var ra := Rect2(main.card_for("a").position, main.card_for("a").size)
@ -193,12 +193,12 @@ func _test_lit_and_choice() -> void:
var g := _group()
var node := main.group_node(g.id)
# A real roll through the hidden choice card: the pop-up opens and answers.
main.prompt_hook = main._ask_player
main.prompt_hook = main.rolling._ask_player
main.start_roll("start")
var d: ChoiceDialog = null
for i in 60:
await process_frame
d = main.pending_choice()
d = main.rolling.pending_choice()
if d:
break
_check(d != null, "a choice card hidden in a collapsed group still asks")
@ -231,7 +231,7 @@ func _test_lit_and_choice() -> void:
if main.current.get("done", false):
break
_check(main.is_entry_lit("b", "e1"), "a fast roll lights hidden members too")
main.set_group_collapsed(g.id, false)
main.grouping.set_group_collapsed(g.id, false)
for i in 3:
await process_frame
_check(main.card_for("a").visible and main.group_node(g.id).get_parent() == main.board.groups, "expanding shows the members again")
@ -247,11 +247,11 @@ func _test_move() -> void:
_check(g.position == before_g + Vector2(100, 50) and main.group_node(g.id).position == g.position, "and the frame")
_check(main.data.get_table("start").position == Vector2(40, 60), "non-members stay put")
# Collapsed groups move their hidden members too.
main.set_group_collapsed(g.id, true)
main.grouping.set_group_collapsed(g.id, true)
await process_frame
main.move_group(g.id, Vector2(-100, -50))
_check(main.data.get_table("a").position == before_a, "a collapsed group moves its hidden members")
main.set_group_collapsed(g.id, false)
main.grouping.set_group_collapsed(g.id, false)
for i in 3:
await process_frame
@ -265,7 +265,7 @@ func _test_drop_in_and_out() -> void:
main.begin_card_drag(loose)
var inside := g.position + Vector2(40, TableGroup.TITLE_H + 30)
main.drag_card(loose, inside)
_check(main._drag_over == main.group_node(g.id), "the frame under a dragged card lights as a drop target")
_check(main.grouping._drag_over == main.group_node(g.id), "the frame under a dragged card lights as a drop target")
main.end_card_drag(loose)
_check(g.has("loose"), "dropping a card in a frame adds it to the group")
for i in 3:
@ -276,7 +276,7 @@ func _test_drop_in_and_out() -> void:
main.end_card_drag(loose)
_check(not g.has("loose") and main.data.group_of("loose") == null, "dragging a card out of its frame takes it out")
# Multi-select drag moves every selected card.
main.set_selection(["start", "loose"])
main.editing.set_selection(["start", "loose"])
var s0 := main.card_for("start").position
var l0 := loose.position
main.begin_card_drag(loose)
@ -297,7 +297,7 @@ func _test_collapse_all_and_fit() -> void:
main.set_all_collapsed(true)
await process_frame
_check(g.collapsed and not _shown("a"), "Collapse all collapses groups too")
_check(main._collapse_all.text == "Expand all", "the button then offers Expand all")
_check(main.top_bar._collapse_all.text == "Expand all", "the button then offers Expand all")
# Fit ignores hidden members: move one far away; the bounds don't reach it.
main.data.get_table("a").position = Vector2(30000, 30000)
var bounds := main.board.content_bounds()
@ -314,7 +314,7 @@ func _test_ungroup_and_delete() -> void:
main.ungroup(g.id)
await process_frame
_check(main.data.groups.is_empty() and main.data.get_table("a") != null and main.card_for("a").visible, "Ungroup keeps the cards")
main._undo()
main.top_bar._undo()
await process_frame
g = _group()
_check(g != null and g.members == ["a", "b"], "Ungroup can be undone")
@ -332,8 +332,8 @@ func _test_ungroup_and_delete() -> void:
await process_frame
_check(main.data.groups.is_empty() and main.data.get_table("a") == null and main.data.get_table("b") == null, "deleting the group deletes its cards")
_check(main.card_for("a") == null and main.data.get_table("start").entries[0].pipes.is_empty(), "their cards and the pipes into them go")
_check(main._toast.visible and main._toast_undo.visible, "with an undo toast")
main._undo()
_check(main.top_bar._toast.visible and main.top_bar._toast_undo.visible, "with an undo toast")
main.top_bar._undo()
await process_frame
_check(main.data.groups.size() == 1 and main.data.get_table("a") != null and main.card_for("b") != null, "undo brings the group and its cards back")

View file

@ -121,7 +121,7 @@ func _test_selection() -> void:
main.select_result("beyond", "e2")
_eq(insp.selection.get("kind"), "result", "select_result")
_check(insp.effects != null and insp.pipe_parts.has("loot") and insp.pipe_parts.has("curios"), "a result shows its effects and both pipes")
main.select_pipe("beyond:e2>loot")
main.inspecting.select_pipe("beyond:e2>loot")
_eq(insp.selection.get("to"), "loot", "select_pipe")
_eq(insp.pipe_parts.keys(), ["loot"], "a pipe shows only its own box")
_eq(main.board.pipes.select_key, "beyond:e2>loot", "the selected pipe is highlighted on the board")
@ -147,7 +147,7 @@ func _test_selection() -> void:
main.delete_table("lp")
await _frames(2)
_check(insp.selection.is_empty(), "deleting the selected card clears the inspector")
main.undo()
main.undo_redo.undo()
await _frames(2)
_check(_t("lp") != null, "(undo brings the card back)")
_eq(_t("lp").to_dict()["name"], keep["name"], "(same card)")
@ -431,10 +431,10 @@ func _test_value_picker() -> void:
var card := main.variable_card("fame")
_check(card != null and card.name == "Fame", "Show on the board adds a variable card")
_eq(got.back(), "@fame", "and picks it")
var steps := main.edits.undo_stack.size()
var steps := main.undo_redo.edits.undo_stack.size()
n = p.create_value("Mood", false)
_eq(n, "@mood", "without a card")
_check(main.variable_card("mood") == null and main.edits.undo_stack.size() == steps, "no card, no board change")
_check(main.variable_card("mood") == null and main.undo_redo.edits.undo_stack.size() == steps, "no card, no board change")
p.queue_free()
await _frames()
@ -454,7 +454,7 @@ func _test_rules_view() -> void:
_eq(got.size(), 1, "setting the same view again doesn't fire")
main.set_rules_view("bogus")
_eq(main.rules_view(), "text", "unknown views are ignored")
main._rules_buttons[0].pressed.emit()
main.top_bar._rules_buttons[0].pressed.emit()
_eq(main.rules_view(), "plain", "the top-bar switch sets it")
_check(not insp.effects.text_mode, "builders are back")
await _frames()
@ -462,32 +462,32 @@ func _test_rules_view() -> void:
func _test_undo() -> void:
print("Undo")
main._commit_edits()
main.undo_redo._commit_edits()
main.select_result("beyond", "e2")
var before := _vault().effects
insp.effects.set_row_amount(0, "7")
main._commit_edits()
main.undo_redo._commit_edits()
_eq(_vault().effects, "@luck -= 7", "(the edit)")
main.undo()
main.undo_redo.undo()
await _frames(2)
_eq(_vault().effects, before, "undo puts the effects back")
_eq(insp.effects.rows[0]["amount"], "1", "the inspector shows the old text")
_eq(insp.selection.get("eid"), "e2", "and keeps the selection")
main.redo()
main.undo_redo.redo()
await _frames(2)
_eq(_vault().effects, "@luck -= 7", "redo")
# Typing in a field is one step once it pauses.
var le: LineEdit = insp.fields["text"]
le.grab_focus()
var steps := main.edits.undo_stack.size()
var steps := main.undo_redo.edits.undo_stack.size()
for s in ["The vault", "The vaults", "The vaults!"]:
le.text = s
le.text_changed.emit(s)
_eq(main.edits.undo_stack.size(), steps, "typing waits for a pause")
main._commit_edits()
_eq(main.edits.undo_stack.size(), steps + 1, "then makes one step")
_eq(main.undo_redo.edits.undo_stack.size(), steps, "typing waits for a pause")
main.undo_redo._commit_edits()
_eq(main.undo_redo.edits.undo_stack.size(), steps + 1, "then makes one step")
le.release_focus()
main.undo()
main.undo_redo.undo()
await _frames(2)
_eq(_vault().text, "The warden's vault", "one undo takes all the typing back")
await _frames()
@ -509,8 +509,8 @@ func _test_dirty_and_save() -> void:
copy.load_dict(main.data.to_dict())
_eq(copy.get_table("loot").tags, ["loot", "treasure"], "the saved form has it")
_eq(copy.get_table("beyond").find_entry("e2").with_for("loot"), {"tier": "3"}, "pipe inputs are saved")
main._commit_edits()
_check(main.can_undo(), "and it's an undo step")
main.undo_redo._commit_edits()
_check(main.undo_redo.can_undo(), "and it's an undo step")
await _frames()
@ -556,15 +556,15 @@ func _test_other_cards() -> void:
func _test_add_kinds() -> void:
print("+ Card ▾")
var labels: Array = main.ADD_KINDS.map(func(k: Array) -> String: return k[0])
var labels: Array = main.editing.ADD_KINDS.map(func(k: Array) -> String: return k[0])
_check(labels.any(func(s: String) -> bool: return s.begins_with("Check")), "Check card is in the menu")
_check(labels.any(func(s: String) -> bool: return s.begins_with("Collection")), "Collection is in the menu")
_eq(main._add_menu.text, "+ Card ▾", "the button reads + Card ▾")
var c := main.add_table(RollTable.KIND_CHECK)
_eq(main.editing._add_menu.text, "+ Card ▾", "the button reads + Card ▾")
var c := main.editing.add_table(RollTable.KIND_CHECK)
_check(c.kind == RollTable.KIND_CHECK and c.name == "Check" and c.entries.size() == 2, "adding a check card")
_eq(insp.selection.get("tid"), c.id, "a new card is selected in the inspector")
var col := main.add_table(RollTable.KIND_VARIABLE, RollTable.VAR_COLLECTION)
var col := main.editing.add_table(RollTable.KIND_VARIABLE, RollTable.VAR_COLLECTION)
_check(col.is_collection() and col.name == "Skills" and col.var_name == "skill_2", "adding a collection (%s, @%s)" % [col.name, col.var_name])
var v := main.add_table(RollTable.KIND_VARIABLE, "number")
var v := main.editing.add_table(RollTable.KIND_VARIABLE, "number")
_eq(v.name, "New variable", "a plain variable keeps its name")
await _frames()

View file

@ -45,8 +45,8 @@ func _init() -> void:
func _load_demo() -> void:
main.prompt_hook = main._ask_player
await main._load_board_file(DEMO)
main.prompt_hook = main.rolling._ask_player
await main.cli._load_board_file(DEMO)
for i in 3:
await process_frame
@ -72,7 +72,7 @@ func _past_spend(d: ChoiceDialog) -> ChoiceDialog:
d.answer(int(o["index"]))
break
await process_frame
return main.pending_choice()
return main.rolling.pending_choice()
func _var(name: String) -> Variant:
@ -153,13 +153,13 @@ func _test_scripted() -> void:
var sheet := main.card_for("report")
_check(Formatter.strip_tags(sheet._sheet_label.text).contains("HP %s" % Expr.format_value(_var("hp"))), "the sheet card is up to date")
_check(Formatter.strip_tags(sheet._sheet_label.text).begins_with("Brin the delver"), "the sheet shows the name")
main.prompt_hook = main._ask_player
main.prompt_hook = main.rolling._ask_player
func _test_dialog_answers() -> void:
main.start_roll("start", true)
await process_frame
var d := main.pending_choice()
var d := main.rolling.pending_choice()
_check(d != null and d.kind == "text", "the text pop-up opens (fast roll still asks)")
if d == null:
return
@ -172,7 +172,7 @@ func _test_dialog_answers() -> void:
d._text.text = "Ann"
d._confirm()
await process_frame
d = main.pending_choice()
d = main.rolling.pending_choice()
_check(d != null and d.kind == "number", "then the number pop-up")
if d == null:
return
@ -181,14 +181,14 @@ func _test_dialog_answers() -> void:
d._spin.value = 2
d._confirm()
await process_frame
d = await _past_spend(main.pending_choice())
d = await _past_spend(main.rolling.pending_choice())
_check(d != null and d.kind == "pick" and d._options.size() == 3, "then the pick pop-up with three options")
if d == null:
return
_check(main.is_entry_lit("explore", "e1") and main.is_entry_lit("explore", "e2"), "the loop's steps are lit before the pick")
d.answer(-1)
await process_frame
_check(main.pending_choice() == null and main.current.get("done", false), "Random finishes the roll")
_check(main.rolling.pending_choice() == null and main.current.get("done", false), "Random finishes the roll")
_eq(_var("name"), "Ann", "typed name saved")
_eq(_var("rooms"), 2, "typed number saved")
var random := false
@ -201,13 +201,13 @@ func _test_dialog_answers() -> void:
func _test_cancel() -> void:
main.start_roll("start")
await process_frame
var d := main.pending_choice()
var d := main.rolling.pending_choice()
_check(d != null, "a pop-up is open")
if d == null:
return
d.close() # Esc does this
await process_frame
_check(main.pending_choice() == null, "Esc closes the pop-up")
_check(main.rolling.pending_choice() == null, "Esc closes the pop-up")
_eq(main.current.get("halted", ""), "Cancelled", "Cancel stops the roll with Cancelled")
_check(main.current.get("done", false), "the cancelled roll is shown, not left hanging")
var last: Dictionary = (main.current["all"] as Array).back()
@ -217,7 +217,7 @@ func _test_cancel() -> void:
# Freeing the dialog some other way also answers Cancel.
main.start_roll("start")
await process_frame
d = main.pending_choice()
d = main.rolling.pending_choice()
if d:
d.free()
await process_frame
@ -227,14 +227,14 @@ func _test_cancel() -> void:
func _test_replace() -> void:
main.start_roll("start")
await process_frame
var first := main.pending_choice()
var first := main.rolling.pending_choice()
_check(first != null, "first roll asks")
var first_reply := first.reply if first else null
var history := main.history.size()
main.start_roll("start")
_check(first_reply != null and first_reply.finished, "a new roll answers the old question with Cancel")
await process_frame
var second := main.pending_choice()
var second := main.rolling.pending_choice()
_check(second != null and second != first, "the new roll opens its own pop-up")
_check(not is_instance_valid(first) or first.is_queued_for_deletion(), "the old pop-up goes away")
_check(not main.current.has("halted"), "the old roll doesn't overwrite the new one")
@ -244,11 +244,11 @@ func _test_replace() -> void:
second._text.text = "Cy"
second._confirm()
await process_frame
var n := main.pending_choice()
var n := main.rolling.pending_choice()
if n:
n.answer(1)
await process_frame
var p := main.pending_choice()
var p := main.rolling.pending_choice()
if p:
p.answer(2)
await process_frame
@ -259,12 +259,12 @@ func _test_replace() -> void:
func _test_keys() -> void:
main.start_roll("start")
await process_frame
var d := main.pending_choice()
var d := main.rolling.pending_choice()
if d:
d._text.text = "Dee"
d._confirm()
await process_frame
d = main.pending_choice()
d = main.rolling.pending_choice()
if d:
# Typing in the number field, then Enter.
var le := d._spin.get_line_edit()
@ -273,7 +273,7 @@ func _test_keys() -> void:
le.text_submitted.emit(le.text)
await process_frame
_eq(_var("rooms"), 4, "a typed number is used")
d = await _past_spend(main.pending_choice())
d = await _past_spend(main.rolling.pending_choice())
_check(d != null and d.kind == "pick", "pick pop-up for the key test")
if d == null:
return
@ -282,7 +282,7 @@ func _test_keys() -> void:
ev.pressed = true
d._input(ev)
await process_frame
_check(main.pending_choice() == null and main.current.get("done", false), "pressing 3 answers")
_check(main.rolling.pending_choice() == null and main.current.get("done", false), "pressing 3 answers")
var paid := false
for s: Dictionary in main.current["all"]:
if s.get("table_id") == "way_out" and Formatter.strip_tags(str(s["text"])) == "Pay the toll":
@ -363,12 +363,12 @@ func _test_settings_rules() -> void:
func _test_add_kinds() -> void:
main.set_mode(Main.Mode.BUILD)
var n := main.data.tables.size()
for k: Array in Main.ADD_KINDS:
var t := main.add_table(str(k[1]), str(k[2]))
for k: Array in MainEditing.ADD_KINDS:
var t := main.editing.add_table(str(k[1]), str(k[2]))
_check(t.kind == k[1] and main.card_for(t.id) != null, "+ Table adds a %s" % str(k[0]))
_eq(main.data.tables.size(), n + Main.ADD_KINDS.size(), "one card per menu item")
var v1 := main.add_table(RollTable.KIND_VARIABLE, "number")
var v2 := main.add_table(RollTable.KIND_VARIABLE, "number")
_eq(main.data.tables.size(), n + MainEditing.ADD_KINDS.size(), "one card per menu item")
var v1 := main.editing.add_table(RollTable.KIND_VARIABLE, "number")
var v2 := main.editing.add_table(RollTable.KIND_VARIABLE, "number")
_check(v1.var_name != v2.var_name, "new variable cards get distinct names")
main.set_mode(Main.Mode.PLAY)
@ -425,7 +425,7 @@ func _test_long_chain() -> void:
_eq(_chips(), ResultTray.MAX_EXPANDED, "expanding shows more steps (capped)")
_check(ms < 4000, "lighting 3,000 steps is quick (%d ms)" % ms)
print(" (3,001-step roll, lit and shown in %d ms)" % ms)
_check(main.result_text(all, ResultTray.COPY_TEXT).length() < 3001 * 40, "copy text indents are capped")
_check(main.rolling.result_text(all, ResultTray.COPY_TEXT).length() < 3001 * 40, "copy text indents are capped")
var line := ResultTray.earlier_line({"root_name": "x", "steps": all})
_check(line.length() < 2000, "Earlier rows show the last few steps of a long chain")
await process_frame

View file

@ -162,7 +162,7 @@ func _find(results: Array, tid: String, eid: String) -> Dictionary:
func _test_search_panel() -> void:
var p := main.open_search()
var p := main.nav.open_search()
await process_frame
_check(p.visible and p.field.has_focus(), "Search opens with the field focused")
p.field.text = "posting"
@ -206,13 +206,13 @@ func _test_focus() -> void:
break
var card := main.card_for("agent")
_check(not g.collapsed and main.data.to_dict()["groups"][0].get("collapsed", false) == false, "focus expands the collapsed group (saved)")
_check(main._toast.visible and main._toast_label.text.contains("Opened group Careers"), "and says so: %s" % main._toast_label.text)
_check(main.top_bar._toast.visible and main.top_bar._toast_label.text.contains("Opened group Careers"), "and says so: %s" % main.top_bar._toast_label.text)
_check(card != null, "the card is built")
if card == null:
return
var view := main.board.view_rect()
var r := Rect2(card.position, card.size)
_check(main.board.zoom >= Main.MIN_FOCUS_ZOOM, "the view zooms in to read it: %.2f" % main.board.zoom)
_check(main.board.zoom >= MainNavigation.MIN_FOCUS_ZOOM, "the view zooms in to read it: %.2f" % main.board.zoom)
_check(view.encloses(Rect2(r.position, Vector2(r.size.x, minf(r.size.y, view.size.y - 20.0)))), "the card is in view: %s in %s" % [str(r), str(view)])
_check(absf(view.get_center().x - r.get_center().x) < 2.0, "and centred")
_check(card.list_scroll != null and card.list_scroll.scroll_vertical > 0, "the long list scrolls to the result")
@ -237,9 +237,9 @@ func _test_focus() -> void:
func _test_minimap() -> void:
var mm := main.board.minimap
main.set_minimap_visible(true)
main.nav.set_minimap_visible(true)
await process_frame
_check(mm.visible and main._map_toggle.button_pressed, "the minimap shows, and its toggle is on")
_check(mm.visible and main.nav._map_toggle.button_pressed, "the minimap shows, and its toggle is on")
_check(mm.position.x + mm.size.x <= main.board.size.x and mm.position.y + mm.size.y <= main.board.size.y, "in the board's bottom-right corner")
mm.set_world(Rect2(-100, -100, 4000, 2000))
var p := Vector2(1234, 567)
@ -282,7 +282,7 @@ func _test_pack() -> void:
main.set_mode(Main.Mode.BUILD)
var before := _blocks()
var bounds0 := main.board.content_bounds()
var moved: int = await main.pack_collapsed_groups()
var moved: int = await main.nav.pack_collapsed_groups()
var after := _blocks()
_check(moved > 0, "Pack moves blocks: %d" % moved)
_check(not _overlaps(after.values()), "nothing overlaps after Pack: %s" % str(after))
@ -293,14 +293,14 @@ func _test_pack() -> void:
_check(bounds1.size.x < bounds0.size.x * 0.5 and bounds1.size.y < bounds0.size.y, "the board gets much smaller: %s -> %s" % [str(bounds0.size), str(bounds1.size)])
var agent := main.data.get_table("agent")
_check(agent.position - main.data.get_group("careers").position == Vector2(22, 68), "members move with their group")
_check(main._toast.visible and main._toast_undo.visible, "with an undo toast")
main._undo()
_check(main.top_bar._toast.visible and main.top_bar._toast_undo.visible, "with an undo toast")
main.top_bar._undo()
await process_frame
var back := _blocks()
_check(back["skills"].position == before["skills"].position and back["start"].position == before["start"].position
and back["careers"].position == before["careers"].position, "undo puts everything back")
# Expanding a packed group makes room instead of overlapping.
await main.pack_collapsed_groups()
await main.nav.pack_collapsed_groups()
main.toggle_group("careers")
for i in 3:
@ -308,7 +308,7 @@ func _test_pack() -> void:
var grown := _blocks()
_check(not _overlaps(grown.values()), "expanding a packed group pushes its neighbours clear: %s" % str(grown))
_check(grown["careers"].position.x < grown["skills"].position.x, "keeping their order")
_check(main._toast_label.text.contains("make room") and main._toast_undo.visible, "and says so, with undo: %s" % main._toast_label.text)
_check(main.top_bar._toast_label.text.contains("make room") and main.top_bar._toast_undo.visible, "and says so, with undo: %s" % main.top_bar._toast_label.text)
func _test_zoom_range() -> void:
@ -322,7 +322,7 @@ func _test_zoom_range() -> void:
## Rects of the blocks Pack works on: groups (compact or frame) and loose cards.
func _blocks() -> Dictionary:
var out := {}
for b: Dictionary in main._layout_blocks():
for b: Dictionary in main.nav._layout_blocks():
out[b["group"] if b["group"] != "" else b["table"]] = b["rect"]
return out

View file

@ -224,7 +224,7 @@ func _test_app() -> void:
{"id": "wounds", "name": "Wounds", "x": 40, "y": 400, "entries": [{"id": "e1", "text": "Ouch"}]}]})
main._rebuild_cards()
await process_frame
var lib := main.templates()
var lib := main.templating.templates()
_check(lib.root == "", "with --sample, templates stay in memory")
# Save a card from the board through the dialog.
var before := lib.list().size()
@ -240,7 +240,7 @@ func _test_app() -> void:
_check(lib.list().size() == before + 1, "Save template adds it to the library")
main.data.get_table("start").name = "Start"
# The picker lists built-ins and user templates, and searches.
var picker := main.open_template_picker()
var picker := main.templating.open_template_picker()
await process_frame
var ids := picker.shown_ids()
_check(ids.has("builtin:2d-check") and ids.has("builtin:counter"), "the list shows the built-in templates")
@ -265,7 +265,7 @@ func _test_app() -> void:
_check(var_card != null and main.card_for(var_card.id) != null, "its variable card is on the board")
# Insert with values and an outside pipe that relinks.
var tpl := TemplateKit.make(_board(), ["chk", "outcome"], "selection", "Check")
var r := main.insert_template(tpl, {"skill": "stealth", "target": "9", "n": "1"})
var r := main.templating.insert_template(tpl, {"skill": "stealth", "target": "9", "n": "1"})
await process_frame
var chk: RollTable = r["tables"][0]
_check(main.card_for(chk.id) != null and chk.name == "stealth check", "the inserted cards appear")
@ -273,14 +273,14 @@ func _test_app() -> void:
var center := main.board.screen_to_world(main.board.size / 2.0)
var ext := TemplateKit.extent(tpl)
_check(chk.position.distance_to((center - ext / 2.0).round().max(Vector2(20, 20 + TableGroup.TITLE_H))) < 2.0, "placed around the view centre")
_check(main._toast.visible and main._toast_undo.visible, "an undo toast follows")
main._undo()
_check(main.top_bar._toast.visible and main.top_bar._toast_undo.visible, "an undo toast follows")
main.top_bar._undo()
await process_frame
_check(main.data.get_table(chk.id) == null, "undo removes the inserted cards")
# Dropped pipes get a report.
main.data.remove_table("wounds")
main._rebuild_cards()
main.insert_template(tpl, {"skill": "x", "target": "1", "n": "1"})
main.templating.insert_template(tpl, {"skill": "x", "target": "1", "n": "1"})
await process_frame
var rep := _top_modal()
_check(rep != null and rep.title_label.text.begins_with("Inserted"), "pipes that can't relink are listed in a report")

View file

@ -93,11 +93,11 @@ func _t(id: String) -> RollTable:
func _label() -> String:
return main.edits.undo_label()
return main.undo_redo.edits.undo_label()
func _steps() -> int:
return main.edits.undo_stack.size()
return main.undo_redo.edits.undo_stack.size()
func _line_edit_with(n: Node, text: String) -> LineEdit:
@ -170,22 +170,22 @@ func _test_typing() -> void:
s += ch
le.text = s
le.text_changed.emit(s)
_check(not main.edits.can_undo() and main.can_undo(), "while typing nothing is committed yet, but Undo is offered")
await create_timer(Main.EDIT_PAUSE + 0.3).timeout
_check(not main.undo_redo.edits.can_undo() and main.undo_redo.can_undo(), "while typing nothing is committed yet, but Undo is offered")
await create_timer(MainHistory.EDIT_PAUSE + 0.3).timeout
_check(_steps() == 1 and _label() == "Rename Loot → Loot of the deep", "a pause commits the typing as one step: %d, %s" % [_steps(), _label()])
for ch in "!!":
s += ch
le.text = s
le.text_changed.emit(s)
main._commit_edits()
main.undo_redo._commit_edits()
_check(_steps() == 1 and _t("a").name == "Loot of the deep!!", "more typing in the same field joins that step: %d" % _steps())
le.release_focus()
main.undo()
main.undo_redo.undo()
_check(_t("a").name == "Loot", "undo puts the old name back")
_check(main._toast_label.text == "Undid: Rename Loot → Loot of the deep!!", "a toast says what was undone: %s" % main._toast_label.text)
main.redo()
_check(_t("a").name == "Loot of the deep!!" and main._toast_label.text.begins_with("Redid: "), "redo brings it back")
main.undo()
_check(main.top_bar._toast_label.text == "Undid: Rename Loot → Loot of the deep!!", "a toast says what was undone: %s" % main.top_bar._toast_label.text)
main.undo_redo.redo()
_check(_t("a").name == "Loot of the deep!!" and main.top_bar._toast_label.text.begins_with("Redid: "), "redo brings it back")
main.undo_redo.undo()
await _frames()
@ -204,9 +204,9 @@ func _test_card_fields() -> void:
main.mark_dirty()
await _frames()
_check(_steps() == n0 + 2, "an effect and details right after merge into one step on the same card: %d" % (_steps() - n0))
main.undo()
main.undo_redo.undo()
_check(_t("a").entries[0].effects == "" and _t("a").details == "" and _t("a").entries[0].weight == 4, "undo takes both back, leaving the weight")
main.undo()
main.undo_redo.undo()
_check(_t("a").entries[0].weight == 1, "and then the weight")
# Settings go through the dialog's applied signal.
main.open_table_settings("b")
@ -222,7 +222,7 @@ func _test_card_fields() -> void:
dlg.close()
await _frames()
_check(_label() == "Edit settings of Gems", "settings are a step: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(not _t("b").card_mode, "undo puts the settings back")
@ -230,41 +230,41 @@ func _test_results_and_tables() -> void:
print("Results and tables")
main.add_entry("a")
_check(_label() == "Add result to Loot" and _t("a").entries.size() == 3, "adding a result: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(_t("a").entries.size() == 2, "undo removes it")
main.redo()
main.undo_redo.redo()
_check(_t("a").entries.size() == 3, "redo adds it back")
main.undo()
main.undo_redo.undo()
main.delete_entry("a", "e2")
_check(_label() == "Delete result “Silver” from Loot", "deleting a result: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(_t("a").find_entry("e2") != null and _t("a").find_entry("e2").text == "Silver", "undo brings the result back")
var t := main.add_table()
var t := main.editing.add_table()
_check(_label() == "Add table New table", "adding a table: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(_t(t.id) == null and main.card_for(t.id) == null, "undo removes the table and its card")
main.add_table(RollTable.KIND_CHOICE, "pick")
main.editing.add_table(RollTable.KIND_CHOICE, "pick")
_check(_label() == "Add choice New choice", "adding a choice card: %s" % _label())
main.undo()
main.undo_redo.undo()
main.delete_table("b")
_check(_label() == "Delete table Gems" and _t("a").entries[0].pipes.is_empty(), "deleting a table: %s" % _label())
main.undo()
main.undo_redo.undo()
await _frames()
_check(_t("b") != null and main.card_for("b") != null and _t("a").entries[0].pipes == ["b"], "undo brings the table, its card and the pipe into it back")
func _test_pipes() -> void:
print("Pipes")
main._begin_edit()
main.undo_redo._begin_edit()
_t("a").entries[1].pipes.append("c")
main.mark_dirty()
await _frames()
_check(_label() == "Add pipe Loot → Weapons", "laying a pipe: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(_t("a").entries[1].pipes.is_empty(), "undo takes the pipe away")
main.remove_pipe("a:e1>b")
_check(_label() == "Remove pipe Loot → Gems" and main._toast_undo.visible, "removing a pipe, with an undo toast: %s" % _label())
main.undo()
_check(_label() == "Remove pipe Loot → Gems" and main.top_bar._toast_undo.visible, "removing a pipe, with an undo toast: %s" % _label())
main.undo_redo.undo()
_check(_t("a").entries[0].pipes == ["b"], "undo lays it again")
var e := _t("a").entries[0]
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
@ -290,12 +290,12 @@ func _test_pipes() -> void:
main.mark_dirty()
await _frames()
_check(_steps() == n0 + 4, "save as, Only if and Otherwise are steps of their own: %d" % (_steps() - n0))
main.undo()
main.undo_redo.undo()
_check(_t("a").entries[0].when_for("b") == "@hp > 2" and not _t("a").entries[0].is_otherwise("b"), "undo: Only if back")
main.undo()
main.undo_redo.undo()
_check(_t("a").entries[0].when_for("b") == "" and _t("a").entries[0].save_for("b") == "gem", "undo: condition gone, save kept")
main.undo()
main.undo()
main.undo_redo.undo()
main.undo_redo.undo()
_check(_t("a").entries[0].count_for("b") == 1 and _t("a").entries[0].save_for("b") == "", "undo: count back to 1")
@ -315,7 +315,7 @@ func _test_drag() -> void:
main.end_card_drag(card)
await _frames()
_check(_steps() == n0 + 1 and _label() == "Move Gems", "a whole drag is one step: %d, %s" % [_steps() - n0, _label()])
main.undo()
main.undo_redo.undo()
_check(_t("b").position == p0 and main.card_for("b").position == p0, "undo moves the card back")
# Dragging into a group frame joins it.
card = main.card_for("b")
@ -324,11 +324,11 @@ func _test_drag() -> void:
main.end_card_drag(card)
await _frames()
_check(_label() == "Add 1 card to group Careers" and main.data.group_of("b") != null, "dropping into a group: %s" % _label())
main.undo()
main.undo_redo.undo()
await _frames()
_check(main.data.group_of("b") == null and _t("b").position == p0, "undo takes it back out")
# Several selected cards move together as one step.
main.set_selection(["a", "b"])
main.editing.set_selection(["a", "b"])
card = main.card_for("a")
var pa := card.position
main.begin_card_drag(card)
@ -336,27 +336,27 @@ func _test_drag() -> void:
main.end_card_drag(card)
await _frames()
_check(_label() == "Move 2 cards", "moving a selection: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(_t("a").position == pa and main.selection.is_empty(), "undo moves them back and clears the selection")
func _test_groups() -> void:
print("Groups")
main.set_selection(["a", "b"])
var g := main.group_selection()
main.editing.set_selection(["a", "b"])
var g := main.grouping.group_selection()
_check(_label() == "Group %s" % g.name, "grouping: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(main.data.get_group(g.id) == null and main.group_node(g.id) == null, "undo removes the group")
main.redo()
main.undo_redo.redo()
_check(main.data.get_group(g.id) != null and main.group_node(g.id) != null, "redo makes it again")
main.undo()
main.undo_redo.undo()
main.ungroup("g1")
_check(_label() == "Ungroup Careers", "ungrouping: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(main.data.get_group("g1") != null and main.data.get_group("g1").members == ["c", "d"], "undo puts the group back")
main.delete_group("g1")
main.grouping.delete_group("g1")
_check(_label() == "Delete group Careers" and _t("c") == null, "deleting a group: %s" % _label())
main.undo()
main.undo_redo.undo()
await _frames()
_check(_t("c") != null and main.card_for("d") != null and main.group_node("g1") != null, "undo brings the group and its cards back")
var gpos := main.data.get_group("g1").position
@ -365,62 +365,62 @@ func _test_groups() -> void:
main.mark_dirty()
await _frames()
_check(_label() == "Move group Careers", "moving a group: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(_t("c").position == cpos and main.data.get_group("g1").position == gpos, "undo moves it back")
main.data.get_group("g1").name = "Jobs"
main.mark_dirty()
await _frames()
_check(_label() == "Rename group Jobs", "renaming a group: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(main.data.get_group("g1").name == "Careers", "undo restores the name")
main.data.remove_from_group("d")
main.mark_dirty()
await _frames()
_check(_label() == "Take 1 card out of group Careers", "taking a card out: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(main.data.get_group("g1").members.has("d"), "undo puts it back in")
func _test_template_and_reset() -> void:
print("Templates and Reset sample")
var tpl := TemplateKit.make(main.data, ["a"], "card", "Loot copy")
var r := main.insert_template(tpl, {})
var r := main.templating.insert_template(tpl, {})
await _frames()
var nt: RollTable = r["tables"][0]
_check(_label() == "Insert template Loot copy" and _t(nt.id) != null, "inserting a template: %s" % _label())
main.undo()
main.undo_redo.undo()
_check(_t(nt.id) == null and main.card_for(nt.id) == null, "undo removes the inserted cards")
await main.reset_sample()
await main.editing.reset_sample()
_check(_label() == "Reset sample" and _t("a") == null, "Reset sample is a step: %s" % _label())
main.undo()
main.undo_redo.undo()
await _frames()
_check(_t("a") != null and _t("a").name == "Loot" and main.data.get_group("g1") != null, "undo brings the board back")
func _test_pack() -> void:
print("Pack")
main.set_group_collapsed("g1", true)
main.grouping.set_group_collapsed("g1", true)
await _frames(3)
_check(not main.edits.can_redo() or true, "collapsing")
_check(not main.undo_redo.edits.can_redo() or true, "collapsing")
var gpos := main.data.get_group("g1").position
var moved: int = await main.pack_collapsed_groups()
var moved: int = await main.nav.pack_collapsed_groups()
_check(moved > 0 and _label() == "Pack collapsed groups", "Pack is a step: %s" % _label())
main.undo()
main.undo_redo.undo()
await _frames()
_check(main.data.get_group("g1").position == gpos, "undo puts the group back")
_check(main.data.get_group("g1").collapsed, "and leaves it collapsed")
main.set_group_collapsed("g1", false)
main.grouping.set_group_collapsed("g1", false)
await _frames(3)
func _test_redo_cleared() -> void:
print("Redo is cleared by a new edit")
main.add_entry("b")
main.undo()
_check(main.edits.can_redo(), "after undo, redo is offered")
main.undo_redo.undo()
_check(main.undo_redo.edits.can_redo(), "after undo, redo is offered")
main.add_entry("a")
_check(not main.edits.can_redo(), "a new edit clears it")
main.undo()
_check(not main.undo_redo.edits.can_redo(), "a new edit clears it")
main.undo_redo.undo()
func _test_view_kept() -> void:
@ -431,11 +431,11 @@ func _test_view_kept() -> void:
main.board.world.position = Vector2(-123, 45)
main.lit_entries["a:e1"] = true
main.lit_entries["b:e1"] = true
var panel := main.open_search()
var panel := main.nav.open_search()
panel.field.text = "loot"
panel.refresh()
main.delete_table("b")
main.undo()
main.undo_redo.undo()
await _frames()
_check(is_equal_approx(main.board.zoom, 0.6) and main.board.world.position == Vector2(-123, 45), "zoom and pan stay")
_check(main.lit_entries.has("a:e1") and main.lit_entries.has("b:e1") and main.is_entry_lit("b", "e1"), "lit results stay lit, also on the table brought back")
@ -447,7 +447,7 @@ func _test_view_kept() -> void:
main.board.fit()
await _frames()
main.add_entry("a")
main.undo()
main.undo_redo.undo()
await _frames(3)
_check(main.board.cards.is_flashing() and main.board.cards.flash_rect() == Rect2(main.card_for("a").position, main.card_for("a").size), "the changed card flashes")
@ -455,38 +455,38 @@ func _test_view_kept() -> void:
func _test_toast() -> void:
print("Toast Undo")
main.delete_entry("a", "e2")
_check(main._toast.visible and main._toast_undo.visible, "deleting shows an undo toast")
main._toast_undo.pressed.emit()
_check(_t("a").find_entry("e2") != null and main.edits.can_redo(), "its Undo goes through the history (redo is offered)")
main.redo()
main.undo()
_check(main.top_bar._toast.visible and main.top_bar._toast_undo.visible, "deleting shows an undo toast")
main.top_bar._toast_undo.pressed.emit()
_check(_t("a").find_entry("e2") != null and main.undo_redo.edits.can_redo(), "its Undo goes through the history (redo is offered)")
main.undo_redo.redo()
main.undo_redo.undo()
main.delete_table("b")
_check(main._toast_undo.visible, "another undo toast")
_check(main.top_bar._toast_undo.visible, "another undo toast")
main.add_entry("a")
_check(not main._toast_undo.visible, "a newer edit hides the toast's Undo, so it can't undo the wrong thing")
main.undo()
main.undo()
_check(not main.top_bar._toast_undo.visible, "a newer edit hides the toast's Undo, so it can't undo the wrong thing")
main.undo_redo.undo()
main.undo_redo.undo()
_check(_t("b") != null, "undo twice brings the table back")
func _test_lazy_cards() -> void:
print("Lazily built cards")
main.set_group_collapsed("g1", true)
main.grouping.set_group_collapsed("g1", true)
await _frames(3)
_check(main.card_for("c") == null, "Weapons is hidden in the collapsed group, with no card")
_t("c").entries[0].text = "Axe"
main.mark_dirty()
await _frames()
_check(_label() == "Edit Weapons", "an edit to a hidden card is a step: %s" % _label())
main.undo()
main.undo_redo.undo()
await _frames(3)
_check(_t("c").entries[0].text == "Sword" and main.card_for("c") == null, "undo restores it and still doesn't build the card")
_check(main.data.get_group("g1").collapsed and main.group_node("g1") != null, "the group stays collapsed")
main.delete_group("g1")
main.undo()
main.grouping.delete_group("g1")
main.undo_redo.undo()
await _frames(3)
_check(main.data.get_group("g1").collapsed and main.card_for("c") == null, "a deleted collapsed group comes back collapsed, cards unbuilt")
main.set_group_collapsed("g1", false)
main.grouping.set_group_collapsed("g1", false)
await _frames(3)
var c := main.card_for("c")
_check(c != null and c.visible and _line_edit_with(c, "Sword") != null, "expanding it builds the restored card")
@ -502,7 +502,7 @@ func _test_collapse_not_undoable() -> void:
await _frames()
_check(_steps() == n0, "collapsing and expanding add no steps")
main.add_entry("a")
main.undo()
main.undo_redo.undo()
_check(_t("b").collapsed, "undo leaves Gems collapsed as it is")
main.toggle_collapse("b")
@ -510,11 +510,11 @@ func _test_collapse_not_undoable() -> void:
func _test_shortcuts_and_buttons() -> void:
print("Shortcuts and buttons")
main.add_entry("a")
_check(not main._undo_button.disabled and main._undo_button.tooltip_text == "Undo: Add result to Loot (Ctrl+Z)", "the Undo button names the step: %s" % main._undo_button.tooltip_text)
_check(main._redo_button.disabled, "Redo is disabled with nothing to redo")
_check(not main.undo_redo._undo_button.disabled and main.undo_redo._undo_button.tooltip_text == "Undo: Add result to Loot (Ctrl+Z)", "the Undo button names the step: %s" % main.undo_redo._undo_button.tooltip_text)
_check(main.undo_redo._redo_button.disabled, "Redo is disabled with nothing to redo")
main._shortcut_input(_key(KEY_Z, false))
_check(_t("a").entries.size() == 2, "Ctrl+Z undoes")
_check(not main._redo_button.disabled and main._redo_button.tooltip_text.begins_with("Redo: Add result to Loot"), "Redo is enabled and named: %s" % main._redo_button.tooltip_text)
_check(not main.undo_redo._redo_button.disabled and main.undo_redo._redo_button.tooltip_text.begins_with("Redo: Add result to Loot"), "Redo is enabled and named: %s" % main.undo_redo._redo_button.tooltip_text)
main._shortcut_input(_key(KEY_Z, true))
_check(_t("a").entries.size() == 3, "Ctrl+Shift+Z redoes")
main._shortcut_input(_key(KEY_Z, false))
@ -525,12 +525,12 @@ func _test_shortcuts_and_buttons() -> void:
main._shortcut_input(_key(KEY_Z, false))
_check(_t("a").entries.size() == 3, "with a text field focused, Ctrl+Z is left to the field")
le.release_focus()
main._undo_button.pressed.emit()
main.undo_redo._undo_button.pressed.emit()
_check(_t("a").entries.size() == 2, "the Undo button undoes")
while main.edits.can_undo():
main.undo()
_check(main._undo_button.disabled and main._undo_button.tooltip_text == "Nothing to undo", "with nothing left, Undo is disabled")
main.redo()
while main.undo_redo.edits.can_undo():
main.undo_redo.undo()
_check(main.undo_redo._undo_button.disabled and main.undo_redo._undo_button.tooltip_text == "Nothing to undo", "with nothing left, Undo is disabled")
main.undo_redo.redo()
func _key(code: Key, shift: bool) -> InputEventKey:
@ -561,18 +561,18 @@ func _test_collections() -> void:
print("Per-collection history")
main.add_entry("a")
var first := main.data
var h := main.edits
var h := main.undo_redo.edits
var other := TowerBoard.new()
other.load_dict({"format_version": 2, "id": "other", "name": "Other", "tables": [
{"id": "x", "name": "X", "x": 0, "y": 0, "entries": [{"id": "e1", "text": "x"}]}]})
await main._show_collection(other)
_check(main.edits != h and not main.edits.can_undo(), "another collection has its own, empty history")
await main.collections._show_collection(other)
_check(main.undo_redo.edits != h and not main.undo_redo.edits.can_undo(), "another collection has its own, empty history")
main.add_entry("x")
_check(main.edits.undo_label() == "Add result to X", "edits there go to its history")
await main._show_collection(first)
_check(main.edits == h and main.edits.undo_label() == "Add result to Loot", "switching back keeps the first history")
_check(main.undo_redo.edits.undo_label() == "Add result to X", "edits there go to its history")
await main.collections._show_collection(first)
_check(main.undo_redo.edits == h and main.undo_redo.edits.undo_label() == "Add result to Loot", "switching back keeps the first history")
var n_before := _t("a").entries.size()
main.undo()
main.undo_redo.undo()
_check(_t("a").entries.size() == n_before - 1, "and undo still works: %d -> %d" % [n_before, _t("a").entries.size()])
@ -591,19 +591,19 @@ func _test_big_board() -> void:
var t := main.data.tables[main.data.tables.size() / 2]
var u := main.data.tables[main.data.tables.size() / 3]
var n := main.data.tables.size()
var full := EditHistory.full_bytes(main.edits.cache)
var full := EditHistory.full_bytes(main.undo_redo.edits.cache)
# One committed edit: what typing costs once it pauses.
t.name = t.name + " (edited)"
main.mark_dirty()
var t1 := Time.get_ticks_usec()
main._commit_edits()
main.undo_redo._commit_edits()
var commit_ms := (Time.get_ticks_usec() - t1) / 1000.0
var cap_ms := main.edits.last_capture_usec / 1000.0
var cap_ms := main.undo_redo.edits.last_capture_usec / 1000.0
u.name = u.name + " (edited)"
main.mark_dirty()
main._commit_edits()
main.undo_redo._commit_edits()
# The oldest step holds the whole board; later ones only what changed.
var step_bytes := int(main.edits.undo_stack.back()["snap"]["bytes"])
var step_bytes := int(main.undo_redo.edits.undo_stack.back()["snap"]["bytes"])
# A keystroke: the history's part (restarting a timer) against all of mark_dirty.
var le := LineEdit.new()
main.add_child(le)
@ -617,18 +617,18 @@ func _test_big_board() -> void:
for i in 20:
main._board_changed()
var base_ms := (Time.get_ticks_usec() - t4) / 1000.0 / 20.0
_check(main.edits.undo_stack.size() == 2, "keystrokes in a text field don't commit until typing pauses")
_check(main.undo_redo.edits.undo_stack.size() == 2, "keystrokes in a text field don't commit until typing pauses")
le.release_focus()
le.queue_free()
main._commit_edits()
main.undo_redo._commit_edits()
var t3 := Time.get_ticks_usec()
main.undo()
main.undo_redo.undo()
var undo_ms := (Time.get_ticks_usec() - t3) / 1000.0
var undo_one_ms := main._last_restore_usec / 1000.0
var undo_one_ms := main.undo_redo._last_restore_usec / 1000.0
# Undoing a deletion rebuilds the whole board.
main.delete_table(u.id)
var t5 := Time.get_ticks_usec()
main.undo()
main.undo_redo.undo()
var undo_del_ms := (Time.get_ticks_usec() - t5) / 1000.0
_check(_t(u.id) != null, "undoing a deletion on the big board brings the card back")
print(" TIMING %d cards: one committed edit %.1f ms (snapshot %.1f ms); keystroke %.2f ms, of which mark_dirty's existing refresh %.2f ms; undo of an edit %.1f ms (board update %.1f ms); undo of a deletion %.1f ms; board %d chars, later step %d bytes" % [

3568
ui/main.gd

File diff suppressed because it is too large Load diff

492
ui/main_cli.gd Normal file
View file

@ -0,0 +1,492 @@
class_name MainCli
extends RefCounted
## Main's command-line flags, used for screenshots and checks (see
## docs/DESIGN.md §5). Only automation needs this file.
var m: Main
func _init(p_main: Main) -> void:
m = p_main
# ---------- Command line (used for screenshots and checks) ----------
# godot --path . -- --screenshot=/tmp/shot.png [--build] [--expand-all] [--collapse-all]
# [--roll=<table id>] [--fast] [--shot-delay=<seconds>]
# [--board=<collection.json>] (with --sample/--screenshot only: show that board instead)
# [--tray=variables] [--hover=<x>,<y>] [--details=<table id>] [--pipe=<pipe key>] [--edit-details=<table id>]
static func _arg_value(args: PackedStringArray, name: String) -> String:
for a in args:
if a.begins_with(name + "="):
return a.substr(name.length() + 1)
return ""
func _run_cli(args: PackedStringArray) -> void:
var board_file := _arg_value(args, "--board")
if board_file != "" and not m._saving_enabled:
await _load_board_file(board_file)
if args.has("--build"):
m.set_mode(Main.Mode.BUILD)
if args.has("--expand-all"):
m.set_all_collapsed(false)
if args.has("--collapse-all"):
m.set_all_collapsed(true)
_run_shell_cli(args)
_run_logic_cli(args)
await _run_group_cli(args)
var roll := _arg_value(args, "--roll")
if roll != "":
m.start_roll(roll, args.has("--fast"))
_run_cli_extras(args)
_run_test_board_cli(args)
var shot := _arg_value(args, "--screenshot")
if shot == "":
return
var delay := _arg_value(args, "--shot-delay")
if args.has("--fit") or _arg_value(args, "--view") != "":
# Let the tray settle first (it can change the board's size).
await m.get_tree().process_frame
await m.get_tree().process_frame
if args.has("--fit"):
m.board.fit()
_apply_view_flag(args)
await m.get_tree().create_timer(delay.to_float() if delay != "" else (2.5 if roll != "" else 0.8)).timeout
var img := m.get_viewport().get_texture().get_image()
img.save_png(shot)
print("Saved screenshot to ", shot)
m.get_tree().quit()
# ----- Extra screenshot flags -----
# --open-settings=<table id> open the settings dialog
# --demo-import=<file> 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 != "":
m.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))
m._add_modal(IoMenu.report_dialog("Imported “%s”" % file.get_file().get_basename(), r))
if args.has("--demo-endless") and m.data.tables.size() >= 2:
var a := m.data.tables[0]
var b := m.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]
m._rebuild_cards()
m.mark_dirty()
var menu := _arg_value(args, "--menu")
if menu == "board":
m.top_bar._board_menu.show_popup()
elif menu == "collections":
m.top_bar._switcher.show_popup()
elif menu == "add":
# The Build tools were only just shown; let them lay out first.
await m.get_tree().process_frame
await m.get_tree().process_frame
m.editing._add_menu.show_popup()
# ----- Logic-card screenshot flags -----
# --answers=<a>|<b>|… answer the first questions automatically, in order
# (an option index or -1 for a pick, a number, or text);
# later questions open the pop-up
# --demo-long=<n> add a table that pipes into itself n times, and fast-roll it
# --confirm-reset open the Variables tab's "Reset all…" confirmation
# --edit-effects=<table id> open the effects editor on every row of a card (Build)
func _run_logic_cli(args: PackedStringArray) -> void:
var answers := _arg_value(args, "--answers")
if answers != "":
var queue: Array = Array(answers.split("|"))
m.prompt_hook = func(req: Dictionary) -> Variant:
if queue.is_empty():
return await m.rolling._ask_player(req)
var a := str(queue.pop_front())
return a if str(req.get("kind", "")) == "text" else a.to_int()
var n := _arg_value(args, "--demo-long").to_int()
if n > 0:
var head := RollTable.create(RollTable.KIND_ROLL, "long_start", "Long chain")
head.entries.resize(1)
head.entries[0].text = "Off we go"
head.entries[0].effects = "@k = 0"
head.entries[0].add_pipe("long_link")
var link := RollTable.create(RollTable.KIND_ROLL, "long_link", "Link")
link.entries.resize(1)
link.entries[0].text = "Link {@k}"
link.entries[0].effects = "@k += 1"
link.entries[0].add_pipe("long_link", "@k < %d" % n)
var y := 40.0
for t in m.data.tables:
y = maxf(y, t.position.y + 80.0)
head.position = Vector2(40, y + 400)
link.position = Vector2(360, y + 400)
m.data.tables.append(head)
m.data.tables.append(link)
m._rebuild_cards()
m.start_roll("long_start", true)
var fx := m.card_for(_arg_value(args, "--edit-effects"))
if fx:
for e in fx.table.entries:
fx._open_effects[e.id] = true
fx.rebuild()
if args.has("--confirm-reset"):
m.tray.set_side(ResultTray.Side.VARIABLES)
m.tray._vars.confirm_reset_all()
# ----- Group and template screenshot flags -----
# --select=<id>,<id>… select cards (Build)
# --group-selected[=<name>] group the selection
# --collapse-groups / --expand-groups every group
# --toggle-group=<group id> collapse or expand one group
# --templates[=<search>] open the template list
# --insert-template=<id> insert a template (builtin:<file> or a user id)
# [--template-values=<name>=<value>|…]
# --insert-form=<id> open a template's parameter form
# --save-template=<table id or name> open the save dialog for one card
# --save-group-template=<group id|first|last>
# --group-menu open the first group's ⋯ menu (Build)
# --drag-demo hold a card over the first group's frame (Build)
# --clear-result empty the tray (the board stays lit)
# --view=<x>,<y>[,<zoom>] centre the view on a world point (after Fit)
func _run_group_cli(args: PackedStringArray) -> void:
var sel := _arg_value(args, "--select")
if sel != "":
m.editing.set_selection(Array(sel.split(",")))
for a in args:
if a == "--group-selected" or a.begins_with("--group-selected="):
var g := m.grouping.group_selection()
if g and a.contains("="):
g.name = a.get_slice("=", 1)
m.grouping._groups_changed()
if args.has("--collapse-groups") or args.has("--expand-groups"):
for g in m.data.groups:
g.collapsed = args.has("--collapse-groups")
m.grouping._groups_changed()
var tg := _arg_value(args, "--toggle-group")
if tg != "":
for gid in tg.split(","):
m.toggle_group(gid)
var ins := _arg_value(args, "--insert-template")
if ins != "":
var tpl := m.templating.templates().get_template(ins)
var values := {}
for pair in _arg_value(args, "--template-values").split("|", false):
values[pair.get_slice("=", 0)] = pair.substr(pair.find("=") + 1)
if tpl.is_empty():
push_warning("No template %s" % ins)
else:
m.templating.insert_template(tpl, values)
var form := _arg_value(args, "--insert-form")
if form != "" and not m.templating.templates().get_template(form).is_empty():
m.begin_template_insert(m.templating.templates().get_template(form))
var st := _arg_value(args, "--save-template")
if st != "":
m.save_template_from([Roller.resolve(m.data, st)], "card")
var sg := _arg_value(args, "--save-group-template")
if sg != "" and not m.data.groups.is_empty():
var gid: String = sg
if sg == "first":
gid = m.data.groups[0].id
elif sg == "last":
gid = m.data.groups[m.data.groups.size() - 1].id
m.save_template_from([], "group", [gid])
for a in args:
if a == "--templates" or a.begins_with("--templates="):
var p := m.templating.open_template_picker()
if a.contains("="):
p._search.text = a.get_slice("=", 1)
p.refresh()
var shown := p.shown_ids()
if not shown.is_empty():
p.select(str(shown[0]))
if args.has("--group-selected") or sel != "" or ins != "":
# Let new cards and frames lay out.
await m.get_tree().process_frame
await m.get_tree().process_frame
if args.has("--group-menu") and not m.data.groups.is_empty():
await m.get_tree().process_frame
var gn := m.group_node(m.data.groups[0].id)
if gn and gn.menu_button:
gn.menu_button.show_popup()
if args.has("--drag-demo") and not m.data.groups.is_empty():
# A card held over the first group's frame, to show the drop highlight.
var g := m.data.groups[0]
for t in m.data.tables:
if not g.has(t.id) and m.card_for(t.id) and m.card_for(t.id).visible:
var c := m.card_for(t.id)
c.get_parent().move_child(c, -1)
m.begin_card_drag(c)
m.drag_card(c, g.position + Vector2(g.size.x * 0.5, TableGroup.TITLE_H + 40))
break
func _apply_view_flag(args: PackedStringArray) -> void:
var v := _arg_value(args, "--view")
if v == "":
return
var parts := v.split(",")
if parts.size() >= 3:
m.board.set_zoom(parts[2].to_float())
var p := Vector2(parts[0].to_float(), parts[1].to_float())
m.board.world.position = m.board.size / 2.0 - p * m.board.zoom
# ---------- Command line extras ----------
## Shows a collection file instead of the sample (screenshots only; nothing is saved).
func _load_board_file(path: String) -> void:
var text := FileAccess.get_file_as_string(path)
if text == "" or not m.data.load_json(text):
push_warning("Couldn't load board file %s" % path)
return
m.rolling._token += 1
m.rolling.cancel_choice()
m.top_bar._switcher.refresh()
m._rebuild_cards()
m.rolling._seed_session()
await m.get_tree().process_frame
await m.get_tree().process_frame
m.board.fit()
func _run_cli_extras(args: PackedStringArray) -> void:
if args.has("--perf"):
_run_perf()
await _run_undo_cli(args)
_run_nav_cli(args)
if args.has("--clear-result"):
# Keeps the board lit but empties the tray (a tall sheet result can fill it).
m.current = {}
m.tray.render()
if _arg_value(args, "--tray") == "variables":
m.tray.set_side(ResultTray.Side.VARIABLES)
var edit := _arg_value(args, "--edit-details")
var ecard := m.card_for(edit)
if ecard:
ecard._table_details_open = true
if not ecard.table.entries.is_empty():
ecard._open_details[ecard.table.entries[0].id] = true
ecard.rebuild()
var pipe := _arg_value(args, "--pipe")
if pipe != "":
m.open_pipe_options(pipe, Vector2(m.size.x * 0.45, m.size.y * 0.3))
await _run_inspector_cli(args)
var hover := _arg_value(args, "--hover")
if hover.contains(","):
# Synthetic mouse move, to check hover pop-ups in screenshots.
await m.get_tree().create_timer(0.3).timeout
var ev := InputEventMouseMotion.new()
ev.position = Vector2(hover.get_slice(",", 0).to_float(), hover.get_slice(",", 1).to_float())
ev.global_position = ev.position
m.get_viewport().notification(Control.NOTIFICATION_VP_MOUSE_ENTER)
m.get_viewport().push_input(ev)
var det := _arg_value(args, "--details")
var card := m.card_for(det)
if card:
await m.get_tree().process_frame
m.details().show_table(card, det)
m.details().pin(card.get_global_rect().position + Vector2(60, 46))
# --test-board open the Test board dialog (shows the last report if any)
# --test-board-run=<runs> ... and start a test with that many runs (100, 500 or 1000)
func _run_test_board_cli(args: PackedStringArray) -> void:
var n := _arg_value(args, "--test-board-run")
if not args.has("--test-board") and n == "":
return
m.set_mode(Main.Mode.BUILD)
var d := TestBoardDialog.new(m)
m._add_modal(d)
if n != "":
d.runs = n.to_int()
d.run_test()
## --perf: times a reload of the current board and the frame cost while idle
## and while panning (vsync off), then prints the numbers and quits.
func _run_perf() -> void:
DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED)
Engine.max_fps = 0
var text := m.data.to_json()
for i in 10:
await m.get_tree().process_frame
var t0 := Time.get_ticks_usec()
m.data.load_json(text)
var tj := Time.get_ticks_usec()
m._rebuild_cards()
var t1 := Time.get_ticks_usec()
m.rolling._seed_session()
var t2 := Time.get_ticks_usec()
await m.get_tree().process_frame
await m.get_tree().process_frame
var t3 := Time.get_ticks_usec()
m.board.fit()
print("PERF load: parse %.1f ms, rebuild_cards %.1f ms, seed %.1f ms, first two frames %.1f ms, total %.1f ms" % [
(tj - t0) / 1000.0, (t1 - tj) / 1000.0, (t2 - t1) / 1000.0, (t3 - t2) / 1000.0, (t3 - t0) / 1000.0])
print("PERF nodes: %d, table cards built: %d of %d" % [Performance.get_monitor(Performance.OBJECT_NODE_COUNT), m.cards.size(), m.data.tables.size()])
for i in 30:
await m.get_tree().process_frame
print("PERF idle (fit view): %s" % await _perf_frames(240, Vector2.ZERO))
m.board.set_zoom(0.6)
print("PERF pan (zoom 0.6): %s" % await _perf_frames(240, Vector2(-6, -2)))
m.board.set_zoom(1.0)
print("PERF idle (zoom 1): %s" % await _perf_frames(240, Vector2.ZERO))
print("PERF pan (zoom 1): %s" % await _perf_frames(240, Vector2(-6, -2)))
if OS.get_cmdline_user_args().has("--perf-layers"):
m.board.fit()
print("PERF idle (fit view again): %s" % await _perf_frames(120, Vector2.ZERO))
m.board.pipes.visible = false
print("PERF idle, no pipes: %s" % await _perf_frames(120, Vector2.ZERO))
m.board.ports.visible = false
print("PERF idle, no pipes or ports: %s" % await _perf_frames(120, Vector2.ZERO))
m.board.cards.visible = false
print("PERF idle, no cards either: %s" % await _perf_frames(120, Vector2.ZERO))
m.board.set_process(false)
m.board.groups.set_process(false)
print("PERF idle, board and group processing off: %s" % await _perf_frames(120, Vector2.ZERO))
m.get_tree().quit()
func _perf_frames(n: int, pan: Vector2) -> String:
var times: Array[float] = []
var last := Time.get_ticks_usec()
for i in n:
if pan != Vector2.ZERO:
m.board.world.position += pan
await m.get_tree().process_frame
var now := Time.get_ticks_usec()
times.append((now - last) / 1000.0)
last = now
times.sort()
var total := 0.0
for t in times:
total += t
return "mean %.2f ms, median %.2f ms, p95 %.2f ms" % [total / n, times[n / 2], times[int(n * 0.95)]]
# ----- Navigation screenshot flags -----
# --search=<text> open the search panel with that query
# --focus=<table id>[:<entry id>] jump to a card (and result)
# --minimap / --no-minimap show or hide the overview
# --pack Build ▸ Arrange ▸ Pack collapsed groups
# --perf print load and frame timings, then quit
func _run_nav_cli(args: PackedStringArray) -> void:
if args.has("--minimap"):
m.nav.set_minimap_visible(true)
if args.has("--no-minimap"):
m.nav.set_minimap_visible(false)
if args.has("--pack"):
await m.nav.pack_collapsed_groups()
var f := _arg_value(args, "--focus")
if f != "":
await m.get_tree().process_frame
m.focus_table(f.get_slice(":", 0), f.get_slice(":", 1) if f.contains(":") else "")
var q := _arg_value(args, "--search")
if q != "":
await m.get_tree().process_frame
var p := m.nav.open_search()
p.field.text = q
p.refresh()
# ----- Undo screenshot flags -----
# --undo-demo=<table id> delete that table (or the last one), then undo: the toast says so
# --undo-tooltip make an edit, then hover the Undo button so its tooltip shows
func _run_undo_cli(args: PackedStringArray) -> void:
var demo := _arg_value(args, "--undo-demo")
if args.has("--undo-demo") or demo != "":
m.set_mode(Main.Mode.BUILD)
var t: RollTable = m.data.get_table(demo) if demo != "" else (m.data.tables.back() if not m.data.tables.is_empty() else null)
if t:
m.delete_table(t.id)
await m.get_tree().process_frame
m.undo_redo.undo()
if args.has("--undo-tooltip"):
m.set_mode(Main.Mode.BUILD)
if not m.data.tables.is_empty():
m.delete_table(m.data.tables.back().id)
m.top_bar._toast.hide()
for i in 3:
await m.get_tree().process_frame
var at := m.undo_redo._undo_button.get_global_rect().get_center()
m.get_viewport().notification(Control.NOTIFICATION_VP_MOUSE_ENTER)
for i in 2:
var ev := InputEventMouseMotion.new()
ev.position = at + Vector2(i, 0)
ev.global_position = ev.position
m.get_viewport().push_input(ev)
await m.get_tree().process_frame
# --inspect=<table id>[:<entry id>][><target id>] select that card, result or pipe
# --rules=text show rules as text
# --pick-open open the inspector's first value picker
# --vars=name=value,… set board values (e.g. collection members)
# --light=<pipe key>,… light pipes and their results, as if rolled
# --window=<w>x<h> resize the window first (screenshots)
# --inspect-scroll=<px> scroll the inspector down
func _run_inspector_cli(args: PackedStringArray) -> void:
var win := _arg_value(args, "--window")
if win.contains("x"):
m.get_window().size = Vector2i(win.get_slice("x", 0).to_int(), win.get_slice("x", 1).to_int())
for i in 3:
await m.get_tree().process_frame
var rv := _arg_value(args, "--rules")
if rv != "":
m.set_rules_view(rv)
var vars := _arg_value(args, "--vars")
if vars != "":
for pair in vars.split(",", false):
var v := pair.get_slice("=", 1)
m.persistent_vars[pair.get_slice("=", 0)] = {"value": Expr.to_value(v) if Expr.is_number(v) else v, "source": ""}
m.local_state._variables_changed()
var light := _arg_value(args, "--light")
if light != "":
for k in light.split(",", false):
m.lit_pipes[k] = true
m.lit_entries[k.get_slice(">", 0)] = true
m._refresh_lit()
var sel := _arg_value(args, "--inspect")
if sel == "":
return
if m.mode != Main.Mode.BUILD:
m.set_mode(Main.Mode.BUILD)
if sel.contains(">"):
m.inspecting.select_pipe(sel)
elif sel.contains(":"):
m.select_result(sel.get_slice(":", 0), sel.get_slice(":", 1))
else:
m.select_card(sel)
var scroll := _arg_value(args, "--inspect-scroll")
if scroll != "":
for i in 3:
await m.get_tree().process_frame
m.inspector._scroll.scroll_vertical = scroll.to_int()
if args.has("--pick-open"):
for i in 3:
await m.get_tree().process_frame
var p := _first_picker(m.inspector)
if p:
p.open_menu()
func _first_picker(n: Node) -> ValuePicker:
for c in n.get_children():
if c is ValuePicker and (c as ValuePicker).is_visible_in_tree():
return c
var r := _first_picker(c)
if r:
return r
return null

1
ui/main_cli.gd.uid Normal file
View file

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

191
ui/main_collections.gd Normal file
View file

@ -0,0 +1,191 @@
class_name MainCollections
extends RefCounted
## Main's app shell: collections (switch, new, rename, duplicate, delete),
## import and export, the table settings dialog and the Test board. Pure rules
## live in CollectionSwitcher, IoMenu and TableSettingsDialog.
var m: Main
func _init(p_main: Main) -> void:
m = p_main
## True when collections can be listed and saved (not --sample / --screenshot).
func collections_enabled() -> bool:
return m._saving_enabled and m.library != null and m.state != null
## Opens the settings dialog for a table (Build mode editor).
func open_table_settings(table_id: String) -> void:
var t := m.data.get_table(table_id)
if t == null:
return
var d := TableSettingsDialog.new(t)
d.template_requested.connect(func() -> void: m.save_template_from([table_id], "card"))
m.undo_redo._begin_edit()
d.applied.connect(func(result: Dictionary) -> void:
if result.get("deck_reset", false) and m.state and m.data.id != "":
m.state.clear_deck(m.data.id, t.id)
if t.kind == RollTable.KIND_VARIABLE:
# Effect chips on other cards name variables by their card.
for c in m.cards.values():
(c as TableCard).rebuild()
else:
var card := m.card_for(t.id)
if card:
card.rebuild()
m.undo_redo._end_edit("Edit settings of %s" % Formatter.strip_tags(t.name))
m.refresh_live()
m.toast("Updated %s" % t.name, true)
)
m._add_modal(d)
# ----- Collections -----
func switch_collection(id: String) -> void:
if not collections_enabled() or id == m.data.id:
return
m.undo_redo._commit_edits()
m._save_timer.stop()
var b := CollectionSwitcher.switch_collection(m.library, m.data, id)
if b == null:
m.toast("Couldn't open that collection")
return
_show_collection(b)
## Swaps the board to `b`: loads that collection's decks, variables and roll
## history (lighting its last roll), rebuilds the cards, fits the view and
## remembers it as the last collection.
func _show_collection(b: TowerBoard) -> void:
# Waiting edits belong to the collection being left.
m.undo_redo._commit_edits()
m.data = b
m.rolling._token += 1
m.rolling.cancel_choice()
m.rolling_ctx = null
m.board.pipes.pulse_key = ""
m.local_state.load_local_state()
if not m.current.is_empty():
m.rolling._light_steps(m.current.get("all", []))
m._rebuild_cards()
m.tray.render()
if m.state:
m.state.set_setting("last_collection", m.data.id)
m.state.save()
m.top_bar._switcher.refresh()
m.top_bar._update_endless_chip()
await m.get_tree().process_frame
await m.get_tree().process_frame
m.board.fit()
func new_collection() -> void:
if not collections_enabled():
return
m._add_modal(ModalCard.ask_text("New collection", "Name", "", "Create", func(n: String) -> void:
_show_collection(CollectionSwitcher.create_collection(m.library, m.data, n))
m.toast("Created “%s”" % m.data.name)
))
func rename_collection() -> void:
if not collections_enabled():
return
m._add_modal(ModalCard.ask_text("Rename collection", "Name", m.data.name, "Rename", func(n: String) -> void:
if CollectionSwitcher.rename_collection(m.library, m.data, n):
m.top_bar._switcher.refresh()
))
func duplicate_collection() -> void:
if not collections_enabled():
return
var copy := CollectionSwitcher.duplicate_collection(m.library, m.data, m.data.name + " copy")
if copy == null:
m.toast("Couldn't duplicate the collection")
return
_show_collection(copy)
m.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." % m.data.name
m._add_modal(ModalCard.confirm("Delete collection", msg, "Delete", func() -> void:
var gone := m.data.name
var gone_id := m.data.id
var next := CollectionSwitcher.delete_collection(m.library, m.data)
if next:
m.undo_redo._histories.erase(gone_id)
_show_collection(next)
m.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(m.data, format)
dlg.file_selected.connect(func(path: String) -> void:
var err := TowerBoard.write_text_atomic(path, IoMenu.export_text(str(format["key"]), m.data))
m.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()
)
m.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()
)
m.add_child(dlg)
dlg.popup_centered_ratio(0.6)
func _import_file(path: String) -> void:
if not FileAccess.file_exists(path):
m.toast("Couldn't read %s" % path.get_file())
return
m._save_now()
var r := IoMenu.import_as_collection(m.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"]:
m._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"]:
m.toast("Imported “%s” as a new collection" % r["board"].name)
# ----- Test board -----
## Build: opens the Test board dialog (core/board_tester.gd), which keeps its
## last report while the app is open.
func open_test_board() -> void:
m._add_modal(TestBoardDialog.new(m))

View file

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

383
ui/main_editing.gd Normal file
View file

@ -0,0 +1,383 @@
class_name MainEditing
extends RefCounted
## Main's Build editing actions: adding and deleting cards, results and
## pipes, laying pipes by drag, and the card selection with its bar.
var m: Main
var _link_from: Dictionary = {}
var _drop_card: TableCard
var _add_menu: MenuButton
var _sel_bar: PanelContainer
var _sel_label: Label
## The "+ Card ▾" kinds: [label, kind, sub, default name].
const ADD_KINDS := [
["Roll table", RollTable.KIND_ROLL, "", "New table"],
["Check card: roll against a target", RollTable.KIND_CHECK, "", "Check"],
["Choice: which option", RollTable.KIND_CHOICE, "pick", "New choice"],
["Choice: how many", RollTable.KIND_CHOICE, "number", "How many?"],
["Choice: open ended", RollTable.KIND_CHOICE, "text", "What is it?"],
["Loop", RollTable.KIND_LOOP, "times", "Repeat"],
["Router: if / else if / otherwise", RollTable.KIND_ROUTER, "", "Router"],
["Variable", RollTable.KIND_VARIABLE, "number", "New variable"],
["Collection (Skills, Contacts…)", RollTable.KIND_VARIABLE, RollTable.VAR_COLLECTION, "Skills"],
["Sheet", RollTable.KIND_SHEET, "", "Sheet"],
]
const MENU_FROM_TEMPLATE := 100
const MENU_GROUP := 101
const MENU_SAVE_SELECTION := 102
func _init(p_main: Main) -> void:
m = p_main
func _make_add_menu() -> MenuButton:
var mb := MenuButton.new()
mb.text = "+ Card ▾"
mb.tooltip_text = "Add a roll table or a logic card"
mb.flat = false
var ref := Style.bar_button("", true)
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_font_override("font", Style.body_bold())
mb.add_theme_font_size_override("font_size", 15)
mb.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
ref.free()
var pm := mb.get_popup()
ModalCard.style_popup(pm)
for i in ADD_KINDS.size():
if i == 1:
pm.add_separator("Logic cards")
pm.add_item(str(ADD_KINDS[i][0]), i)
pm.add_separator("Groups and templates")
pm.add_item("From template…", MENU_FROM_TEMPLATE)
pm.add_item("Group selected cards Ctrl+G", MENU_GROUP)
pm.add_item("Save selection as template…", MENU_SAVE_SELECTION)
pm.about_to_popup.connect(func() -> void:
pm.set_item_disabled(pm.get_item_index(MENU_GROUP), m.selection.is_empty())
pm.set_item_disabled(pm.get_item_index(MENU_SAVE_SELECTION), m.selection.is_empty())
)
pm.id_pressed.connect(func(id: int) -> void:
match id:
MENU_FROM_TEMPLATE:
m.templating.open_template_picker()
MENU_GROUP:
m.grouping.group_selection()
MENU_SAVE_SELECTION:
m.templating.save_selection_as_template()
_:
var k: Array = ADD_KINDS[id]
add_table(str(k[1]), str(k[2]))
)
return mb
## Adds a card of any kind (RollTable.create) in the middle of the view.
func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "") -> RollTable:
m.undo_redo._begin_edit()
var center := m.board.screen_to_world(m.board.size / 2.0)
var name := "New table"
var found := false
for k: Array in ADD_KINDS:
if k[1] == kind and k[2] == sub:
name = str(k[3])
found = true
break
if not found:
for k: Array in ADD_KINDS:
if k[1] == kind and (sub == "" or kind != RollTable.KIND_CHOICE) and k[2] != RollTable.VAR_COLLECTION:
name = str(k[3])
break
var t := RollTable.create(kind, TowerBoard.new_id("t"), name, sub)
if kind == RollTable.KIND_ROLL or kind == RollTable.KIND_CHECK:
for e in t.entries:
e.id = TowerBoard.new_id("e")
if kind == RollTable.KIND_VARIABLE:
t.var_name = _free_var_name(t.var_name)
t.position = Vector2(maxf(20.0, roundf(center.x - 128.0)), maxf(20.0, roundf(center.y - 120.0)))
m.data.tables.append(t)
var card := TableCard.new()
m.board.cards.add_child(card)
card.setup(m, t)
m.cards[t.id] = card
m.undo_redo._end_edit()
if m.mode == Main.Mode.BUILD:
m.select_card(t.id)
return t
## Adds a variable card declaring @`var_name` (labelled `label`) beside the
## view's centre, for the value pickers' "+ New value…". An existing card
## for that name is returned as it is.
func add_variable_card(label: String, var_name: String, type: String = "number") -> RollTable:
var have := m.variable_card(var_name)
if have:
return have
m.undo_redo._begin_edit()
var center := m.board.screen_to_world(m.board.size / 2.0)
var t := RollTable.create(RollTable.KIND_VARIABLE, TowerBoard.new_id("t"), label, type)
t.var_name = _free_var_name(var_name)
t.position = Vector2(maxf(20.0, roundf(center.x - 300.0)), maxf(20.0, roundf(center.y + 40.0)))
m.data.tables.append(t)
var card := TableCard.new()
m.board.cards.add_child(card)
card.setup(m, t)
m.cards[t.id] = card
m.undo_redo._end_edit("Add value %s" % label)
return t
## `base`, or base_2, base_3… when another variable card already uses it.
func _free_var_name(base: String) -> String:
var used := {}
for t in m.data.tables:
if t.kind == RollTable.KIND_VARIABLE:
used[t.var_name] = true
var n := base
var k := 2
while used.has(n):
n = "%s_%d" % [base, k]
k += 1
return n
func reset_sample() -> void:
m.undo_redo._begin_edit()
m.data.tables = SampleBoard.create().tables
m.data.groups.clear()
m.lit_entries.clear()
m.lit_pipes.clear()
m.undo_redo._keep_history = true
m._rebuild_cards()
m.undo_redo._keep_history = false
m.undo_redo._end_edit("Reset sample")
await m.get_tree().process_frame
await m.get_tree().process_frame
m.board.fit()
m.toast("Board reset to the sample tables", true)
func add_entry(tid: String) -> void:
m.undo_redo._begin_edit()
var t := m.data.get_table(tid)
var e := TableEntry.new(TowerBoard.new_id("e"), "Result %d" % (t.entries.size() + 1))
if t.is_ranged():
var hi := 0
for x in t.entries:
hi = maxi(hi, x.range_hi)
e.has_range = true
e.range_lo = clampi(hi + 1, t.min_value(), t.die_size())
e.range_hi = e.range_lo
e.text = "New range"
t.entries.append(e)
t.collapsed = false
m.card_for(tid).rebuild()
m.undo_redo._end_edit()
func delete_entry(tid: String, eid: String) -> void:
var t := m.data.get_table(tid)
var e := t.find_entry(eid)
if e == null:
return
m.undo_redo._begin_edit()
t.entries.erase(e)
m.card_for(tid).rebuild()
m.undo_redo._end_edit()
m.toast("Deleted “%s”" % e.text, true)
func delete_table(tid: String) -> void:
var t := m.data.get_table(tid)
if t == null:
return
m.undo_redo._begin_edit()
var in_group := m.data.group_of(tid)
m.data.remove_table(tid)
m.local_state.forget_table_state(tid)
m.selection.erase(tid)
var card := m.card_for(tid)
m.cards.erase(tid)
if card:
card.queue_free()
for c in m.cards.values():
(c as TableCard).rebuild()
if in_group:
m.grouping._groups_changed()
_update_selection_bar()
m.undo_redo._end_edit()
m.toast("Deleted %s" % t.name, true)
func remove_pipe(key: String) -> void:
var from := key.get_slice(">", 0)
var to := key.get_slice(">", 1)
var t := m.data.get_table(from.get_slice(":", 0))
var target := m.data.get_table(to)
if t == null:
return
var e := t.find_entry(from.get_slice(":", 1))
if e == null:
return
m.undo_redo._begin_edit()
e.pipes.erase(to)
m.lit_pipes.erase(key)
m.board.pipes.hover_key = ""
var card := m.card_for(t.id)
if card:
card.rebuild()
m.undo_redo._end_edit()
m.toast("Removed pipe from “%s” to %s" % [e.text, target.name if target else to], true)
func start_link(tid: String, eid: String) -> void:
_link_from = {"tid": tid, "eid": eid}
func update_link() -> void:
var over := _card_under_mouse()
if over != _drop_card:
if is_instance_valid(_drop_card):
_drop_card.set_drop_target(false)
_drop_card = over
if _drop_card:
_drop_card.set_drop_target(true)
func finish_link() -> void:
var over := _card_under_mouse()
if is_instance_valid(_drop_card):
_drop_card.set_drop_target(false)
_drop_card = null
if _link_from.is_empty() or over == null:
_link_from = {}
return
var t := m.data.get_table(_link_from["tid"])
var e := t.find_entry(_link_from["eid"]) if t else null
_link_from = {}
if e == null or e.pipes.has(over.table.id):
return
if over.table.kind == RollTable.KIND_VARIABLE:
m.toast("Variable cards aren't rolled, so pipes can't lead into them. Use an effect such as @%s += 1." % over.table.var_name)
return
m.undo_redo._begin_edit()
# Each range on a ranged table takes a single pipe, so a new one replaces the old.
var replaced: RollTable = null
if t.is_ranged():
if not e.pipes.is_empty():
replaced = m.data.get_table(e.pipes[0])
e.pipes.clear()
e.pipes.append(over.table.id)
m.card_for(t.id).rebuild()
m.undo_redo._end_edit()
var msg := "“%s” now rolls on %s" % [e.text, over.table.name]
if replaced:
msg += " instead of %s" % replaced.name
m.toast(msg, true)
func _card_under_mouse() -> TableCard:
var gp := m.get_global_mouse_position()
var kids := m.board.cards.get_children()
for i in range(kids.size() - 1, -1, -1):
var card := kids[i] as TableCard
if card and card.visible and card.get_global_rect().has_point(gp):
return card
return null
# ----- Selection (Build) -----
func is_selected(tid: String) -> bool:
return m.selection.has(tid)
func toggle_selected(tid: String) -> void:
var c := m.card_for(tid)
if c == null or not c.visible:
return
if m.selection.has(tid):
m.selection.erase(tid)
else:
m.selection[tid] = true
c.set_selected(m.selection.has(tid))
_update_selection_bar()
func set_selection(ids: Array) -> void:
clear_selection()
for tid: Variant in ids:
var c := m.card_for(str(tid))
if c and c.visible:
m.selection[str(tid)] = true
c.set_selected(true)
_update_selection_bar()
func clear_selection() -> void:
for tid: String in m.selection:
var c := m.card_for(tid)
if c:
c.set_selected(false)
m.selection.clear()
_update_selection_bar()
## Adds every visible card touching a world rectangle to the selection.
func select_in_rect(r: Rect2) -> void:
for tid: String in m.cards:
var c: TableCard = m.cards[tid]
if c.visible and Rect2(c.position, c.size).intersects(r):
m.selection[tid] = true
c.set_selected(true)
_update_selection_bar()
func _build_selection_bar() -> void:
_sel_bar = PanelContainer.new()
var sb := Style.box(Style.FELT_DEEP, 10, [14, 7, 8, 7])
Style.bordered(sb, 1, Color(1, 1, 1, 0.12))
sb.shadow_color = Color(0, 0, 0, 0.4)
sb.shadow_size = 14
sb.shadow_offset = Vector2(0, 6)
_sel_bar.add_theme_stylebox_override("panel", sb)
var h := HBoxContainer.new()
h.add_theme_constant_override("separation", 8)
_sel_bar.add_child(h)
_sel_label = Style.make_label("", Style.body_bold(), 15, Style.ON_FELT)
_sel_label.size_flags_vertical = Control.SIZE_SHRINK_CENTER
h.add_child(_sel_label)
var grp := Style.bar_button("Group", true)
grp.tooltip_text = "Put the selected cards in a group (Ctrl+G)"
grp.pressed.connect(func() -> void: m.grouping.group_selection())
h.add_child(grp)
var tpl := Style.bar_button("Save as template…")
tpl.tooltip_text = "Save the selected cards as a reusable template"
tpl.pressed.connect(m.templating.save_selection_as_template)
h.add_child(tpl)
var clr := Style.bar_button("Clear")
clr.tooltip_text = "Clear the selection (Esc)"
clr.pressed.connect(clear_selection)
h.add_child(clr)
_sel_bar.hide()
m.board.add_child(_sel_bar)
m.board.resized.connect(_place_selection_bar)
func _update_selection_bar() -> void:
if _sel_bar == null:
return
var n := m.selection.size()
_sel_bar.visible = n > 0 and m.mode == Main.Mode.BUILD
_sel_label.text = "%d %s selected" % [n, "card" if n == 1 else "cards"]
_place_selection_bar.call_deferred()
func _place_selection_bar() -> void:
if _sel_bar and _sel_bar.visible:
_sel_bar.reset_size()
_sel_bar.position = Vector2((m.board.size.x - _sel_bar.size.x) / 2.0, 14.0)

1
ui/main_editing.gd.uid Normal file
View file

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

372
ui/main_groups.gd Normal file
View file

@ -0,0 +1,372 @@
class_name MainGroups
extends RefCounted
## Main's groups and card drags. A group is a frame around a block of cards
## (TableGroup). Expanded, its GroupCard sits in board.groups behind the pipes;
## collapsed, it sits with the cards and its members are hidden. Groups are
## presentation only: rolling, lighting and the tray never look at them.
var m: Main
var _group_nodes: Dictionary = {} # group id -> GroupCard
var _hidden_cache: Variant = null # table id -> GroupCard, or null when stale
## Ids of the cards being dragged and the group the pointer is over (Build).
var _drag_set: Array[String] = []
var _drag_from: Dictionary = {} # table id -> its position when the drag began
var _drag_over: GroupCard
func _init(p_main: Main) -> void:
m = p_main
func group_node(gid: String) -> GroupCard:
var n: GroupCard = _group_nodes.get(gid)
return n if is_instance_valid(n) else null
## Table id -> the GroupCard of the collapsed group hiding it.
func hidden_groups() -> Dictionary:
if _hidden_cache == null:
var out := {}
if m.data:
for g in m.data.groups:
var n := group_node(g.id)
if g.collapsed and n:
for tid in g.members:
out[tid] = n
_hidden_cache = out
return _hidden_cache
## Rebuilds every group's node, in the right layer, and hides the members of
## collapsed groups.
func _rebuild_groups() -> void:
for n in _group_nodes.values():
if is_instance_valid(n):
if (n as Node).get_parent():
(n as Node).get_parent().remove_child(n)
(n as Node).queue_free()
_group_nodes.clear()
_hidden_cache = null
if m.data == null or m.board == null:
return
for g in m.data.groups:
var n := GroupCard.new()
if g.collapsed:
m.board.cards.add_child(n)
else:
m.board.groups.add_child(n)
n.setup(m, g)
_group_nodes[g.id] = n
_apply_group_visibility()
## After a membership or group change: rebuild the group nodes and keep the
## rest in step.
func _groups_changed() -> void:
_rebuild_groups()
m._update_collapse_all()
## Builds the cards that are on show and frees the ones hidden in collapsed
## groups, so a big board with most of it collapsed stays light.
func _apply_group_visibility() -> void:
_hidden_cache = null
var hidden := hidden_groups()
var built := false
for t in m.data.tables:
var c: TableCard = m.cards.get(t.id)
if hidden.has(t.id):
if c:
m.selection.erase(t.id)
m.cards.erase(t.id)
# Hidden until it goes at the end of the frame (a deferred
# call of its own may still run).
c.hide()
c.queue_free()
elif c == null:
c = TableCard.new()
m.board.cards.add_child(c)
c.setup(m, t)
m.cards[t.id] = c
built = true
if built:
# Collapsed group cards stay on top of the table cards.
for g in m.data.groups:
var n := group_node(g.id)
if g.collapsed and n and n.get_parent() == m.board.cards:
m.board.cards.move_child(n, -1)
m.editing._update_selection_bar()
## "tid:eid" keys of a group's lit results, in roll order.
func lit_keys_for_group(g: TableGroup) -> Array:
var members := {}
for tid in g.members:
members[tid] = true
var out: Array = []
for k: String in m.lit_texts:
var i := k.rfind(":")
if i > 0 and members.has(k.substr(0, i)):
out.append(k)
return out
func _refresh_group_lits() -> void:
for g in m.data.groups:
var n := group_node(g.id)
if n and g.collapsed:
n.refresh_lit(lit_keys_for_group(g))
func toggle_group(gid: String) -> void:
var g := m.data.get_group(gid)
if g == null:
return
var compact := Rect2()
var blocks: Array = []
var n := group_node(gid)
if g.collapsed and n:
compact = Rect2(n.position, n.size)
blocks = m.nav._layout_blocks(gid)
g.collapsed = not g.collapsed
m.details().hide_for()
_groups_changed()
m.mark_dirty("", false)
if not g.collapsed:
var room := m.nav._make_room_for(g, compact, blocks)
if int(room["moved"]) > 0:
m.toast("Opened %s and moved %d %s to make room" % [Formatter.strip_tags(g.name), room["moved"],
"block" if int(room["moved"]) == 1 else "blocks"], true)
func set_group_collapsed(gid: String, collapsed: bool) -> void:
var g := m.data.get_group(gid)
if g and g.collapsed != collapsed:
toggle_group(gid)
## Moves a group and its members (dragging the title bar).
func move_group(gid: String, delta: Vector2) -> void:
var g := m.data.get_group(gid)
if g == null:
return
m.data.move_group(gid, delta)
for tid in g.members:
var c := m.card_for(tid)
if c:
c.position = m.data.get_table(tid).position
var n := group_node(gid)
if n:
n.sync_rect()
## "Group 1", "Group 2"… whichever isn't used.
func _free_group_name() -> String:
var used := {}
for g in m.data.groups:
used[g.name] = true
var k := 1
while used.has("Group %d" % k):
k += 1
return "Group %d" % k
## Ctrl+G: groups the selected cards (taking them out of any other group).
func group_selection() -> TableGroup:
var ids: Array[String] = []
for t in m.data.tables:
if m.selection.has(t.id):
ids.append(t.id)
if ids.is_empty():
m.toast("Select some cards first: Ctrl- or Shift-click their headers, or Ctrl-drag on the felt")
return null
m.undo_redo._begin_edit()
var g := m.data.add_group(_free_group_name(), ids)
var rects: Array = []
for tid in ids:
var c := m.card_for(tid)
rects.append(Rect2(c.position, c.size))
g.fit_to(rects)
# Groups don't nest: emptied groups stay, so they can be refilled or ungrouped.
m.clear_selection()
_groups_changed()
m.undo_redo._end_edit()
m.toast("Grouped %d %s as “%s”" % [ids.size(), "card" if ids.size() == 1 else "cards", g.name], true)
return g
## Removes the group; its cards stay where they are.
func ungroup(gid: String) -> void:
var g := m.data.get_group(gid)
if g == null:
return
m.undo_redo._begin_edit()
m.data.ungroup(gid)
_groups_changed()
m.undo_redo._end_edit()
m.toast("Ungrouped “%s”" % Formatter.strip_tags(g.name), true)
func confirm_delete_group(gid: String) -> void:
var g := m.data.get_group(gid)
if g == null:
return
var n := g.members.size()
m._add_modal(ModalCard.confirm("Delete group",
"Delete “%s” and the %d %s in it? Pipes from other cards into them are removed too. You can undo this from the message that follows." % [Formatter.strip_tags(g.name), n, "card" if n == 1 else "cards"],
"Delete group and cards", func() -> void: delete_group(gid), true))
## Deletes a group and every card in it (undo from the toast).
func delete_group(gid: String) -> void:
var g := m.data.get_group(gid)
if g == null:
return
m.undo_redo._begin_edit()
var gname := Formatter.strip_tags(g.name)
var gone := m.data.delete_group(gid)
for tid in gone:
m.local_state.forget_table_state(tid)
m.selection.erase(tid)
var card := m.card_for(tid)
m.cards.erase(tid)
if card:
card.get_parent().remove_child(card)
card.queue_free()
for c in m.cards.values():
(c as TableCard).rebuild()
_groups_changed()
m.undo_redo._end_edit()
m.toast("Deleted “%s” and its %d %s" % [gname, gone.size(), "card" if gone.size() == 1 else "cards"], true)
## The group details editor (Build): a card-styled dialog with the text.
func edit_group_details(gid: String) -> void:
var g := m.data.get_group(gid)
if g == null:
return
var d := ModalCard.new("Details for %s" % Formatter.strip_tags(g.name), 520.0)
var te := TextEdit.new()
te.text = g.details
te.placeholder_text = "Shown when hovering the group's title (BBCode)"
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
te.custom_minimum_size = Vector2(0, 120)
ModalCard.style_text_edit(te)
d.body.add_child(te)
d.add_button("Cancel", "plain", d.close)
d.add_button("Save", "primary", func() -> void:
m.undo_redo._begin_edit()
g.details = te.text.strip_edges()
d.close()
var n := group_node(gid)
if n:
n.rebuild()
m.undo_redo._end_edit()
)
m._add_modal(d)
## The expanded group frame containing a world point (the smallest, if they overlap).
func _frame_at(p: Vector2) -> TableGroup:
var best: TableGroup = null
for g in m.data.groups:
if g.collapsed or not g.rect().has_point(p):
continue
if best == null or g.rect().get_area() < best.rect().get_area():
best = g
return best
# ----- Card drags (TableCard calls these) -----
func begin_card_drag(card: TableCard) -> void:
if m.mode == Main.Mode.BUILD and card and card.table:
m.select_card(card.table.id)
m.undo_redo._begin_edit()
_drag_set.clear()
if m.mode == Main.Mode.BUILD and m.selection.has(card.table.id) and m.selection.size() > 1:
for tid: String in m.selection:
if m.cards.has(tid):
_drag_set.append(tid)
else:
_drag_set.append(card.table.id)
_drag_from.clear()
# The frames of the dragged cards' groups hold still, so a card can leave them.
for tid in _drag_set:
_drag_from[tid] = m.data.get_table(tid).position
var g := m.data.group_of(tid)
if g:
m.board.groups.frozen[g.id] = true
## Moves the dragged card (and the rest of a multi-selection) so `card` lands at `to`.
func drag_card(card: TableCard, to: Vector2) -> void:
var delta := to - card.position
if _drag_set.size() > 1:
# Keep every selected card on the board.
for tid in _drag_set:
var c := m.card_for(tid)
delta.x = maxf(delta.x, 10.0 - c.position.x)
delta.y = maxf(delta.y, 10.0 - c.position.y)
for tid in _drag_set:
var c := m.card_for(tid)
c.position += delta
c.table.position = c.position
else:
card.position = to
card.table.position = to
if m.mode == Main.Mode.BUILD:
var over := _frame_at(card.position + card.size / 2.0)
var node := group_node(over.id) if over else null
if node != _drag_over:
if is_instance_valid(_drag_over):
_drag_over.set_drop_target(false)
_drag_over = node
if node:
node.set_drop_target(true)
## Drop: in Build, a card dropped in a group frame joins it, and one dropped
## outside its own (held) frame leaves it.
func end_card_drag(_card: TableCard) -> void:
if is_instance_valid(_drag_over):
_drag_over.set_drop_target(false)
_drag_over = null
var joined := {}
var left := 0
if m.mode == Main.Mode.BUILD:
for tid in _drag_set:
var c := m.card_for(tid)
if c == null:
continue
var center := c.position + c.size / 2.0
var g0 := m.data.group_of(tid)
var target := _frame_at(center)
if target != null and target != g0:
m.data.add_to_group(tid, target.id)
joined[target.name] = int(joined.get(target.name, 0)) + 1
elif target == null and g0 != null and not g0.rect().has_point(center):
m.data.remove_from_group(tid)
left += 1
m.board.groups.frozen.clear()
var moved := false
for tid in _drag_set:
var t := m.data.get_table(tid)
if t and t.position != _drag_from.get(tid, t.position):
moved = true
_drag_set.clear()
_drag_from.clear()
if not joined.is_empty() or left > 0:
_groups_changed()
var parts := PackedStringArray()
for gname: String in joined:
parts.append("added %d to “%s”" % [joined[gname], Formatter.strip_tags(gname)])
if left > 0:
parts.append("took %d out of %s" % [left, "its group" if left == 1 else "their groups"])
var msg := ", ".join(parts)
m.undo_redo._end_edit()
m.toast(msg.substr(0, 1).to_upper() + msg.substr(1), true)
return
# A click on a header without a drag isn't an edit.
m.mark_dirty("", moved)

1
ui/main_groups.gd.uid Normal file
View file

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

357
ui/main_history.gd Normal file
View file

@ -0,0 +1,357 @@
class_name MainHistory
extends RefCounted
## Main's undo and redo, and its toolbar buttons.
##
## Every change to the saved collection goes through mark_dirty, which records
## an undo step in `edits` (EditHistory; one per collection, kept in memory
## while the app runs, so switching collections and back keeps it). Steps are
## whole-board snapshots, so undo needs nothing from the card editors.
##
## Coalescing: typing in a text field commits once typing pauses for
## EDIT_PAUSE, and later typing in the same field merges into that step until
## focus moves; other edits commit at the end of the frame (a whole drag is one
## step), and repeated edits to the same card or pipe within
## EditHistory.COALESCE_SECS merge. Main's actions call _begin_edit
## before changing anything (committing pending typing as its own step) and
## _end_edit after, which commits at once.
##
## Collapsing cards and groups is saved but treated as view state: it isn't a
## step, and undo leaves things collapsed or expanded as they are.
##
## Ctrl+Z undoes, Ctrl+Shift+Z or Ctrl+Y redoes, in Build and Play, unless a
## text field has focus (it keeps its own Ctrl+Z for the text being typed) or
## a dialog is open.
const EDIT_PAUSE := 0.8
var m: Main
var edits: EditHistory
var _histories: Dictionary = {} # collection id -> EditHistory
var _edit_timer: Timer
var _edit_pending := false
var _edit_focus := 0
var _commit_queued := false
var _restoring := false
var _keep_history := false
var _undo_button: Button
var _redo_button: Button
## How long the last undo or redo took to rebuild the board (microseconds).
var _last_restore_usec := 0
func _init(p_main: Main) -> void:
m = p_main
## Call after changing the saved collection: schedules the save, refreshes
## what depends on the board and records an undo step (see the top of this file).
## `label` names the step and commits it at once; without one the step is
## named from the change, and committed at the end of the frame, or once
## typing pauses when a text field has focus. `undoable` false is for saved
## view state (collapsing), which isn't an undo step.
func mark_dirty(label: String = "", undoable: bool = true) -> void:
m._board_changed()
if not undoable or edits == null or _restoring:
return
_edit_pending = true
if label != "":
_commit_edits(label)
return
var f := m.get_viewport().gui_get_focus_owner() if m.is_inside_tree() else null
if f is LineEdit or f is TextEdit:
_edit_focus = f.get_instance_id()
_edit_timer.start()
else:
_edit_focus = 0
_queue_commit()
func _build_edit_timer() -> void:
_edit_timer = Timer.new()
_edit_timer.one_shot = true
_edit_timer.wait_time = EDIT_PAUSE
_edit_timer.timeout.connect(func() -> void: _commit_edits())
m.add_child(_edit_timer)
m.get_viewport().gui_focus_changed.connect(_on_focus_changed)
## Typing in one field and then moving to another makes two steps.
func _on_focus_changed(c: Control) -> void:
if _edit_pending and _edit_focus != 0 and (c == null or c.get_instance_id() != _edit_focus):
_queue_commit()
m.inspecting._inspect_focus(c)
## Picks this collection's history (making one) and takes the board as its
## baseline; a history whose board changed from outside starts over.
func _sync_history() -> void:
if m.data == null:
return
if _edit_timer:
_edit_timer.stop()
_edit_pending = false
var h: EditHistory = _histories.get(m.data.id)
if h == null:
h = EditHistory.new(m.data)
_histories[m.data.id] = h
else:
h.resync(m.data)
edits = h
_update_undo_buttons()
## Before an action changes the board: commits edits still waiting (typing)
## as a step of their own, so the action's step starts from here.
func _begin_edit() -> void:
_commit_edits()
## After an action changed the board: like mark_dirty, but the step is
## committed now (named `label`, or from the change).
func _end_edit(label: String = "") -> void:
m._board_changed()
if edits == null or _restoring:
return
_edit_pending = true
_commit_edits(label)
func _queue_commit() -> void:
if not _commit_queued:
_commit_queued = true
_commit_edits.call_deferred()
## Records waiting edits as an undo step now (see EditHistory.commit).
func _commit_edits(label: String = "") -> void:
_commit_queued = false
if _edit_timer:
_edit_timer.stop()
if not _edit_pending or edits == null:
return
_edit_pending = false
var r := edits.commit(m.data, label, _edit_focus)
if r["step"]:
if m.top_bar._toast_serial >= 0 and edits.top_serial() != m.top_bar._toast_serial:
m.top_bar._toast_serial = -1
m.top_bar._toast_undo.hide()
_update_undo_buttons()
func can_undo() -> bool:
return edits != null and (edits.can_undo() or _edit_pending)
func can_redo() -> bool:
return edits != null and edits.can_redo() and not _edit_pending
## Steps back one edit. Returns false when there was nothing to undo (or it
## has to wait for a roll or a dialog).
func undo() -> bool:
if not _history_ready():
return false
_commit_edits()
if not edits.can_undo():
m.toast("Nothing to undo")
return false
var e := edits.pop_undo()
_apply_history(e, "Undid")
return true
func redo() -> bool:
if not _history_ready():
return false
_commit_edits()
if not edits.can_redo():
m.toast("Nothing to redo")
return false
var e := edits.pop_redo()
_apply_history(e, "Redid")
return true
func _history_ready() -> bool:
if edits == null:
return false
if m.rolling_ctx != null or m.rolling._choice_waiting("Answer the waiting question first"):
m.toast("Wait for the roll to finish before undoing")
return false
return true
## Puts the board back to a snapshot from the history, keeping the view, the
## mode, the open search and the lit results of tables that still exist. Only
## what changed is rebuilt (EditHistory.patch, _refresh_patched); cards hidden
## in collapsed groups stay unbuilt.
func _apply_history(e: Dictionary, verb: String) -> void:
var t0 := Time.get_ticks_usec()
var d := EditHistory.diff(e["from"], e["snap"])
_restoring = true
if m.inspecting._pipe_popover and m.inspecting._pipe_popover.visible:
m.inspecting._pipe_popover.hide()
if m.inspector:
m.inspector.close_menus()
m.details().hide_for()
m.board.pipes.hover_key = ""
m.editing._drop_card = null
m.editing._link_from = {}
m.clear_selection()
var p := EditHistory.patch(m.data, e["snap"], e["from"])
if not p.is_empty():
edits.cache = p["snap"]
_refresh_patched(p, d)
else:
edits.cache = EditHistory.restore(m.data, e["snap"])
_keep_history = true
m._rebuild_cards()
_keep_history = false
_restoring = false
m._board_changed()
m._refresh_lit()
m.tray.render()
_update_undo_buttons()
m.toast("%s: %s" % [verb, e["label"]])
_last_restore_usec = Time.get_ticks_usec() - t0
_flash_changes(d)
## After EditHistory.patch: frees the cards of removed tables, rebuilds the
## groups if they changed, builds cards for tables brought back (unless a
## collapsed group hides them) and moves and rebuilds the changed ones. A
## changed variable card rebuilds every card (other cards' effect chips name
## it).
func _refresh_patched(p: Dictionary, d: Dictionary) -> void:
for tid: String in p["removed"]:
var c := m.card_for(tid)
m.cards.erase(tid)
if c:
c.get_parent().remove_child(c)
c.queue_free()
if p["groups_changed"]:
m.grouping._groups_changed()
else:
for gid: String in p["groups"]:
var n := m.group_node(gid)
if n:
n.sync_rect()
m.grouping._apply_group_visibility()
var all := false
for tid: String in p["tables"]:
var t := m.data.get_table(tid)
if t and t.kind == RollTable.KIND_VARIABLE and (d["changed"] as Array).has(tid):
all = true
for tid: String in (m.cards.keys() if all else p["tables"]):
var c := m.card_for(tid)
if c == null:
continue
c.position = c.table.position
if all or (d["changed"] as Array).has(tid):
c.rebuild()
m._update_collapse_all()
## Rings the cards an undo or redo changed, once they have laid out. One
## changed card that's off screen is brought into view (without changing the
## zoom); bigger changes leave the view alone.
func _flash_changes(d: Dictionary) -> void:
for i in 2:
await m.get_tree().process_frame
var nodes: Array[Control] = []
var hidden := m.hidden_groups()
for tid: String in EditHistory.touched_tables(d):
var n: Control = m.card_for(tid)
if n == null:
n = hidden.get(tid)
if n and is_instance_valid(n) and not nodes.has(n):
nodes.append(n)
for gid: String in (d["gadded"] as Array) + (d["gchanged"] as Array):
var n := m.group_node(gid)
if n and not nodes.has(n):
nodes.append(n)
if nodes.is_empty():
return
var view := m.board.view_rect()
if nodes.size() == 1 and not view.intersects(Rect2(nodes[0].position, nodes[0].size)):
m.board.animate_to(Rect2(nodes[0].position, nodes[0].size).get_center(), m.board.zoom)
view = Rect2()
var shown: Array[Control] = []
for n in nodes:
if view.size == Vector2.ZERO or view.intersects(Rect2(n.position, n.size)):
shown.append(n)
m.board.cards.flash_all(shown)
func _make_history_buttons(tools: HBoxContainer) -> void:
_undo_button = Style.bar_button("Undo")
_undo_button.pressed.connect(func() -> void: undo())
m.top_bar._bar_icon(_undo_button, func(c: Control) -> void: _draw_turn_arrow(c, false))
_redo_button = Style.bar_button("Redo")
_redo_button.pressed.connect(func() -> void: redo())
m.top_bar._bar_icon(_redo_button, func(c: Control) -> void: _draw_turn_arrow(c, true))
for b in [_undo_button, _redo_button]:
# Icon-only (the tooltip names the step), so the Build bar fits at 1280 px.
(b as Button).text = ""
for n in ["normal", "hover", "pressed", "hover_pressed", "disabled"]:
var sb := (b as Button).get_theme_stylebox(n) as StyleBoxFlat
if sb:
sb.content_margin_left = 26
(b as Button).focus_mode = Control.FOCUS_NONE
(b as Button).add_theme_color_override("font_disabled_color", Color(Style.ON_FELT, 0.35))
tools.add_child(b)
## A curved arrow, pointing left (undo) or right (redo).
func _draw_turn_arrow(c: Control, right: bool) -> void:
var b := c.get_parent() as Button
var col := Style.ON_FELT if b == null or not b.disabled else Color(Style.ON_FELT, 0.35)
var s := -1.0 if right else 1.0
var o := Vector2(8, 9)
c.draw_arc(o, 5.0, -PI * 0.95 if not right else -PI * 0.05, PI * 0.5 if not right else -PI * 1.5, 16, col, 1.8, true)
var tip := o + Vector2(-5.0 * s, -0.4)
c.draw_colored_polygon(PackedVector2Array([tip + Vector2(-3.2 * s, -1.0), tip + Vector2(3.2 * s, -1.0), tip + Vector2(0, 3.6)]), col)
func _update_undo_buttons() -> void:
if _undo_button == null:
return
_undo_button.disabled = not can_undo()
_redo_button.disabled = not can_redo()
if edits and edits.can_undo() and not _edit_pending:
_undo_button.tooltip_text = "Undo: %s (Ctrl+Z)" % edits.undo_label()
elif _edit_pending:
_undo_button.tooltip_text = "Undo your latest edit (Ctrl+Z)"
else:
_undo_button.tooltip_text = "Nothing to undo"
_redo_button.tooltip_text = ("Redo: %s (Ctrl+Shift+Z or Ctrl+Y)" % edits.redo_label()) if can_redo() else "Nothing to redo"
for b in [_undo_button, _redo_button]:
for k in (b as Button).get_children():
(k as CanvasItem).queue_redraw()
## True while a dialog (a ModalCard) is open over the board.
func _modal_open() -> bool:
for c in m.get_children():
if c is ModalCard and (c as ModalCard).visible:
return true
return false
## Ctrl+Z / Ctrl+Shift+Z / Ctrl+Y outside text fields.
func _history_shortcut(k: InputEventKey) -> bool:
if not (k.ctrl_pressed or k.meta_pressed) or k.alt_pressed:
return false
var is_undo := k.keycode == KEY_Z and not k.shift_pressed
var is_redo := (k.keycode == KEY_Z and k.shift_pressed) or (k.keycode == KEY_Y and not k.shift_pressed)
if not is_undo and not is_redo:
return false
var f := m.get_viewport().gui_get_focus_owner()
if f is LineEdit or f is TextEdit or _modal_open():
return false
if is_undo:
undo()
else:
redo()
return true

1
ui/main_history.gd.uid Normal file
View file

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

112
ui/main_inspector.gd Normal file
View file

@ -0,0 +1,112 @@
class_name MainInspectorLink
extends RefCounted
## Main's side of the Build inspector (docs/PLAIN.md §5). The inspector edits
## the selected card, result or pipe. The display side calls select_card /
## select_result / select_pipe / clear_inspector; Main also selects from the
## board: a card's title (drag start), focus entering a result's field on a
## card, a clicked pipe, the ⚙.
var m: Main
var _pipe_popover: PipePopover
func _init(p_main: Main) -> void:
m = p_main
## Build mode: a clicked pipe opens in the inspector. The old pop-up
## (PipePopover) is only a fallback for when there is no inspector.
func open_pipe_options(key: String, at: Vector2) -> void:
if m.inspector != null:
m.details().hide_for()
select_pipe(key)
return
if _pipe_popover == null:
_pipe_popover = PipePopover.new()
m.add_child(_pipe_popover)
_pipe_popover.setup(m)
m.details().hide_for()
_pipe_popover.open(key, at)
## The card's ⚙ button. Main.open_table_settings comes from the app-shell work;
## until it exists this only says so.
func request_table_settings(tid: String) -> void:
if m.mode == Main.Mode.BUILD and m.inspector != null:
select_card(tid)
return
if m.has_method("open_table_settings"):
m.call("open_table_settings", tid)
else:
m.toast("Table settings aren't available yet")
func select_card(table_id: String) -> void:
if m.inspector == null or m.data.get_table(table_id) == null:
return
m.inspector.select({"kind": "card", "tid": table_id})
func select_result(table_id: String, entry_id: String) -> void:
var t := m.data.get_table(table_id)
if m.inspector == null or t == null or t.find_entry(entry_id) == null:
return
m.inspector.select({"kind": "result", "tid": table_id, "eid": entry_id})
## `key` is a pipe key, "tid:eid>to" (Roller.pipe_key).
func select_pipe(key: String) -> void:
var from := key.get_slice(">", 0)
var tid := from.get_slice(":", 0)
var eid := from.get_slice(":", 1)
var to := key.get_slice(">", 1)
var t := m.data.get_table(tid)
var e := t.find_entry(eid) if t else null
if m.inspector == null or e == null or not e.pipes.has(to):
return
m.inspector.select({"kind": "pipe", "tid": tid, "eid": eid, "to": to})
func clear_inspector() -> void:
if m.inspector:
m.inspector.clear()
## What the inspector shows: {kind: "card" | "result" | "pipe", tid, eid?, to?} or {}.
func inspector_selection() -> Dictionary:
return m.inspector.selection.duplicate() if m.inspector else {}
## After the inspector changed a card: refreshes it (every card when a
## variable's name or label changed, since other cards show it).
func inspector_edited(tid: String, all_cards: bool = false) -> void:
m.local_state._ref_cache.clear()
if all_cards:
for c in m.cards.values():
(c as TableCard).rebuild()
else:
var card := m.card_for(tid)
if card:
card.rebuild()
## Focus entering a field on a card in Build selects that result (or the card).
func _inspect_focus(c: Control) -> void:
if m.mode != Main.Mode.BUILD or m.inspector == null or c == null or m.inspector.is_ancestor_of(c):
return
var n: Node = c
while n != null and not (n is TableCard):
n = n.get_parent()
var card := n as TableCard
if card == null or card.table == null:
return
for eid: String in card.rows:
var row: Node = card.rows[eid]
if is_instance_valid(row) and row.is_ancestor_of(c):
var s := m.inspector.selection
if str(s.get("tid", "")) != card.table.id or str(s.get("eid", "")) != eid or str(s.get("kind", "")) == "card":
select_result(card.table.id, eid)
return
if str(m.inspector.selection.get("tid", "")) != card.table.id:
select_card(card.table.id)

1
ui/main_inspector.gd.uid Normal file
View file

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

338
ui/main_navigation.gd Normal file
View file

@ -0,0 +1,338 @@
class_name MainNavigation
extends RefCounted
## Main's navigation: search, focus (jump to a card), the minimap and
## Arrange (pack collapsed groups, make room).
## focus_table zooms in to at least this, so the card can be read.
const READABLE_ZOOM := 0.85
## ...but zooms out as far as this to fit a tall card.
const MIN_FOCUS_ZOOM := 0.7
const PACK_GAP := 60.0
const ARRANGE_PACK := 0
const ARRANGE_COLLAPSE := 1
var m: Main
var _search_button: Button
var _search_panel: SearchPanel
var _map_toggle: Button
func _init(p_main: Main) -> void:
m = p_main
# ----- Search (top bar, Ctrl+F) -----
func toggle_search() -> void:
if _search_panel and _search_panel.visible:
_search_panel.close()
else:
open_search()
## Opens the search pop-over (Ctrl+F), with its field focused.
func open_search() -> SearchPanel:
if _search_panel == null:
_search_panel = SearchPanel.new()
m.add_child(_search_panel)
_search_panel.setup(m)
_search_panel.open(_search_button)
return _search_panel
# ----- Focus: jump to a card -----
## Shows a card: expands its group if that's collapsed (saved, with a toast),
## expands the card if it's collapsed and an entry was asked for, glides the
## view so the card sits in the middle at a readable zoom and flashes a ring
## around it. With `entry_id`, a long list scrolls to that result
## (TableCard.reveal) and its row flashes too. Unknown ids do nothing.
func focus_table(table_id: String, entry_id: String = "") -> void:
var t := m.data.get_table(table_id)
if t == null:
return
if entry_id != "" and t.find_entry(entry_id) == null:
entry_id = ""
var notes := PackedStringArray()
var undoable := false
var settle := false
var g := m.data.group_of(table_id)
if g and g.collapsed:
var info := _expand_group(g)
notes.append("Opened group %s" % Formatter.strip_tags(g.name))
if int(info["moved"]) > 0:
notes.append("moved %d %s to make room" % [info["moved"], "block" if int(info["moved"]) == 1 else "blocks"])
undoable = true
settle = true
if entry_id != "" and t.collapsed and t.kind != RollTable.KIND_VARIABLE and t.kind != RollTable.KIND_SHEET:
t.collapsed = false
var c0 := m.card_for(table_id)
if c0:
c0.rebuild()
m.mark_dirty("", false)
settle = true
var card := m.card_for(table_id)
if card == null:
return
if settle or card.size.y <= 0.0:
# Let a card that was just built or expanded lay out before measuring it.
for i in 3:
await m.get_tree().process_frame
card = m.card_for(table_id)
if card == null:
return
# On top of any card it overlaps.
card.get_parent().move_child(card, -1)
if entry_id != "":
card.reveal(entry_id)
var r := Rect2(card.position, card.size)
m.board.animate_to(_focus_point(r), _focus_zoom(r))
m.board.cards.flash(card)
if not notes.is_empty():
m.toast(", ".join(notes), undoable)
if entry_id != "":
# The list scrolls on the next layout pass; ring the row after it.
await m.get_tree().process_frame
if is_instance_valid(card):
m.board.cards.flash(card, entry_rect(card, entry_id))
## Centres a group: its frame, or its compact card when collapsed (which
## isn't expanded), and flashes it.
func focus_group(gid: String) -> void:
var g := m.data.get_group(gid)
var n := m.group_node(gid)
if g == null or n == null:
return
if g.collapsed:
n.get_parent().move_child(n, -1)
var r := Rect2(n.position, n.size)
var z := _focus_zoom(r) if g.collapsed else clampf(_fit_zoom(r), BoardView.MIN_ZOOM, READABLE_ZOOM)
m.board.animate_to(r.get_center() if not g.collapsed or r.size.y * z < m.board.size.y else _focus_point(r), z)
m.board.cards.flash(n)
## The world rect of an entry's row on a card (anchor_for geometry), or Rect2().
func entry_rect(card: TableCard, eid: String) -> Rect2:
var a := card.anchor_for(eid)
var row: Control = card.rows.get(eid)
if a.is_empty() or row == null:
return Rect2()
var p: Vector2 = a["pos"]
var h := row.size.y
return Rect2(card.position.x + 3.0, p.y - h / 2.0, card.size.x - 6.0, h)
func _fit_zoom(r: Rect2) -> float:
return minf((m.board.size.x - 80.0) / maxf(r.size.x, 1.0), (m.board.size.y - 80.0) / maxf(r.size.y, 1.0))
func _focus_zoom(r: Rect2) -> float:
var z := maxf(m.board.zoom, READABLE_ZOOM)
return clampf(minf(z, maxf(MIN_FOCUS_ZOOM, _fit_zoom(r))), BoardView.MIN_ZOOM, BoardView.MAX_ZOOM)
## The middle of a card, or a point that keeps its top in view when it's
## taller than the board at the zoom focus_table picks.
func _focus_point(r: Rect2) -> Vector2:
var z := _focus_zoom(r)
var c := r.get_center()
if r.size.y > (m.board.size.y - 80.0) / z:
c.y = r.position.y - 40.0 / z + m.board.size.y / 2.0 / z
return c
## Expands a collapsed group (saved) and makes room for it. Returns
## _make_room_for's {moved}.
func _expand_group(g: TableGroup) -> Dictionary:
var n := m.group_node(g.id)
var compact := Rect2(n.position, n.size) if n else Rect2()
var blocks := _layout_blocks(g.id)
g.collapsed = false
m.details().hide_for()
m.grouping._groups_changed()
m.mark_dirty("", false)
return _make_room_for(g, compact, blocks)
# ----- Minimap -----
func _make_map_toggle() -> Button:
var b := Style.bar_button("Map")
b.toggle_mode = true
b.tooltip_text = "Show an overview of the board in the corner (M)"
var on := Style.bordered(Style.box(Color(Style.BRASS, 0.16), 8, [12, 6, 12, 6]), 1, Style.BRASS)
b.add_theme_stylebox_override("pressed", on)
b.add_theme_stylebox_override("hover_pressed", on)
m.top_bar._bar_icon(b, func(c: Control) -> void:
c.draw_rect(Rect2(1, 2, 14, 12), Style.ON_FELT, false, 1.5)
c.draw_rect(Rect2(4, 5, 4, 3), Style.ON_FELT)
c.draw_rect(Rect2(9, 8, 3, 3), Style.BRASS))
b.toggled.connect(func(pressed: bool) -> void: set_minimap_visible(pressed, true))
_nav_mode_changed.call_deferred()
return b
## Shows or hides the minimap; `remember` saves the choice for this mode.
func set_minimap_visible(on: bool, remember: bool = false) -> void:
if m.board == null:
return
m.board.minimap.visible = on
if _map_toggle:
_map_toggle.set_pressed_no_signal(on)
if remember and m.state:
m.state.set_setting(_minimap_key(), on)
m.state.save()
func _minimap_key() -> String:
return "minimap_build" if m.mode == Main.Mode.BUILD else "minimap_play"
## Off by default in Play (which stays simple), on by default in Build;
## either is remembered once toggled.
func _minimap_default() -> bool:
var dflt := m.mode == Main.Mode.BUILD
return bool(m.state.get_setting(_minimap_key(), dflt)) if m.state else dflt
## set_mode calls this after switching.
func _nav_mode_changed() -> void:
set_minimap_visible(_minimap_default())
# ----- Arrange: pack collapsed groups -----
func _make_arrange_menu() -> MenuButton:
var mb := MenuButton.new()
mb.text = "Arrange ▾"
mb.tooltip_text = "Tidy the layout of the board"
mb.flat = false
var ref := Style.bar_button("")
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_font_size_override("font_size", 15)
mb.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
ref.free()
var pm := mb.get_popup()
ModalCard.style_popup(pm)
pm.add_item("Pack collapsed groups", ARRANGE_PACK)
pm.set_item_tooltip(0, "Move collapsed groups and the cards between them together, closing the gaps, in reading order")
# Build mode's bar has no room for the Collapse all button, so it lives here.
pm.add_item("Collapse all", ARRANGE_COLLAPSE)
pm.about_to_popup.connect(func() -> void:
pm.set_item_text(pm.get_item_index(ARRANGE_COLLAPSE), "Collapse all" if m._any_expanded() else "Expand all"))
pm.id_pressed.connect(func(id: int) -> void:
if id == ARRANGE_PACK:
pack_collapsed_groups()
elif id == ARRANGE_COLLAPSE:
m.set_all_collapsed(m._any_expanded()))
return mb
## The blocks Pack and make-room move: every group (its compact card when
## collapsed, its frame when expanded) and every card in no group, as
## [{rect, group, table}] with one of group / table set. `skip` is a group id
## to leave out.
func _layout_blocks(skip: String = "") -> Array:
var out: Array = []
var grouped := {}
for g in m.data.groups:
for tid in g.members:
grouped[tid] = true
if g.id == skip:
continue
var r := g.rect()
if g.collapsed:
var n := m.group_node(g.id)
r = Rect2(n.position, n.size) if n else Rect2(g.position, Vector2(TableCard.WIDTH, 120))
out.append({"rect": r, "group": g.id, "table": ""})
for t in m.data.tables:
if grouped.has(t.id):
continue
var c := m.card_for(t.id)
var r := Rect2(c.position, c.size) if c else Rect2(t.position, Vector2(TableCard.WIDTH, 120))
out.append({"rect": r, "group": "", "table": t.id})
return out
func _move_block(b: Dictionary, delta: Vector2) -> void:
if delta == Vector2.ZERO:
return
if b["group"] != "":
m.move_group(str(b["group"]), delta)
else:
var t := m.data.get_table(str(b["table"]))
t.position += delta
var c := m.card_for(t.id)
if c:
c.position = t.position
## Build ▸ Arrange ▸ Pack collapsed groups: closes the gaps that collapsed
## blocks leave (BoardLayout.pack), keeping reading order, then fits the view.
## Saved, with undo. Returns how many blocks moved.
func pack_collapsed_groups() -> int:
var any := false
for g in m.data.groups:
if g.collapsed:
any = true
break
if not any:
m.toast("Collapse some groups first: Pack closes the gaps they leave")
return 0
var blocks := _layout_blocks()
var rects: Array = []
for b: Dictionary in blocks:
rects.append(b["rect"])
var offsets := BoardLayout.pack(rects, PACK_GAP, PACK_GAP)
m.undo_redo._begin_edit()
var moved := 0
for i in blocks.size():
var d := offsets[i].round()
if d != Vector2.ZERO:
_move_block(blocks[i], d)
moved += 1
if moved == 0:
m.toast("Already packed")
return 0
m.undo_redo._end_edit("Pack collapsed groups")
m.toast("Packed the board: moved %d %s" % [moved, "block" if moved == 1 else "blocks"], true)
await m.get_tree().process_frame
await m.get_tree().process_frame
m.board.fit()
return moved
## After a group expands in place: if its frame now covers other blocks, they
## shift right or down to clear it (BoardLayout.make_room). `blocks` are the
## other blocks (_layout_blocks) measured before the group expanded, while
## every group card was laid out. Returns {moved}; the move is an undo step
## of its own (expanding the group isn't one).
func _make_room_for(g: TableGroup, compact: Rect2, blocks: Array) -> Dictionary:
if compact.size == Vector2.ZERO or blocks.is_empty():
return {"moved": 0}
var grown := g.rect()
var rects: Array = []
var hits := false
for b: Dictionary in blocks:
var r: Rect2 = b["rect"]
rects.append(r)
if r.intersects(grown):
hits = true
if not hits:
return {"moved": 0}
m.undo_redo._begin_edit()
var offsets := BoardLayout.make_room(rects, compact, grown, PACK_GAP)
var moved := 0
for i in blocks.size():
var d := offsets[i].round()
if d != Vector2.ZERO:
_move_block(blocks[i], d)
moved += 1
if moved > 0:
m.undo_redo._end_edit("Make room for %s" % Formatter.strip_tags(g.name))
return {"moved": moved}

View file

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

398
ui/main_rolling.gd Normal file
View file

@ -0,0 +1,398 @@
class_name MainRolling
extends RefCounted
## Main's rolling: starting a roll, choice questions, playback on the board
## and in the tray, the session seed and copying results.
## Chains longer than this show at once instead of animating.
const LONG_CHAIN := 40
## Copy-as-text indents by depth up to this many levels.
const MAX_INDENT := 8
var m: Main
var _token := 0
var _pulse_tween: Tween
var _choice: ChoiceDialog
func _init(p_main: Main) -> void:
m = p_main
## Rolls a table and plays the result down its pipes. A fast roll (Shift held
## while clicking, or `fast`) skips the flicker and the beads and shows the
## whole result at once. Choice cards still ask (docs/LOGIC.md §8): before a
## question opens, the steps so far light up; after the last answer the rest
## of the roll shows at once. Starting a roll while a question is open cancels
## the old roll.
func start_roll(tid: String, fast: bool = false) -> void:
var t := m.data.get_table(tid)
if t == null or t.kind == RollTable.KIND_VARIABLE:
return
# A minimized question keeps waiting; a new roll must not cancel it.
if _choice_waiting("Answer the waiting question first"):
return
fast = fast or Input.is_key_pressed(KEY_SHIFT)
_archive_current()
_token += 1
var my := _token
# A question left open by the previous roll answers Cancel; that roll then
# sees it has been replaced and stops quietly.
cancel_choice()
if _pulse_tween and _pulse_tween.is_valid():
_pulse_tween.kill()
m.board.pipes.pulse_key = ""
for c in m.cards.values():
(c as TableCard).set_rolling(false)
(c as TableCard).clear_flick()
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks)
ctx.prompt = _prompt_for.bind(my)
m.rolling_ctx = ctx
m.current = {"collection": m.data.id, "root": tid, "root_name": t.name, "time": Time.get_unix_time_from_system(),
"steps": [], "all": [], "done": false, "pending": true}
var tree: Dictionary = await Roller.roll_async(m.data, tid, ctx)
if m.rolling_ctx == ctx:
m.rolling_ctx = null
if my != _token or not m.is_inside_tree():
# Another roll started while this one waited for an answer.
m.local_state._store_decks()
if ctx.persistent_changed:
m.local_state._store_variables()
return
var prompted: bool = m.current.get("prompted", false)
m.lit_entries.clear()
m.lit_pipes.clear()
m.lit_texts.clear()
m.current = {"collection": m.data.id, "root": tid, "root_name": t.name, "time": m.current.get("time", Time.get_unix_time_from_system()),
"steps": [], "all": Roller.flatten(tree, []), "done": false, "chain_vars": ctx.chain_vars.duplicate()}
if ctx.halted != "":
m.current["halted"] = ctx.halted
m.local_state._store_roll(ctx)
if fast or prompted or (m.current["all"] as Array).size() > LONG_CHAIN:
_finish_fast_roll()
return
m._refresh_lit()
m.tray.render()
await _play_node(tree, my)
if my == _token:
m.current["steps"] = m.current["all"]
m.current["done"] = true
m.tray.render()
m.refresh_live()
## The roll's prompt hook: lights the steps so far, then asks through
## prompt_hook (the pop-up, or a test's script). A reply for a roll that has
## been replaced in the meantime is turned into Cancel.
func _prompt_for(req: Dictionary, my: int) -> Variant:
if my != _token:
return null
m.current["prompted"] = true
m.current["asking"] = Formatter.strip_tags(str(req.get("title", "")))
show_progress()
var reply: Variant = await m.prompt_hook.call(req)
if my != _token:
return null
m.current.erase("asking")
return reply
## Lights the steps of the running roll so far (Roller.progress) on the board
## and in the tray, all at once. Used just before a question opens.
func show_progress() -> void:
if m.rolling_ctx == null:
return
var steps := Roller.progress(m.rolling_ctx)
m.lit_entries.clear()
m.lit_pipes.clear()
m.lit_texts.clear()
_light_steps(steps)
m._refresh_lit()
_reveal_steps(steps)
m.current["steps"] = steps
m.current["all"] = steps
m.current["fast"] = true
m.refresh_live()
m.tray.render()
## The real prompt hook: opens the choice pop-up and waits for its answer
## (an index or -1 for a pick, an int, a String, or null for Cancel).
func _ask_player(req: Dictionary) -> Variant:
cancel_choice()
var d := ChoiceDialog.new(req)
_choice = d
var waiter := d.reply
m._add_modal(d)
var v: Variant = await waiter.done
if _choice == d:
_choice = null
return v
## True (after a toast with a Show button) while a question is minimized.
func _choice_waiting(message: String) -> bool:
var d := pending_choice()
if d == null or not d.minimized:
return false
d.nudge(message)
return true
## The open choice pop-up, or null.
func pending_choice() -> ChoiceDialog:
return _choice if is_instance_valid(_choice) else null
## Closes an open choice pop-up as Cancel (its roll stops with "Cancelled").
func cancel_choice() -> void:
var d := pending_choice()
_choice = null
if d != null:
d.answer(null)
## Plays a result tree step by step. Iterative (an explicit stack), so long
## chains don't recurse.
func _play_node(root_node: Dictionary, my: int) -> void:
var stack: Array = [[root_node, 0, ""]] # node, depth, pipe key that led to it
while not stack.is_empty():
var top: Array = stack.pop_back()
var n: Dictionary = top[0]
if my != _token or n.is_empty():
return
var key: String = top[2]
if key != "":
m.lit_pipes[key] = true
await _pulse(key, my)
if my != _token:
return
await _play_one(n, my, int(top[1]))
if my != _token:
return
if n.has("stop"):
continue
var kids: Array = n["children"]
var eid := (n["entry"] as TableEntry).id
var tid := (n["table"] as RollTable).id
for k in range(kids.size() - 1, -1, -1):
var c: Dictionary = kids[k]
var ck := "" if (c.has("pass") or c.has("after")) else Roller.link_key(tid, eid, c)
stack.append([c, int(top[1]) + 1, ck])
## Animates one node: the card tumbles (plain rolls only), then the result lights.
func _play_one(n: Dictionary, my: int, depth: int) -> void:
var t: RollTable = n["table"]
var stopped := n.has("stop")
var card := m.card_for(t.id)
var tumble: bool = not n.has("kind") or bool(n.get("random", false))
# A table hidden in a collapsed group rolls on the group's card.
var gcard: GroupCard = m.hidden_groups().get(t.id)
if not stopped and gcard and tumble:
gcard.set_rolling(true)
await m.get_tree().create_timer(0.35).timeout
if my != _token:
return
gcard = m.hidden_groups().get(t.id)
if gcard:
gcard.set_rolling(false)
elif not stopped and card and tumble:
card.set_rolling(true)
for k in 8:
card = m.card_for(t.id)
if card == null:
break
if t.collapsed:
card.set_more_text("Rolling… %s" % t.fmt(m.rng.randi_range(t.min_value(), maxi(t.min_value(), t.die_size()))))
else:
card.flick_random()
await m.get_tree().create_timer((40.0 + k * 16.0) / 1000.0).timeout
if my != _token:
return
card = m.card_for(t.id)
if card:
card.clear_flick()
card.set_rolling(false)
if not stopped:
var e: TableEntry = n["entry"]
var ek := Roller.entry_key(t.id, e.id)
m.lit_entries[ek] = true
m.lit_texts[ek] = str(n.get("summary", e.text))
m._refresh_lit()
if card:
card.reveal(e.id)
(m.current["steps"] as Array).append(Roller.step_of(n, depth))
m.tray.render()
## Shows the whole current roll at once: every result and pipe on its path lit,
## long lists scrolled to their result, and the full chain in the tray.
func _finish_fast_roll() -> void:
var all: Array = m.current["all"]
_light_steps(all)
m._refresh_lit()
_reveal_steps(all)
m.current["steps"] = all
m.current["done"] = true
m.current["fast"] = true
m.refresh_live()
m.tray.render()
## Scrolls long cards to the last result each table gave in `steps` (one
## reveal per table, so thousands of steps cost one pass).
func _reveal_steps(steps: Array) -> void:
var last := {}
for s: Dictionary in steps:
if s.has("entry_id") and not s.get("stop", false):
last[str(s.get("table_id", ""))] = str(s["entry_id"])
for tid: String in last:
var card := m.card_for(tid)
if card:
card.reveal(last[tid])
func _pulse(key: String, my: int) -> void:
var length := m.board.pipes.path_length(key)
if length <= 0.0 or my != _token:
return
m.board.pipes.pulse_key = key
m.board.pipes.pulse_t = 0.0
_pulse_tween = m.create_tween().set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_IN_OUT)
_pulse_tween.tween_property(m.board.pipes, "pulse_t", 1.0, clampf(length * 0.8, 260.0, 650.0) / 1000.0)
await _pulse_tween.finished
if m.board.pipes.pulse_key == key:
m.board.pipes.pulse_key = ""
## Moves the current roll to the Earlier list (it's already in the saved history).
func _archive_current() -> void:
# A roll still waiting for an answer is cancelled, not kept.
if m.current.is_empty() or m.current.get("archived", false) or m.current.get("pending", false):
return
m.current["archived"] = true
var rec := m.current.duplicate()
rec["steps"] = m.current["all"]
m.history.push_front(rec)
if m.history.size() > Main.HISTORY_SIZE:
m.history.resize(Main.HISTORY_SIZE)
## Opens the session: the collection's saved history, decks and variables. With
## no saved history (a fresh start, or --sample / --screenshot), it seeds a game
## already under way: a couple of earlier rolls, saved variables for the
## Variables tab, and a current roll that runs through the d100 travel table
## into the collapsed trinket table.
func _seed_session() -> void:
m.local_state.load_local_state()
if not m.current.is_empty():
_light_steps(m.current.get("all", []))
m._refresh_lit()
m.refresh_live()
m.tray.render()
return
var now := Time.get_unix_time_from_system()
# Seeded rolls draw from scratch decks so they don't use up real cards.
var scratch := {}
for seed_roll in [["monsters", 9], ["loot", 4]]:
if m.data.get_table(seed_roll[0]):
var tree := Roller.roll(m.data, seed_roll[0], m.rng, 0, scratch)
var steps := Roller.flatten(tree, [])
m.history.push_front({"collection": m.data.id, "root": seed_roll[0], "root_name": m.data.get_table(seed_roll[0]).name,
"time": now - seed_roll[1] * 60, "steps": steps, "all": steps, "archived": true})
# A quest-style chain earlier in the session saved who guides the party and
# the day's weather, so {@guide} and {@weather} have values.
if m.persistent_vars.is_empty():
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, scratch)
for pair in [["@guide", "names"], ["@weather", "weather"]]:
if m.data.get_table(pair[1]):
var n := Roller.roll(m.data, pair[1], m.rng, 0, scratch, ctx)
if not n.is_empty() and not n.has("stop"):
ctx.save(pair[0], Formatter.to_export_bbcode(str(n["summary"])), pair[1])
var start := "wilderness" if m.data.get_table("wilderness") else _first_rollable()
if start == "":
m.refresh_live()
m.tray.render()
return
var best: Dictionary
if m.data.get_table("trinkets"):
best = Roller.roll(m.data, start, m.rng, 0, scratch)
for i in 400:
if Roller.reaches(best, "trinkets"):
break
best = Roller.roll(m.data, start, m.rng, 0, scratch)
else:
# Any other board: one roll with the headless answers, through the real
# variables, so variable and sheet cards have values to show.
best = Roller.roll(m.data, start, m.rng, 0, scratch, Roller.new_context(m.data, m.rng, m.persistent_vars, scratch))
var all := Roller.flatten(best, [])
m.current = {"collection": m.data.id, "root": start, "root_name": m.data.get_table(start).name, "time": now - 60,
"steps": all, "all": all, "done": true, "chain_vars": {}}
Roller.collect_lit(best, m.lit_entries, m.lit_pipes, m.lit_texts)
m._refresh_lit()
m.refresh_live()
m.tray.render()
## The first table that can start a roll (not a variable card), or "".
func _first_rollable() -> String:
for t in m.data.tables:
if t.kind != RollTable.KIND_VARIABLE:
return t.id
return ""
## Lights the entries and pipes of a roll from its saved steps.
func _light_steps(steps: Array) -> void:
var stack: Array = []
for s: Dictionary in steps:
var d := int(s.get("depth", 0))
stack.resize(d)
stack.append(s)
if s.get("stop", false) or not s.has("entry_id"):
continue
var tid := str(s.get("table_id", ""))
var ek := Roller.entry_key(tid, str(s["entry_id"]))
m.lit_entries[ek] = true
m.lit_texts[ek] = str(s.get("text", ""))
if d > 0 and not (s.has("pass") or s.has("after")) and stack[d - 1] is Dictionary and (stack[d - 1] as Dictionary).has("entry_id"):
var p: Dictionary = stack[d - 1]
var ptid := str(p.get("table_id", ""))
var peid := str(p["entry_id"])
m.lit_pipes[Roller.ref_key(ptid, peid, tid) if s.get("inline", false) else Roller.pipe_key(ptid, peid, tid)] = true
# ----- Copy -----
## Copies the current result: ResultTray.COPY_TEXT, COPY_BBCODE or COPY_DETAILS.
func copy_current(kind: int) -> void:
if m.current.is_empty():
return
var text := result_text(m.current.get("all", []), kind)
DisplayServer.clipboard_set(text)
m.toast(["Copied as text", "Copied as BBCode", "Copied with details"][clampi(kind, 0, 2)])
## One line per table rolled, indented by depth. Inline rolls are already part
## of their parent's text, so they don't get lines of their own.
func result_text(steps: Array, kind: int) -> String:
var lines := PackedStringArray()
for s: Dictionary in steps:
if s.get("inline", false):
continue
# Long pipe chains nest thousands deep; cap the indent so the text stays usable.
var indent := " ".repeat(mini(int(s.get("depth", 0)), MAX_INDENT))
var tname := str(s.get("table", ""))
var text := str(s.get("text", ""))
if kind == ResultTray.COPY_BBCODE:
lines.append(indent + "[b]%s:[/b] %s" % [Formatter.to_export_bbcode(tname), Formatter.to_export_bbcode(text)])
else:
lines.append(indent + "%s: %s" % [Formatter.strip_tags(tname), Formatter.strip_tags(text)])
if kind == ResultTray.COPY_DETAILS:
var t := m.data.get_table(str(s.get("table_id", "")))
var e := t.find_entry(str(s.get("entry_id", ""))) if t else null
if e and e.details.strip_edges() != "":
var pad := indent + " "
lines.append(pad + Formatter.strip_tags(e.details).strip_edges().replace("\n", "\n" + pad))
return "\n".join(lines)

1
ui/main_rolling.gd.uid Normal file
View file

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

255
ui/main_state.gd Normal file
View file

@ -0,0 +1,255 @@
class_name MainState
extends RefCounted
## Main's local state for the current collection: decks, persistent
## variables and roll history (StateStore), and the variable actions.
## Everything here is keyed by the current collection id (data.id). With saving
## disabled (--sample / --screenshot) `state` is null and it all stays in memory.
var m: Main
var _ref_cache: Dictionary = {} # entry text -> Array[String] of referenced table ids
func _init(p_main: Main) -> void:
m = p_main
## Loads the current collection's decks, persistent variables and roll history.
## Call it again after switching `data` to another collection (then rebuild the
## cards and call tray.render()).
func load_local_state() -> void:
m.decks = {}
m.persistent_vars = {}
m.history.clear()
m.current = {}
m.lit_entries.clear()
m.lit_pipes.clear()
m.lit_texts.clear()
_ref_cache.clear()
if m.state == null or m.data == null:
return
m.persistent_vars = m.state.get_variables(m.data.id)
for t in m.data.tables:
var d := m.state.get_deck(m.data.id, t.id)
if not d.is_empty():
m.decks[t.id] = DeckState.from_dict(d)
var recs := m.state.get_history(m.data.id)
for i in recs.size():
var rec: Dictionary = recs[i]
if not (rec.get("steps") is Array):
continue
rec["all"] = rec["steps"]
rec["done"] = true
if m.current.is_empty():
m.current = rec
elif m.history.size() < Main.HISTORY_SIZE:
rec["archived"] = true
m.history.append(rec)
## After a roll: saves the decks, any changed persistent variables and the
## history record.
func _store_roll(ctx: RollContext) -> void:
if m.state == null:
return
_store_decks()
if ctx.persistent_changed:
_store_variables()
m.state.add_history({"collection": m.data.id, "root": m.current["root"], "root_name": m.current["root_name"],
"time": m.current["time"], "steps": m.current["all"], "chain_vars": m.current.get("chain_vars", {})})
m.state.save()
func _store_decks() -> void:
if m.state == null:
return
for tid: String in m.decks:
m.state.set_deck(m.data.id, tid, (m.decks[tid] as DeckState).to_dict())
func _store_variables() -> void:
if m.state == null:
return
m.state.clear_variables(m.data.id)
for n: String in m.persistent_vars:
var v: Variant = m.persistent_vars[n]
if v is Dictionary:
m.state.set_variable(m.data.id, n, v.get("value", ""), str(v.get("source", "")))
else:
m.state.set_variable(m.data.id, n, str(v))
## A deleted table's deck and the variables it set are forgotten.
func forget_table_state(tid: String) -> void:
m.decks.erase(tid)
for n in m.persistent_vars.keys():
var v: Variant = m.persistent_vars[n]
if v is Dictionary and str(v.get("source", "")) == tid:
m.persistent_vars.erase(n)
if m.state:
m.state.forget_table(m.data.id, tid)
m.state.save()
if m.tray:
m.tray.render()
## Vector2i(cards left, total) for a card-mode table.
func cards_left(tid: String) -> Vector2i:
var t := m.data.get_table(tid)
if t == null:
return Vector2i.ZERO
var deck: DeckState = m.decks.get(tid)
return deck.cards_left(t) if deck else DeckState.new().cards_left(t)
func reshuffle_table(tid: String) -> void:
var t := m.data.get_table(tid)
if t == null:
return
m.decks.erase(tid)
if m.state:
m.state.clear_deck(m.data.id, tid)
m.state.save()
var card := m.card_for(tid)
if card:
card.update_deck()
m.toast("Reshuffled %s" % Formatter.strip_tags(t.name))
## The expanded text an entry showed in the last roll, or "" if it isn't lit.
func lit_text(tid: String, eid: String) -> String:
return str(m.lit_texts.get(Roller.entry_key(tid, eid), ""))
## Ids of the tables an entry's text references (cached until the next edit).
func ref_targets_for(e: TableEntry) -> Array[String]:
if not _ref_cache.has(e.text):
_ref_cache[e.text] = Roller.ref_targets(m.data, e.text)
return _ref_cache[e.text]
# ----- Variables -----
func set_variable(name: String, value: String) -> void:
var old: Variant = m.persistent_vars.get(name)
var source := str(old.get("source", "")) if old is Dictionary else ""
# A number stays a number when the new text is one too.
var was: Variant = old.get("value") if old is Dictionary else null
var card := variable_card(name)
if source == "" and card:
source = card.id
var as_number := Expr.is_number(was) or (card != null and card.var_type == "number")
var typed: Variant = Expr.to_value(value) if as_number and Expr.is_number(value) else value
m.persistent_vars[name] = {"value": typed, "source": source}
_variables_changed()
func clear_variable(name: String) -> void:
if not m.persistent_vars.erase(name):
return
_variables_changed()
m.toast("Cleared {@%s}" % name)
## The variable card declaring `name` (no "@"), or null.
func variable_card(name: String) -> RollTable:
for t in m.data.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name == name:
return t
return null
## Every board variable name: the set ones and the ones variable cards declare.
func variable_names() -> Array[String]:
var seen := {}
for n: String in m.persistent_vars:
seen[n] = true
for t in m.data.tables:
if t.kind == RollTable.KIND_VARIABLE and t.var_name != "":
seen[t.var_name] = true
var out: Array[String] = []
for n: String in seen:
out.append(n)
out.sort_custom(func(a: String, b: String) -> bool: return a.naturalnocasecmp_to(b) < 0)
return out
## `reset @name`: a declared variable goes back to its starting value, an
## undeclared one is cleared.
func reset_variable(name: String) -> void:
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks)
var err := Effects.reset_one(name, ctx)
_variables_changed()
if err != "":
m.toast("Couldn't reset @%s: %s" % [name, err])
else:
var v: Variant = ctx.get_value("@" + name)
m.toast("Reset @%s%s" % [name, "" if v == null else " to " + Expr.format_value(v)])
## Resets every board variable (see reset_variable).
func reset_all_variables() -> void:
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks)
for n in variable_names():
Effects.reset_one(n, ctx)
_variables_changed()
m.toast("Reset every variable")
## Saves the variables and re-renders what shows them.
func _variables_changed() -> void:
_store_variables()
if m.state:
m.state.save()
m.refresh_live()
m.tray.render()
## Rolls the variable's source table again and saves the new result.
func reroll_variable(name: String) -> void:
var v: Variant = m.persistent_vars.get(name)
var source := str(v.get("source", "")) if v is Dictionary else ""
var t := m.data.get_table(source)
if t == null:
m.toast("{@%s} has no table to re-roll from" % name)
return
var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks)
var n := Roller.roll(m.data, source, m.rng, 0, m.decks, ctx)
if n.is_empty() or n.has("stop"):
m.toast("Couldn't re-roll {@%s}: %s" % [name, Formatter.strip_tags(str(n.get("summary", "no result")))])
return
var value := Formatter.to_export_bbcode(str(n["summary"]))
m.persistent_vars[name] = {"value": value, "source": source}
_store_decks()
_store_variables()
if m.state:
m.state.save()
m._refresh_lit()
m.refresh_live()
m.tray.render()
m.toast("{@%s} is now %s" % [name, Formatter.strip_tags(value)])
## Re-rolling only makes sense for a text value a roll table gave (a pipe's
## "save as" or a {@var|Table}); numbers and logic-card values can't be.
func can_reroll_variable(name: String) -> bool:
var v: Variant = m.persistent_vars.get(name)
if not (v is Dictionary) or variable_card(name) != null:
return false
if Expr.is_number((v as Dictionary).get("value")):
return false
var t := m.data.get_table(str((v as Dictionary).get("source", "")))
return t != null and t.kind == RollTable.KIND_ROLL
## Sets a collection member's saved value (@<stem>_<item>), keeping numbers
## as numbers. Members are local values like the Variables panel's.
func set_collection_member(t: RollTable, item: String, value: String) -> void:
var n := "%s_%s" % [t.var_name, item]
m.persistent_vars[n] = {"value": Expr.to_value(value) if Expr.is_number(value) else value, "source": t.id}
_variables_changed()
func remove_collection_member(t: RollTable, item: String) -> void:
if m.persistent_vars.erase("%s_%s" % [t.var_name, item]):
_variables_changed()

1
ui/main_state.gd.uid Normal file
View file

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

166
ui/main_templates.gd Normal file
View file

@ -0,0 +1,166 @@
class_name MainTemplates
extends RefCounted
## Main's templates: saving cards as templates, inserting, import and export.
## Saved in user://templates (TemplateLibrary), shared by every collection.
## --sample runs keep them in memory only.
var m: Main
var _templates: TemplateLibrary
func _init(p_main: Main) -> void:
m = p_main
func templates() -> TemplateLibrary:
if _templates == null:
_templates = TemplateLibrary.new("user://" if m._saving_enabled else "")
return _templates
## Opens the save dialog for a template of these tables (and groups).
func save_template_from(table_ids: Array, kind: String, group_ids: Array = []) -> void:
var tname := "Template"
if kind == "card" and table_ids.size() == 1 and m.data.get_table(str(table_ids[0])):
tname = Formatter.strip_tags(m.data.get_table(str(table_ids[0])).name)
elif kind == "group" and group_ids.size() == 1 and m.data.get_group(str(group_ids[0])):
tname = Formatter.strip_tags(m.data.get_group(str(group_ids[0])).name)
var tpl := TemplateKit.make(m.data, table_ids, kind, tname, "", group_ids)
if (tpl["tables"] as Array).is_empty():
m.toast("Nothing to save: the template would have no cards")
return
if kind == "selection":
tpl["name"] = "%d cards" % (tpl["tables"] as Array).size()
m._add_modal(TemplateForms.save_dialog(tpl, func(out: Dictionary) -> void:
var id := templates().add(out)
if id == "":
m.toast("Couldn't save the template")
else:
m.toast("Saved template “%s”. Insert it from + Table ▾ → From template…" % out["name"])
))
## The selection as a template; groups whose cards are all selected come along.
func save_selection_as_template() -> void:
if m.selection.is_empty():
m.toast("Select some cards first")
return
var gids: Array = []
for g in m.data.groups:
if g.members.is_empty():
continue
var all := true
for member in g.members:
if not m.selection.has(member):
all = false
break
if all:
gids.append(g.id)
save_template_from(m.selection.keys(), "selection", gids)
func open_template_picker() -> TemplatePicker:
var p := TemplatePicker.new(m, templates())
m._add_modal(p)
return p
## Asks for the template's parameters (if it has any), then inserts it.
func begin_template_insert(tpl: Dictionary) -> void:
if (tpl.get("params", []) as Array).is_empty():
insert_template(tpl, {})
return
m._add_modal(TemplateForms.params_dialog(tpl, func(values: Dictionary) -> void: insert_template(tpl, values)))
## Inserts a template at the view centre: parameters substituted, fresh ids,
## outside pipes relinked by name (or dropped and reported). Returns
## TemplateKit.instantiate's result.
func insert_template(tpl: Dictionary, values: Dictionary) -> Dictionary:
m.undo_redo._begin_edit()
var ext := TemplateKit.extent(tpl)
var center := m.board.screen_to_world(m.board.size / 2.0)
var origin := (center - ext / 2.0).round()
origin = Vector2(maxf(20.0, origin.x), maxf(20.0 + TableGroup.TITLE_H, origin.y))
var r := TemplateKit.insert(tpl, values, m.data, origin)
for t: RollTable in r["tables"]:
if t.kind == RollTable.KIND_VARIABLE and t.var_name == "":
t.var_name = m.editing._free_var_name("var")
var card := TableCard.new()
m.board.cards.add_child(card)
card.setup(m, t)
m.cards[t.id] = card
m.grouping._groups_changed()
m.undo_redo._end_edit("Insert template %s" % Formatter.strip_tags(str(tpl.get("name", "template"))))
var n := (r["tables"] as Array).size()
var msg := "Inserted “%s” (%d %s)" % [str(tpl.get("name", "template")), n, "card" if n == 1 else "cards"]
var relinked: Array = r["relinked"]
if not relinked.is_empty():
msg += " · %d %s relinked by name" % [relinked.size(), "pipe" if relinked.size() == 1 else "pipes"]
var dropped: Array = r["dropped"]
if dropped.is_empty():
m.toast(msg, true)
else:
m.toast(msg + " · %d left out" % dropped.size(), true)
var d := ModalCard.new("Inserted “%s”" % str(tpl.get("name", "template")), 540.0)
d.body.add_child(ModalCard.note("These pipes led to cards outside the template, and this collection has no card with that name, so they were left out. Lay them again by hand, or rename a card and insert again.", Style.INK))
d.body.add_child(ModalCard.section("Left out (%d)" % dropped.size()))
for what: String in dropped:
d.body.add_child(ModalCard.note("• " + what, Style.INK))
if not relinked.is_empty():
d.body.add_child(ModalCard.section("Relinked (%d)" % relinked.size()))
for what: String in relinked:
d.body.add_child(ModalCard.note("• " + what))
d.add_button("Done", "primary", d.close)
m._add_modal(d)
return r
func export_template(id: String) -> void:
var text := templates().export_text(id)
if text == "":
m.toast("Couldn't read that template")
return
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 template"
dlg.filters = PackedStringArray(["*.json ; TableTower template"])
dlg.current_file = id.trim_prefix(TemplateLibrary.BUILTIN_PREFIX) + ".template.json"
dlg.file_selected.connect(func(path: String) -> void:
var err := TowerBoard.write_text_atomic(path, text)
m.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()
)
m.add_child(dlg)
dlg.popup_centered_ratio(0.6)
func import_template_file(picker: TemplatePicker = null) -> void:
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 a template"
dlg.filters = PackedStringArray(["*.json ; TableTower template"])
dlg.file_selected.connect(func(path: String) -> void:
var r := templates().import_text(FileAccess.get_file_as_string(path))
if r["ok"]:
m.toast("Imported template “%s”" % r["name"])
if is_instance_valid(picker):
picker.refresh()
picker.select(r["id"])
else:
m._add_modal(IoMenu.report_dialog("Couldn't import %s" % path.get_file(), {"errors": r["errors"]}))
)
dlg.visibility_changed.connect(func() -> void:
if not dlg.visible:
dlg.queue_free.call_deferred()
)
m.add_child(dlg)
dlg.popup_centered_ratio(0.6)

1
ui/main_templates.gd.uid Normal file
View file

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

318
ui/main_top_bar.gd Normal file
View file

@ -0,0 +1,318 @@
class_name MainTopBar
extends RefCounted
## Main's top bar (brand, Play/Build, collections, Build tools, rules switch,
## search, zoom), the toast at the bottom and the endless-loop warning chip.
var m: Main
var _hint: Label
var _play_button: Button
var _build_button: Button
var _build_tools: Control
var _collapse_all: Button
var _switcher: CollectionSwitcher
var _board_menu: IoMenu
var _toast: PanelContainer
var _toast_label: Label
var _toast_undo: Button
var _toast_timer: Timer
## The undo step the toast's Undo button undoes (EditHistory serial), or -1.
var _toast_serial := -1
var _endless_chip: PanelContainer
var _endless_label: Label
var _endless_timer: Timer
var _rules_buttons: Array[Button] = []
func _init(p_main: Main) -> void:
m = p_main
func _build_top_bar() -> Control:
var bar := PanelContainer.new()
var sb := Style.box(Style.FELT_DEEP, 0, [16, 10, 16, 10])
sb.border_width_bottom = 1
sb.border_color = Color(1, 1, 1, 0.07)
bar.add_theme_stylebox_override("panel", sb)
var h := HBoxContainer.new()
h.add_theme_constant_override("separation", 10)
bar.add_child(h)
var brand := HBoxContainer.new()
brand.add_theme_constant_override("separation", 9)
var mark := Control.new()
mark.custom_minimum_size = Vector2(20, 24)
mark.size_flags_vertical = Control.SIZE_SHRINK_CENTER
mark.draw.connect(func() -> void: Icons.draw_tower(mark, Vector2(0, 0), 20.0 / 22.0, Style.ON_FELT, Style.BRASS))
brand.add_child(mark)
var title := Style.make_label("TableTower", Style.display(), 23, Style.ON_FELT)
title.size_flags_vertical = Control.SIZE_SHRINK_CENTER
brand.add_child(title)
h.add_child(brand)
var seg := PanelContainer.new()
seg.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.28), 9, [3, 3, 3, 3]))
seg.size_flags_vertical = Control.SIZE_SHRINK_CENTER
var seg_row := HBoxContainer.new()
seg_row.add_theme_constant_override("separation", 0)
seg.add_child(seg_row)
var group := ButtonGroup.new()
_play_button = _seg_button("Play", group)
_build_button = _seg_button("Build", group)
_play_button.button_pressed = true
_play_button.pressed.connect(func() -> void: m.set_mode(Main.Mode.PLAY))
_build_button.pressed.connect(func() -> void: m.set_mode(Main.Mode.BUILD))
seg_row.add_child(_play_button)
seg_row.add_child(_build_button)
h.add_child(seg)
_switcher = CollectionSwitcher.new()
_switcher.size_flags_vertical = Control.SIZE_SHRINK_CENTER
_switcher.setup(m)
h.add_child(_switcher)
_hint = Style.make_label(Main.HINTS[m.mode], Style.body(), 15, Style.ON_FELT_MUTED)
_hint.size_flags_horizontal = Control.SIZE_EXPAND_FILL
_hint.size_flags_vertical = Control.SIZE_SHRINK_CENTER
_hint.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
_hint.custom_minimum_size = Vector2(60, 0)
h.add_child(_hint)
var tools := HBoxContainer.new()
tools.add_theme_constant_override("separation", 6)
_build_tools = tools
m.undo_redo._make_history_buttons(tools)
m.editing._add_menu = m.editing._make_add_menu()
tools.add_child(m.editing._add_menu)
_board_menu = IoMenu.new()
_board_menu.setup(true, m.collections_enabled())
_board_menu.reset_requested.connect(m.editing.reset_sample)
_board_menu.import_requested.connect(m.collections.import_collection)
_board_menu.test_requested.connect(m.collections.open_test_board)
_board_menu.export_requested.connect(m.collections.export_collection)
tools.add_child(_board_menu)
# Test board… lives in the Board ▾ menu to keep the Build bar from overflowing.
tools.add_child(m.nav._make_arrange_menu())
tools.visible = false
h.add_child(tools)
_endless_chip = _make_endless_chip()
h.add_child(_endless_chip)
h.add_child(_make_rules_switch())
m.nav._search_button = _make_search_button()
h.add_child(m.nav._search_button)
_collapse_all = Style.bar_button("Collapse all")
_collapse_all.tooltip_text = "Collapse or expand every table at once"
_collapse_all.pressed.connect(func() -> void: m.set_all_collapsed(m._any_expanded()))
h.add_child(_collapse_all)
var zoom := HBoxContainer.new()
zoom.add_theme_constant_override("separation", 6)
var zout := Style.bar_button("−")
zout.tooltip_text = "Zoom out"
zout.custom_minimum_size = Vector2(34, 0)
zout.pressed.connect(func() -> void: m.board.set_zoom(m.board.zoom / 1.15))
var zfit := Style.bar_button("Fit")
zfit.tooltip_text = "Show every table"
zfit.pressed.connect(func() -> void: m.board.fit())
var zin := Style.bar_button("+")
zin.tooltip_text = "Zoom in"
zin.custom_minimum_size = Vector2(34, 0)
zin.pressed.connect(func() -> void: m.board.set_zoom(m.board.zoom * 1.15))
for b in [zout, zfit, zin]:
zoom.add_child(b)
m.nav._map_toggle = m.nav._make_map_toggle()
zoom.add_child(m.nav._map_toggle)
h.add_child(zoom)
return bar
func _seg_button(text: String, group: ButtonGroup) -> Button:
var b := Button.new()
b.text = text
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", 16)
var normal := Style.box(Color(0, 0, 0, 0), 7, [16, 6, 16, 6])
var hover := Style.box(Color(1, 1, 1, 0.06), 7, [16, 6, 16, 6])
var pressed := Style.box(Style.CARD, 7, [16, 6, 16, 6])
Style.skin_button(b, normal, hover, pressed, Style.ON_FELT_MUTED, Style.ON_FELT, Style.INK)
return b
func _make_search_button() -> Button:
var b := Style.bar_button("Search")
b.tooltip_text = "Find a card by its name, results, prompt, variables or group (Ctrl+F)"
_bar_icon(b, func(c: Control) -> void:
c.draw_arc(Vector2(6.5, 6.5), 5.0, 0.0, TAU, 24, Style.ON_FELT, 1.8, true)
c.draw_line(Vector2(10.3, 10.3), Vector2(14.5, 14.5), Style.ON_FELT, 2.4, true))
b.pressed.connect(m.nav.toggle_search)
return b
## Puts a 16 px drawn icon at the left of a top-bar button.
func _bar_icon(b: Button, paint: Callable) -> void:
for n in ["normal", "hover", "pressed", "hover_pressed", "disabled"]:
var sb := b.get_theme_stylebox(n) as StyleBoxFlat
if sb:
sb.content_margin_left = 32
var icon := Control.new()
icon.mouse_filter = Control.MOUSE_FILTER_IGNORE
icon.size = Vector2(16, 16)
icon.draw.connect(paint.bind(icon))
b.add_child(icon)
b.resized.connect(func() -> void: icon.position = Vector2(11, roundf((b.size.y - 16.0) / 2.0)))
func _sync_rules_switch() -> void:
if _rules_buttons.size() == 2:
_rules_buttons[0].set_pressed_no_signal(m.rules_plain())
_rules_buttons[1].set_pressed_no_signal(not m.rules_plain())
## The top bar's compact "Plain | Text" rules switch.
func _make_rules_switch() -> Control:
var seg := PanelContainer.new()
seg.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.28), 9, [3, 3, 3, 3]))
seg.size_flags_vertical = Control.SIZE_SHRINK_CENTER
seg.tooltip_text = "Show rules in plain words, or as the rule text they're stored as"
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 0)
seg.add_child(row)
var group := ButtonGroup.new()
_rules_buttons.clear()
for pair in [["Plain", "plain"], ["Text", "text"]]:
var b := _seg_button(str(pair[0]), group)
b.add_theme_font_size_override("font_size", 14)
for n in ["normal", "hover", "pressed", "hover_pressed"]:
var sb := b.get_theme_stylebox(n) as StyleBoxFlat
if sb:
sb.content_margin_left = 10
sb.content_margin_right = 10
sb.content_margin_top = 4
sb.content_margin_bottom = 4
b.tooltip_text = "Rules: show them in plain words" if pair[1] == "plain" else "Rules: show them as rule text (@luck -= 1)"
b.focus_mode = Control.FOCUS_NONE
var v: String = pair[1]
b.pressed.connect(func() -> void: m.set_rules_view(v))
row.add_child(b)
_rules_buttons.append(b)
_sync_rules_switch()
return seg
# ----- Toast -----
func _build_toast() -> void:
_toast = PanelContainer.new()
var sb := Style.box(Style.CARD, 10, [16, 9, 10, 9])
sb.shadow_color = Color(0, 0, 0, 0.4)
sb.shadow_size = 18
sb.shadow_offset = Vector2(0, 8)
_toast.add_theme_stylebox_override("panel", sb)
var h := HBoxContainer.new()
h.add_theme_constant_override("separation", 12)
_toast.add_child(h)
_toast_label = Style.make_label("", Style.body(), 15, Style.INK)
_toast_label.size_flags_vertical = Control.SIZE_SHRINK_CENTER
h.add_child(_toast_label)
_toast_undo = Button.new()
_toast_undo.text = "Undo"
_toast_undo.add_theme_font_override("font", Style.body_bold())
_toast_undo.add_theme_font_size_override("font_size", 15)
var un := Style.box(Style.FELT, 7, [12, 5, 12, 5])
var uh := Style.box(Style.FELT_HOVER, 7, [12, 5, 12, 5])
Style.skin_button(_toast_undo, un, uh, uh, Style.BRASS)
_toast_undo.pressed.connect(_undo)
_toast_undo.focus_mode = Control.FOCUS_NONE
h.add_child(_toast_undo)
_toast.hide()
m.add_child(_toast)
_toast_timer = Timer.new()
_toast_timer.one_shot = true
_toast_timer.wait_time = 5.0
_toast_timer.timeout.connect(func() -> void:
_toast.hide()
_toast_serial = -1
)
m.add_child(_toast_timer)
## Shows a message at the bottom. With `undoable`, it has an Undo button for
## the edit just committed (it goes through the edit history, like Ctrl+Z).
func toast(message: String, undoable: bool = false) -> void:
_toast_serial = m.undo_redo.edits.top_serial() if undoable and m.undo_redo.edits else -1
_toast_label.text = message
_toast_undo.visible = _toast_serial >= 0
_toast.show()
_toast.reset_size()
_place_toast()
_toast_timer.start()
func _place_toast() -> void:
if _toast and _toast.visible:
_toast.reset_size()
_toast.position = Vector2((m.size.x - _toast.size.x) / 2.0, m.size.y - _toast.size.y - 20.0)
## The toast's Undo button: undoes the step the toast was about, if it is
## still the newest one.
func _undo() -> void:
m.undo_redo._commit_edits()
if _toast_serial < 0 or m.undo_redo.edits == null or m.undo_redo.edits.top_serial() != _toast_serial:
_toast_undo.hide()
if m.undo_redo.edits and m.undo_redo.edits.can_undo():
toast("Newer edits came after that one. Undo (Ctrl+Z) steps back through them.")
return
m.undo_redo.undo()
# ----- 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 = Control.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 m.data == null:
return
var ids := Roller.endless_cycles(m.data)
if m.mode != Main.Mode.BUILD or ids.is_empty():
_endless_chip.hide()
return
var names := PackedStringArray()
for id in ids:
var t := m.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()
## The endless-loop check walks the whole board (about 30 ms on an 800-card
## board), so edits schedule it to run once typing pauses instead of on every
## keystroke.
func _schedule_endless_check() -> void:
if _endless_timer == null:
_endless_timer = Timer.new()
_endless_timer.one_shot = true
_endless_timer.wait_time = 0.4
_endless_timer.timeout.connect(_update_endless_chip)
m.add_child(_endless_timer)
_endless_timer.start()

1
ui/main_top_bar.gd.uid Normal file
View file

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